blob: 4dc446be20cb6e68ad27232f110771f8fb688d78 [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
171static void termcap_mode_start(void);
172static void termcap_mode_end(void);
173static void clear_chars(COORD coord, DWORD n);
174static void clear_screen(void);
175static void clear_to_end_of_display(void);
176static void clear_to_end_of_line(void);
177static void scroll(unsigned cLines);
178static void set_scroll_region(unsigned left, unsigned top,
179 unsigned right, unsigned bottom);
180static void insert_lines(unsigned cLines);
181static void delete_lines(unsigned cLines);
182static void gotoxy(unsigned x, unsigned y);
183static void normvideo(void);
184static void textattr(WORD wAttr);
185static void textcolor(WORD wAttr);
186static void textbackground(WORD wAttr);
187static void standout(void);
188static void standend(void);
189static void visual_bell(void);
190static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200191static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000192static void create_conin(void);
193static int s_cursor_visible = TRUE;
194static int did_create_conin = FALSE;
195#else
196static int s_dont_use_vimrun = TRUE;
197static int need_vimrun_warning = FALSE;
198static char *vimrun_path = "vimrun ";
199#endif
200
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200201static int win32_getattrs(char_u *name);
202static int win32_setattrs(char_u *name, int attrs);
203static int win32_set_archive(char_u *name);
204
Bram Moolenaar071d4272004-06-13 20:20:40 +0000205#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100206static int vtp_working = 0;
207static void vtp_init();
208static void vtp_exit();
209static int vtp_printf(char *format, ...);
210static void vtp_sgr_bulk(int arg);
211static void vtp_sgr_bulks(int argc, int *argv);
212
213static guicolor_T save_console_bg_rgb;
214static guicolor_T save_console_fg_rgb;
215
216# ifdef FEAT_TERMGUICOLORS
217# define USE_VTP (vtp_working && p_tgc)
218# else
219# define USE_VTP 0
220# endif
221
222static void set_console_color_rgb(void);
223static void reset_console_color_rgb(void);
224#endif
225
226/* This flag is newly created from Windows 10 */
227#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
228# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
229#endif
230
231#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100239#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100240/* Dynamic loading for portability */
241typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
242{
243 ULONG cbSize;
244 COORD dwSize;
245 COORD dwCursorPosition;
246 WORD wAttributes;
247 SMALL_RECT srWindow;
248 COORD dwMaximumWindowSize;
249 WORD wPopupAttributes;
250 BOOL bFullscreenSupported;
251 COLORREF ColorTable[16];
252} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
253typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
254static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
255typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
256static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
257static BOOL has_csbiex = FALSE;
258
259/*
260 * Get version number including build number
261 */
262typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
263# define MAKE_VER(major, minor, build) \
264 (((major) << 24) | ((minor) << 16) | (build))
265
266 static DWORD
267get_build_number(void)
268{
269 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
270 HMODULE hNtdll;
271 PfnRtlGetVersion pRtlGetVersion;
272 DWORD ver = MAKE_VER(0, 0, 0);
273
274 hNtdll = GetModuleHandle("ntdll.dll");
275 if (hNtdll != NULL)
276 {
277 pRtlGetVersion =
278 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
279 pRtlGetVersion(&osver);
280 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
281 min(osver.dwMinorVersion, 255),
282 min(osver.dwBuildNumber, 32767));
283 }
284 return ver;
285}
286
287
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288/*
289 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100291 */
292 static BOOL
293read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
299 enum
300 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100301 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 static DWORD s_dwIndex = 0;
305 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100306 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100307 int head;
308 int tail;
309 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200311 if (nLength == -2)
312 return (s_dwMax > 0) ? TRUE : FALSE;
313
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100314 if (!win8_or_later)
315 {
316 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200317 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
318 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 }
320
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321 if (s_dwMax == 0)
322 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100323 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200324 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
325 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100327 s_dwIndex = 0;
328 s_dwMax = dwEvents;
329 if (dwEvents == 0)
330 {
331 *lpEvents = 0;
332 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100334
335 if (s_dwMax > 1)
336 {
337 head = 0;
338 tail = s_dwMax - 1;
339 while (head != tail)
340 {
341 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
342 && s_irCache[head + 1].EventType
343 == WINDOW_BUFFER_SIZE_EVENT)
344 {
345 /* Remove duplicate event to avoid flicker. */
346 for (i = head; i < tail; ++i)
347 s_irCache[i] = s_irCache[i + 1];
348 --tail;
349 continue;
350 }
351 head++;
352 }
353 s_dwMax = tail + 1;
354 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100355 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100356
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100357 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200358 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100359 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100360 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100361 return TRUE;
362}
363
364/*
365 * Version of PeekConsoleInput() that works with IME.
366 */
367 static BOOL
368peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 HANDLE hInput,
370 INPUT_RECORD *lpBuffer,
371 DWORD nLength,
372 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100373{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100374 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375}
376
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100377# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200378 static DWORD
379msg_wait_for_multiple_objects(
380 DWORD nCount,
381 LPHANDLE pHandles,
382 BOOL fWaitAll,
383 DWORD dwMilliseconds,
384 DWORD dwWakeMask)
385{
386 if (read_console_input(NULL, NULL, -2, NULL))
387 return WAIT_OBJECT_0;
388 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
389 dwMilliseconds, dwWakeMask);
390}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100391# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200392
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100393# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200394 static DWORD
395wait_for_single_object(
396 HANDLE hHandle,
397 DWORD dwMilliseconds)
398{
399 if (read_console_input(NULL, NULL, -2, NULL))
400 return WAIT_OBJECT_0;
401 return WaitForSingleObject(hHandle, dwMilliseconds);
402}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100403# endif
404#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200405
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 static void
407get_exe_name(void)
408{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100409 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
410 * as the maximum length that works (plus a NUL byte). */
411#define MAX_ENV_PATH_LEN 8192
412 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200413 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414
415 if (exe_name == NULL)
416 {
417 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100418 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 if (*temp != NUL)
420 exe_name = FullName_save((char_u *)temp, FALSE);
421 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000422
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200423 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000424 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200425 exe_path = vim_strnsave(exe_name,
426 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000428 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200429 /* Append our starting directory to $PATH, so that when doing
430 * "!xxd" it's found in our starting directory. Needed because
431 * SearchPath() also looks there. */
432 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100433 if (p == NULL
434 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100436 if (p == NULL || *p == NUL)
437 temp[0] = NUL;
438 else
439 {
440 STRCPY(temp, p);
441 STRCAT(temp, ";");
442 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100444 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200445 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000446 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448}
449
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200450/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100451 * Unescape characters in "p" that appear in "escaped".
452 */
453 static void
454unescape_shellxquote(char_u *p, char_u *escaped)
455{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100456 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100457 int n;
458
459 while (*p != NUL)
460 {
461 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
462 mch_memmove(p, p + 1, l--);
463#ifdef FEAT_MBYTE
464 n = (*mb_ptr2len)(p);
465#else
466 n = 1;
467#endif
468 p += n;
469 l -= n;
470 }
471}
472
473/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 * Load library "name".
475 */
476 HINSTANCE
477vimLoadLib(char *name)
478{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200479 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200481 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
482 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200483 if (exe_path == NULL)
484 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200485 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200486 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 WCHAR old_dirw[MAXPATHL];
488
489 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
490 {
491 /* Change directory to where the executable is, both to make
492 * sure we find a .dll there and to avoid looking for a .dll
493 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100494 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200495 dll = LoadLibrary(name);
496 SetCurrentDirectoryW(old_dirw);
497 return dll;
498 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200499 }
500 return dll;
501}
502
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100503#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
504/*
505 * Get related information about 'funcname' which is imported by 'hInst'.
506 * If 'info' is 0, return the function address.
507 * If 'info' is 1, return the module name which the function is imported from.
508 */
509 static void *
510get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
511{
512 PBYTE pImage = (PBYTE)hInst;
513 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
514 PIMAGE_NT_HEADERS pPE;
515 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
516 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
517 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
518 PIMAGE_IMPORT_BY_NAME pImpName;
519
520 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
521 return NULL;
522 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
523 if (pPE->Signature != IMAGE_NT_SIGNATURE)
524 return NULL;
525 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
526 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
527 .VirtualAddress);
528 for (; pImpDesc->FirstThunk; ++pImpDesc)
529 {
530 if (!pImpDesc->OriginalFirstThunk)
531 continue;
532 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
533 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
534 for (; pIAT->u1.Function; ++pIAT, ++pINT)
535 {
536 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
537 continue;
538 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
539 + (UINT_PTR)(pINT->u1.AddressOfData));
540 if (strcmp((char *)pImpName->Name, funcname) == 0)
541 {
542 switch (info)
543 {
544 case 0:
545 return (void *)pIAT->u1.Function;
546 case 1:
547 return (void *)(pImage + pImpDesc->Name);
548 default:
549 return NULL;
550 }
551 }
552 }
553 }
554 return NULL;
555}
556
557/*
558 * Get the module handle which 'funcname' in 'hInst' is imported from.
559 */
560 HINSTANCE
561find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
562{
563 char *modulename;
564
565 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
566 if (modulename != NULL)
567 return GetModuleHandleA(modulename);
568 return NULL;
569}
570
571/*
572 * Get the address of 'funcname' which is imported by 'hInst' DLL.
573 */
574 void *
575get_dll_import_func(HINSTANCE hInst, const char *funcname)
576{
577 return get_imported_func_info(hInst, funcname, 0);
578}
579#endif
580
Bram Moolenaar071d4272004-06-13 20:20:40 +0000581#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
582# ifndef GETTEXT_DLL
583# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100584# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000585# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200586/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000587static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200588static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000589static char *null_libintl_textdomain(const char *);
590static char *null_libintl_bindtextdomain(const char *, const char *);
591static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100592static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100593static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000594
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200595static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000596char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200597char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
598 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000599char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
600char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000602char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
603 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100604int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100605int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606
607 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100608dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609{
610 int i;
611 static struct
612 {
613 char *name;
614 FARPROC *ptr;
615 } libintl_entry[] =
616 {
617 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200618 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
620 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
621 {NULL, NULL}
622 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100623 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624
625 /* No need to initialize twice. */
626 if (hLibintlDLL)
627 return 1;
628 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100629 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100630#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100631 if (!hLibintlDLL)
632 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100633#endif
634 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000635 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200636 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000637 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200638 verbose_enter();
639 EMSG2(_(e_loadlib), GETTEXT_DLL);
640 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200642 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643 }
644 for (i = 0; libintl_entry[i].name != NULL
645 && libintl_entry[i].ptr != NULL; ++i)
646 {
647 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
648 libintl_entry[i].name)) == NULL)
649 {
650 dyn_libintl_end();
651 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000652 {
653 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000655 verbose_leave();
656 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657 return 0;
658 }
659 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000660
661 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000662 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000663 "bind_textdomain_codeset");
664 if (dyn_libintl_bind_textdomain_codeset == NULL)
665 dyn_libintl_bind_textdomain_codeset =
666 null_libintl_bind_textdomain_codeset;
667
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100668 /* _putenv() function for the libintl.dll is optional. */
669 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
670 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100671 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100672 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100673 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
674 }
675 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100676 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100677 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
678 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100679
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 return 1;
681}
682
683 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100684dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685{
686 if (hLibintlDLL)
687 FreeLibrary(hLibintlDLL);
688 hLibintlDLL = NULL;
689 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200690 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691 dyn_libintl_textdomain = null_libintl_textdomain;
692 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000693 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100694 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100695 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000696}
697
698 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000699null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700{
701 return (char*)msgid;
702}
703
704 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200705null_libintl_ngettext(
706 const char *msgid,
707 const char *msgid_plural,
708 unsigned long n)
709{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200710 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200711}
712
Bram Moolenaaree695f72016-08-03 22:08:45 +0200713 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100714null_libintl_bindtextdomain(
715 const char *domainname UNUSED,
716 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717{
718 return NULL;
719}
720
721 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100722null_libintl_bind_textdomain_codeset(
723 const char *domainname UNUSED,
724 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000725{
726 return NULL;
727}
728
729 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100730null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000731{
732 return NULL;
733}
734
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200735 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100736null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100737{
738 return 0;
739}
740
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200741 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100742null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100743{
744 return 0;
745}
746
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747#endif /* DYNAMIC_GETTEXT */
748
749/* This symbol is not defined in older versions of the SDK or Visual C++ */
750
751#ifndef VER_PLATFORM_WIN32_WINDOWS
752# define VER_PLATFORM_WIN32_WINDOWS 1
753#endif
754
755DWORD g_PlatformId;
756
757#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100758# ifndef PROTO
759# include <aclapi.h>
760# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200761# ifndef PROTECTED_DACL_SECURITY_INFORMATION
762# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
763# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764#endif
765
Bram Moolenaar27515922013-06-29 15:36:26 +0200766#ifdef HAVE_ACL
767/*
768 * Enables or disables the specified privilege.
769 */
770 static BOOL
771win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
772{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100773 BOOL bResult;
774 LUID luid;
775 HANDLE hToken;
776 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200777
778 if (!OpenProcessToken(GetCurrentProcess(),
779 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
780 return FALSE;
781
782 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
783 {
784 CloseHandle(hToken);
785 return FALSE;
786 }
787
Bram Moolenaar45500912014-07-09 20:51:07 +0200788 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200789 tokenPrivileges.Privileges[0].Luid = luid;
790 tokenPrivileges.Privileges[0].Attributes = bEnable ?
791 SE_PRIVILEGE_ENABLED : 0;
792
793 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
794 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
795
796 CloseHandle(hToken);
797
798 return bResult && GetLastError() == ERROR_SUCCESS;
799}
800#endif
801
Bram Moolenaar071d4272004-06-13 20:20:40 +0000802/*
803 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
804 * VER_PLATFORM_WIN32_WINDOWS (Win95).
805 */
806 void
807PlatformId(void)
808{
809 static int done = FALSE;
810
811 if (!done)
812 {
813 OSVERSIONINFO ovi;
814
815 ovi.dwOSVersionInfoSize = sizeof(ovi);
816 GetVersionEx(&ovi);
817
818 g_PlatformId = ovi.dwPlatformId;
819
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100820 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
821 || ovi.dwMajorVersion > 6)
822 win8_or_later = TRUE;
823
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200825 /* Enable privilege for getting or setting SACLs. */
826 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000827#endif
828 done = TRUE;
829 }
830}
831
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832#ifndef FEAT_GUI_W32
833
834#define SHIFT (SHIFT_PRESSED)
835#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
836#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
837#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
838
839
840/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
841 * We map function keys to their ANSI terminal equivalents, as produced
842 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
843 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
844 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
845 * combinations of function/arrow/etc keys.
846 */
847
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000848static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000849{
850 WORD wVirtKey;
851 BOOL fAnsiKey;
852 int chAlone;
853 int chShift;
854 int chCtrl;
855 int chAlt;
856} VirtKeyMap[] =
857{
858
859/* Key ANSI alone shift ctrl alt */
860 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
861
862 { VK_F1, TRUE, ';', 'T', '^', 'h', },
863 { VK_F2, TRUE, '<', 'U', '_', 'i', },
864 { VK_F3, TRUE, '=', 'V', '`', 'j', },
865 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
866 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
867 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
868 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
869 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
870 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
871 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
872 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
873 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
874
875 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
876 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
877 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
878 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
879 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
880 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
881 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
882 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
883 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
884 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
885
886 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
887
888#if 0
889 /* Most people don't have F13-F20, but what the hell... */
890 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
891 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
892 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
893 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
894 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
895 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
896 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
897 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
898#endif
899 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
900 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
901 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
902 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
903
904 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
905 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
906 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
907 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
908 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
909 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
910 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
911 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
912 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
913 /* Sorry, out of number space! <negri>*/
914 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
915
916};
917
918
919#ifdef _MSC_VER
920// The ToAscii bug destroys several registers. Need to turn off optimization
921// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000922# pragma warning(push)
923# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924# pragma optimize("", off)
925#endif
926
927#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200928# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200930# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931#endif
932
933/* The return code indicates key code size. */
934 static int
935#ifdef __BORLANDC__
936 __stdcall
937#endif
938win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000939 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940{
941 UINT uMods = pker->dwControlKeyState;
942 static int s_iIsDead = 0;
943 static WORD awAnsiCode[2];
944 static BYTE abKeystate[256];
945
946
947 if (s_iIsDead == 2)
948 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200949 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 s_iIsDead = 0;
951 return 1;
952 }
953
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200954 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 return 1;
956
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200957 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200960 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961
962 if (uMods & SHIFT_PRESSED)
963 abKeystate[VK_SHIFT] = 0x80;
964 if (uMods & CAPSLOCK_ON)
965 abKeystate[VK_CAPITAL] = 1;
966
967 if ((uMods & ALT_GR) == ALT_GR)
968 {
969 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
970 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
971 }
972
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200973 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
974 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000975
976 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200977 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978
979 return s_iIsDead;
980}
981
982#ifdef _MSC_VER
983/* MUST switch optimization on again here, otherwise a call to
984 * decode_key_event() may crash (e.g. when hitting caps-lock) */
985# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000986# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987
988# if (_MSC_VER < 1100)
989/* MUST turn off global optimisation for this next function, or
990 * pressing ctrl-minus in insert mode crashes Vim when built with
991 * VC4.1. -- negri. */
992# pragma optimize("g", off)
993# endif
994#endif
995
996static BOOL g_fJustGotFocus = FALSE;
997
998/*
999 * Decode a KEY_EVENT into one or two keystrokes
1000 */
1001 static BOOL
1002decode_key_event(
1003 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001004 WCHAR *pch,
1005 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006 int *pmodifiers,
1007 BOOL fDoPost)
1008{
1009 int i;
1010 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1011
1012 *pch = *pch2 = NUL;
1013 g_fJustGotFocus = FALSE;
1014
1015 /* ignore key up events */
1016 if (!pker->bKeyDown)
1017 return FALSE;
1018
1019 /* ignore some keystrokes */
1020 switch (pker->wVirtualKeyCode)
1021 {
1022 /* modifiers */
1023 case VK_SHIFT:
1024 case VK_CONTROL:
1025 case VK_MENU: /* Alt key */
1026 return FALSE;
1027
1028 default:
1029 break;
1030 }
1031
1032 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001033 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 {
1035 /* Ctrl-6 is Ctrl-^ */
1036 if (pker->wVirtualKeyCode == '6')
1037 {
1038 *pch = Ctrl_HAT;
1039 return TRUE;
1040 }
1041 /* Ctrl-2 is Ctrl-@ */
1042 else if (pker->wVirtualKeyCode == '2')
1043 {
1044 *pch = NUL;
1045 return TRUE;
1046 }
1047 /* Ctrl-- is Ctrl-_ */
1048 else if (pker->wVirtualKeyCode == 0xBD)
1049 {
1050 *pch = Ctrl__;
1051 return TRUE;
1052 }
1053 }
1054
1055 /* Shift-TAB */
1056 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1057 {
1058 *pch = K_NUL;
1059 *pch2 = '\017';
1060 return TRUE;
1061 }
1062
1063 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1064 {
1065 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1066 {
1067 if (nModifs == 0)
1068 *pch = VirtKeyMap[i].chAlone;
1069 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1070 *pch = VirtKeyMap[i].chShift;
1071 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1072 *pch = VirtKeyMap[i].chCtrl;
1073 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1074 *pch = VirtKeyMap[i].chAlt;
1075
1076 if (*pch != 0)
1077 {
1078 if (VirtKeyMap[i].fAnsiKey)
1079 {
1080 *pch2 = *pch;
1081 *pch = K_NUL;
1082 }
1083
1084 return TRUE;
1085 }
1086 }
1087 }
1088
1089 i = win32_kbd_patch_key(pker);
1090
1091 if (i < 0)
1092 *pch = NUL;
1093 else
1094 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001095 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001096
1097 if (pmodifiers != NULL)
1098 {
1099 /* Pass on the ALT key as a modifier, but only when not combined
1100 * with CTRL (which is ALTGR). */
1101 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1102 *pmodifiers |= MOD_MASK_ALT;
1103
1104 /* Pass on SHIFT only for special keys, because we don't know when
1105 * it's already included with the character. */
1106 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1107 *pmodifiers |= MOD_MASK_SHIFT;
1108
1109 /* Pass on CTRL only for non-special keys, because we don't know
1110 * when it's already included with the character. And not when
1111 * combined with ALT (which is ALTGR). */
1112 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1113 && *pch >= 0x20 && *pch < 0x80)
1114 *pmodifiers |= MOD_MASK_CTRL;
1115 }
1116 }
1117
1118 return (*pch != NUL);
1119}
1120
1121#ifdef _MSC_VER
1122# pragma optimize("", on)
1123#endif
1124
1125#endif /* FEAT_GUI_W32 */
1126
1127
1128#ifdef FEAT_MOUSE
1129
1130/*
1131 * For the GUI the mouse handling is in gui_w32.c.
1132 */
1133# ifdef FEAT_GUI_W32
1134 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001135mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136{
1137}
1138# else
1139static int g_fMouseAvail = FALSE; /* mouse present */
1140static int g_fMouseActive = FALSE; /* mouse enabled */
1141static int g_nMouseClick = -1; /* mouse status */
1142static int g_xMouse; /* mouse x coordinate */
1143static int g_yMouse; /* mouse y coordinate */
1144
1145/*
1146 * Enable or disable mouse input
1147 */
1148 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001149mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150{
1151 DWORD cmodein;
1152
1153 if (!g_fMouseAvail)
1154 return;
1155
1156 g_fMouseActive = on;
1157 GetConsoleMode(g_hConIn, &cmodein);
1158
1159 if (g_fMouseActive)
1160 cmodein |= ENABLE_MOUSE_INPUT;
1161 else
1162 cmodein &= ~ENABLE_MOUSE_INPUT;
1163
1164 SetConsoleMode(g_hConIn, cmodein);
1165}
1166
Bram Moolenaar157d8132018-03-06 17:09:20 +01001167
1168#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1169/*
1170 * Called when 'balloonevalterm' changed.
1171 */
1172 void
1173mch_bevalterm_changed(void)
1174{
1175 mch_setmouse(g_fMouseActive);
1176}
1177#endif
1178
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179/*
1180 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1181 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1182 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1183 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1184 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1185 * and we return the mouse position in g_xMouse and g_yMouse.
1186 *
1187 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1188 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1189 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1190 *
1191 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1192 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1193 *
1194 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1195 * moves, even if it stays within the same character cell. We ignore
1196 * all MOUSE_MOVED messages if the position hasn't really changed, and
1197 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1198 * we're only interested in MOUSE_DRAG).
1199 *
1200 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1201 * 2-button mouses by pressing the left & right buttons simultaneously.
1202 * In practice, it's almost impossible to click both at the same time,
1203 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1204 * in such cases, if the user is clicking quickly.
1205 */
1206 static BOOL
1207decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001208 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209{
1210 static int s_nOldButton = -1;
1211 static int s_nOldMouseClick = -1;
1212 static int s_xOldMouse = -1;
1213 static int s_yOldMouse = -1;
1214 static linenr_T s_old_topline = 0;
1215#ifdef FEAT_DIFF
1216 static int s_old_topfill = 0;
1217#endif
1218 static int s_cClicks = 1;
1219 static BOOL s_fReleased = TRUE;
1220 static DWORD s_dwLastClickTime = 0;
1221 static BOOL s_fNextIsMiddle = FALSE;
1222
1223 static DWORD cButtons = 0; /* number of buttons supported */
1224
1225 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1226 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1227 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1228 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1229
1230 int nButton;
1231
1232 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1233 cButtons = 2;
1234
1235 if (!g_fMouseAvail || !g_fMouseActive)
1236 {
1237 g_nMouseClick = -1;
1238 return FALSE;
1239 }
1240
1241 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1242 if (g_fJustGotFocus)
1243 {
1244 g_fJustGotFocus = FALSE;
1245 return FALSE;
1246 }
1247
1248 /* unprocessed mouse click? */
1249 if (g_nMouseClick != -1)
1250 return TRUE;
1251
1252 nButton = -1;
1253 g_xMouse = pmer->dwMousePosition.X;
1254 g_yMouse = pmer->dwMousePosition.Y;
1255
1256 if (pmer->dwEventFlags == MOUSE_MOVED)
1257 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001258 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259 * events even when the mouse moves only within a char cell.) */
1260 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1261 return FALSE;
1262 }
1263
1264 /* If no buttons are pressed... */
1265 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1266 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001267 nButton = MOUSE_RELEASE;
1268
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1270 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001271 {
1272#ifdef FEAT_BEVAL_TERM
1273 /* do return mouse move events when we want them */
1274 if (p_bevalterm)
1275 nButton = MOUSE_DRAG;
1276 else
1277#endif
1278 return FALSE;
1279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280
Bram Moolenaar071d4272004-06-13 20:20:40 +00001281 s_fReleased = TRUE;
1282 }
1283 else /* one or more buttons pressed */
1284 {
1285 /* on a 2-button mouse, hold down left and right buttons
1286 * simultaneously to get MIDDLE. */
1287
1288 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1289 {
1290 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1291
1292 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001293 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294 if (dwLR == LEFT || dwLR == RIGHT)
1295 {
1296 for (;;)
1297 {
1298 /* wait a short time for next input event */
1299 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1300 != WAIT_OBJECT_0)
1301 break;
1302 else
1303 {
1304 DWORD cRecords = 0;
1305 INPUT_RECORD ir;
1306 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1307
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001308 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001309
1310 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1311 || !(pmer2->dwButtonState & LEFT_RIGHT))
1312 break;
1313 else
1314 {
1315 if (pmer2->dwEventFlags != MOUSE_MOVED)
1316 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001317 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318
1319 return decode_mouse_event(pmer2);
1320 }
1321 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1322 s_yOldMouse == pmer2->dwMousePosition.Y)
1323 {
1324 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001325 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001326
1327 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001328 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329
1330 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1331 break;
1332 }
1333 else
1334 break;
1335 }
1336 }
1337 }
1338 }
1339 }
1340
1341 if (s_fNextIsMiddle)
1342 {
1343 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1344 ? MOUSE_DRAG : MOUSE_MIDDLE;
1345 s_fNextIsMiddle = FALSE;
1346 }
1347 else if (cButtons == 2 &&
1348 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1349 {
1350 nButton = MOUSE_MIDDLE;
1351
1352 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1353 {
1354 s_fNextIsMiddle = TRUE;
1355 nButton = MOUSE_RELEASE;
1356 }
1357 }
1358 else if ((pmer->dwButtonState & LEFT) == LEFT)
1359 nButton = MOUSE_LEFT;
1360 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1361 nButton = MOUSE_MIDDLE;
1362 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1363 nButton = MOUSE_RIGHT;
1364
1365 if (! s_fReleased && ! s_fNextIsMiddle
1366 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1367 return FALSE;
1368
1369 s_fReleased = s_fNextIsMiddle;
1370 }
1371
1372 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1373 {
1374 /* button pressed or released, without mouse moving */
1375 if (nButton != -1 && nButton != MOUSE_RELEASE)
1376 {
1377 DWORD dwCurrentTime = GetTickCount();
1378
1379 if (s_xOldMouse != g_xMouse
1380 || s_yOldMouse != g_yMouse
1381 || s_nOldButton != nButton
1382 || s_old_topline != curwin->w_topline
1383#ifdef FEAT_DIFF
1384 || s_old_topfill != curwin->w_topfill
1385#endif
1386 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1387 {
1388 s_cClicks = 1;
1389 }
1390 else if (++s_cClicks > 4)
1391 {
1392 s_cClicks = 1;
1393 }
1394
1395 s_dwLastClickTime = dwCurrentTime;
1396 }
1397 }
1398 else if (pmer->dwEventFlags == MOUSE_MOVED)
1399 {
1400 if (nButton != -1 && nButton != MOUSE_RELEASE)
1401 nButton = MOUSE_DRAG;
1402
1403 s_cClicks = 1;
1404 }
1405
1406 if (nButton == -1)
1407 return FALSE;
1408
1409 if (nButton != MOUSE_RELEASE)
1410 s_nOldButton = nButton;
1411
1412 g_nMouseClick = nButton;
1413
1414 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1415 g_nMouseClick |= MOUSE_SHIFT;
1416 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1417 g_nMouseClick |= MOUSE_CTRL;
1418 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1419 g_nMouseClick |= MOUSE_ALT;
1420
1421 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1422 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1423
1424 /* only pass on interesting (i.e., different) mouse events */
1425 if (s_xOldMouse == g_xMouse
1426 && s_yOldMouse == g_yMouse
1427 && s_nOldMouseClick == g_nMouseClick)
1428 {
1429 g_nMouseClick = -1;
1430 return FALSE;
1431 }
1432
1433 s_xOldMouse = g_xMouse;
1434 s_yOldMouse = g_yMouse;
1435 s_old_topline = curwin->w_topline;
1436#ifdef FEAT_DIFF
1437 s_old_topfill = curwin->w_topfill;
1438#endif
1439 s_nOldMouseClick = g_nMouseClick;
1440
1441 return TRUE;
1442}
1443
1444# endif /* FEAT_GUI_W32 */
1445#endif /* FEAT_MOUSE */
1446
1447
1448#ifdef MCH_CURSOR_SHAPE
1449/*
1450 * Set the shape of the cursor.
1451 * 'thickness' can be from 1 (thin) to 99 (block)
1452 */
1453 static void
1454mch_set_cursor_shape(int thickness)
1455{
1456 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1457 ConsoleCursorInfo.dwSize = thickness;
1458 ConsoleCursorInfo.bVisible = s_cursor_visible;
1459
1460 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1461 if (s_cursor_visible)
1462 SetConsoleCursorPosition(g_hConOut, g_coord);
1463}
1464
1465 void
1466mch_update_cursor(void)
1467{
1468 int idx;
1469 int thickness;
1470
1471 /*
1472 * How the cursor is drawn depends on the current mode.
1473 */
1474 idx = get_shape_idx(FALSE);
1475
1476 if (shape_table[idx].shape == SHAPE_BLOCK)
1477 thickness = 99; /* 100 doesn't work on W95 */
1478 else
1479 thickness = shape_table[idx].percentage;
1480 mch_set_cursor_shape(thickness);
1481}
1482#endif
1483
1484#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1485/*
1486 * Handle FOCUS_EVENT.
1487 */
1488 static void
1489handle_focus_event(INPUT_RECORD ir)
1490{
1491 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1492 ui_focus_change((int)g_fJustGotFocus);
1493}
1494
1495/*
1496 * Wait until console input from keyboard or mouse is available,
1497 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001498 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499 * Return TRUE if something is available FALSE if not.
1500 */
1501 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001502WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503{
1504 DWORD dwNow = 0, dwEndTime = 0;
1505 INPUT_RECORD ir;
1506 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001507 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001508#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001509 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001510#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511
1512 if (msec > 0)
1513 /* Wait until the specified time has elapsed. */
1514 dwEndTime = GetTickCount() + msec;
1515 else if (msec < 0)
1516 /* Wait forever. */
1517 dwEndTime = INFINITE;
1518
1519 /* We need to loop until the end of the time period, because
1520 * we might get multiple unusable mouse events in that time.
1521 */
1522 for (;;)
1523 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001524#ifdef MESSAGE_QUEUE
1525 parse_queued_messages();
1526#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001527#ifdef FEAT_MZSCHEME
1528 mzvim_check_threads();
1529#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530#ifdef FEAT_CLIENTSERVER
1531 serverProcessPendingMessages();
1532#endif
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 Moolenaarfeeb4d02017-12-05 15:14:46 +01001918 if (c == K_NUL && (ch2 & 0xff00) != 0)
1919 {
1920 /* fAnsiKey with modifier keys */
1921 typeahead[typeaheadlen + n] = (char_u)ch2;
1922 n++;
1923 }
1924 else
1925 {
1926 typeahead[typeaheadlen + n] = 3;
1927 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1928 n += 2;
1929 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001930 }
1931
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932 /* Use the ALT key to set the 8th bit of the character
1933 * when it's one byte, the 8th bit isn't set yet and not
1934 * using a double-byte encoding (would become a lead
1935 * byte). */
1936 if ((modifiers & MOD_MASK_ALT)
1937 && n == 1
1938 && (typeahead[typeaheadlen] & 0x80) == 0
1939#ifdef FEAT_MBYTE
1940 && !enc_dbcs
1941#endif
1942 )
1943 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001944#ifdef FEAT_MBYTE
1945 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1946 typeahead + typeaheadlen);
1947#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001949#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 modifiers &= ~MOD_MASK_ALT;
1951 }
1952
1953 if (modifiers != 0)
1954 {
1955 /* Prepend modifiers to the character. */
1956 mch_memmove(typeahead + typeaheadlen + 3,
1957 typeahead + typeaheadlen, n);
1958 typeahead[typeaheadlen++] = K_SPECIAL;
1959 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1960 typeahead[typeaheadlen++] = modifiers;
1961 }
1962
1963 typeaheadlen += n;
1964
1965#ifdef MCH_WRITE_DUMP
1966 if (fdDump)
1967 fputc(c, fdDump);
1968#endif
1969 }
1970 }
1971 }
1972
1973#ifdef MCH_WRITE_DUMP
1974 if (fdDump)
1975 {
1976 fputs("]\n", fdDump);
1977 fflush(fdDump);
1978 }
1979#endif
1980
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981theend:
1982 /* Move typeahead to "buf", as much as fits. */
1983 len = 0;
1984 while (len < maxlen && typeaheadlen > 0)
1985 {
1986 buf[len++] = typeahead[0];
1987 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1988 }
1989 return len;
1990
1991#else /* FEAT_GUI_W32 */
1992 return 0;
1993#endif /* FEAT_GUI_W32 */
1994}
1995
Bram Moolenaar82881492012-11-20 16:53:39 +01001996#ifndef PROTO
1997# ifndef __MINGW32__
1998# include <shellapi.h> /* required for FindExecutable() */
1999# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000#endif
2001
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002002/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002003 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2004 * If "use_path" is FALSE: Return TRUE if "name" exists.
2005 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2006 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002007 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002008 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002010executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002011{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002012 char *dum;
2013 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002014 char *curpath, *newpath;
2015 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016
Bram Moolenaar43663192017-03-05 14:29:12 +01002017 if (!use_path)
2018 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002019 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002020 {
2021 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002022 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002023 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002024 *path = vim_strsave((char_u *)name);
2025 else
2026 *path = FullName_save((char_u *)name, FALSE);
2027 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002028 return TRUE;
2029 }
2030 return FALSE;
2031 }
2032
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002033#ifdef FEAT_MBYTE
2034 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002036 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002037 WCHAR fnamew[_MAX_PATH];
2038 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002039 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002040
2041 if (p != NULL)
2042 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002043 wcurpath = _wgetenv(L"PATH");
2044 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2045 * sizeof(WCHAR));
2046 if (wnewpath == NULL)
2047 return FALSE;
2048 wcscpy(wnewpath, L".;");
2049 wcscat(wnewpath, wcurpath);
2050 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2051 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002052 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002053 if (n == 0)
2054 return FALSE;
2055 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2056 return FALSE;
2057 if (path != NULL)
2058 *path = utf16_to_enc(fnamew, NULL);
2059 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002060 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002062#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002063
2064 curpath = getenv("PATH");
2065 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2066 if (newpath == NULL)
2067 return FALSE;
2068 STRCPY(newpath, ".;");
2069 STRCAT(newpath, curpath);
2070 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2071 vim_free(newpath);
2072 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002073 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002074 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002075 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002076 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002077 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002078 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079}
2080
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002081#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002082 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002083/*
2084 * Bad parameter handler.
2085 *
2086 * Certain MS CRT functions will intentionally crash when passed invalid
2087 * parameters to highlight possible security holes. Setting this function as
2088 * the bad parameter handler will prevent the crash.
2089 *
2090 * In debug builds the parameters contain CRT information that might help track
2091 * down the source of a problem, but in non-debug builds the arguments are all
2092 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2093 * worth allowing these to make debugging of issues easier.
2094 */
2095 static void
2096bad_param_handler(const wchar_t *expression,
2097 const wchar_t *function,
2098 const wchar_t *file,
2099 unsigned int line,
2100 uintptr_t pReserved)
2101{
2102}
2103
2104# define SET_INVALID_PARAM_HANDLER \
2105 ((void)_set_invalid_parameter_handler(bad_param_handler))
2106#else
2107# define SET_INVALID_PARAM_HANDLER
2108#endif
2109
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110#ifdef FEAT_GUI_W32
2111
2112/*
2113 * GUI version of mch_init().
2114 */
2115 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002116mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117{
2118#ifndef __MINGW32__
2119 extern int _fmode;
2120#endif
2121
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002122 /* Silently handle invalid parameters to CRT functions */
2123 SET_INVALID_PARAM_HANDLER;
2124
Bram Moolenaar071d4272004-06-13 20:20:40 +00002125 /* Let critical errors result in a failure, not in a dialog box. Required
2126 * for the timestamp test to work on removed floppies. */
2127 SetErrorMode(SEM_FAILCRITICALERRORS);
2128
2129 _fmode = O_BINARY; /* we do our own CR-LF translation */
2130
2131 /* Specify window size. Is there a place to get the default from? */
2132 Rows = 25;
2133 Columns = 80;
2134
2135 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002136 {
2137 char_u vimrun_location[_MAX_PATH + 4];
2138
2139 /* First try in same directory as gvim.exe */
2140 STRCPY(vimrun_location, exe_name);
2141 STRCPY(gettail(vimrun_location), "vimrun.exe");
2142 if (mch_getperm(vimrun_location) >= 0)
2143 {
2144 if (*skiptowhite(vimrun_location) != NUL)
2145 {
2146 /* Enclose path with white space in double quotes. */
2147 mch_memmove(vimrun_location + 1, vimrun_location,
2148 STRLEN(vimrun_location) + 1);
2149 *vimrun_location = '"';
2150 STRCPY(gettail(vimrun_location), "vimrun\" ");
2151 }
2152 else
2153 STRCPY(gettail(vimrun_location), "vimrun ");
2154
2155 vimrun_path = (char *)vim_strsave(vimrun_location);
2156 s_dont_use_vimrun = FALSE;
2157 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002158 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002159 s_dont_use_vimrun = FALSE;
2160
2161 /* Don't give the warning for a missing vimrun.exe right now, but only
2162 * when vimrun was supposed to be used. Don't bother people that do
2163 * not need vimrun.exe. */
2164 if (s_dont_use_vimrun)
2165 need_vimrun_warning = TRUE;
2166 }
2167
2168 /*
2169 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2170 * Otherwise the default "findstr /n" is used.
2171 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002172 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2174
2175#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002176 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177#endif
2178}
2179
2180
2181#else /* FEAT_GUI_W32 */
2182
2183#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2184#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2185
2186/*
2187 * ClearConsoleBuffer()
2188 * Description:
2189 * Clears the entire contents of the console screen buffer, using the
2190 * specified attribute.
2191 * Returns:
2192 * TRUE on success
2193 */
2194 static BOOL
2195ClearConsoleBuffer(WORD wAttribute)
2196{
2197 CONSOLE_SCREEN_BUFFER_INFO csbi;
2198 COORD coord;
2199 DWORD NumCells, dummy;
2200
2201 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2202 return FALSE;
2203
2204 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2205 coord.X = 0;
2206 coord.Y = 0;
2207 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2208 coord, &dummy))
2209 {
2210 return FALSE;
2211 }
2212 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2213 coord, &dummy))
2214 {
2215 return FALSE;
2216 }
2217
2218 return TRUE;
2219}
2220
2221/*
2222 * FitConsoleWindow()
2223 * Description:
2224 * Checks if the console window will fit within given buffer dimensions.
2225 * Also, if requested, will shrink the window to fit.
2226 * Returns:
2227 * TRUE on success
2228 */
2229 static BOOL
2230FitConsoleWindow(
2231 COORD dwBufferSize,
2232 BOOL WantAdjust)
2233{
2234 CONSOLE_SCREEN_BUFFER_INFO csbi;
2235 COORD dwWindowSize;
2236 BOOL NeedAdjust = FALSE;
2237
2238 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2239 {
2240 /*
2241 * A buffer resize will fail if the current console window does
2242 * not lie completely within that buffer. To avoid this, we might
2243 * have to move and possibly shrink the window.
2244 */
2245 if (csbi.srWindow.Right >= dwBufferSize.X)
2246 {
2247 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2248 if (dwWindowSize.X > dwBufferSize.X)
2249 dwWindowSize.X = dwBufferSize.X;
2250 csbi.srWindow.Right = dwBufferSize.X - 1;
2251 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2252 NeedAdjust = TRUE;
2253 }
2254 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2255 {
2256 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2257 if (dwWindowSize.Y > dwBufferSize.Y)
2258 dwWindowSize.Y = dwBufferSize.Y;
2259 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2260 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2261 NeedAdjust = TRUE;
2262 }
2263 if (NeedAdjust && WantAdjust)
2264 {
2265 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2266 return FALSE;
2267 }
2268 return TRUE;
2269 }
2270
2271 return FALSE;
2272}
2273
2274typedef struct ConsoleBufferStruct
2275{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002276 BOOL IsValid;
2277 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002278 PCHAR_INFO Buffer;
2279 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002280 PSMALL_RECT Regions;
2281 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282} ConsoleBuffer;
2283
2284/*
2285 * SaveConsoleBuffer()
2286 * Description:
2287 * Saves important information about the console buffer, including the
2288 * actual buffer contents. The saved information is suitable for later
2289 * restoration by RestoreConsoleBuffer().
2290 * Returns:
2291 * TRUE if all information was saved; FALSE otherwise
2292 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2293 */
2294 static BOOL
2295SaveConsoleBuffer(
2296 ConsoleBuffer *cb)
2297{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002298 DWORD NumCells;
2299 COORD BufferCoord;
2300 SMALL_RECT ReadRegion;
2301 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002302 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002303
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 if (cb == NULL)
2305 return FALSE;
2306
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002307 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 {
2309 cb->IsValid = FALSE;
2310 return FALSE;
2311 }
2312 cb->IsValid = TRUE;
2313
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002314 /*
2315 * Allocate a buffer large enough to hold the entire console screen
2316 * buffer. If this ConsoleBuffer structure has already been initialized
2317 * with a buffer of the correct size, then just use that one.
2318 */
2319 if (!cb->IsValid || cb->Buffer == NULL ||
2320 cb->BufferSize.X != cb->Info.dwSize.X ||
2321 cb->BufferSize.Y != cb->Info.dwSize.Y)
2322 {
2323 cb->BufferSize.X = cb->Info.dwSize.X;
2324 cb->BufferSize.Y = cb->Info.dwSize.Y;
2325 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2326 vim_free(cb->Buffer);
2327 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2328 if (cb->Buffer == NULL)
2329 return FALSE;
2330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331
2332 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002333 * We will now copy the console screen buffer into our buffer.
2334 * ReadConsoleOutput() seems to be limited as far as how much you
2335 * can read at a time. Empirically, this number seems to be about
2336 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2337 * in chunks until it is all copied. The chunks will all have the
2338 * same horizontal characteristics, so initialize them now. The
2339 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002341 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002342 ReadRegion.Left = 0;
2343 ReadRegion.Right = cb->Info.dwSize.X - 1;
2344 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002345
2346 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2347 if (cb->Regions == NULL || numregions != cb->NumRegions)
2348 {
2349 cb->NumRegions = numregions;
2350 vim_free(cb->Regions);
2351 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2352 if (cb->Regions == NULL)
2353 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002354 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002355 return FALSE;
2356 }
2357 }
2358
2359 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002361 /*
2362 * Read into position (0, Y) in our buffer.
2363 */
2364 BufferCoord.Y = Y;
2365 /*
2366 * Read the region whose top left corner is (0, Y) and whose bottom
2367 * right corner is (width - 1, Y + Y_incr - 1). This should define
2368 * a region of size width by Y_incr. Don't worry if this region is
2369 * too large for the remaining buffer; it will be cropped.
2370 */
2371 ReadRegion.Top = Y;
2372 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002373 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002374 cb->Buffer, /* our buffer */
2375 cb->BufferSize, /* dimensions of our buffer */
2376 BufferCoord, /* offset in our buffer */
2377 &ReadRegion)) /* region to save */
2378 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002379 VIM_CLEAR(cb->Buffer);
2380 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002381 return FALSE;
2382 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002383 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384 }
2385
2386 return TRUE;
2387}
2388
2389/*
2390 * RestoreConsoleBuffer()
2391 * Description:
2392 * Restores important information about the console buffer, including the
2393 * actual buffer contents, if desired. The information to restore is in
2394 * the same format used by SaveConsoleBuffer().
2395 * Returns:
2396 * TRUE on success
2397 */
2398 static BOOL
2399RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002400 ConsoleBuffer *cb,
2401 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002403 COORD BufferCoord;
2404 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002405 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406
2407 if (cb == NULL || !cb->IsValid)
2408 return FALSE;
2409
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002410 /*
2411 * Before restoring the buffer contents, clear the current buffer, and
2412 * restore the cursor position and window information. Doing this now
2413 * prevents old buffer contents from "flashing" onto the screen.
2414 */
2415 if (RestoreScreen)
2416 ClearConsoleBuffer(cb->Info.wAttributes);
2417
2418 FitConsoleWindow(cb->Info.dwSize, TRUE);
2419 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2420 return FALSE;
2421 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2422 return FALSE;
2423
2424 if (!RestoreScreen)
2425 {
2426 /*
2427 * No need to restore the screen buffer contents, so we're done.
2428 */
2429 return TRUE;
2430 }
2431
2432 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2433 return FALSE;
2434 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2435 return FALSE;
2436
2437 /*
2438 * Restore the screen buffer contents.
2439 */
2440 if (cb->Buffer != NULL)
2441 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002442 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002443 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002444 BufferCoord.X = cb->Regions[i].Left;
2445 BufferCoord.Y = cb->Regions[i].Top;
2446 WriteRegion = cb->Regions[i];
2447 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2448 cb->Buffer, /* our buffer */
2449 cb->BufferSize, /* dimensions of our buffer */
2450 BufferCoord, /* offset in our buffer */
2451 &WriteRegion)) /* region to restore */
2452 {
2453 return FALSE;
2454 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002455 }
2456 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457
2458 return TRUE;
2459}
2460
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002461#define FEAT_RESTORE_ORIG_SCREEN
2462#ifdef FEAT_RESTORE_ORIG_SCREEN
2463static ConsoleBuffer g_cbOrig = { 0 };
2464#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465static ConsoleBuffer g_cbNonTermcap = { 0 };
2466static ConsoleBuffer g_cbTermcap = { 0 };
2467
2468#ifdef FEAT_TITLE
2469#ifdef __BORLANDC__
2470typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2471#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002472typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473#endif
2474char g_szOrigTitle[256] = { 0 };
2475HWND g_hWnd = NULL; /* also used in os_mswin.c */
2476static HICON g_hOrigIconSmall = NULL;
2477static HICON g_hOrigIcon = NULL;
2478static HICON g_hVimIcon = NULL;
2479static BOOL g_fCanChangeIcon = FALSE;
2480
2481/* ICON* are not defined in VC++ 4.0 */
2482#ifndef ICON_SMALL
2483#define ICON_SMALL 0
2484#endif
2485#ifndef ICON_BIG
2486#define ICON_BIG 1
2487#endif
2488/*
2489 * GetConsoleIcon()
2490 * Description:
2491 * Attempts to retrieve the small icon and/or the big icon currently in
2492 * use by a given window.
2493 * Returns:
2494 * TRUE on success
2495 */
2496 static BOOL
2497GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002498 HWND hWnd,
2499 HICON *phIconSmall,
2500 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501{
2502 if (hWnd == NULL)
2503 return FALSE;
2504
2505 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002506 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2507 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002509 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2510 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 return TRUE;
2512}
2513
2514/*
2515 * SetConsoleIcon()
2516 * Description:
2517 * Attempts to change the small icon and/or the big icon currently in
2518 * use by a given window.
2519 * Returns:
2520 * TRUE on success
2521 */
2522 static BOOL
2523SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002524 HWND hWnd,
2525 HICON hIconSmall,
2526 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 if (hWnd == NULL)
2529 return FALSE;
2530
2531 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002532 SendMessage(hWnd, WM_SETICON,
2533 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002535 SendMessage(hWnd, WM_SETICON,
2536 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537 return TRUE;
2538}
2539
2540/*
2541 * SaveConsoleTitleAndIcon()
2542 * Description:
2543 * Saves the current console window title in g_szOrigTitle, for later
2544 * restoration. Also, attempts to obtain a handle to the console window,
2545 * and use it to save the small and big icons currently in use by the
2546 * console window. This is not always possible on some versions of Windows;
2547 * nor is it possible when running Vim remotely using Telnet (since the
2548 * console window the user sees is owned by a remote process).
2549 */
2550 static void
2551SaveConsoleTitleAndIcon(void)
2552{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553 /* Save the original title. */
2554 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2555 return;
2556
2557 /*
2558 * Obtain a handle to the console window using GetConsoleWindow() from
2559 * KERNEL32.DLL; we need to handle in order to change the window icon.
2560 * This function only exists on NT-based Windows, starting with Windows
2561 * 2000. On older operating systems, we can't change the window icon
2562 * anyway.
2563 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002564 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 if (g_hWnd == NULL)
2566 return;
2567
2568 /* Save the original console window icon. */
2569 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2570 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2571 return;
2572
2573 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002574 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002575 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 if (g_hVimIcon != NULL)
2577 g_fCanChangeIcon = TRUE;
2578}
2579#endif
2580
2581static int g_fWindInitCalled = FALSE;
2582static int g_fTermcapMode = FALSE;
2583static CONSOLE_CURSOR_INFO g_cci;
2584static DWORD g_cmodein = 0;
2585static DWORD g_cmodeout = 0;
2586
2587/*
2588 * non-GUI version of mch_init().
2589 */
2590 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002591mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002593#ifndef FEAT_RESTORE_ORIG_SCREEN
2594 CONSOLE_SCREEN_BUFFER_INFO csbi;
2595#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596#ifndef __MINGW32__
2597 extern int _fmode;
2598#endif
2599
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002600 /* Silently handle invalid parameters to CRT functions */
2601 SET_INVALID_PARAM_HANDLER;
2602
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 /* Let critical errors result in a failure, not in a dialog box. Required
2604 * for the timestamp test to work on removed floppies. */
2605 SetErrorMode(SEM_FAILCRITICALERRORS);
2606
2607 _fmode = O_BINARY; /* we do our own CR-LF translation */
2608 out_flush();
2609
2610 /* Obtain handles for the standard Console I/O devices */
2611 if (read_cmd_fd == 0)
2612 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2613 else
2614 create_conin();
2615 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2616
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002617#ifdef FEAT_RESTORE_ORIG_SCREEN
2618 /* Save the initial console buffer for later restoration */
2619 SaveConsoleBuffer(&g_cbOrig);
2620 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2621#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002623 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2624 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2625#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 if (cterm_normal_fg_color == 0)
2627 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2628 if (cterm_normal_bg_color == 0)
2629 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2630
2631 /* set termcap codes to current text attributes */
2632 update_tcap(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002633 swap_tcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634
2635 GetConsoleCursorInfo(g_hConOut, &g_cci);
2636 GetConsoleMode(g_hConIn, &g_cmodein);
2637 GetConsoleMode(g_hConOut, &g_cmodeout);
2638
2639#ifdef FEAT_TITLE
2640 SaveConsoleTitleAndIcon();
2641 /*
2642 * Set both the small and big icons of the console window to Vim's icon.
2643 * Note that Vim presently only has one size of icon (32x32), but it
2644 * automatically gets scaled down to 16x16 when setting the small icon.
2645 */
2646 if (g_fCanChangeIcon)
2647 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2648#endif
2649
2650 ui_get_shellsize();
2651
2652#ifdef MCH_WRITE_DUMP
2653 fdDump = fopen("dump", "wt");
2654
2655 if (fdDump)
2656 {
2657 time_t t;
2658
2659 time(&t);
2660 fputs(ctime(&t), fdDump);
2661 fflush(fdDump);
2662 }
2663#endif
2664
2665 g_fWindInitCalled = TRUE;
2666
2667#ifdef FEAT_MOUSE
2668 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2669#endif
2670
2671#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002672 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002673#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002674
2675 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676}
2677
2678/*
2679 * non-GUI version of mch_exit().
2680 * Shut down and exit with status `r'
2681 * Careful: mch_exit() may be called before mch_init()!
2682 */
2683 void
2684mch_exit(int r)
2685{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002686 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002688 vtp_exit();
2689
Bram Moolenaar955f1982017-02-05 15:10:51 +01002690 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002691 if (g_fWindInitCalled)
2692 settmode(TMODE_COOK);
2693
2694 ml_close_all(TRUE); /* remove all memfiles */
2695
2696 if (g_fWindInitCalled)
2697 {
2698#ifdef FEAT_TITLE
2699 mch_restore_title(3);
2700 /*
2701 * Restore both the small and big icons of the console window to
2702 * what they were at startup. Don't do this when the window is
2703 * closed, Vim would hang here.
2704 */
2705 if (g_fCanChangeIcon && !g_fForceExit)
2706 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2707#endif
2708
2709#ifdef MCH_WRITE_DUMP
2710 if (fdDump)
2711 {
2712 time_t t;
2713
2714 time(&t);
2715 fputs(ctime(&t), fdDump);
2716 fclose(fdDump);
2717 }
2718 fdDump = NULL;
2719#endif
2720 }
2721
2722 SetConsoleCursorInfo(g_hConOut, &g_cci);
2723 SetConsoleMode(g_hConIn, g_cmodein);
2724 SetConsoleMode(g_hConOut, g_cmodeout);
2725
2726#ifdef DYNAMIC_GETTEXT
2727 dyn_libintl_end();
2728#endif
2729
2730 exit(r);
2731}
2732#endif /* !FEAT_GUI_W32 */
2733
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734/*
2735 * Do we have an interactive window?
2736 */
2737 int
2738mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002739 int argc UNUSED,
2740 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741{
2742 get_exe_name();
2743
2744#ifdef FEAT_GUI_W32
2745 return OK; /* GUI always has a tty */
2746#else
2747 if (isatty(1))
2748 return OK;
2749 return FAIL;
2750#endif
2751}
2752
2753
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002754#ifdef FEAT_MBYTE
2755/*
2756 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2757 * if it already exists. When "len" is > 0, also expand short to long
2758 * filenames.
2759 * Return FAIL if wide functions are not available, OK otherwise.
2760 * NOTE: much of this is identical to fname_case(), keep in sync!
2761 */
2762 static int
2763fname_casew(
2764 WCHAR *name,
2765 int len)
2766{
2767 WCHAR szTrueName[_MAX_PATH + 2];
2768 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2769 WCHAR *ptrue, *ptruePrev;
2770 WCHAR *porig, *porigPrev;
2771 int flen;
2772 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002773 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002774 int c;
2775 int slen;
2776
2777 flen = (int)wcslen(name);
2778 if (flen > _MAX_PATH)
2779 return OK;
2780
2781 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2782
2783 /* Build the new name in szTrueName[] one component at a time. */
2784 porig = name;
2785 ptrue = szTrueName;
2786
2787 if (iswalpha(porig[0]) && porig[1] == L':')
2788 {
2789 /* copy leading drive letter */
2790 *ptrue++ = *porig++;
2791 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002792 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002793 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002794
2795 while (*porig != NUL)
2796 {
2797 /* copy \ characters */
2798 while (*porig == psepc)
2799 *ptrue++ = *porig++;
2800
2801 ptruePrev = ptrue;
2802 porigPrev = porig;
2803 while (*porig != NUL && *porig != psepc)
2804 {
2805 *ptrue++ = *porig++;
2806 }
2807 *ptrue = NUL;
2808
2809 /* To avoid a slow failure append "\*" when searching a directory,
2810 * server or network share. */
2811 wcscpy(szTrueNameTemp, szTrueName);
2812 slen = (int)wcslen(szTrueNameTemp);
2813 if (*porig == psepc && slen + 2 < _MAX_PATH)
2814 wcscpy(szTrueNameTemp + slen, L"\\*");
2815
2816 /* Skip "", "." and "..". */
2817 if (ptrue > ptruePrev
2818 && (ptruePrev[0] != L'.'
2819 || (ptruePrev[1] != NUL
2820 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2821 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2822 != INVALID_HANDLE_VALUE)
2823 {
2824 c = *porig;
2825 *porig = NUL;
2826
2827 /* Only use the match when it's the same name (ignoring case) or
2828 * expansion is allowed and there is a match with the short name
2829 * and there is enough room. */
2830 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2831 || (len > 0
2832 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2833 && (int)(ptruePrev - szTrueName)
2834 + (int)wcslen(fb.cFileName) < len)))
2835 {
2836 wcscpy(ptruePrev, fb.cFileName);
2837
2838 /* Look for exact match and prefer it if found. Must be a
2839 * long name, otherwise there would be only one match. */
2840 while (FindNextFileW(hFind, &fb))
2841 {
2842 if (*fb.cAlternateFileName != NUL
2843 && (wcscoll(porigPrev, fb.cFileName) == 0
2844 || (len > 0
2845 && (_wcsicoll(porigPrev,
2846 fb.cAlternateFileName) == 0
2847 && (int)(ptruePrev - szTrueName)
2848 + (int)wcslen(fb.cFileName) < len))))
2849 {
2850 wcscpy(ptruePrev, fb.cFileName);
2851 break;
2852 }
2853 }
2854 }
2855 FindClose(hFind);
2856 *porig = c;
2857 ptrue = ptruePrev + wcslen(ptruePrev);
2858 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002859 }
2860
2861 wcscpy(name, szTrueName);
2862 return OK;
2863}
2864#endif
2865
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866/*
2867 * fname_case(): Set the case of the file name, if it already exists.
2868 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002869 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870 */
2871 void
2872fname_case(
2873 char_u *name,
2874 int len)
2875{
2876 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002877 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878 char *ptrue, *ptruePrev;
2879 char *porig, *porigPrev;
2880 int flen;
2881 WIN32_FIND_DATA fb;
2882 HANDLE hFind;
2883 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002884 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002886 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002887 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002888 return;
2889
2890 slash_adjust(name);
2891
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002892#ifdef FEAT_MBYTE
2893 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2894 {
2895 WCHAR *p = enc_to_utf16(name, NULL);
2896
2897 if (p != NULL)
2898 {
2899 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002900 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002901
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002902 wcsncpy(buf, p, _MAX_PATH);
2903 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002904 vim_free(p);
2905
2906 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2907 {
2908 q = utf16_to_enc(buf, NULL);
2909 if (q != NULL)
2910 {
2911 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2912 vim_free(q);
2913 return;
2914 }
2915 }
2916 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002917 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002918 }
2919#endif
2920
2921 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2922 * So we should check this after calling wide function. */
2923 if (flen > _MAX_PATH)
2924 return;
2925
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002927 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 ptrue = szTrueName;
2929
2930 if (isalpha(porig[0]) && porig[1] == ':')
2931 {
2932 /* copy leading drive letter */
2933 *ptrue++ = *porig++;
2934 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002936 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937
2938 while (*porig != NUL)
2939 {
2940 /* copy \ characters */
2941 while (*porig == psepc)
2942 *ptrue++ = *porig++;
2943
2944 ptruePrev = ptrue;
2945 porigPrev = porig;
2946 while (*porig != NUL && *porig != psepc)
2947 {
2948#ifdef FEAT_MBYTE
2949 int l;
2950
2951 if (enc_dbcs)
2952 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002953 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954 while (--l >= 0)
2955 *ptrue++ = *porig++;
2956 }
2957 else
2958#endif
2959 *ptrue++ = *porig++;
2960 }
2961 *ptrue = NUL;
2962
Bram Moolenaar464c9252010-10-13 20:37:41 +02002963 /* To avoid a slow failure append "\*" when searching a directory,
2964 * server or network share. */
2965 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002966 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002967 if (*porig == psepc && slen + 2 < _MAX_PATH)
2968 STRCPY(szTrueNameTemp + slen, "\\*");
2969
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970 /* Skip "", "." and "..". */
2971 if (ptrue > ptruePrev
2972 && (ptruePrev[0] != '.'
2973 || (ptruePrev[1] != NUL
2974 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002975 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002976 != INVALID_HANDLE_VALUE)
2977 {
2978 c = *porig;
2979 *porig = NUL;
2980
2981 /* Only use the match when it's the same name (ignoring case) or
2982 * expansion is allowed and there is a match with the short name
2983 * and there is enough room. */
2984 if (_stricoll(porigPrev, fb.cFileName) == 0
2985 || (len > 0
2986 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2987 && (int)(ptruePrev - szTrueName)
2988 + (int)strlen(fb.cFileName) < len)))
2989 {
2990 STRCPY(ptruePrev, fb.cFileName);
2991
2992 /* Look for exact match and prefer it if found. Must be a
2993 * long name, otherwise there would be only one match. */
2994 while (FindNextFile(hFind, &fb))
2995 {
2996 if (*fb.cAlternateFileName != NUL
2997 && (strcoll(porigPrev, fb.cFileName) == 0
2998 || (len > 0
2999 && (_stricoll(porigPrev,
3000 fb.cAlternateFileName) == 0
3001 && (int)(ptruePrev - szTrueName)
3002 + (int)strlen(fb.cFileName) < len))))
3003 {
3004 STRCPY(ptruePrev, fb.cFileName);
3005 break;
3006 }
3007 }
3008 }
3009 FindClose(hFind);
3010 *porig = c;
3011 ptrue = ptruePrev + strlen(ptruePrev);
3012 }
3013 }
3014
3015 STRCPY(name, szTrueName);
3016}
3017
3018
3019/*
3020 * Insert user name in s[len].
3021 */
3022 int
3023mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003024 char_u *s,
3025 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003027 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028 DWORD cch = sizeof szUserName;
3029
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003030#ifdef FEAT_MBYTE
3031 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3032 {
3033 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3034 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3035
3036 if (GetUserNameW(wszUserName, &wcch))
3037 {
3038 char_u *p = utf16_to_enc(wszUserName, NULL);
3039
3040 if (p != NULL)
3041 {
3042 vim_strncpy(s, p, len - 1);
3043 vim_free(p);
3044 return OK;
3045 }
3046 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003047 }
3048#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049 if (GetUserName(szUserName, &cch))
3050 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003051 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052 return OK;
3053 }
3054 s[0] = NUL;
3055 return FAIL;
3056}
3057
3058
3059/*
3060 * Insert host name in s[len].
3061 */
3062 void
3063mch_get_host_name(
3064 char_u *s,
3065 int len)
3066{
3067 DWORD cch = len;
3068
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003069#ifdef FEAT_MBYTE
3070 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3071 {
3072 WCHAR wszHostName[256 + 1];
3073 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3074
3075 if (GetComputerNameW(wszHostName, &wcch))
3076 {
3077 char_u *p = utf16_to_enc(wszHostName, NULL);
3078
3079 if (p != NULL)
3080 {
3081 vim_strncpy(s, p, len - 1);
3082 vim_free(p);
3083 return;
3084 }
3085 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003086 }
3087#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003088 if (!GetComputerName((LPSTR)s, &cch))
3089 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090}
3091
3092
3093/*
3094 * return process ID
3095 */
3096 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003097mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098{
3099 return (long)GetCurrentProcessId();
3100}
3101
3102
3103/*
3104 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3105 * Return OK for success, FAIL for failure.
3106 */
3107 int
3108mch_dirname(
3109 char_u *buf,
3110 int len)
3111{
3112 /*
3113 * Originally this was:
3114 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3115 * But the Win32s known bug list says that getcwd() doesn't work
3116 * so use the Win32 system call instead. <Negri>
3117 */
3118#ifdef FEAT_MBYTE
3119 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3120 {
3121 WCHAR wbuf[_MAX_PATH + 1];
3122
3123 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3124 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003125 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126
3127 if (p != NULL)
3128 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003129 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130 vim_free(p);
3131 return OK;
3132 }
3133 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003134 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135 }
3136#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003137 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138}
3139
3140/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003141 * Get file permissions for "name".
3142 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003143 */
3144 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003145mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003147 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003148 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003150 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003151 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152}
3153
3154
3155/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003156 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003157 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003158 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159 */
3160 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003161mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003162{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003163 long n = -1;
3164
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165#ifdef FEAT_MBYTE
3166 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3167 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003168 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169
3170 if (p != NULL)
3171 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003172 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003174 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003175 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003176 }
3177 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003178 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003180 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003181 if (n == -1)
3182 return FAIL;
3183
3184 win32_set_archive(name);
3185
3186 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187}
3188
3189/*
3190 * Set hidden flag for "name".
3191 */
3192 void
3193mch_hide(char_u *name)
3194{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003195 int attrs = win32_getattrs(name);
3196 if (attrs == -1)
3197 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003199 attrs |= FILE_ATTRIBUTE_HIDDEN;
3200 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201}
3202
3203/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003204 * Return TRUE if file "name" exists and is hidden.
3205 */
3206 int
3207mch_ishidden(char_u *name)
3208{
3209 int f = win32_getattrs(name);
3210
3211 if (f == -1)
3212 return FALSE; /* file does not exist at all */
3213
3214 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3215}
3216
3217/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218 * return TRUE if "name" is a directory
3219 * return FALSE if "name" is not a directory or upon error
3220 */
3221 int
3222mch_isdir(char_u *name)
3223{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003224 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003225
3226 if (f == -1)
3227 return FALSE; /* file does not exist at all */
3228
3229 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3230}
3231
3232/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003233 * return TRUE if "name" is a directory, NOT a symlink to a directory
3234 * return FALSE if "name" is not a directory
3235 * return FALSE for error
3236 */
3237 int
3238mch_isrealdir(char_u *name)
3239{
3240 return mch_isdir(name) && !mch_is_symbolic_link(name);
3241}
3242
3243/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003244 * Create directory "name".
3245 * Return 0 on success, -1 on error.
3246 */
3247 int
3248mch_mkdir(char_u *name)
3249{
3250#ifdef FEAT_MBYTE
3251 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3252 {
3253 WCHAR *p;
3254 int retval;
3255
3256 p = enc_to_utf16(name, NULL);
3257 if (p == NULL)
3258 return -1;
3259 retval = _wmkdir(p);
3260 vim_free(p);
3261 return retval;
3262 }
3263#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003264 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003265}
3266
3267/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003268 * Delete directory "name".
3269 * Return 0 on success, -1 on error.
3270 */
3271 int
3272mch_rmdir(char_u *name)
3273{
3274#ifdef FEAT_MBYTE
3275 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3276 {
3277 WCHAR *p;
3278 int retval;
3279
3280 p = enc_to_utf16(name, NULL);
3281 if (p == NULL)
3282 return -1;
3283 retval = _wrmdir(p);
3284 vim_free(p);
3285 return retval;
3286 }
3287#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003288 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003289}
3290
3291/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003292 * Return TRUE if file "fname" has more than one link.
3293 */
3294 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003295mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003296{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003297 BY_HANDLE_FILE_INFORMATION info;
3298
3299 return win32_fileinfo(fname, &info) == FILEINFO_OK
3300 && info.nNumberOfLinks > 1;
3301}
3302
3303/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003304 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003305 */
3306 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003307mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003308{
3309 HANDLE hFind;
3310 int res = FALSE;
3311 WIN32_FIND_DATAA findDataA;
3312 DWORD fileFlags = 0, reparseTag = 0;
3313#ifdef FEAT_MBYTE
3314 WCHAR *wn = NULL;
3315 WIN32_FIND_DATAW findDataW;
3316
3317 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003318 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003319 if (wn != NULL)
3320 {
3321 hFind = FindFirstFileW(wn, &findDataW);
3322 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003323 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003324 {
3325 fileFlags = findDataW.dwFileAttributes;
3326 reparseTag = findDataW.dwReserved0;
3327 }
3328 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003329 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003330#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003331 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003332 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003333 if (hFind != INVALID_HANDLE_VALUE)
3334 {
3335 fileFlags = findDataA.dwFileAttributes;
3336 reparseTag = findDataA.dwReserved0;
3337 }
3338 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003339
3340 if (hFind != INVALID_HANDLE_VALUE)
3341 FindClose(hFind);
3342
3343 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003344 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3345 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003346 res = TRUE;
3347
3348 return res;
3349}
3350
3351/*
3352 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3353 * link.
3354 */
3355 int
3356mch_is_linked(char_u *fname)
3357{
3358 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3359 return TRUE;
3360 return FALSE;
3361}
3362
3363/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003364 * Get the by-handle-file-information for "fname".
3365 * Returns FILEINFO_OK when OK.
3366 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3367 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3368 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3369 */
3370 int
3371win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3372{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003373 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003374 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003375#ifdef FEAT_MBYTE
3376 WCHAR *wn = NULL;
3377
3378 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003379 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003380 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003381 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003382 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003383 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003384 if (wn != NULL)
3385 {
3386 hFile = CreateFileW(wn, /* file name */
3387 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003388 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003389 NULL, /* security descriptor */
3390 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003391 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003392 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003393 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003394 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003395 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003396#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003397 hFile = CreateFile((LPCSTR)fname, /* file name */
3398 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003399 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003400 NULL, /* security descriptor */
3401 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003402 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003403 NULL); /* handle to template file */
3404
3405 if (hFile != INVALID_HANDLE_VALUE)
3406 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003407 if (GetFileInformationByHandle(hFile, info) != 0)
3408 res = FILEINFO_OK;
3409 else
3410 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003411 CloseHandle(hFile);
3412 }
3413
Bram Moolenaar03f48552006-02-28 23:52:23 +00003414 return res;
3415}
3416
3417/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003418 * get file attributes for `name'
3419 * -1 : error
3420 * else FILE_ATTRIBUTE_* defined in winnt.h
3421 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003422 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003423win32_getattrs(char_u *name)
3424{
3425 int attr;
3426#ifdef FEAT_MBYTE
3427 WCHAR *p = NULL;
3428
3429 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3430 p = enc_to_utf16(name, NULL);
3431
3432 if (p != NULL)
3433 {
3434 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003435 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003436 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003437 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003438#endif
3439 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003440
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003441 return attr;
3442}
3443
3444/*
3445 * set file attributes for `name' to `attrs'
3446 *
3447 * return -1 for failure, 0 otherwise
3448 */
3449 static
3450 int
3451win32_setattrs(char_u *name, int attrs)
3452{
3453 int res;
3454#ifdef FEAT_MBYTE
3455 WCHAR *p = NULL;
3456
3457 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3458 p = enc_to_utf16(name, NULL);
3459
3460 if (p != NULL)
3461 {
3462 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003463 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003464 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003465 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466#endif
3467 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003468
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003469 return res ? 0 : -1;
3470}
3471
3472/*
3473 * Set archive flag for "name".
3474 */
3475 static
3476 int
3477win32_set_archive(char_u *name)
3478{
3479 int attrs = win32_getattrs(name);
3480 if (attrs == -1)
3481 return -1;
3482
3483 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3484 return win32_setattrs(name, attrs);
3485}
3486
3487/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488 * Return TRUE if file or directory "name" is writable (not readonly).
3489 * Strange semantics of Win32: a readonly directory is writable, but you can't
3490 * delete a file. Let's say this means it is writable.
3491 */
3492 int
3493mch_writable(char_u *name)
3494{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003495 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003497 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3498 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499}
3500
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003502 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003503 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003504 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3505 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506 */
3507 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003508mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003510 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003511 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003512 char_u *p;
3513
3514 if (len >= _MAX_PATH) /* safety check */
3515 return FALSE;
3516
3517 /* If there already is an extension try using the name directly. Also do
3518 * this with a Unix-shell like 'shell'. */
3519 if (vim_strchr(gettail(name), '.') != NULL
3520 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003521 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003522 return TRUE;
3523
3524 /*
3525 * Loop over all extensions in $PATHEXT.
3526 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003527 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003528 p = mch_getenv("PATHEXT");
3529 if (p == NULL)
3530 p = (char_u *)".com;.exe;.bat;.cmd";
3531 while (*p)
3532 {
3533 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3534 {
3535 /* A single "." means no extension is added. */
3536 buf[len] = NUL;
3537 ++p;
3538 if (*p)
3539 ++p;
3540 }
3541 else
3542 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003543 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003544 return TRUE;
3545 }
3546 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003548
3549/*
3550 * Check what "name" is:
3551 * NODE_NORMAL: file or directory (or doesn't exist)
3552 * NODE_WRITABLE: writable device, socket, fifo, etc.
3553 * NODE_OTHER: non-writable things
3554 */
3555 int
3556mch_nodetype(char_u *name)
3557{
3558 HANDLE hFile;
3559 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003560#ifdef FEAT_MBYTE
3561 WCHAR *wn = NULL;
3562#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563
Bram Moolenaar043545e2006-10-10 16:44:07 +00003564 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3565 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3566 * here. */
3567 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3568 return NODE_WRITABLE;
3569
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003570#ifdef FEAT_MBYTE
3571 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003572 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003573
3574 if (wn != NULL)
3575 {
3576 hFile = CreateFileW(wn, /* file name */
3577 GENERIC_WRITE, /* access mode */
3578 0, /* share mode */
3579 NULL, /* security descriptor */
3580 OPEN_EXISTING, /* creation disposition */
3581 0, /* file attributes */
3582 NULL); /* handle to template file */
3583 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003584 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003585 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003586#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003587 hFile = CreateFile((LPCSTR)name, /* file name */
3588 GENERIC_WRITE, /* access mode */
3589 0, /* share mode */
3590 NULL, /* security descriptor */
3591 OPEN_EXISTING, /* creation disposition */
3592 0, /* file attributes */
3593 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003594
3595 if (hFile == INVALID_HANDLE_VALUE)
3596 return NODE_NORMAL;
3597
3598 type = GetFileType(hFile);
3599 CloseHandle(hFile);
3600 if (type == FILE_TYPE_CHAR)
3601 return NODE_WRITABLE;
3602 if (type == FILE_TYPE_DISK)
3603 return NODE_NORMAL;
3604 return NODE_OTHER;
3605}
3606
3607#ifdef HAVE_ACL
3608struct my_acl
3609{
3610 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3611 PSID pSidOwner;
3612 PSID pSidGroup;
3613 PACL pDacl;
3614 PACL pSacl;
3615};
3616#endif
3617
3618/*
3619 * Return a pointer to the ACL of file "fname" in allocated memory.
3620 * Return NULL if the ACL is not available for whatever reason.
3621 */
3622 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003623mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003624{
3625#ifndef HAVE_ACL
3626 return (vim_acl_T)NULL;
3627#else
3628 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003629 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003631 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3632 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003633 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003634# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003635 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003636
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003637 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3638 wn = enc_to_utf16(fname, NULL);
3639 if (wn != NULL)
3640 {
3641 /* Try to retrieve the entire security descriptor. */
3642 err = GetNamedSecurityInfoW(
3643 wn, // Abstract filename
3644 SE_FILE_OBJECT, // File Object
3645 OWNER_SECURITY_INFORMATION |
3646 GROUP_SECURITY_INFORMATION |
3647 DACL_SECURITY_INFORMATION |
3648 SACL_SECURITY_INFORMATION,
3649 &p->pSidOwner, // Ownership information.
3650 &p->pSidGroup, // Group membership.
3651 &p->pDacl, // Discretionary information.
3652 &p->pSacl, // For auditing purposes.
3653 &p->pSecurityDescriptor);
3654 if (err == ERROR_ACCESS_DENIED ||
3655 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003657 /* Retrieve only DACL. */
3658 (void)GetNamedSecurityInfoW(
3659 wn,
3660 SE_FILE_OBJECT,
3661 DACL_SECURITY_INFORMATION,
3662 NULL,
3663 NULL,
3664 &p->pDacl,
3665 NULL,
3666 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003667 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003668 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003669 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003670 mch_free_acl((vim_acl_T)p);
3671 p = NULL;
3672 }
3673 vim_free(wn);
3674 }
3675 else
3676# endif
3677 {
3678 /* Try to retrieve the entire security descriptor. */
3679 err = GetNamedSecurityInfo(
3680 (LPSTR)fname, // Abstract filename
3681 SE_FILE_OBJECT, // File Object
3682 OWNER_SECURITY_INFORMATION |
3683 GROUP_SECURITY_INFORMATION |
3684 DACL_SECURITY_INFORMATION |
3685 SACL_SECURITY_INFORMATION,
3686 &p->pSidOwner, // Ownership information.
3687 &p->pSidGroup, // Group membership.
3688 &p->pDacl, // Discretionary information.
3689 &p->pSacl, // For auditing purposes.
3690 &p->pSecurityDescriptor);
3691 if (err == ERROR_ACCESS_DENIED ||
3692 err == ERROR_PRIVILEGE_NOT_HELD)
3693 {
3694 /* Retrieve only DACL. */
3695 (void)GetNamedSecurityInfo(
3696 (LPSTR)fname,
3697 SE_FILE_OBJECT,
3698 DACL_SECURITY_INFORMATION,
3699 NULL,
3700 NULL,
3701 &p->pDacl,
3702 NULL,
3703 &p->pSecurityDescriptor);
3704 }
3705 if (p->pSecurityDescriptor == NULL)
3706 {
3707 mch_free_acl((vim_acl_T)p);
3708 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003709 }
3710 }
3711 }
3712
3713 return (vim_acl_T)p;
3714#endif
3715}
3716
Bram Moolenaar27515922013-06-29 15:36:26 +02003717#ifdef HAVE_ACL
3718/*
3719 * Check if "acl" contains inherited ACE.
3720 */
3721 static BOOL
3722is_acl_inherited(PACL acl)
3723{
3724 DWORD i;
3725 ACL_SIZE_INFORMATION acl_info;
3726 PACCESS_ALLOWED_ACE ace;
3727
3728 acl_info.AceCount = 0;
3729 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3730 for (i = 0; i < acl_info.AceCount; i++)
3731 {
3732 GetAce(acl, i, (LPVOID *)&ace);
3733 if (ace->Header.AceFlags & INHERITED_ACE)
3734 return TRUE;
3735 }
3736 return FALSE;
3737}
3738#endif
3739
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740/*
3741 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3742 * Errors are ignored.
3743 * This must only be called with "acl" equal to what mch_get_acl() returned.
3744 */
3745 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003746mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747{
3748#ifdef HAVE_ACL
3749 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003750 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003752 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003753 {
3754# ifdef FEAT_MBYTE
3755 WCHAR *wn = NULL;
3756# endif
3757
3758 /* Set security flags */
3759 if (p->pSidOwner)
3760 sec_info |= OWNER_SECURITY_INFORMATION;
3761 if (p->pSidGroup)
3762 sec_info |= GROUP_SECURITY_INFORMATION;
3763 if (p->pDacl)
3764 {
3765 sec_info |= DACL_SECURITY_INFORMATION;
3766 /* Do not inherit its parent's DACL.
3767 * If the DACL is inherited, Cygwin permissions would be changed.
3768 */
3769 if (!is_acl_inherited(p->pDacl))
3770 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3771 }
3772 if (p->pSacl)
3773 sec_info |= SACL_SECURITY_INFORMATION;
3774
3775# ifdef FEAT_MBYTE
3776 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3777 wn = enc_to_utf16(fname, NULL);
3778 if (wn != NULL)
3779 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003780 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003781 wn, // Abstract filename
3782 SE_FILE_OBJECT, // File Object
3783 sec_info,
3784 p->pSidOwner, // Ownership information.
3785 p->pSidGroup, // Group membership.
3786 p->pDacl, // Discretionary information.
3787 p->pSacl // For auditing purposes.
3788 );
3789 vim_free(wn);
3790 }
3791 else
3792# endif
3793 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003794 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003795 (LPSTR)fname, // Abstract filename
3796 SE_FILE_OBJECT, // File Object
3797 sec_info,
3798 p->pSidOwner, // Ownership information.
3799 p->pSidGroup, // Group membership.
3800 p->pDacl, // Discretionary information.
3801 p->pSacl // For auditing purposes.
3802 );
3803 }
3804 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003805#endif
3806}
3807
3808 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003809mch_free_acl(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;
3813
3814 if (p != NULL)
3815 {
3816 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3817 vim_free(p);
3818 }
3819#endif
3820}
3821
3822#ifndef FEAT_GUI_W32
3823
3824/*
3825 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3826 */
3827 static BOOL WINAPI
3828handler_routine(
3829 DWORD dwCtrlType)
3830{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003831 INPUT_RECORD ir;
3832 DWORD out;
3833
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 switch (dwCtrlType)
3835 {
3836 case CTRL_C_EVENT:
3837 if (ctrl_c_interrupts)
3838 g_fCtrlCPressed = TRUE;
3839 return TRUE;
3840
3841 case CTRL_BREAK_EVENT:
3842 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003843 ctrl_break_was_pressed = TRUE;
3844 /* ReadConsoleInput is blocking, send a key event to continue. */
3845 ir.EventType = KEY_EVENT;
3846 ir.Event.KeyEvent.bKeyDown = TRUE;
3847 ir.Event.KeyEvent.wRepeatCount = 1;
3848 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3849 ir.Event.KeyEvent.wVirtualScanCode = 0;
3850 ir.Event.KeyEvent.dwControlKeyState = 0;
3851 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3852 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003853 return TRUE;
3854
3855 /* fatal events: shut down gracefully */
3856 case CTRL_CLOSE_EVENT:
3857 case CTRL_LOGOFF_EVENT:
3858 case CTRL_SHUTDOWN_EVENT:
3859 windgoto((int)Rows - 1, 0);
3860 g_fForceExit = TRUE;
3861
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003862 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863 (dwCtrlType == CTRL_CLOSE_EVENT
3864 ? _("close")
3865 : dwCtrlType == CTRL_LOGOFF_EVENT
3866 ? _("logoff")
3867 : _("shutdown")));
3868#ifdef DEBUG
3869 OutputDebugString(IObuff);
3870#endif
3871
3872 preserve_exit(); /* output IObuff, preserve files and exit */
3873
3874 return TRUE; /* not reached */
3875
3876 default:
3877 return FALSE;
3878 }
3879}
3880
3881
3882/*
3883 * set the tty in (raw) ? "raw" : "cooked" mode
3884 */
3885 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003886mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887{
3888 DWORD cmodein;
3889 DWORD cmodeout;
3890 BOOL bEnableHandler;
3891
3892 GetConsoleMode(g_hConIn, &cmodein);
3893 GetConsoleMode(g_hConOut, &cmodeout);
3894 if (tmode == TMODE_RAW)
3895 {
3896 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3897 ENABLE_ECHO_INPUT);
3898#ifdef FEAT_MOUSE
3899 if (g_fMouseActive)
3900 cmodein |= ENABLE_MOUSE_INPUT;
3901#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003902 cmodeout &= ~(
3903#ifdef FEAT_TERMGUICOLORS
3904 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3905 * VTP. */
3906 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3907#else
3908 ENABLE_PROCESSED_OUTPUT |
3909#endif
3910 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 bEnableHandler = TRUE;
3912 }
3913 else /* cooked */
3914 {
3915 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3916 ENABLE_ECHO_INPUT);
3917 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3918 bEnableHandler = FALSE;
3919 }
3920 SetConsoleMode(g_hConIn, cmodein);
3921 SetConsoleMode(g_hConOut, cmodeout);
3922 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3923
3924#ifdef MCH_WRITE_DUMP
3925 if (fdDump)
3926 {
3927 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3928 tmode == TMODE_RAW ? "raw" :
3929 tmode == TMODE_COOK ? "cooked" : "normal",
3930 cmodein, cmodeout);
3931 fflush(fdDump);
3932 }
3933#endif
3934}
3935
3936
3937/*
3938 * Get the size of the current window in `Rows' and `Columns'
3939 * Return OK when size could be determined, FAIL otherwise.
3940 */
3941 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003942mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943{
3944 CONSOLE_SCREEN_BUFFER_INFO csbi;
3945
3946 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3947 {
3948 /*
3949 * For some reason, we are trying to get the screen dimensions
3950 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3951 * variables are really intended to mean the size of Vim screen
3952 * while in termcap mode.
3953 */
3954 Rows = g_cbTermcap.Info.dwSize.Y;
3955 Columns = g_cbTermcap.Info.dwSize.X;
3956 }
3957 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3958 {
3959 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3960 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3961 }
3962 else
3963 {
3964 Rows = 25;
3965 Columns = 80;
3966 }
3967 return OK;
3968}
3969
3970/*
3971 * Set a console window to `xSize' * `ySize'
3972 */
3973 static void
3974ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003975 HANDLE hConsole,
3976 int xSize,
3977 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978{
3979 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3980 SMALL_RECT srWindowRect; /* hold the new console size */
3981 COORD coordScreen;
3982
3983#ifdef MCH_WRITE_DUMP
3984 if (fdDump)
3985 {
3986 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3987 fflush(fdDump);
3988 }
3989#endif
3990
3991 /* get the largest size we can size the console window to */
3992 coordScreen = GetLargestConsoleWindowSize(hConsole);
3993
3994 /* define the new console window size and scroll position */
3995 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3996 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3997 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3998
3999 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4000 {
4001 int sx, sy;
4002
4003 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4004 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4005 if (sy < ySize || sx < xSize)
4006 {
4007 /*
4008 * Increasing number of lines/columns, do buffer first.
4009 * Use the maximal size in x and y direction.
4010 */
4011 if (sy < ySize)
4012 coordScreen.Y = ySize;
4013 else
4014 coordScreen.Y = sy;
4015 if (sx < xSize)
4016 coordScreen.X = xSize;
4017 else
4018 coordScreen.X = sx;
4019 SetConsoleScreenBufferSize(hConsole, coordScreen);
4020 }
4021 }
4022
4023 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
4024 {
4025#ifdef MCH_WRITE_DUMP
4026 if (fdDump)
4027 {
4028 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4029 GetLastError());
4030 fflush(fdDump);
4031 }
4032#endif
4033 }
4034
4035 /* define the new console buffer size */
4036 coordScreen.X = xSize;
4037 coordScreen.Y = ySize;
4038
4039 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4040 {
4041#ifdef MCH_WRITE_DUMP
4042 if (fdDump)
4043 {
4044 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4045 GetLastError());
4046 fflush(fdDump);
4047 }
4048#endif
4049 }
4050}
4051
4052
4053/*
4054 * Set the console window to `Rows' * `Columns'
4055 */
4056 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004057mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058{
4059 COORD coordScreen;
4060
4061 /* Don't change window size while still starting up */
4062 if (suppress_winsize != 0)
4063 {
4064 suppress_winsize = 2;
4065 return;
4066 }
4067
4068 if (term_console)
4069 {
4070 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4071
4072 /* Clamp Rows and Columns to reasonable values */
4073 if (Rows > coordScreen.Y)
4074 Rows = coordScreen.Y;
4075 if (Columns > coordScreen.X)
4076 Columns = coordScreen.X;
4077
4078 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4079 }
4080}
4081
4082/*
4083 * Rows and/or Columns has changed.
4084 */
4085 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004086mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004087{
4088 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4089}
4090
4091
4092/*
4093 * Called when started up, to set the winsize that was delayed.
4094 */
4095 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004096mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097{
4098 if (suppress_winsize == 2)
4099 {
4100 suppress_winsize = 0;
4101 mch_set_shellsize();
4102 shell_resized();
4103 }
4104 suppress_winsize = 0;
4105}
4106#endif /* FEAT_GUI_W32 */
4107
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004108 static BOOL
4109vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004110 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004111 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004112 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004113 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004114 PROCESS_INFORMATION *pi,
4115 LPVOID *env,
4116 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004117{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004118#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004119 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4120 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004121 BOOL ret;
4122 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004123
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004124 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4125 if (wcmd == NULL)
4126 goto fallback;
4127 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004128 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004129 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4130 if (wcwd == NULL)
4131 {
4132 vim_free(wcmd);
4133 goto fallback;
4134 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004135 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004136
4137 ret = CreateProcessW(
4138 NULL, /* Executable name */
4139 wcmd, /* Command to execute */
4140 NULL, /* Process security attributes */
4141 NULL, /* Thread security attributes */
4142 inherit_handles, /* Inherit handles */
4143 flags, /* Creation flags */
4144 env, /* Environment */
4145 wcwd, /* Current directory */
4146 (LPSTARTUPINFOW)si, /* Startup information */
4147 pi); /* Process information */
4148 vim_free(wcmd);
4149 if (wcwd != NULL)
4150 vim_free(wcwd);
4151 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004152 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004153fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004154#endif
4155 return CreateProcess(
4156 NULL, /* Executable name */
4157 cmd, /* Command to execute */
4158 NULL, /* Process security attributes */
4159 NULL, /* Thread security attributes */
4160 inherit_handles, /* Inherit handles */
4161 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004162 env, /* Environment */
4163 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004164 si, /* Startup information */
4165 pi); /* Process information */
4166}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004167
4168
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004169 static HINSTANCE
4170vim_shell_execute(
4171 char *cmd,
4172 INT n_show_cmd)
4173{
4174#ifdef FEAT_MBYTE
4175 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4176 {
4177 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4178 if (wcmd != NULL)
4179 {
4180 HINSTANCE ret;
4181 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4182 vim_free(wcmd);
4183 return ret;
4184 }
4185 }
4186#endif
4187 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4188}
4189
4190
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191#if defined(FEAT_GUI_W32) || defined(PROTO)
4192
4193/*
4194 * Specialised version of system() for Win32 GUI mode.
4195 * This version proceeds as follows:
4196 * 1. Create a console window for use by the subprocess
4197 * 2. Run the subprocess (it gets the allocated console by default)
4198 * 3. Wait for the subprocess to terminate and get its exit code
4199 * 4. Prompt the user to press a key to close the console window
4200 */
4201 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004202mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004203{
4204 STARTUPINFO si;
4205 PROCESS_INFORMATION pi;
4206 DWORD ret = 0;
4207 HWND hwnd = GetFocus();
4208
4209 si.cb = sizeof(si);
4210 si.lpReserved = NULL;
4211 si.lpDesktop = NULL;
4212 si.lpTitle = NULL;
4213 si.dwFlags = STARTF_USESHOWWINDOW;
4214 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004215 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004216 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004217 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004218 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004219 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220 else
4221 si.wShowWindow = SW_SHOWNORMAL;
4222 si.cbReserved2 = 0;
4223 si.lpReserved2 = NULL;
4224
Bram Moolenaar071d4272004-06-13 20:20:40 +00004225 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004226 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004227 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4228 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004229
4230 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231 {
4232#ifdef FEAT_GUI
4233 int delay = 1;
4234
4235 /* Keep updating the window while waiting for the shell to finish. */
4236 for (;;)
4237 {
4238 MSG msg;
4239
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004240 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241 {
4242 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004243 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004244 delay = 1;
4245 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004246 }
4247 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4248 break;
4249
4250 /* We start waiting for a very short time and then increase it, so
4251 * that we respond quickly when the process is quick, and don't
4252 * consume too much overhead when it's slow. */
4253 if (delay < 50)
4254 delay += 10;
4255 }
4256#else
4257 WaitForSingleObject(pi.hProcess, INFINITE);
4258#endif
4259
4260 /* Get the command exit code */
4261 GetExitCodeProcess(pi.hProcess, &ret);
4262 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263
4264 /* Close the handles to the subprocess, so that it goes away */
4265 CloseHandle(pi.hThread);
4266 CloseHandle(pi.hProcess);
4267
4268 /* Try to get input focus back. Doesn't always work though. */
4269 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4270
4271 return ret;
4272}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004273
4274/*
4275 * Thread launched by the gui to send the current buffer data to the
4276 * process. This way avoid to hang up vim totally if the children
4277 * process take a long time to process the lines.
4278 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004279 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004280sub_process_writer(LPVOID param)
4281{
4282 HANDLE g_hChildStd_IN_Wr = param;
4283 linenr_T lnum = curbuf->b_op_start.lnum;
4284 DWORD len = 0;
4285 DWORD l;
4286 char_u *lp = ml_get(lnum);
4287 char_u *s;
4288 int written = 0;
4289
4290 for (;;)
4291 {
4292 l = (DWORD)STRLEN(lp + written);
4293 if (l == 0)
4294 len = 0;
4295 else if (lp[written] == NL)
4296 {
4297 /* NL -> NUL translation */
4298 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4299 }
4300 else
4301 {
4302 s = vim_strchr(lp + written, NL);
4303 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4304 s == NULL ? l : (DWORD)(s - (lp + written)),
4305 &len, NULL);
4306 }
4307 if (len == (int)l)
4308 {
4309 /* Finished a line, add a NL, unless this line should not have
4310 * one. */
4311 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004312 || (!curbuf->b_p_bin
4313 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004314 || (lnum != curbuf->b_no_eol_lnum
4315 && (lnum != curbuf->b_ml.ml_line_count
4316 || curbuf->b_p_eol)))
4317 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004318 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004319 }
4320
4321 ++lnum;
4322 if (lnum > curbuf->b_op_end.lnum)
4323 break;
4324
4325 lp = ml_get(lnum);
4326 written = 0;
4327 }
4328 else if (len > 0)
4329 written += len;
4330 }
4331
4332 /* finished all the lines, close pipe */
4333 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004334 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004335}
4336
4337
4338# define BUFLEN 100 /* length for buffer, stolen from unix version */
4339
4340/*
4341 * This function read from the children's stdout and write the
4342 * data on screen or in the buffer accordingly.
4343 */
4344 static void
4345dump_pipe(int options,
4346 HANDLE g_hChildStd_OUT_Rd,
4347 garray_T *ga,
4348 char_u buffer[],
4349 DWORD *buffer_off)
4350{
4351 DWORD availableBytes = 0;
4352 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004353 int ret;
4354 DWORD len;
4355 DWORD toRead;
4356 int repeatCount;
4357
4358 /* we query the pipe to see if there is any data to read
4359 * to avoid to perform a blocking read */
4360 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4361 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004362 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004363 NULL, /* number of read bytes */
4364 &availableBytes, /* available bytes total */
4365 NULL); /* byteLeft */
4366
4367 repeatCount = 0;
4368 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004369 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004370 {
4371 repeatCount++;
4372 toRead =
4373# ifdef FEAT_MBYTE
4374 (DWORD)(BUFLEN - *buffer_off);
4375# else
4376 (DWORD)BUFLEN;
4377# endif
4378 toRead = availableBytes < toRead ? availableBytes : toRead;
4379 ReadFile(g_hChildStd_OUT_Rd, buffer
4380# ifdef FEAT_MBYTE
4381 + *buffer_off, toRead
4382# else
4383 , toRead
4384# endif
4385 , &len, NULL);
4386
4387 /* If we haven't read anything, there is a problem */
4388 if (len == 0)
4389 break;
4390
4391 availableBytes -= len;
4392
4393 if (options & SHELL_READ)
4394 {
4395 /* Do NUL -> NL translation, append NL separated
4396 * lines to the current buffer. */
4397 for (i = 0; i < len; ++i)
4398 {
4399 if (buffer[i] == NL)
4400 append_ga_line(ga);
4401 else if (buffer[i] == NUL)
4402 ga_append(ga, NL);
4403 else
4404 ga_append(ga, buffer[i]);
4405 }
4406 }
4407# ifdef FEAT_MBYTE
4408 else if (has_mbyte)
4409 {
4410 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004411 int c;
4412 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004413
4414 len += *buffer_off;
4415 buffer[len] = NUL;
4416
4417 /* Check if the last character in buffer[] is
4418 * incomplete, keep these bytes for the next
4419 * round. */
4420 for (p = buffer; p < buffer + len; p += l)
4421 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004422 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004423 if (l == 0)
4424 l = 1; /* NUL byte? */
4425 else if (MB_BYTE2LEN(*p) != l)
4426 break;
4427 }
4428 if (p == buffer) /* no complete character */
4429 {
4430 /* avoid getting stuck at an illegal byte */
4431 if (len >= 12)
4432 ++p;
4433 else
4434 {
4435 *buffer_off = len;
4436 return;
4437 }
4438 }
4439 c = *p;
4440 *p = NUL;
4441 msg_puts(buffer);
4442 if (p < buffer + len)
4443 {
4444 *p = c;
4445 *buffer_off = (DWORD)((buffer + len) - p);
4446 mch_memmove(buffer, p, *buffer_off);
4447 return;
4448 }
4449 *buffer_off = 0;
4450 }
4451# endif /* FEAT_MBYTE */
4452 else
4453 {
4454 buffer[len] = NUL;
4455 msg_puts(buffer);
4456 }
4457
4458 windgoto(msg_row, msg_col);
4459 cursor_on();
4460 out_flush();
4461 }
4462}
4463
4464/*
4465 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4466 * for communication and doesn't open any new window.
4467 */
4468 static int
4469mch_system_piped(char *cmd, int options)
4470{
4471 STARTUPINFO si;
4472 PROCESS_INFORMATION pi;
4473 DWORD ret = 0;
4474
4475 HANDLE g_hChildStd_IN_Rd = NULL;
4476 HANDLE g_hChildStd_IN_Wr = NULL;
4477 HANDLE g_hChildStd_OUT_Rd = NULL;
4478 HANDLE g_hChildStd_OUT_Wr = NULL;
4479
4480 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4481 DWORD len;
4482
4483 /* buffer used to receive keys */
4484 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4485 int ta_len = 0; /* valid bytes in ta_buf[] */
4486
4487 DWORD i;
4488 int c;
4489 int noread_cnt = 0;
4490 garray_T ga;
4491 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004492 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004493 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004494
4495 SECURITY_ATTRIBUTES saAttr;
4496
4497 /* Set the bInheritHandle flag so pipe handles are inherited. */
4498 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4499 saAttr.bInheritHandle = TRUE;
4500 saAttr.lpSecurityDescriptor = NULL;
4501
4502 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4503 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004504 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004505 /* Create a pipe for the child process's STDIN. */
4506 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4507 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004508 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004509 {
4510 CloseHandle(g_hChildStd_IN_Rd);
4511 CloseHandle(g_hChildStd_IN_Wr);
4512 CloseHandle(g_hChildStd_OUT_Rd);
4513 CloseHandle(g_hChildStd_OUT_Wr);
4514 MSG_PUTS(_("\nCannot create pipes\n"));
4515 }
4516
4517 si.cb = sizeof(si);
4518 si.lpReserved = NULL;
4519 si.lpDesktop = NULL;
4520 si.lpTitle = NULL;
4521 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4522
4523 /* set-up our file redirection */
4524 si.hStdError = g_hChildStd_OUT_Wr;
4525 si.hStdOutput = g_hChildStd_OUT_Wr;
4526 si.hStdInput = g_hChildStd_IN_Rd;
4527 si.wShowWindow = SW_HIDE;
4528 si.cbReserved2 = 0;
4529 si.lpReserved2 = NULL;
4530
4531 if (options & SHELL_READ)
4532 ga_init2(&ga, 1, BUFLEN);
4533
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004534 if (cmd != NULL)
4535 {
4536 p = (char *)vim_strsave((char_u *)cmd);
4537 if (p != NULL)
4538 unescape_shellxquote((char_u *)p, p_sxe);
4539 else
4540 p = cmd;
4541 }
4542
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004543 /* Now, run the command.
4544 * About "Inherit handles" being TRUE: this command can be litigious,
4545 * handle inheritance was deactivated for pending temp file, but, if we
4546 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004547 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4548 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004549
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004550 if (p != cmd)
4551 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004552
4553 /* Close our unused side of the pipes */
4554 CloseHandle(g_hChildStd_IN_Rd);
4555 CloseHandle(g_hChildStd_OUT_Wr);
4556
4557 if (options & SHELL_WRITE)
4558 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004559 HANDLE thread = (HANDLE)
4560 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004561 0, /* default stack size */
4562 sub_process_writer, /* function to be executed */
4563 g_hChildStd_IN_Wr, /* parameter */
4564 0, /* creation flag, start immediately */
4565 NULL); /* we don't care about thread id */
4566 CloseHandle(thread);
4567 g_hChildStd_IN_Wr = NULL;
4568 }
4569
4570 /* Keep updating the window while waiting for the shell to finish. */
4571 for (;;)
4572 {
4573 MSG msg;
4574
Bram Moolenaar175d0702013-12-11 18:36:33 +01004575 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004576 {
4577 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004578 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004579 }
4580
4581 /* write pipe information in the window */
4582 if ((options & (SHELL_READ|SHELL_WRITE))
4583# ifdef FEAT_GUI
4584 || gui.in_use
4585# endif
4586 )
4587 {
4588 len = 0;
4589 if (!(options & SHELL_EXPAND)
4590 && ((options &
4591 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4592 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4593# ifdef FEAT_GUI
4594 || gui.in_use
4595# endif
4596 )
4597 && (ta_len > 0 || noread_cnt > 4))
4598 {
4599 if (ta_len == 0)
4600 {
4601 /* Get extra characters when we don't have any. Reset the
4602 * counter and timer. */
4603 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004604 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4605 }
4606 if (ta_len > 0 || len > 0)
4607 {
4608 /*
4609 * For pipes: Check for CTRL-C: send interrupt signal to
4610 * child. Check for CTRL-D: EOF, close pipe to child.
4611 */
4612 if (len == 1 && cmd != NULL)
4613 {
4614 if (ta_buf[ta_len] == Ctrl_C)
4615 {
4616 /* Learn what exit code is expected, for
4617 * now put 9 as SIGKILL */
4618 TerminateProcess(pi.hProcess, 9);
4619 }
4620 if (ta_buf[ta_len] == Ctrl_D)
4621 {
4622 CloseHandle(g_hChildStd_IN_Wr);
4623 g_hChildStd_IN_Wr = NULL;
4624 }
4625 }
4626
4627 /* replace K_BS by <BS> and K_DEL by <DEL> */
4628 for (i = ta_len; i < ta_len + len; ++i)
4629 {
4630 if (ta_buf[i] == CSI && len - i > 2)
4631 {
4632 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4633 if (c == K_DEL || c == K_KDEL || c == K_BS)
4634 {
4635 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4636 (size_t)(len - i - 2));
4637 if (c == K_DEL || c == K_KDEL)
4638 ta_buf[i] = DEL;
4639 else
4640 ta_buf[i] = Ctrl_H;
4641 len -= 2;
4642 }
4643 }
4644 else if (ta_buf[i] == '\r')
4645 ta_buf[i] = '\n';
4646# ifdef FEAT_MBYTE
4647 if (has_mbyte)
4648 i += (*mb_ptr2len_len)(ta_buf + i,
4649 ta_len + len - i) - 1;
4650# endif
4651 }
4652
4653 /*
4654 * For pipes: echo the typed characters. For a pty this
4655 * does not seem to work.
4656 */
4657 for (i = ta_len; i < ta_len + len; ++i)
4658 {
4659 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4660 msg_putchar(ta_buf[i]);
4661# ifdef FEAT_MBYTE
4662 else if (has_mbyte)
4663 {
4664 int l = (*mb_ptr2len)(ta_buf + i);
4665
4666 msg_outtrans_len(ta_buf + i, l);
4667 i += l - 1;
4668 }
4669# endif
4670 else
4671 msg_outtrans_len(ta_buf + i, 1);
4672 }
4673 windgoto(msg_row, msg_col);
4674 out_flush();
4675
4676 ta_len += len;
4677
4678 /*
4679 * Write the characters to the child, unless EOF has been
4680 * typed for pipes. Write one character at a time, to
4681 * avoid losing too much typeahead. When writing buffer
4682 * lines, drop the typed characters (only check for
4683 * CTRL-C).
4684 */
4685 if (options & SHELL_WRITE)
4686 ta_len = 0;
4687 else if (g_hChildStd_IN_Wr != NULL)
4688 {
4689 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4690 1, &len, NULL);
4691 // if we are typing in, we want to keep things reactive
4692 delay = 1;
4693 if (len > 0)
4694 {
4695 ta_len -= len;
4696 mch_memmove(ta_buf, ta_buf + len, ta_len);
4697 }
4698 }
4699 }
4700 }
4701 }
4702
4703 if (ta_len)
4704 ui_inchar_undo(ta_buf, ta_len);
4705
4706 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4707 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004708 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004709 break;
4710 }
4711
4712 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004713 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004714
4715 /* We start waiting for a very short time and then increase it, so
4716 * that we respond quickly when the process is quick, and don't
4717 * consume too much overhead when it's slow. */
4718 if (delay < 50)
4719 delay += 10;
4720 }
4721
4722 /* Close the pipe */
4723 CloseHandle(g_hChildStd_OUT_Rd);
4724 if (g_hChildStd_IN_Wr != NULL)
4725 CloseHandle(g_hChildStd_IN_Wr);
4726
4727 WaitForSingleObject(pi.hProcess, INFINITE);
4728
4729 /* Get the command exit code */
4730 GetExitCodeProcess(pi.hProcess, &ret);
4731
4732 if (options & SHELL_READ)
4733 {
4734 if (ga.ga_len > 0)
4735 {
4736 append_ga_line(&ga);
4737 /* remember that the NL was missing */
4738 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4739 }
4740 else
4741 curbuf->b_no_eol_lnum = 0;
4742 ga_clear(&ga);
4743 }
4744
4745 /* Close the handles to the subprocess, so that it goes away */
4746 CloseHandle(pi.hThread);
4747 CloseHandle(pi.hProcess);
4748
4749 return ret;
4750}
4751
4752 static int
4753mch_system(char *cmd, int options)
4754{
4755 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004756 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004757 return mch_system_piped(cmd, options);
4758 else
4759 return mch_system_classic(cmd, options);
4760}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761#else
4762
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004763# ifdef FEAT_MBYTE
4764 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004765mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004766{
4767 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4768 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004769 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004770 if (wcmd != NULL)
4771 {
4772 int ret = _wsystem(wcmd);
4773 vim_free(wcmd);
4774 return ret;
4775 }
4776 }
4777 return system(cmd);
4778}
4779# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004780# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004781# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782
4783#endif
4784
4785/*
4786 * Either execute a command by calling the shell or start a new shell
4787 */
4788 int
4789mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004790 char_u *cmd,
4791 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792{
4793 int x = 0;
4794 int tmode = cur_tmode;
4795#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004796 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004797# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004798 int did_set_title = FALSE;
4799
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004800 /* Change the title to reflect that we are in a subshell. */
4801 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4802 {
4803 WCHAR szShellTitle[512];
4804
4805 if (GetConsoleTitleW(szShellTitle,
4806 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4807 {
4808 if (cmd == NULL)
4809 wcscat(szShellTitle, L" :sh");
4810 else
4811 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004812 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004813
4814 if (wn != NULL)
4815 {
4816 wcscat(szShellTitle, L" - !");
4817 if ((wcslen(szShellTitle) + wcslen(wn) <
4818 sizeof(szShellTitle)/sizeof(WCHAR)))
4819 wcscat(szShellTitle, wn);
4820 SetConsoleTitleW(szShellTitle);
4821 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004822 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004823 }
4824 }
4825 }
4826 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004827 if (!did_set_title)
4828# endif
4829 /* Change the title to reflect that we are in a subshell. */
4830 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004832 if (cmd == NULL)
4833 strcat(szShellTitle, " :sh");
4834 else
4835 {
4836 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004837 if ((strlen(szShellTitle) + strlen((char *)cmd)
4838 < sizeof(szShellTitle)))
4839 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004840 }
4841 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843#endif
4844
4845 out_flush();
4846
4847#ifdef MCH_WRITE_DUMP
4848 if (fdDump)
4849 {
4850 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4851 fflush(fdDump);
4852 }
4853#endif
4854
4855 /*
4856 * Catch all deadly signals while running the external command, because a
4857 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4858 */
4859 signal(SIGINT, SIG_IGN);
4860#if defined(__GNUC__) && !defined(__MINGW32__)
4861 signal(SIGKILL, SIG_IGN);
4862#else
4863 signal(SIGBREAK, SIG_IGN);
4864#endif
4865 signal(SIGILL, SIG_IGN);
4866 signal(SIGFPE, SIG_IGN);
4867 signal(SIGSEGV, SIG_IGN);
4868 signal(SIGTERM, SIG_IGN);
4869 signal(SIGABRT, SIG_IGN);
4870
4871 if (options & SHELL_COOKED)
4872 settmode(TMODE_COOK); /* set to normal mode */
4873
4874 if (cmd == NULL)
4875 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004876 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877 }
4878 else
4879 {
4880 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004881 char_u *newcmd = NULL;
4882 char_u *cmdbase = cmd;
4883 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004884
4885 /* Skip a leading ", ( and "(. */
4886 if (*cmdbase == '"' )
4887 ++cmdbase;
4888 if (*cmdbase == '(')
4889 ++cmdbase;
4890
Bram Moolenaar1c465442017-03-12 20:10:05 +01004891 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004892 {
4893 STARTUPINFO si;
4894 PROCESS_INFORMATION pi;
4895 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004896 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004897 char_u *p;
4898
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004899 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004900 si.cb = sizeof(si);
4901 si.lpReserved = NULL;
4902 si.lpDesktop = NULL;
4903 si.lpTitle = NULL;
4904 si.dwFlags = 0;
4905 si.cbReserved2 = 0;
4906 si.lpReserved2 = NULL;
4907
4908 cmdbase = skipwhite(cmdbase + 5);
4909 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004910 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004911 {
4912 cmdbase = skipwhite(cmdbase + 4);
4913 si.dwFlags = STARTF_USESHOWWINDOW;
4914 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004915 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004916 }
4917 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004918 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004919 {
4920 cmdbase = skipwhite(cmdbase + 2);
4921 flags = CREATE_NO_WINDOW;
4922 si.dwFlags = STARTF_USESTDHANDLES;
4923 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004924 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004925 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004926 NULL, // Security att.
4927 OPEN_EXISTING, // Open flags
4928 FILE_ATTRIBUTE_NORMAL, // File att.
4929 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004930 si.hStdOutput = si.hStdInput;
4931 si.hStdError = si.hStdInput;
4932 }
4933
4934 /* Remove a trailing ", ) and )" if they have a match
4935 * at the start of the command. */
4936 if (cmdbase > cmd)
4937 {
4938 p = cmdbase + STRLEN(cmdbase);
4939 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4940 *--p = NUL;
4941 if (p > cmdbase && p[-1] == ')'
4942 && (*cmd =='(' || cmd[1] == '('))
4943 *--p = NUL;
4944 }
4945
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004946 newcmd = cmdbase;
4947 unescape_shellxquote(cmdbase, p_sxe);
4948
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004949 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004950 * If creating new console, arguments are passed to the
4951 * 'cmd.exe' as-is. If it's not, arguments are not treated
4952 * correctly for current 'cmd.exe'. So unescape characters in
4953 * shellxescape except '|' for avoiding to be treated as
4954 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004955 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004956 if (flags != CREATE_NEW_CONSOLE)
4957 {
4958 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004959 char_u *cmd_shell = mch_getenv("COMSPEC");
4960
4961 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004962 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004963
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004964 subcmd = vim_strsave_escaped_ext(cmdbase,
4965 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004966 if (subcmd != NULL)
4967 {
4968 /* make "cmd.exe /c arguments" */
4969 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004970 newcmd = lalloc(cmdlen, TRUE);
4971 if (newcmd != NULL)
4972 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004973 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004974 else
4975 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004976 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004977 }
4978 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004979
4980 /*
4981 * Now, start the command as a process, so that it doesn't
4982 * inherit our handles which causes unpleasant dangling swap
4983 * files if we exit before the spawned process
4984 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004985 if (vim_create_process((char *)newcmd, FALSE, flags,
4986 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004987 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004988 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4989 > (HINSTANCE)32)
4990 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004991 else
4992 {
4993 x = -1;
4994#ifdef FEAT_GUI_W32
4995 EMSG(_("E371: Command not found"));
4996#endif
4997 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004998
4999 if (newcmd != cmdbase)
5000 vim_free(newcmd);
5001
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005002 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005003 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005004 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005005 CloseHandle(si.hStdInput);
5006 }
5007 /* Close the handles to the subprocess, so that it goes away */
5008 CloseHandle(pi.hThread);
5009 CloseHandle(pi.hProcess);
5010 }
5011 else
5012 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005013 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005014#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005015 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005016#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005017 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5018
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005019 newcmd = lalloc(cmdlen, TRUE);
5020 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021 {
5022#if defined(FEAT_GUI_W32)
5023 if (need_vimrun_warning)
5024 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005025 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5026 "External commands will not pause after completion.\n"
5027 "See :help win32-vimrun for more information.");
5028 char *title = _("Vim Warning");
5029# ifdef FEAT_MBYTE
5030 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5031 {
5032 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5033 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5034
5035 if (wmsg != NULL && wtitle != NULL)
5036 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5037 vim_free(wmsg);
5038 vim_free(wtitle);
5039 }
5040 else
5041# endif
5042 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043 need_vimrun_warning = FALSE;
5044 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005045 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005046 /* Use vimrun to execute the command. It opens a console
5047 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005048 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005049 vimrun_path,
5050 (msg_silent != 0 || (options & SHELL_DOOUT))
5051 ? "-s " : "",
5052 p_sh, p_shcf, cmd);
5053 else
5054#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005055 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005056 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005057 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005058 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005060 }
5061 }
5062
5063 if (tmode == TMODE_RAW)
5064 settmode(TMODE_RAW); /* set to raw mode */
5065
5066 /* Print the return value, unless "vimrun" was used. */
5067 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5068#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005069 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070#endif
5071 )
5072 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005073 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005074 msg_putchar('\n');
5075 }
5076#ifdef FEAT_TITLE
5077 resettitle();
5078#endif
5079
5080 signal(SIGINT, SIG_DFL);
5081#if defined(__GNUC__) && !defined(__MINGW32__)
5082 signal(SIGKILL, SIG_DFL);
5083#else
5084 signal(SIGBREAK, SIG_DFL);
5085#endif
5086 signal(SIGILL, SIG_DFL);
5087 signal(SIGFPE, SIG_DFL);
5088 signal(SIGSEGV, SIG_DFL);
5089 signal(SIGTERM, SIG_DFL);
5090 signal(SIGABRT, SIG_DFL);
5091
5092 return x;
5093}
5094
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005095#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005096 static HANDLE
5097job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005098 char_u *fname,
5099 DWORD dwDesiredAccess,
5100 DWORD dwShareMode,
5101 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5102 DWORD dwCreationDisposition,
5103 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005104{
5105 HANDLE h;
5106# ifdef FEAT_MBYTE
5107 WCHAR *wn = NULL;
5108 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5109 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005110 wn = enc_to_utf16(fname, NULL);
5111 if (wn != NULL)
5112 {
5113 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5114 lpSecurityAttributes, dwCreationDisposition,
5115 dwFlagsAndAttributes, NULL);
5116 vim_free(wn);
5117 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005118 }
5119 if (wn == NULL)
5120# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005121 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5122 lpSecurityAttributes, dwCreationDisposition,
5123 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005124 return h;
5125}
5126
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005127/*
5128 * Turn the dictionary "env" into a NUL separated list that can be used as the
5129 * environment argument of vim_create_process().
5130 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005131 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005132win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005133{
5134 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005135 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005136 LPVOID base = GetEnvironmentStringsW();
5137
5138 /* for last \0 */
5139 if (ga_grow(gap, 1) == FAIL)
5140 return;
5141
5142 if (base)
5143 {
5144 WCHAR *p = (WCHAR*) base;
5145
5146 /* for last \0 */
5147 if (ga_grow(gap, 1) == FAIL)
5148 return;
5149
5150 while (*p != 0 || *(p + 1) != 0)
5151 {
5152 if (ga_grow(gap, 1) == OK)
5153 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5154 p++;
5155 }
5156 FreeEnvironmentStrings(base);
5157 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5158 }
5159
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005160 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005161 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005162 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005163 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005164 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005165 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005166 typval_T *item = &dict_lookup(hi)->di_tv;
5167 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5168 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5169 --todo;
5170 if (wkey != NULL && wval != NULL)
5171 {
5172 size_t n;
5173 size_t lkey = wcslen(wkey);
5174 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005175
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005176 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5177 continue;
5178 for (n = 0; n < lkey; n++)
5179 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5180 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5181 for (n = 0; n < lval; n++)
5182 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5183 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5184 }
5185 if (wkey != NULL) vim_free(wkey);
5186 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005187 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005188 }
5189 }
5190
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005191# ifdef FEAT_CLIENTSERVER
5192 if (is_terminal)
5193 {
5194 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
5195 size_t lval = STRLEN(servername);
5196 size_t n;
5197
5198 if (ga_grow(gap, (int)(14 + lval + 2)) == OK)
5199 {
5200 for (n = 0; n < 15; n++)
5201 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5202 (WCHAR)"VIM_SERVERNAME="[n];
5203 for (n = 0; n < lval; n++)
5204 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5205 (WCHAR)servername[n];
5206 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5207 }
5208 }
5209# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005210}
5211
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005212 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005213mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005214{
5215 STARTUPINFO si;
5216 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005217 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005218 SECURITY_ATTRIBUTES saAttr;
5219 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005220 HANDLE ifd[2];
5221 HANDLE ofd[2];
5222 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005223 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005224
5225 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5226 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5227 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5228 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5229 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5230 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5231 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5232
5233 if (use_out_for_err && use_null_for_out)
5234 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005235
5236 ifd[0] = INVALID_HANDLE_VALUE;
5237 ifd[1] = INVALID_HANDLE_VALUE;
5238 ofd[0] = INVALID_HANDLE_VALUE;
5239 ofd[1] = INVALID_HANDLE_VALUE;
5240 efd[0] = INVALID_HANDLE_VALUE;
5241 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005242 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005243
Bram Moolenaar14207f42016-10-27 21:13:10 +02005244 jo = CreateJobObject(NULL, NULL);
5245 if (jo == NULL)
5246 {
5247 job->jv_status = JOB_FAILED;
5248 goto failed;
5249 }
5250
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005251 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005252 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005253
Bram Moolenaar76467df2016-02-12 19:30:26 +01005254 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005255 ZeroMemory(&si, sizeof(si));
5256 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005257 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005258 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005259
Bram Moolenaard8070362016-02-15 21:56:54 +01005260 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5261 saAttr.bInheritHandle = TRUE;
5262 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005263
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005264 if (use_file_for_in)
5265 {
5266 char_u *fname = options->jo_io_name[PART_IN];
5267
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005268 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5269 FILE_SHARE_READ | FILE_SHARE_WRITE,
5270 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5271 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005272 {
5273 EMSG2(_(e_notopen), fname);
5274 goto failed;
5275 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005276 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005277 else if (!use_null_for_in &&
5278 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005279 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005280 goto failed;
5281
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005282 if (use_file_for_out)
5283 {
5284 char_u *fname = options->jo_io_name[PART_OUT];
5285
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005286 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5287 FILE_SHARE_READ | FILE_SHARE_WRITE,
5288 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5289 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005290 {
5291 EMSG2(_(e_notopen), fname);
5292 goto failed;
5293 }
5294 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005295 else if (!use_null_for_out &&
5296 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005297 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005298 goto failed;
5299
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005300 if (use_file_for_err)
5301 {
5302 char_u *fname = options->jo_io_name[PART_ERR];
5303
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005304 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5305 FILE_SHARE_READ | FILE_SHARE_WRITE,
5306 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5307 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005308 {
5309 EMSG2(_(e_notopen), fname);
5310 goto failed;
5311 }
5312 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005313 else if (!use_out_for_err && !use_null_for_err &&
5314 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005315 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005316 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005317
Bram Moolenaard8070362016-02-15 21:56:54 +01005318 si.dwFlags |= STARTF_USESTDHANDLES;
5319 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005320 si.hStdOutput = ofd[1];
5321 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5322
5323 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5324 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005325 if (options->jo_set & JO_CHANNEL)
5326 {
5327 channel = options->jo_channel;
5328 if (channel != NULL)
5329 ++channel->ch_refcount;
5330 }
5331 else
5332 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005333 if (channel == NULL)
5334 goto failed;
5335 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005336
5337 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005338 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005339 CREATE_DEFAULT_ERROR_MODE |
5340 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005341 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005342 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005343 &si, &pi,
5344 ga.ga_data,
5345 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005346 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005347 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005348 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005349 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005350 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005351
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005352 ga_clear(&ga);
5353
Bram Moolenaar14207f42016-10-27 21:13:10 +02005354 if (!AssignProcessToJobObject(jo, pi.hProcess))
5355 {
5356 /* if failing, switch the way to terminate
5357 * process with TerminateProcess. */
5358 CloseHandle(jo);
5359 jo = NULL;
5360 }
5361 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005362 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005363 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005364 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005365 job->jv_status = JOB_STARTED;
5366
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005367 CloseHandle(ifd[0]);
5368 CloseHandle(ofd[1]);
5369 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005370 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005371
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005372 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005373 if (channel != NULL)
5374 {
5375 channel_set_pipes(channel,
5376 use_file_for_in || use_null_for_in
5377 ? INVALID_FD : (sock_T)ifd[1],
5378 use_file_for_out || use_null_for_out
5379 ? INVALID_FD : (sock_T)ofd[0],
5380 use_out_for_err || use_file_for_err || use_null_for_err
5381 ? INVALID_FD : (sock_T)efd[0]);
5382 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005383 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005384 return;
5385
5386failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005387 CloseHandle(ifd[0]);
5388 CloseHandle(ofd[0]);
5389 CloseHandle(efd[0]);
5390 CloseHandle(ifd[1]);
5391 CloseHandle(ofd[1]);
5392 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005393 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005394 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005395}
5396
5397 char *
5398mch_job_status(job_T *job)
5399{
5400 DWORD dwExitCode = 0;
5401
Bram Moolenaar76467df2016-02-12 19:30:26 +01005402 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5403 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005404 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005405 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005406 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005407 {
5408 ch_log(job->jv_channel, "Job ended");
5409 job->jv_status = JOB_ENDED;
5410 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005411 return "dead";
5412 }
5413 return "run";
5414}
5415
Bram Moolenaar97792de2016-10-15 18:36:49 +02005416 job_T *
5417mch_detect_ended_job(job_T *job_list)
5418{
5419 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5420 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5421 job_T *job = job_list;
5422
5423 while (job != NULL)
5424 {
5425 DWORD n;
5426 DWORD result;
5427
5428 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5429 && job != NULL; job = job->jv_next)
5430 {
5431 if (job->jv_status == JOB_STARTED)
5432 {
5433 jobHandles[n] = job->jv_proc_info.hProcess;
5434 jobArray[n] = job;
5435 ++n;
5436 }
5437 }
5438 if (n == 0)
5439 continue;
5440 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5441 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5442 {
5443 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5444
5445 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5446 return wait_job;
5447 }
5448 }
5449 return NULL;
5450}
5451
Bram Moolenaarfb630902016-10-29 14:55:00 +02005452 static BOOL
5453terminate_all(HANDLE process, int code)
5454{
5455 PROCESSENTRY32 pe;
5456 HANDLE h = INVALID_HANDLE_VALUE;
5457 DWORD pid = GetProcessId(process);
5458
5459 if (pid != 0)
5460 {
5461 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5462 if (h != INVALID_HANDLE_VALUE)
5463 {
5464 pe.dwSize = sizeof(PROCESSENTRY32);
5465 if (!Process32First(h, &pe))
5466 goto theend;
5467
5468 do
5469 {
5470 if (pe.th32ParentProcessID == pid)
5471 {
5472 HANDLE ph = OpenProcess(
5473 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5474 if (ph != NULL)
5475 {
5476 terminate_all(ph, code);
5477 CloseHandle(ph);
5478 }
5479 }
5480 } while (Process32Next(h, &pe));
5481
5482 CloseHandle(h);
5483 }
5484 }
5485
5486theend:
5487 return TerminateProcess(process, code);
5488}
5489
5490/*
5491 * Send a (deadly) signal to "job".
5492 * Return FAIL if it didn't work.
5493 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005494 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005495mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005496{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005497 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005498
Bram Moolenaar923d9262016-02-25 20:56:01 +01005499 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005500 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005501 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005502 if (job->jv_job_object != NULL)
5503 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005504 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005505 }
5506
5507 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5508 return FAIL;
5509 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005510 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5511 job->jv_proc_info.dwProcessId)
5512 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005513 FreeConsole();
5514 return ret;
5515}
5516
5517/*
5518 * Clear the data related to "job".
5519 */
5520 void
5521mch_clear_job(job_T *job)
5522{
5523 if (job->jv_status != JOB_FAILED)
5524 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005525 if (job->jv_job_object != NULL)
5526 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005527 CloseHandle(job->jv_proc_info.hProcess);
5528 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005529}
5530#endif
5531
Bram Moolenaar071d4272004-06-13 20:20:40 +00005532
5533#ifndef FEAT_GUI_W32
5534
5535/*
5536 * Start termcap mode
5537 */
5538 static void
5539termcap_mode_start(void)
5540{
5541 DWORD cmodein;
5542
5543 if (g_fTermcapMode)
5544 return;
5545
5546 SaveConsoleBuffer(&g_cbNonTermcap);
5547
5548 if (g_cbTermcap.IsValid)
5549 {
5550 /*
5551 * We've been in termcap mode before. Restore certain screen
5552 * characteristics, including the buffer size and the window
5553 * size. Since we will be redrawing the screen, we don't need
5554 * to restore the actual contents of the buffer.
5555 */
5556 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005557 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5559 Rows = g_cbTermcap.Info.dwSize.Y;
5560 Columns = g_cbTermcap.Info.dwSize.X;
5561 }
5562 else
5563 {
5564 /*
5565 * This is our first time entering termcap mode. Clear the console
5566 * screen buffer, and resize the buffer to match the current window
5567 * size. We will use this as the size of our editing environment.
5568 */
5569 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005570 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5572 }
5573
5574#ifdef FEAT_TITLE
5575 resettitle();
5576#endif
5577
5578 GetConsoleMode(g_hConIn, &cmodein);
5579#ifdef FEAT_MOUSE
5580 if (g_fMouseActive)
5581 cmodein |= ENABLE_MOUSE_INPUT;
5582 else
5583 cmodein &= ~ENABLE_MOUSE_INPUT;
5584#endif
5585 cmodein |= ENABLE_WINDOW_INPUT;
5586 SetConsoleMode(g_hConIn, cmodein);
5587
5588 redraw_later_clear();
5589 g_fTermcapMode = TRUE;
5590}
5591
5592
5593/*
5594 * End termcap mode
5595 */
5596 static void
5597termcap_mode_end(void)
5598{
5599 DWORD cmodein;
5600 ConsoleBuffer *cb;
5601 COORD coord;
5602 DWORD dwDummy;
5603
5604 if (!g_fTermcapMode)
5605 return;
5606
5607 SaveConsoleBuffer(&g_cbTermcap);
5608
5609 GetConsoleMode(g_hConIn, &cmodein);
5610 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5611 SetConsoleMode(g_hConIn, cmodein);
5612
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005613#ifdef FEAT_RESTORE_ORIG_SCREEN
5614 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5615#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005617#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005619 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 SetConsoleCursorInfo(g_hConOut, &g_cci);
5621
5622 if (p_rs || exiting)
5623 {
5624 /*
5625 * Clear anything that happens to be on the current line.
5626 */
5627 coord.X = 0;
5628 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5629 FillConsoleOutputCharacter(g_hConOut, ' ',
5630 cb->Info.dwSize.X, coord, &dwDummy);
5631 /*
5632 * The following is just for aesthetics. If we are exiting without
5633 * restoring the screen, then we want to have a prompt string
5634 * appear at the bottom line. However, the command interpreter
5635 * seems to always advance the cursor one line before displaying
5636 * the prompt string, which causes the screen to scroll. To
5637 * counter this, move the cursor up one line before exiting.
5638 */
5639 if (exiting && !p_rs)
5640 coord.Y--;
5641 /*
5642 * Position the cursor at the leftmost column of the desired row.
5643 */
5644 SetConsoleCursorPosition(g_hConOut, coord);
5645 }
5646
5647 g_fTermcapMode = FALSE;
5648}
5649#endif /* FEAT_GUI_W32 */
5650
5651
5652#ifdef FEAT_GUI_W32
5653 void
5654mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005655 char_u *s UNUSED,
5656 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657{
5658 /* never used */
5659}
5660
5661#else
5662
5663/*
5664 * clear `n' chars, starting from `coord'
5665 */
5666 static void
5667clear_chars(
5668 COORD coord,
5669 DWORD n)
5670{
5671 DWORD dwDummy;
5672
5673 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005674
5675 if (!USE_VTP)
5676 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5677 else
5678 FillConsoleOutputAttribute(g_hConOut, 0, n, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005679}
5680
5681
5682/*
5683 * Clear the screen
5684 */
5685 static void
5686clear_screen(void)
5687{
5688 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005689
5690 if (!USE_VTP)
5691 clear_chars(g_coord, Rows * Columns);
5692 else
5693 {
5694 set_console_color_rgb();
5695 gotoxy(1, 1);
5696 vtp_printf("\033[2J");
5697 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698}
5699
5700
5701/*
5702 * Clear to end of display
5703 */
5704 static void
5705clear_to_end_of_display(void)
5706{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005707 COORD save = g_coord;
5708
5709 if (!USE_VTP)
5710 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005712 else
5713 {
5714 set_console_color_rgb();
5715 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5716 vtp_printf("\033[0J");
5717
5718 gotoxy(save.X + 1, save.Y + 1);
5719 g_coord = save;
5720 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721}
5722
5723
5724/*
5725 * Clear to end of line
5726 */
5727 static void
5728clear_to_end_of_line(void)
5729{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005730 COORD save = g_coord;
5731
5732 if (!USE_VTP)
5733 clear_chars(g_coord, Columns - g_coord.X);
5734 else
5735 {
5736 set_console_color_rgb();
5737 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5738 vtp_printf("\033[0K");
5739
5740 gotoxy(save.X + 1, save.Y + 1);
5741 g_coord = save;
5742 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743}
5744
5745
5746/*
5747 * Scroll the scroll region up by `cLines' lines
5748 */
5749 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005750scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005751{
5752 COORD oldcoord = g_coord;
5753
5754 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5755 delete_lines(cLines);
5756
5757 g_coord = oldcoord;
5758}
5759
5760
5761/*
5762 * Set the scroll region
5763 */
5764 static void
5765set_scroll_region(
5766 unsigned left,
5767 unsigned top,
5768 unsigned right,
5769 unsigned bottom)
5770{
5771 if (left >= right
5772 || top >= bottom
5773 || right > (unsigned) Columns - 1
5774 || bottom > (unsigned) Rows - 1)
5775 return;
5776
5777 g_srScrollRegion.Left = left;
5778 g_srScrollRegion.Top = top;
5779 g_srScrollRegion.Right = right;
5780 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005781
5782 if (USE_VTP)
5783 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784}
5785
5786
5787/*
5788 * Insert `cLines' lines at the current cursor position
5789 */
5790 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005791insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792{
5793 SMALL_RECT source;
5794 COORD dest;
5795 CHAR_INFO fill;
5796
5797 dest.X = 0;
5798 dest.Y = g_coord.Y + cLines;
5799
5800 source.Left = 0;
5801 source.Top = g_coord.Y;
5802 source.Right = g_srScrollRegion.Right;
5803 source.Bottom = g_srScrollRegion.Bottom - cLines;
5804
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005805 if (!USE_VTP)
5806 {
5807 fill.Char.AsciiChar = ' ';
5808 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005809
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005810 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5811 }
5812 else
5813 {
5814 set_console_color_rgb();
5815
5816 gotoxy(1, source.Top + 1);
5817 vtp_printf("\033[%dT", cLines);
5818 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005819
5820 /* Here we have to deal with a win32 console flake: If the scroll
5821 * region looks like abc and we scroll c to a and fill with d we get
5822 * cbd... if we scroll block c one line at a time to a, we get cdd...
5823 * vim expects cdd consistently... So we have to deal with that
5824 * here... (this also occurs scrolling the same way in the other
5825 * direction). */
5826
5827 if (source.Bottom < dest.Y)
5828 {
5829 COORD coord;
5830
5831 coord.X = 0;
5832 coord.Y = source.Bottom;
5833 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5834 }
5835}
5836
5837
5838/*
5839 * Delete `cLines' lines at the current cursor position
5840 */
5841 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005842delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843{
5844 SMALL_RECT source;
5845 COORD dest;
5846 CHAR_INFO fill;
5847 int nb;
5848
5849 dest.X = 0;
5850 dest.Y = g_coord.Y;
5851
5852 source.Left = 0;
5853 source.Top = g_coord.Y + cLines;
5854 source.Right = g_srScrollRegion.Right;
5855 source.Bottom = g_srScrollRegion.Bottom;
5856
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005857 if (!USE_VTP)
5858 {
5859 fill.Char.AsciiChar = ' ';
5860 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005862 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5863 }
5864 else
5865 {
5866 set_console_color_rgb();
5867
5868 gotoxy(1, source.Top + 1);
5869 vtp_printf("\033[%dS", cLines);
5870 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005871
5872 /* Here we have to deal with a win32 console flake: If the scroll
5873 * region looks like abc and we scroll c to a and fill with d we get
5874 * cbd... if we scroll block c one line at a time to a, we get cdd...
5875 * vim expects cdd consistently... So we have to deal with that
5876 * here... (this also occurs scrolling the same way in the other
5877 * direction). */
5878
5879 nb = dest.Y + (source.Bottom - source.Top) + 1;
5880
5881 if (nb < source.Top)
5882 {
5883 COORD coord;
5884
5885 coord.X = 0;
5886 coord.Y = nb;
5887 clear_chars(coord, Columns * (source.Top - nb));
5888 }
5889}
5890
5891
5892/*
5893 * Set the cursor position
5894 */
5895 static void
5896gotoxy(
5897 unsigned x,
5898 unsigned y)
5899{
5900 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5901 return;
5902
5903 /* external cursor coords are 1-based; internal are 0-based */
5904 g_coord.X = x - 1;
5905 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005906
5907 if (!USE_VTP)
5908 SetConsoleCursorPosition(g_hConOut, g_coord);
5909 else
5910 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005911}
5912
5913
5914/*
5915 * Set the current text attribute = (foreground | background)
5916 * See ../doc/os_win32.txt for the numbers.
5917 */
5918 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005919textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005921 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005922
5923 SetConsoleTextAttribute(g_hConOut, wAttr);
5924}
5925
5926
5927 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005928textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005930 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005932 if (!USE_VTP)
5933 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5934 else
5935 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936}
5937
5938
5939 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005940textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005942 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005944 if (!USE_VTP)
5945 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5946 else
5947 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948}
5949
5950
5951/*
5952 * restore the default text attribute (whatever we started with)
5953 */
5954 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005955normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005956{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005957 if (!USE_VTP)
5958 textattr(g_attrDefault);
5959 else
5960 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961}
5962
5963
5964static WORD g_attrPreStandout = 0;
5965
5966/*
5967 * Make the text standout, by brightening it
5968 */
5969 static void
5970standout(void)
5971{
5972 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005973
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5975}
5976
5977
5978/*
5979 * Turn off standout mode
5980 */
5981 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005982standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005983{
5984 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005985 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005986
5987 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005988}
5989
5990
5991/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005992 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993 */
5994 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005995mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005996{
5997 char_u *p;
5998 int n;
5999
6000 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6001 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006002 if (
6003#ifdef FEAT_TERMGUICOLORS
6004 !p_tgc &&
6005#endif
6006 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006007 {
6008 p = T_ME + 2;
6009 n = getdigits(&p);
6010 if (*p == 'm' && n > 0)
6011 {
6012 cterm_normal_fg_color = (n & 0xf) + 1;
6013 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6014 }
6015 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006016#ifdef FEAT_TERMGUICOLORS
6017 cterm_normal_fg_gui_color = INVALCOLOR;
6018 cterm_normal_bg_gui_color = INVALCOLOR;
6019#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020}
6021
6022
6023/*
6024 * visual bell: flash the screen
6025 */
6026 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006027visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028{
6029 COORD coordOrigin = {0, 0};
6030 WORD attrFlash = ~g_attrCurrent & 0xff;
6031
6032 DWORD dwDummy;
6033 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6034
6035 if (oldattrs == NULL)
6036 return;
6037 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6038 coordOrigin, &dwDummy);
6039 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6040 coordOrigin, &dwDummy);
6041
6042 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006043 if (!USE_VTP)
6044 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006045 coordOrigin, &dwDummy);
6046 vim_free(oldattrs);
6047}
6048
6049
6050/*
6051 * Make the cursor visible or invisible
6052 */
6053 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006054cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006055{
6056 s_cursor_visible = fVisible;
6057#ifdef MCH_CURSOR_SHAPE
6058 mch_update_cursor();
6059#endif
6060}
6061
6062
6063/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006064 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006065 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006067 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006069 char_u *pchBuf,
6070 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071{
6072 COORD coord = g_coord;
6073 DWORD written;
6074
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006075#ifdef FEAT_MBYTE
6076 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6077 {
6078 static WCHAR *unicodebuf = NULL;
6079 static int unibuflen = 0;
6080 int length;
6081 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006082
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006083 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6084 if (unicodebuf == NULL || length > unibuflen)
6085 {
6086 vim_free(unicodebuf);
6087 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6088 unibuflen = length;
6089 }
6090 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6091 unicodebuf, unibuflen);
6092
6093 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006094
6095 if (!USE_VTP)
6096 {
6097 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6098 coord, &written);
6099 /* When writing fails or didn't write a single character, pretend one
6100 * character was written, otherwise we get stuck. */
6101 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6102 coord, &cchwritten) == 0
6103 || cchwritten == 0)
6104 cchwritten = 1;
6105 }
6106 else
6107 {
6108 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6109 NULL) == 0 || cchwritten == 0)
6110 cchwritten = 1;
6111 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006112
6113 if (cchwritten == length)
6114 {
6115 written = cbToWrite;
6116 g_coord.X += (SHORT)cells;
6117 }
6118 else
6119 {
6120 char_u *p = pchBuf;
6121 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006122 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006123 written = p - pchBuf;
6124 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6125 }
6126 }
6127 else
6128#endif
6129 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006130 if (!USE_VTP)
6131 {
6132 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6133 coord, &written);
6134 /* When writing fails or didn't write a single character, pretend one
6135 * character was written, otherwise we get stuck. */
6136 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6137 coord, &written) == 0
6138 || written == 0)
6139 written = 1;
6140 }
6141 else
6142 {
6143 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6144 NULL) == 0 || written == 0)
6145 written = 1;
6146 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006147
6148 g_coord.X += (SHORT) written;
6149 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150
6151 while (g_coord.X > g_srScrollRegion.Right)
6152 {
6153 g_coord.X -= (SHORT) Columns;
6154 if (g_coord.Y < g_srScrollRegion.Bottom)
6155 g_coord.Y++;
6156 }
6157
6158 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6159
6160 return written;
6161}
6162
6163
6164/*
6165 * mch_write(): write the output buffer to the screen, translating ESC
6166 * sequences into calls to console output routines.
6167 */
6168 void
6169mch_write(
6170 char_u *s,
6171 int len)
6172{
6173 s[len] = NUL;
6174
6175 if (!term_console)
6176 {
6177 write(1, s, (unsigned)len);
6178 return;
6179 }
6180
6181 /* translate ESC | sequences into faked bios calls */
6182 while (len--)
6183 {
6184 /* optimization: use one single write_chars for runs of text,
6185 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006186 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187
6188 if (p_wd)
6189 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006190 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191 if (prefix != 0)
6192 prefix = 1;
6193 }
6194
6195 if (prefix != 0)
6196 {
6197 DWORD nWritten;
6198
6199 nWritten = write_chars(s, prefix);
6200#ifdef MCH_WRITE_DUMP
6201 if (fdDump)
6202 {
6203 fputc('>', fdDump);
6204 fwrite(s, sizeof(char_u), nWritten, fdDump);
6205 fputs("<\n", fdDump);
6206 }
6207#endif
6208 len -= (nWritten - 1);
6209 s += nWritten;
6210 }
6211 else if (s[0] == '\n')
6212 {
6213 /* \n, newline: go to the beginning of the next line or scroll */
6214 if (g_coord.Y == g_srScrollRegion.Bottom)
6215 {
6216 scroll(1);
6217 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6218 }
6219 else
6220 {
6221 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6222 }
6223#ifdef MCH_WRITE_DUMP
6224 if (fdDump)
6225 fputs("\\n\n", fdDump);
6226#endif
6227 s++;
6228 }
6229 else if (s[0] == '\r')
6230 {
6231 /* \r, carriage return: go to beginning of line */
6232 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6233#ifdef MCH_WRITE_DUMP
6234 if (fdDump)
6235 fputs("\\r\n", fdDump);
6236#endif
6237 s++;
6238 }
6239 else if (s[0] == '\b')
6240 {
6241 /* \b, backspace: move cursor one position left */
6242 if (g_coord.X > g_srScrollRegion.Left)
6243 g_coord.X--;
6244 else if (g_coord.Y > g_srScrollRegion.Top)
6245 {
6246 g_coord.X = g_srScrollRegion.Right;
6247 g_coord.Y--;
6248 }
6249 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6250#ifdef MCH_WRITE_DUMP
6251 if (fdDump)
6252 fputs("\\b\n", fdDump);
6253#endif
6254 s++;
6255 }
6256 else if (s[0] == '\a')
6257 {
6258 /* \a, bell */
6259 MessageBeep(0xFFFFFFFF);
6260#ifdef MCH_WRITE_DUMP
6261 if (fdDump)
6262 fputs("\\a\n", fdDump);
6263#endif
6264 s++;
6265 }
6266 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6267 {
6268#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006269 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006271 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006272 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273
6274 switch (s[2])
6275 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276 case '0': case '1': case '2': case '3': case '4':
6277 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006278 p = s + 1;
6279 do
6280 {
6281 ++p;
6282 args[argc] = getdigits(&p);
6283 argc += (argc < 15) ? 1 : 0;
6284 if (p > s + len)
6285 break;
6286 } while (*p == ';');
6287
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288 if (p > s + len)
6289 break;
6290
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006291 arg1 = args[0];
6292 arg2 = args[1];
6293 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006295 if (argc == 1 && args[0] == 0)
6296 normvideo();
6297 else if (argc == 1)
6298 {
6299 if (USE_VTP)
6300 textcolor((WORD) arg1);
6301 else
6302 textattr((WORD) arg1);
6303 }
6304 else if (USE_VTP)
6305 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006306 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006307 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006308 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006309 gotoxy(arg2, arg1);
6310 }
6311 else if (argc == 2 && *p == 'r')
6312 {
6313 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6314 }
6315 else if (argc == 1 && *p == 'A')
6316 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 gotoxy(g_coord.X + 1,
6318 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6319 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006320 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321 {
6322 textbackground((WORD) arg1);
6323 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006324 else if (argc == 1 && *p == 'C')
6325 {
6326 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6327 g_coord.Y + 1);
6328 }
6329 else if (argc == 1 && *p == 'f')
6330 {
6331 textcolor((WORD) arg1);
6332 }
6333 else if (argc == 1 && *p == 'H')
6334 {
6335 gotoxy(1, arg1);
6336 }
6337 else if (argc == 1 && *p == 'L')
6338 {
6339 insert_lines(arg1);
6340 }
6341 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342 {
6343 delete_lines(arg1);
6344 }
6345
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006346 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347 s = p + 1;
6348 break;
6349
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351 gotoxy(g_coord.X + 1,
6352 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6353 goto got3;
6354
6355 case 'B':
6356 visual_bell();
6357 goto got3;
6358
6359 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6361 g_coord.Y + 1);
6362 goto got3;
6363
6364 case 'E':
6365 termcap_mode_end();
6366 goto got3;
6367
6368 case 'F':
6369 standout();
6370 goto got3;
6371
6372 case 'f':
6373 standend();
6374 goto got3;
6375
6376 case 'H':
6377 gotoxy(1, 1);
6378 goto got3;
6379
6380 case 'j':
6381 clear_to_end_of_display();
6382 goto got3;
6383
6384 case 'J':
6385 clear_screen();
6386 goto got3;
6387
6388 case 'K':
6389 clear_to_end_of_line();
6390 goto got3;
6391
6392 case 'L':
6393 insert_lines(1);
6394 goto got3;
6395
6396 case 'M':
6397 delete_lines(1);
6398 goto got3;
6399
6400 case 'S':
6401 termcap_mode_start();
6402 goto got3;
6403
6404 case 'V':
6405 cursor_visible(TRUE);
6406 goto got3;
6407
6408 case 'v':
6409 cursor_visible(FALSE);
6410 goto got3;
6411
6412 got3:
6413 s += 3;
6414 len -= 2;
6415 }
6416
6417#ifdef MCH_WRITE_DUMP
6418 if (fdDump)
6419 {
6420 fputs("ESC | ", fdDump);
6421 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6422 fputc('\n', fdDump);
6423 }
6424#endif
6425 }
6426 else
6427 {
6428 /* Write a single character */
6429 DWORD nWritten;
6430
6431 nWritten = write_chars(s, 1);
6432#ifdef MCH_WRITE_DUMP
6433 if (fdDump)
6434 {
6435 fputc('>', fdDump);
6436 fwrite(s, sizeof(char_u), nWritten, fdDump);
6437 fputs("<\n", fdDump);
6438 }
6439#endif
6440
6441 len -= (nWritten - 1);
6442 s += nWritten;
6443 }
6444 }
6445
6446#ifdef MCH_WRITE_DUMP
6447 if (fdDump)
6448 fflush(fdDump);
6449#endif
6450}
6451
6452#endif /* FEAT_GUI_W32 */
6453
6454
6455/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006456 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006457 */
6458 void
6459mch_delay(
6460 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006461 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462{
6463#ifdef FEAT_GUI_W32
6464 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006465#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006467# ifdef FEAT_MZSCHEME
6468 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6469 {
6470 int towait = p_mzq;
6471
6472 /* if msec is large enough, wait by portions in p_mzq */
6473 while (msec > 0)
6474 {
6475 mzvim_check_threads();
6476 if (msec < towait)
6477 towait = msec;
6478 Sleep(towait);
6479 msec -= towait;
6480 }
6481 }
6482 else
6483# endif
6484 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006486 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487#endif
6488}
6489
6490
6491/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006492 * This version of remove is not scared by a readonly (backup) file.
6493 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494 * Return 0 for success, -1 for failure.
6495 */
6496 int
6497mch_remove(char_u *name)
6498{
6499#ifdef FEAT_MBYTE
6500 WCHAR *wn = NULL;
6501 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006502#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503
Bram Moolenaar203258c2016-01-17 22:15:16 +01006504 /*
6505 * On Windows, deleting a directory's symbolic link is done by
6506 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6507 */
6508 if (mch_isdir(name) && mch_is_symbolic_link(name))
6509 return mch_rmdir(name);
6510
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006511 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6512
6513#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6515 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006516 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 if (wn != NULL)
6518 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 n = DeleteFileW(wn) ? 0 : -1;
6520 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006521 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 }
6523 }
6524#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006525 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526}
6527
6528
6529/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006530 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 */
6532 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006533mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534{
6535#ifndef FEAT_GUI_W32 /* never used */
6536 if (g_fCtrlCPressed || g_fCBrkPressed)
6537 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006538 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6540 got_int = TRUE;
6541 }
6542#endif
6543}
6544
Bram Moolenaaree273972016-01-02 21:11:51 +01006545/* physical RAM to leave for the OS */
6546#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006547
6548/*
6549 * How much main memory in KiB that can be used by VIM.
6550 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006551 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006552mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006553{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006554 MEMORYSTATUSEX ms;
6555
Bram Moolenaaree273972016-01-02 21:11:51 +01006556 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006557 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6558 * what fits in 32 bits. But it's not always available. */
6559 ms.dwLength = sizeof(MEMORYSTATUSEX);
6560 GlobalMemoryStatusEx(&ms);
6561 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006562 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006563 /* Process address space fits in physical RAM, use all of it. */
6564 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006565 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006566 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006567 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006568 /* Catch old NT box or perverse hardware setup. */
6569 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006570 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006571 /* Use physical RAM less reserve for OS + data. */
6572 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006573}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006574
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575#ifdef FEAT_MBYTE
6576/*
6577 * Same code as below, but with wide functions and no comments.
6578 * Return 0 for success, non-zero for failure.
6579 */
6580 int
6581mch_wrename(WCHAR *wold, WCHAR *wnew)
6582{
6583 WCHAR *p;
6584 int i;
6585 WCHAR szTempFile[_MAX_PATH + 1];
6586 WCHAR szNewPath[_MAX_PATH + 1];
6587 HANDLE hf;
6588
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006589 p = wold;
6590 for (i = 0; wold[i] != NUL; ++i)
6591 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6592 && wold[i + 1] != 0)
6593 p = wold + i + 1;
6594 if ((int)(wold + i - p) < 8 || p[6] != '~')
6595 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596
6597 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6598 return -1;
6599 *p = NUL;
6600
6601 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6602 return -2;
6603
6604 if (!DeleteFileW(szTempFile))
6605 return -3;
6606
6607 if (!MoveFileW(wold, szTempFile))
6608 return -4;
6609
6610 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6611 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6612 return -5;
6613 if (!CloseHandle(hf))
6614 return -6;
6615
6616 if (!MoveFileW(szTempFile, wnew))
6617 {
6618 (void)MoveFileW(szTempFile, wold);
6619 return -7;
6620 }
6621
6622 DeleteFileW(szTempFile);
6623
6624 if (!DeleteFileW(wold))
6625 return -8;
6626
6627 return 0;
6628}
6629#endif
6630
6631
6632/*
6633 * mch_rename() works around a bug in rename (aka MoveFile) in
6634 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6635 * file whose short file name is "FOO.BAR" (its long file name will
6636 * be correct: "foo.bar~"). Because a file can be accessed by
6637 * either its SFN or its LFN, "foo.bar" has effectively been
6638 * renamed to "foo.bar", which is not at all what was wanted. This
6639 * seems to happen only when renaming files with three-character
6640 * extensions by appending a suffix that does not include ".".
6641 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6642 *
6643 * There is another problem, which isn't really a bug but isn't right either:
6644 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6645 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6646 * service pack 6. Doesn't seem to happen on Windows 98.
6647 *
6648 * Like rename(), returns 0 upon success, non-zero upon failure.
6649 * Should probably set errno appropriately when errors occur.
6650 */
6651 int
6652mch_rename(
6653 const char *pszOldFile,
6654 const char *pszNewFile)
6655{
6656 char szTempFile[_MAX_PATH+1];
6657 char szNewPath[_MAX_PATH+1];
6658 char *pszFilePart;
6659 HANDLE hf;
6660#ifdef FEAT_MBYTE
6661 WCHAR *wold = NULL;
6662 WCHAR *wnew = NULL;
6663 int retval = -1;
6664
6665 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6666 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006667 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6668 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 if (wold != NULL && wnew != NULL)
6670 retval = mch_wrename(wold, wnew);
6671 vim_free(wold);
6672 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006673 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674 }
6675#endif
6676
6677 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006678 * No need to play tricks unless the file name contains a "~" as the
6679 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006681 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6682 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6683 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684
6685 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6686 * a directory, no error is returned and pszFilePart will be NULL. */
6687 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6688 || pszFilePart == NULL)
6689 return -1;
6690 *pszFilePart = NUL;
6691
6692 /* Get (and create) a unique temporary file name in directory of new file */
6693 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6694 return -2;
6695
6696 /* blow the temp file away */
6697 if (!DeleteFile(szTempFile))
6698 return -3;
6699
6700 /* rename old file to the temp file */
6701 if (!MoveFile(pszOldFile, szTempFile))
6702 return -4;
6703
6704 /* now create an empty file called pszOldFile; this prevents the operating
6705 * system using pszOldFile as an alias (SFN) if we're renaming within the
6706 * same directory. For example, we're editing a file called
6707 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6708 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6709 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006710 * cause all sorts of problems later in buf_write(). So, we create an
6711 * empty file called filena~1.txt and the system will have to find some
6712 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006713 */
6714 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6715 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6716 return -5;
6717 if (!CloseHandle(hf))
6718 return -6;
6719
6720 /* rename the temp file to the new file */
6721 if (!MoveFile(szTempFile, pszNewFile))
6722 {
6723 /* Renaming failed. Rename the file back to its old name, so that it
6724 * looks like nothing happened. */
6725 (void)MoveFile(szTempFile, pszOldFile);
6726
6727 return -7;
6728 }
6729
6730 /* Seems to be left around on Novell filesystems */
6731 DeleteFile(szTempFile);
6732
6733 /* finally, remove the empty old file */
6734 if (!DeleteFile(pszOldFile))
6735 return -8;
6736
6737 return 0; /* success */
6738}
6739
6740/*
6741 * Get the default shell for the current hardware platform
6742 */
6743 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006744default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746 PlatformId();
6747
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006748 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749}
6750
6751/*
6752 * mch_access() extends access() to do more detailed check on network drives.
6753 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6754 */
6755 int
6756mch_access(char *n, int p)
6757{
6758 HANDLE hFile;
6759 DWORD am;
6760 int retval = -1; /* default: fail */
6761#ifdef FEAT_MBYTE
6762 WCHAR *wn = NULL;
6763
6764 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006765 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766#endif
6767
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006768 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769 {
6770 char TempName[_MAX_PATH + 16] = "";
6771#ifdef FEAT_MBYTE
6772 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6773#endif
6774
6775 if (p & R_OK)
6776 {
6777 /* Read check is performed by seeing if we can do a find file on
6778 * the directory for any file. */
6779#ifdef FEAT_MBYTE
6780 if (wn != NULL)
6781 {
6782 int i;
6783 WIN32_FIND_DATAW d;
6784
6785 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6786 TempNameW[i] = wn[i];
6787 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6788 TempNameW[i++] = '\\';
6789 TempNameW[i++] = '*';
6790 TempNameW[i++] = 0;
6791
6792 hFile = FindFirstFileW(TempNameW, &d);
6793 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006794 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006795 else
6796 (void)FindClose(hFile);
6797 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006798 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799#endif
6800 {
6801 char *pch;
6802 WIN32_FIND_DATA d;
6803
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006804 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 pch = TempName + STRLEN(TempName) - 1;
6806 if (*pch != '\\' && *pch != '/')
6807 *++pch = '\\';
6808 *++pch = '*';
6809 *++pch = NUL;
6810
6811 hFile = FindFirstFile(TempName, &d);
6812 if (hFile == INVALID_HANDLE_VALUE)
6813 goto getout;
6814 (void)FindClose(hFile);
6815 }
6816 }
6817
6818 if (p & W_OK)
6819 {
6820 /* Trying to create a temporary file in the directory should catch
6821 * directories on read-only network shares. However, in
6822 * directories whose ACL allows writes but denies deletes will end
6823 * up keeping the temporary file :-(. */
6824#ifdef FEAT_MBYTE
6825 if (wn != NULL)
6826 {
6827 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006828 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829 else
6830 DeleteFileW(TempNameW);
6831 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006832 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833#endif
6834 {
6835 if (!GetTempFileName(n, "VIM", 0, TempName))
6836 goto getout;
6837 mch_remove((char_u *)TempName);
6838 }
6839 }
6840 }
6841 else
6842 {
6843 /* Trying to open the file for the required access does ACL, read-only
6844 * network share, and file attribute checks. */
6845 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6846 | ((p & R_OK) ? GENERIC_READ : 0);
6847#ifdef FEAT_MBYTE
6848 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006849 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006850 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851#endif
6852 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6853 if (hFile == INVALID_HANDLE_VALUE)
6854 goto getout;
6855 CloseHandle(hFile);
6856 }
6857
6858 retval = 0; /* success */
6859getout:
6860#ifdef FEAT_MBYTE
6861 vim_free(wn);
6862#endif
6863 return retval;
6864}
6865
6866#if defined(FEAT_MBYTE) || defined(PROTO)
6867/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006868 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869 */
6870 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006871mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006873 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6874# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875 WCHAR *wn;
6876 int f;
6877
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006878 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006880 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 if (wn != NULL)
6882 {
6883 f = _wopen(wn, flags, mode);
6884 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006885 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 }
6887 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006888# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006890 /* open() can open a file which name is longer than _MAX_PATH bytes
6891 * and shorter than _MAX_PATH characters successfully, but sometimes it
6892 * causes unexpected error in another part. We make it an error explicitly
6893 * here. */
6894 if (strlen(name) >= _MAX_PATH)
6895 return -1;
6896
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 return open(name, flags, mode);
6898}
6899
6900/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006901 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902 */
6903 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006904mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905{
6906 WCHAR *wn, *wm;
6907 FILE *f = NULL;
6908
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006909 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006911# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006912 /* Work around an annoying assertion in the Microsoft debug CRT
6913 * when mode's text/binary setting doesn't match _get_fmode(). */
6914 char newMode = mode[strlen(mode) - 1];
6915 int oldMode = 0;
6916
6917 _get_fmode(&oldMode);
6918 if (newMode == 't')
6919 _set_fmode(_O_TEXT);
6920 else if (newMode == 'b')
6921 _set_fmode(_O_BINARY);
6922# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006923 wn = enc_to_utf16((char_u *)name, NULL);
6924 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 if (wn != NULL && wm != NULL)
6926 f = _wfopen(wn, wm);
6927 vim_free(wn);
6928 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006929
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006930# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006931 _set_fmode(oldMode);
6932# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006933 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006934 }
6935
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006936 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6937 * and shorter than _MAX_PATH characters successfully, but sometimes it
6938 * causes unexpected error in another part. We make it an error explicitly
6939 * here. */
6940 if (strlen(name) >= _MAX_PATH)
6941 return NULL;
6942
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943 return fopen(name, mode);
6944}
6945#endif
6946
6947#ifdef FEAT_MBYTE
6948/*
6949 * SUB STREAM (aka info stream) handling:
6950 *
6951 * NTFS can have sub streams for each file. Normal contents of file is
6952 * stored in the main stream, and extra contents (author information and
6953 * title and so on) can be stored in sub stream. After Windows 2000, user
6954 * can access and store those informations in sub streams via explorer's
6955 * property menuitem in right click menu. Those informations in sub streams
6956 * were lost when copying only the main stream. So we have to copy sub
6957 * streams.
6958 *
6959 * Incomplete explanation:
6960 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6961 * More useful info and an example:
6962 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6963 */
6964
6965/*
6966 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6967 * and write to stream "substream" of file "to".
6968 * Errors are ignored.
6969 */
6970 static void
6971copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6972{
6973 HANDLE hTo;
6974 WCHAR *to_name;
6975
6976 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6977 wcscpy(to_name, to);
6978 wcscat(to_name, substream);
6979
6980 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6981 FILE_ATTRIBUTE_NORMAL, NULL);
6982 if (hTo != INVALID_HANDLE_VALUE)
6983 {
6984 long done;
6985 DWORD todo;
6986 DWORD readcnt, written;
6987 char buf[4096];
6988
6989 /* Copy block of bytes at a time. Abort when something goes wrong. */
6990 for (done = 0; done < len; done += written)
6991 {
6992 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006993 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6994 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6996 FALSE, FALSE, context)
6997 || readcnt != todo
6998 || !WriteFile(hTo, buf, todo, &written, NULL)
6999 || written != todo)
7000 break;
7001 }
7002 CloseHandle(hTo);
7003 }
7004
7005 free(to_name);
7006}
7007
7008/*
7009 * Copy info streams from file "from" to file "to".
7010 */
7011 static void
7012copy_infostreams(char_u *from, char_u *to)
7013{
7014 WCHAR *fromw;
7015 WCHAR *tow;
7016 HANDLE sh;
7017 WIN32_STREAM_ID sid;
7018 int headersize;
7019 WCHAR streamname[_MAX_PATH];
7020 DWORD readcount;
7021 void *context = NULL;
7022 DWORD lo, hi;
7023 int len;
7024
7025 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007026 fromw = enc_to_utf16(from, NULL);
7027 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028 if (fromw != NULL && tow != NULL)
7029 {
7030 /* Open the file for reading. */
7031 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7032 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7033 if (sh != INVALID_HANDLE_VALUE)
7034 {
7035 /* Use BackupRead() to find the info streams. Repeat until we
7036 * have done them all.*/
7037 for (;;)
7038 {
7039 /* Get the header to find the length of the stream name. If
7040 * the "readcount" is zero we have done all info streams. */
7041 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007042 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007043 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7044 &readcount, FALSE, FALSE, &context)
7045 || readcount == 0)
7046 break;
7047
7048 /* We only deal with streams that have a name. The normal
7049 * file data appears to be without a name, even though docs
7050 * suggest it is called "::$DATA". */
7051 if (sid.dwStreamNameSize > 0)
7052 {
7053 /* Read the stream name. */
7054 if (!BackupRead(sh, (LPBYTE)streamname,
7055 sid.dwStreamNameSize,
7056 &readcount, FALSE, FALSE, &context))
7057 break;
7058
7059 /* Copy an info stream with a name ":anything:$DATA".
7060 * Skip "::$DATA", it has no stream name (examples suggest
7061 * it might be used for the normal file contents).
7062 * Note that BackupRead() counts bytes, but the name is in
7063 * wide characters. */
7064 len = readcount / sizeof(WCHAR);
7065 streamname[len] = 0;
7066 if (len > 7 && wcsicmp(streamname + len - 6,
7067 L":$DATA") == 0)
7068 {
7069 streamname[len - 6] = 0;
7070 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007071 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007072 }
7073 }
7074
7075 /* Advance to the next stream. We might try seeking too far,
7076 * but BackupSeek() doesn't skip over stream borders, thus
7077 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007078 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 &lo, &hi, &context);
7080 }
7081
7082 /* Clear the context. */
7083 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7084
7085 CloseHandle(sh);
7086 }
7087 }
7088 vim_free(fromw);
7089 vim_free(tow);
7090}
7091#endif
7092
7093/*
7094 * Copy file attributes from file "from" to file "to".
7095 * For Windows NT and later we copy info streams.
7096 * Always returns zero, errors are ignored.
7097 */
7098 int
7099mch_copy_file_attribute(char_u *from, char_u *to)
7100{
7101#ifdef FEAT_MBYTE
7102 /* File streams only work on Windows NT and later. */
7103 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007104 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105#endif
7106 return 0;
7107}
7108
7109#if defined(MYRESETSTKOFLW) || defined(PROTO)
7110/*
7111 * Recreate a destroyed stack guard page in win32.
7112 * Written by Benjamin Peterson.
7113 */
7114
7115/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116#define MIN_STACK_WINNT 2
7117
7118/*
7119 * This function does the same thing as _resetstkoflw(), which is only
7120 * available in DevStudio .net and later.
7121 * Returns 0 for failure, 1 for success.
7122 */
7123 int
7124myresetstkoflw(void)
7125{
7126 BYTE *pStackPtr;
7127 BYTE *pGuardPage;
7128 BYTE *pStackBase;
7129 BYTE *pLowestPossiblePage;
7130 MEMORY_BASIC_INFORMATION mbi;
7131 SYSTEM_INFO si;
7132 DWORD nPageSize;
7133 DWORD dummy;
7134
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136
7137 /* We need to know the system page size. */
7138 GetSystemInfo(&si);
7139 nPageSize = si.dwPageSize;
7140
7141 /* ...and the current stack pointer */
7142 pStackPtr = (BYTE*)_alloca(1);
7143
7144 /* ...and the base of the stack. */
7145 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7146 return 0;
7147 pStackBase = (BYTE*)mbi.AllocationBase;
7148
7149 /* ...and the page thats min_stack_req pages away from stack base; this is
7150 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007151 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007152
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007154 /* We want the first committed page in the stack Start at the stack
7155 * base and move forward through memory until we find a committed block.
7156 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007157 BYTE *pBlock = pStackBase;
7158
Bram Moolenaara466c992005-07-09 21:03:22 +00007159 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007160 {
7161 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7162 return 0;
7163
7164 pBlock += mbi.RegionSize;
7165
7166 if (mbi.State & MEM_COMMIT)
7167 break;
7168 }
7169
7170 /* mbi now describes the first committed block in the stack. */
7171 if (mbi.Protect & PAGE_GUARD)
7172 return 1;
7173
7174 /* decide where the guard page should start */
7175 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7176 pGuardPage = pLowestPossiblePage;
7177 else
7178 pGuardPage = (BYTE*)mbi.BaseAddress;
7179
7180 /* allocate the guard page */
7181 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7182 return 0;
7183
7184 /* apply the guard attribute to the page */
7185 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7186 &dummy))
7187 return 0;
7188 }
7189
7190 return 1;
7191}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007192#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007193
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007194
7195#if defined(FEAT_MBYTE) || defined(PROTO)
7196/*
7197 * The command line arguments in UCS2
7198 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007199static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007200static LPWSTR *ArglistW = NULL;
7201static int global_argc = 0;
7202static char **global_argv;
7203
7204static int used_file_argc = 0; /* last argument in global_argv[] used
7205 for the argument list. */
7206static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7207 command line arguments added to
7208 the argument list */
7209static int used_file_count = 0; /* nr of entries in used_file_indexes */
7210static int used_file_literal = FALSE; /* take file names literally */
7211static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007212static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007213static int used_alist_count = 0;
7214
7215
7216/*
7217 * Get the command line arguments. Unicode version.
7218 * Returns argc. Zero when something fails.
7219 */
7220 int
7221get_cmd_argsW(char ***argvp)
7222{
7223 char **argv = NULL;
7224 int argc = 0;
7225 int i;
7226
Bram Moolenaar14993322014-09-09 12:25:33 +02007227 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007228 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7229 if (ArglistW != NULL)
7230 {
7231 argv = malloc((nArgsW + 1) * sizeof(char *));
7232 if (argv != NULL)
7233 {
7234 argc = nArgsW;
7235 argv[argc] = NULL;
7236 for (i = 0; i < argc; ++i)
7237 {
7238 int len;
7239
7240 /* Convert each Unicode argument to the current codepage. */
7241 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007242 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007243 (LPSTR *)&argv[i], &len, 0, 0);
7244 if (argv[i] == NULL)
7245 {
7246 /* Out of memory, clear everything. */
7247 while (i > 0)
7248 free(argv[--i]);
7249 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007250 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007251 argc = 0;
7252 }
7253 }
7254 }
7255 }
7256
7257 global_argc = argc;
7258 global_argv = argv;
7259 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007260 {
7261 if (used_file_indexes != NULL)
7262 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007263 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007264 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007265
7266 if (argvp != NULL)
7267 *argvp = argv;
7268 return argc;
7269}
7270
7271 void
7272free_cmd_argsW(void)
7273{
7274 if (ArglistW != NULL)
7275 {
7276 GlobalFree(ArglistW);
7277 ArglistW = NULL;
7278 }
7279}
7280
7281/*
7282 * Remember "name" is an argument that was added to the argument list.
7283 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7284 * is called.
7285 */
7286 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007287used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007288{
7289 int i;
7290
7291 if (used_file_indexes == NULL)
7292 return;
7293 for (i = used_file_argc + 1; i < global_argc; ++i)
7294 if (STRCMP(global_argv[i], name) == 0)
7295 {
7296 used_file_argc = i;
7297 used_file_indexes[used_file_count++] = i;
7298 break;
7299 }
7300 used_file_literal = literal;
7301 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007302 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007303}
7304
7305/*
7306 * Remember the length of the argument list as it was. If it changes then we
7307 * leave it alone when 'encoding' is set.
7308 */
7309 void
7310set_alist_count(void)
7311{
7312 used_alist_count = GARGCOUNT;
7313}
7314
7315/*
7316 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7317 * has been changed while starting up. Use the UCS-2 command line arguments
7318 * and convert them to 'encoding'.
7319 */
7320 void
7321fix_arg_enc(void)
7322{
7323 int i;
7324 int idx;
7325 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007326 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007327
7328 /* Safety checks:
7329 * - if argument count differs between the wide and non-wide argument
7330 * list, something must be wrong.
7331 * - the file name arguments must have been located.
7332 * - the length of the argument list wasn't changed by the user.
7333 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007334 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007335 || ArglistW == NULL
7336 || used_file_indexes == NULL
7337 || used_file_count == 0
7338 || used_alist_count != GARGCOUNT)
7339 return;
7340
Bram Moolenaar86b68352004-12-27 21:59:20 +00007341 /* Remember the buffer numbers for the arguments. */
7342 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7343 if (fnum_list == NULL)
7344 return; /* out of memory */
7345 for (i = 0; i < GARGCOUNT; ++i)
7346 fnum_list[i] = GARGLIST[i].ae_fnum;
7347
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007348 /* Clear the argument list. Make room for the new arguments. */
7349 alist_clear(&global_alist);
7350 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007351 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007352
7353 for (i = 0; i < used_file_count; ++i)
7354 {
7355 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007356 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007357 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007358 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007359 int literal = used_file_literal;
7360
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007361#ifdef FEAT_DIFF
7362 /* When using diff mode may need to concatenate file name to
7363 * directory name. Just like it's done in main(). */
7364 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7365 && !mch_isdir(alist_name(&GARGLIST[0])))
7366 {
7367 char_u *r;
7368
7369 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7370 if (r != NULL)
7371 {
7372 vim_free(str);
7373 str = r;
7374 }
7375 }
7376#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007377 /* Re-use the old buffer by renaming it. When not using literal
7378 * names it's done by alist_expand() below. */
7379 if (used_file_literal)
7380 buf_set_name(fnum_list[i], str);
7381
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007382 /* Check backtick literal. backtick literal is already expanded in
7383 * main.c, so this part add str as literal. */
7384 if (literal == FALSE)
7385 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007386 size_t len = STRLEN(str);
7387
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007388 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7389 literal = TRUE;
7390 }
7391 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007392 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007393 }
7394
7395 if (!used_file_literal)
7396 {
7397 /* Now expand wildcards in the arguments. */
7398 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7399 * filename characters but are excluded from 'isfname' to make
7400 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7401 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007402 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007403 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7404 }
7405
7406 /* If wildcard expansion failed, we are editing the first file of the
7407 * arglist and there is no file name: Edit the first argument now. */
7408 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7409 {
7410 do_cmdline_cmd((char_u *)":rewind");
7411 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007412 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007413 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007414
7415 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007416}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007418
7419 int
7420mch_setenv(char *var, char *value, int x)
7421{
7422 char_u *envbuf;
7423
7424 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7425 if (envbuf == NULL)
7426 return -1;
7427
7428 sprintf((char *)envbuf, "%s=%s", var, value);
7429
7430#ifdef FEAT_MBYTE
7431 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7432 {
7433 WCHAR *p = enc_to_utf16(envbuf, NULL);
7434
7435 vim_free(envbuf);
7436 if (p == NULL)
7437 return -1;
7438 _wputenv(p);
7439# ifdef libintl_wputenv
7440 libintl_wputenv(p);
7441# endif
7442 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7443 vim_free(p);
7444 }
7445 else
7446#endif
7447 {
7448 _putenv((char *)envbuf);
7449# ifdef libintl_putenv
7450 libintl_putenv((char *)envbuf);
7451# endif
7452 /* Unlike Un*x systems, we can free the string for _putenv(). */
7453 vim_free(envbuf);
7454 }
7455
7456 return 0;
7457}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007458
7459#ifndef FEAT_GUI_W32
7460
7461/*
7462 * Support for 256 colors and 24-bit colors was added in Windows 10
7463 * version 1703 (Creators update).
7464 */
7465# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7466
7467 static void
7468vtp_init(void)
7469{
7470 DWORD ver, mode;
7471 HMODULE hKerneldll;
7472 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7473
7474 ver = get_build_number();
7475 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7476 GetConsoleMode(g_hConOut, &mode);
7477 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7478 if (SetConsoleMode(g_hConOut, mode) == 0)
7479 vtp_working = 0;
7480
7481 /* Use functions supported from Vista */
7482 hKerneldll = GetModuleHandle("kernel32.dll");
7483 if (hKerneldll != NULL)
7484 {
7485 pGetConsoleScreenBufferInfoEx =
7486 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7487 hKerneldll, "GetConsoleScreenBufferInfoEx");
7488 pSetConsoleScreenBufferInfoEx =
7489 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7490 hKerneldll, "SetConsoleScreenBufferInfoEx");
7491 if (pGetConsoleScreenBufferInfoEx != NULL
7492 && pSetConsoleScreenBufferInfoEx != NULL)
7493 has_csbiex = TRUE;
7494 }
7495
7496 csbi.cbSize = sizeof(csbi);
7497 if (has_csbiex)
7498 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7499 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[0];
7500 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[7];
7501
7502 set_console_color_rgb();
7503}
7504
7505 static void
7506vtp_exit(void)
7507{
7508 reset_console_color_rgb();
7509}
7510
7511 static int
7512vtp_printf(
7513 char *format,
7514 ...)
7515{
7516 char_u buf[100];
7517 va_list list;
7518 DWORD result;
7519
7520 va_start(list, format);
7521 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7522 va_end(list);
7523 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7524 return (int)result;
7525}
7526
7527 static void
7528vtp_sgr_bulk(
7529 int arg)
7530{
7531 int args[1];
7532
7533 args[0] = arg;
7534 vtp_sgr_bulks(1, args);
7535}
7536
7537 static void
7538vtp_sgr_bulks(
7539 int argc,
7540 int *args
7541)
7542{
7543 /* 2('\033[') + 4('255.') * 16 + NUL */
7544 char_u buf[2 + (4 * 16) + 1];
7545 char_u *p;
7546 int i;
7547
7548 p = buf;
7549 *p++ = '\033';
7550 *p++ = '[';
7551
7552 for (i = 0; i < argc; ++i)
7553 {
7554 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7555 *p++ = ';';
7556 }
7557 p--;
7558 *p++ = 'm';
7559 *p = NUL;
7560 vtp_printf((char *)buf);
7561}
7562
7563 static void
7564set_console_color_rgb(void)
7565{
7566# ifdef FEAT_TERMGUICOLORS
7567 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7568 int id;
7569 guicolor_T fg = INVALCOLOR;
7570 guicolor_T bg = INVALCOLOR;
7571
7572 if (!USE_VTP)
7573 return;
7574
7575 id = syn_name2id((char_u *)"Normal");
7576 if (id > 0)
7577 syn_id2colors(id, &fg, &bg);
7578 if (fg == INVALCOLOR)
7579 fg = 0xc0c0c0; /* white text */
7580 if (bg == INVALCOLOR)
7581 bg = 0x000000; /* black background */
7582 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7583 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7584
7585 csbi.cbSize = sizeof(csbi);
7586 if (has_csbiex)
7587 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7588
7589 csbi.cbSize = sizeof(csbi);
7590 csbi.srWindow.Right += 1;
7591 csbi.srWindow.Bottom += 1;
7592 csbi.ColorTable[0] = (COLORREF)bg;
7593 csbi.ColorTable[7] = (COLORREF)fg;
7594 if (has_csbiex)
7595 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7596# endif
7597}
7598
7599 static void
7600reset_console_color_rgb(void)
7601{
7602# ifdef FEAT_TERMGUICOLORS
7603 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7604
7605 csbi.cbSize = sizeof(csbi);
7606 if (has_csbiex)
7607 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7608
7609 csbi.cbSize = sizeof(csbi);
7610 csbi.srWindow.Right += 1;
7611 csbi.srWindow.Bottom += 1;
7612 csbi.ColorTable[0] = (COLORREF)save_console_bg_rgb;
7613 csbi.ColorTable[7] = (COLORREF)save_console_fg_rgb;
7614 if (has_csbiex)
7615 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7616# endif
7617}
7618
7619 void
7620control_console_color_rgb(void)
7621{
7622 if (USE_VTP)
7623 set_console_color_rgb();
7624 else
7625 reset_console_color_rgb();
7626}
7627
7628 int
7629has_vtp_working(void)
7630{
7631 return vtp_working;
7632}
7633
7634 int
7635use_vtp(void)
7636{
7637 return USE_VTP;
7638}
7639
7640#endif