blob: b70a0025d1d2d02cd51fc634d2e6b322f104f653 [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;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004491 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
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004785#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4786/*
4787 * Use a terminal window to run a shell command in.
4788 */
4789 static int
4790mch_call_shell_terminal(
4791 char_u *cmd,
4792 int options UNUSED) /* SHELL_*, see vim.h */
4793{
4794 jobopt_T opt;
4795 char_u *newcmd = NULL;
4796 typval_T argvar[2];
4797 long_u cmdlen;
4798 int retval = -1;
4799 buf_T *buf;
4800 aco_save_T aco;
4801 oparg_T oa; /* operator arguments */
4802
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004803 if (cmd == NULL)
4804 cmdlen = STRLEN(p_sh) + 1;
4805 else
4806 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004807 newcmd = lalloc(cmdlen, TRUE);
4808 if (newcmd == NULL)
4809 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004810 if (cmd == NULL)
4811 {
4812 STRCPY(newcmd, p_sh);
4813 ch_log(NULL, "starting terminal to run a shell");
4814 }
4815 else
4816 {
4817 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4818 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4819 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004820
4821 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004822
4823 argvar[0].v_type = VAR_STRING;
4824 argvar[0].vval.v_string = newcmd;
4825 argvar[1].v_type = VAR_UNKNOWN;
4826 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
4827
4828 /* Find a window to make "buf" curbuf. */
4829 aucmd_prepbuf(&aco, buf);
4830
4831 clear_oparg(&oa);
4832 while (term_use_loop())
4833 {
4834 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4835 {
4836 /* If terminal_loop() returns OK we got a key that is handled
4837 * in Normal model. We don't do redrawing anyway. */
4838 if (terminal_loop(TRUE) == OK)
4839 normal_cmd(&oa, TRUE);
4840 }
4841 else
4842 normal_cmd(&oa, TRUE);
4843 }
4844 retval = 0;
4845 ch_log(NULL, "system command finished");
4846
4847 /* restore curwin/curbuf and a few other things */
4848 aucmd_restbuf(&aco);
4849
4850 wait_return(TRUE);
4851 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4852
4853 vim_free(newcmd);
4854 return retval;
4855}
4856#endif
4857
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858/*
4859 * Either execute a command by calling the shell or start a new shell
4860 */
4861 int
4862mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004863 char_u *cmd,
4864 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865{
4866 int x = 0;
4867 int tmode = cur_tmode;
4868#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004869 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004870# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004871 int did_set_title = FALSE;
4872
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004873 /* Change the title to reflect that we are in a subshell. */
4874 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4875 {
4876 WCHAR szShellTitle[512];
4877
4878 if (GetConsoleTitleW(szShellTitle,
4879 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4880 {
4881 if (cmd == NULL)
4882 wcscat(szShellTitle, L" :sh");
4883 else
4884 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004885 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004886
4887 if (wn != NULL)
4888 {
4889 wcscat(szShellTitle, L" - !");
4890 if ((wcslen(szShellTitle) + wcslen(wn) <
4891 sizeof(szShellTitle)/sizeof(WCHAR)))
4892 wcscat(szShellTitle, wn);
4893 SetConsoleTitleW(szShellTitle);
4894 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004895 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004896 }
4897 }
4898 }
4899 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004900 if (!did_set_title)
4901# endif
4902 /* Change the title to reflect that we are in a subshell. */
4903 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004905 if (cmd == NULL)
4906 strcat(szShellTitle, " :sh");
4907 else
4908 {
4909 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004910 if ((strlen(szShellTitle) + strlen((char *)cmd)
4911 < sizeof(szShellTitle)))
4912 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004913 }
4914 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916#endif
4917
4918 out_flush();
4919
4920#ifdef MCH_WRITE_DUMP
4921 if (fdDump)
4922 {
4923 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4924 fflush(fdDump);
4925 }
4926#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004927#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4928 /* TODO: make the terminal window work with input or output redirected. */
4929 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4930 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4931 {
4932 /* Use a terminal window to run the command in. */
4933 x = mch_call_shell_terminal(cmd, options);
4934#ifdef FEAT_TITLE
4935 resettitle();
4936#endif
4937 return x;
4938 }
4939#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940
4941 /*
4942 * Catch all deadly signals while running the external command, because a
4943 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4944 */
4945 signal(SIGINT, SIG_IGN);
4946#if defined(__GNUC__) && !defined(__MINGW32__)
4947 signal(SIGKILL, SIG_IGN);
4948#else
4949 signal(SIGBREAK, SIG_IGN);
4950#endif
4951 signal(SIGILL, SIG_IGN);
4952 signal(SIGFPE, SIG_IGN);
4953 signal(SIGSEGV, SIG_IGN);
4954 signal(SIGTERM, SIG_IGN);
4955 signal(SIGABRT, SIG_IGN);
4956
4957 if (options & SHELL_COOKED)
4958 settmode(TMODE_COOK); /* set to normal mode */
4959
4960 if (cmd == NULL)
4961 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004962 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963 }
4964 else
4965 {
4966 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004967 char_u *newcmd = NULL;
4968 char_u *cmdbase = cmd;
4969 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004970
4971 /* Skip a leading ", ( and "(. */
4972 if (*cmdbase == '"' )
4973 ++cmdbase;
4974 if (*cmdbase == '(')
4975 ++cmdbase;
4976
Bram Moolenaar1c465442017-03-12 20:10:05 +01004977 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004978 {
4979 STARTUPINFO si;
4980 PROCESS_INFORMATION pi;
4981 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004982 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004983 char_u *p;
4984
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004985 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004986 si.cb = sizeof(si);
4987 si.lpReserved = NULL;
4988 si.lpDesktop = NULL;
4989 si.lpTitle = NULL;
4990 si.dwFlags = 0;
4991 si.cbReserved2 = 0;
4992 si.lpReserved2 = NULL;
4993
4994 cmdbase = skipwhite(cmdbase + 5);
4995 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004996 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004997 {
4998 cmdbase = skipwhite(cmdbase + 4);
4999 si.dwFlags = STARTF_USESHOWWINDOW;
5000 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005001 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005002 }
5003 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005004 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005005 {
5006 cmdbase = skipwhite(cmdbase + 2);
5007 flags = CREATE_NO_WINDOW;
5008 si.dwFlags = STARTF_USESTDHANDLES;
5009 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005010 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005011 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005012 NULL, // Security att.
5013 OPEN_EXISTING, // Open flags
5014 FILE_ATTRIBUTE_NORMAL, // File att.
5015 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005016 si.hStdOutput = si.hStdInput;
5017 si.hStdError = si.hStdInput;
5018 }
5019
5020 /* Remove a trailing ", ) and )" if they have a match
5021 * at the start of the command. */
5022 if (cmdbase > cmd)
5023 {
5024 p = cmdbase + STRLEN(cmdbase);
5025 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5026 *--p = NUL;
5027 if (p > cmdbase && p[-1] == ')'
5028 && (*cmd =='(' || cmd[1] == '('))
5029 *--p = NUL;
5030 }
5031
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005032 newcmd = cmdbase;
5033 unescape_shellxquote(cmdbase, p_sxe);
5034
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005035 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005036 * If creating new console, arguments are passed to the
5037 * 'cmd.exe' as-is. If it's not, arguments are not treated
5038 * correctly for current 'cmd.exe'. So unescape characters in
5039 * shellxescape except '|' for avoiding to be treated as
5040 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005041 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005042 if (flags != CREATE_NEW_CONSOLE)
5043 {
5044 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005045 char_u *cmd_shell = mch_getenv("COMSPEC");
5046
5047 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005048 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005049
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005050 subcmd = vim_strsave_escaped_ext(cmdbase,
5051 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005052 if (subcmd != NULL)
5053 {
5054 /* make "cmd.exe /c arguments" */
5055 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005056 newcmd = lalloc(cmdlen, TRUE);
5057 if (newcmd != NULL)
5058 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005059 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005060 else
5061 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005062 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005063 }
5064 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005065
5066 /*
5067 * Now, start the command as a process, so that it doesn't
5068 * inherit our handles which causes unpleasant dangling swap
5069 * files if we exit before the spawned process
5070 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005071 if (vim_create_process((char *)newcmd, FALSE, flags,
5072 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005073 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005074 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5075 > (HINSTANCE)32)
5076 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005077 else
5078 {
5079 x = -1;
5080#ifdef FEAT_GUI_W32
5081 EMSG(_("E371: Command not found"));
5082#endif
5083 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005084
5085 if (newcmd != cmdbase)
5086 vim_free(newcmd);
5087
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005088 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005089 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005090 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005091 CloseHandle(si.hStdInput);
5092 }
5093 /* Close the handles to the subprocess, so that it goes away */
5094 CloseHandle(pi.hThread);
5095 CloseHandle(pi.hProcess);
5096 }
5097 else
5098 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005099 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005100#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005101 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005102#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005103 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5104
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005105 newcmd = lalloc(cmdlen, TRUE);
5106 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005107 {
5108#if defined(FEAT_GUI_W32)
5109 if (need_vimrun_warning)
5110 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005111 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5112 "External commands will not pause after completion.\n"
5113 "See :help win32-vimrun for more information.");
5114 char *title = _("Vim Warning");
5115# ifdef FEAT_MBYTE
5116 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5117 {
5118 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5119 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5120
5121 if (wmsg != NULL && wtitle != NULL)
5122 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5123 vim_free(wmsg);
5124 vim_free(wtitle);
5125 }
5126 else
5127# endif
5128 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005129 need_vimrun_warning = FALSE;
5130 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005131 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005132 /* Use vimrun to execute the command. It opens a console
5133 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005134 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005135 vimrun_path,
5136 (msg_silent != 0 || (options & SHELL_DOOUT))
5137 ? "-s " : "",
5138 p_sh, p_shcf, cmd);
5139 else
5140#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005141 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005142 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005143 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005144 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005145 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005146 }
5147 }
5148
5149 if (tmode == TMODE_RAW)
5150 settmode(TMODE_RAW); /* set to raw mode */
5151
5152 /* Print the return value, unless "vimrun" was used. */
5153 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5154#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005155 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005156#endif
5157 )
5158 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005159 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005160 msg_putchar('\n');
5161 }
5162#ifdef FEAT_TITLE
5163 resettitle();
5164#endif
5165
5166 signal(SIGINT, SIG_DFL);
5167#if defined(__GNUC__) && !defined(__MINGW32__)
5168 signal(SIGKILL, SIG_DFL);
5169#else
5170 signal(SIGBREAK, SIG_DFL);
5171#endif
5172 signal(SIGILL, SIG_DFL);
5173 signal(SIGFPE, SIG_DFL);
5174 signal(SIGSEGV, SIG_DFL);
5175 signal(SIGTERM, SIG_DFL);
5176 signal(SIGABRT, SIG_DFL);
5177
5178 return x;
5179}
5180
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005181#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005182 static HANDLE
5183job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005184 char_u *fname,
5185 DWORD dwDesiredAccess,
5186 DWORD dwShareMode,
5187 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5188 DWORD dwCreationDisposition,
5189 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005190{
5191 HANDLE h;
5192# ifdef FEAT_MBYTE
5193 WCHAR *wn = NULL;
5194 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5195 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005196 wn = enc_to_utf16(fname, NULL);
5197 if (wn != NULL)
5198 {
5199 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5200 lpSecurityAttributes, dwCreationDisposition,
5201 dwFlagsAndAttributes, NULL);
5202 vim_free(wn);
5203 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005204 }
5205 if (wn == NULL)
5206# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005207 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5208 lpSecurityAttributes, dwCreationDisposition,
5209 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005210 return h;
5211}
5212
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005213/*
5214 * Turn the dictionary "env" into a NUL separated list that can be used as the
5215 * environment argument of vim_create_process().
5216 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005217 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005218win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005219{
5220 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005221 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005222 LPVOID base = GetEnvironmentStringsW();
5223
5224 /* for last \0 */
5225 if (ga_grow(gap, 1) == FAIL)
5226 return;
5227
5228 if (base)
5229 {
5230 WCHAR *p = (WCHAR*) base;
5231
5232 /* for last \0 */
5233 if (ga_grow(gap, 1) == FAIL)
5234 return;
5235
5236 while (*p != 0 || *(p + 1) != 0)
5237 {
5238 if (ga_grow(gap, 1) == OK)
5239 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5240 p++;
5241 }
5242 FreeEnvironmentStrings(base);
5243 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5244 }
5245
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005246 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005247 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005248 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005249 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005250 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005251 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005252 typval_T *item = &dict_lookup(hi)->di_tv;
5253 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5254 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5255 --todo;
5256 if (wkey != NULL && wval != NULL)
5257 {
5258 size_t n;
5259 size_t lkey = wcslen(wkey);
5260 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005261
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005262 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5263 continue;
5264 for (n = 0; n < lkey; n++)
5265 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5266 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5267 for (n = 0; n < lval; n++)
5268 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5269 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5270 }
5271 if (wkey != NULL) vim_free(wkey);
5272 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005273 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005274 }
5275 }
5276
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005277# ifdef FEAT_CLIENTSERVER
5278 if (is_terminal)
5279 {
5280 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
5281 size_t lval = STRLEN(servername);
5282 size_t n;
5283
5284 if (ga_grow(gap, (int)(14 + lval + 2)) == OK)
5285 {
5286 for (n = 0; n < 15; n++)
5287 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5288 (WCHAR)"VIM_SERVERNAME="[n];
5289 for (n = 0; n < lval; n++)
5290 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5291 (WCHAR)servername[n];
5292 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5293 }
5294 }
5295# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005296}
5297
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005298 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005299mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005300{
5301 STARTUPINFO si;
5302 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005303 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005304 SECURITY_ATTRIBUTES saAttr;
5305 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005306 HANDLE ifd[2];
5307 HANDLE ofd[2];
5308 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005309 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005310
5311 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5312 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5313 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5314 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5315 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5316 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5317 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5318
5319 if (use_out_for_err && use_null_for_out)
5320 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005321
5322 ifd[0] = INVALID_HANDLE_VALUE;
5323 ifd[1] = INVALID_HANDLE_VALUE;
5324 ofd[0] = INVALID_HANDLE_VALUE;
5325 ofd[1] = INVALID_HANDLE_VALUE;
5326 efd[0] = INVALID_HANDLE_VALUE;
5327 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005328 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005329
Bram Moolenaar14207f42016-10-27 21:13:10 +02005330 jo = CreateJobObject(NULL, NULL);
5331 if (jo == NULL)
5332 {
5333 job->jv_status = JOB_FAILED;
5334 goto failed;
5335 }
5336
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005337 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005338 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005339
Bram Moolenaar76467df2016-02-12 19:30:26 +01005340 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005341 ZeroMemory(&si, sizeof(si));
5342 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005343 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005344 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005345
Bram Moolenaard8070362016-02-15 21:56:54 +01005346 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5347 saAttr.bInheritHandle = TRUE;
5348 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005349
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005350 if (use_file_for_in)
5351 {
5352 char_u *fname = options->jo_io_name[PART_IN];
5353
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005354 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5355 FILE_SHARE_READ | FILE_SHARE_WRITE,
5356 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5357 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005358 {
5359 EMSG2(_(e_notopen), fname);
5360 goto failed;
5361 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005362 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005363 else if (!use_null_for_in &&
5364 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005365 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005366 goto failed;
5367
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005368 if (use_file_for_out)
5369 {
5370 char_u *fname = options->jo_io_name[PART_OUT];
5371
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005372 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5373 FILE_SHARE_READ | FILE_SHARE_WRITE,
5374 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5375 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005376 {
5377 EMSG2(_(e_notopen), fname);
5378 goto failed;
5379 }
5380 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005381 else if (!use_null_for_out &&
5382 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005383 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005384 goto failed;
5385
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005386 if (use_file_for_err)
5387 {
5388 char_u *fname = options->jo_io_name[PART_ERR];
5389
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005390 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5391 FILE_SHARE_READ | FILE_SHARE_WRITE,
5392 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5393 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005394 {
5395 EMSG2(_(e_notopen), fname);
5396 goto failed;
5397 }
5398 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005399 else if (!use_out_for_err && !use_null_for_err &&
5400 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005401 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005402 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005403
Bram Moolenaard8070362016-02-15 21:56:54 +01005404 si.dwFlags |= STARTF_USESTDHANDLES;
5405 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005406 si.hStdOutput = ofd[1];
5407 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5408
5409 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5410 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005411 if (options->jo_set & JO_CHANNEL)
5412 {
5413 channel = options->jo_channel;
5414 if (channel != NULL)
5415 ++channel->ch_refcount;
5416 }
5417 else
5418 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005419 if (channel == NULL)
5420 goto failed;
5421 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005422
5423 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005424 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005425 CREATE_DEFAULT_ERROR_MODE |
5426 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005427 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005428 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005429 &si, &pi,
5430 ga.ga_data,
5431 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005432 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005433 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005434 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005435 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005436 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005437
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005438 ga_clear(&ga);
5439
Bram Moolenaar14207f42016-10-27 21:13:10 +02005440 if (!AssignProcessToJobObject(jo, pi.hProcess))
5441 {
5442 /* if failing, switch the way to terminate
5443 * process with TerminateProcess. */
5444 CloseHandle(jo);
5445 jo = NULL;
5446 }
5447 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005448 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005449 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005450 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005451 job->jv_status = JOB_STARTED;
5452
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005453 CloseHandle(ifd[0]);
5454 CloseHandle(ofd[1]);
5455 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005456 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005457
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005458 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005459 if (channel != NULL)
5460 {
5461 channel_set_pipes(channel,
5462 use_file_for_in || use_null_for_in
5463 ? INVALID_FD : (sock_T)ifd[1],
5464 use_file_for_out || use_null_for_out
5465 ? INVALID_FD : (sock_T)ofd[0],
5466 use_out_for_err || use_file_for_err || use_null_for_err
5467 ? INVALID_FD : (sock_T)efd[0]);
5468 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005469 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005470 return;
5471
5472failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005473 CloseHandle(ifd[0]);
5474 CloseHandle(ofd[0]);
5475 CloseHandle(efd[0]);
5476 CloseHandle(ifd[1]);
5477 CloseHandle(ofd[1]);
5478 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005479 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005480 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005481}
5482
5483 char *
5484mch_job_status(job_T *job)
5485{
5486 DWORD dwExitCode = 0;
5487
Bram Moolenaar76467df2016-02-12 19:30:26 +01005488 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5489 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005490 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005491 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005492 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005493 {
5494 ch_log(job->jv_channel, "Job ended");
5495 job->jv_status = JOB_ENDED;
5496 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005497 return "dead";
5498 }
5499 return "run";
5500}
5501
Bram Moolenaar97792de2016-10-15 18:36:49 +02005502 job_T *
5503mch_detect_ended_job(job_T *job_list)
5504{
5505 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5506 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5507 job_T *job = job_list;
5508
5509 while (job != NULL)
5510 {
5511 DWORD n;
5512 DWORD result;
5513
5514 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5515 && job != NULL; job = job->jv_next)
5516 {
5517 if (job->jv_status == JOB_STARTED)
5518 {
5519 jobHandles[n] = job->jv_proc_info.hProcess;
5520 jobArray[n] = job;
5521 ++n;
5522 }
5523 }
5524 if (n == 0)
5525 continue;
5526 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5527 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5528 {
5529 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5530
5531 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5532 return wait_job;
5533 }
5534 }
5535 return NULL;
5536}
5537
Bram Moolenaarfb630902016-10-29 14:55:00 +02005538 static BOOL
5539terminate_all(HANDLE process, int code)
5540{
5541 PROCESSENTRY32 pe;
5542 HANDLE h = INVALID_HANDLE_VALUE;
5543 DWORD pid = GetProcessId(process);
5544
5545 if (pid != 0)
5546 {
5547 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5548 if (h != INVALID_HANDLE_VALUE)
5549 {
5550 pe.dwSize = sizeof(PROCESSENTRY32);
5551 if (!Process32First(h, &pe))
5552 goto theend;
5553
5554 do
5555 {
5556 if (pe.th32ParentProcessID == pid)
5557 {
5558 HANDLE ph = OpenProcess(
5559 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5560 if (ph != NULL)
5561 {
5562 terminate_all(ph, code);
5563 CloseHandle(ph);
5564 }
5565 }
5566 } while (Process32Next(h, &pe));
5567
5568 CloseHandle(h);
5569 }
5570 }
5571
5572theend:
5573 return TerminateProcess(process, code);
5574}
5575
5576/*
5577 * Send a (deadly) signal to "job".
5578 * Return FAIL if it didn't work.
5579 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005580 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005581mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005582{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005583 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005584
Bram Moolenaar923d9262016-02-25 20:56:01 +01005585 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005586 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005587 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005588 if (job->jv_job_object != NULL)
5589 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005590 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005591 }
5592
5593 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5594 return FAIL;
5595 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005596 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5597 job->jv_proc_info.dwProcessId)
5598 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005599 FreeConsole();
5600 return ret;
5601}
5602
5603/*
5604 * Clear the data related to "job".
5605 */
5606 void
5607mch_clear_job(job_T *job)
5608{
5609 if (job->jv_status != JOB_FAILED)
5610 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005611 if (job->jv_job_object != NULL)
5612 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005613 CloseHandle(job->jv_proc_info.hProcess);
5614 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005615}
5616#endif
5617
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618
5619#ifndef FEAT_GUI_W32
5620
5621/*
5622 * Start termcap mode
5623 */
5624 static void
5625termcap_mode_start(void)
5626{
5627 DWORD cmodein;
5628
5629 if (g_fTermcapMode)
5630 return;
5631
5632 SaveConsoleBuffer(&g_cbNonTermcap);
5633
5634 if (g_cbTermcap.IsValid)
5635 {
5636 /*
5637 * We've been in termcap mode before. Restore certain screen
5638 * characteristics, including the buffer size and the window
5639 * size. Since we will be redrawing the screen, we don't need
5640 * to restore the actual contents of the buffer.
5641 */
5642 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005643 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005644 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5645 Rows = g_cbTermcap.Info.dwSize.Y;
5646 Columns = g_cbTermcap.Info.dwSize.X;
5647 }
5648 else
5649 {
5650 /*
5651 * This is our first time entering termcap mode. Clear the console
5652 * screen buffer, and resize the buffer to match the current window
5653 * size. We will use this as the size of our editing environment.
5654 */
5655 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005656 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5658 }
5659
5660#ifdef FEAT_TITLE
5661 resettitle();
5662#endif
5663
5664 GetConsoleMode(g_hConIn, &cmodein);
5665#ifdef FEAT_MOUSE
5666 if (g_fMouseActive)
5667 cmodein |= ENABLE_MOUSE_INPUT;
5668 else
5669 cmodein &= ~ENABLE_MOUSE_INPUT;
5670#endif
5671 cmodein |= ENABLE_WINDOW_INPUT;
5672 SetConsoleMode(g_hConIn, cmodein);
5673
5674 redraw_later_clear();
5675 g_fTermcapMode = TRUE;
5676}
5677
5678
5679/*
5680 * End termcap mode
5681 */
5682 static void
5683termcap_mode_end(void)
5684{
5685 DWORD cmodein;
5686 ConsoleBuffer *cb;
5687 COORD coord;
5688 DWORD dwDummy;
5689
5690 if (!g_fTermcapMode)
5691 return;
5692
5693 SaveConsoleBuffer(&g_cbTermcap);
5694
5695 GetConsoleMode(g_hConIn, &cmodein);
5696 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5697 SetConsoleMode(g_hConIn, cmodein);
5698
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005699#ifdef FEAT_RESTORE_ORIG_SCREEN
5700 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5701#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005703#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005705 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 SetConsoleCursorInfo(g_hConOut, &g_cci);
5707
5708 if (p_rs || exiting)
5709 {
5710 /*
5711 * Clear anything that happens to be on the current line.
5712 */
5713 coord.X = 0;
5714 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5715 FillConsoleOutputCharacter(g_hConOut, ' ',
5716 cb->Info.dwSize.X, coord, &dwDummy);
5717 /*
5718 * The following is just for aesthetics. If we are exiting without
5719 * restoring the screen, then we want to have a prompt string
5720 * appear at the bottom line. However, the command interpreter
5721 * seems to always advance the cursor one line before displaying
5722 * the prompt string, which causes the screen to scroll. To
5723 * counter this, move the cursor up one line before exiting.
5724 */
5725 if (exiting && !p_rs)
5726 coord.Y--;
5727 /*
5728 * Position the cursor at the leftmost column of the desired row.
5729 */
5730 SetConsoleCursorPosition(g_hConOut, coord);
5731 }
5732
5733 g_fTermcapMode = FALSE;
5734}
5735#endif /* FEAT_GUI_W32 */
5736
5737
5738#ifdef FEAT_GUI_W32
5739 void
5740mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005741 char_u *s UNUSED,
5742 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743{
5744 /* never used */
5745}
5746
5747#else
5748
5749/*
5750 * clear `n' chars, starting from `coord'
5751 */
5752 static void
5753clear_chars(
5754 COORD coord,
5755 DWORD n)
5756{
5757 DWORD dwDummy;
5758
5759 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005760
5761 if (!USE_VTP)
5762 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5763 else
5764 FillConsoleOutputAttribute(g_hConOut, 0, n, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005765}
5766
5767
5768/*
5769 * Clear the screen
5770 */
5771 static void
5772clear_screen(void)
5773{
5774 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005775
5776 if (!USE_VTP)
5777 clear_chars(g_coord, Rows * Columns);
5778 else
5779 {
5780 set_console_color_rgb();
5781 gotoxy(1, 1);
5782 vtp_printf("\033[2J");
5783 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784}
5785
5786
5787/*
5788 * Clear to end of display
5789 */
5790 static void
5791clear_to_end_of_display(void)
5792{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005793 COORD save = g_coord;
5794
5795 if (!USE_VTP)
5796 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005798 else
5799 {
5800 set_console_color_rgb();
5801 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5802 vtp_printf("\033[0J");
5803
5804 gotoxy(save.X + 1, save.Y + 1);
5805 g_coord = save;
5806 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005807}
5808
5809
5810/*
5811 * Clear to end of line
5812 */
5813 static void
5814clear_to_end_of_line(void)
5815{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005816 COORD save = g_coord;
5817
5818 if (!USE_VTP)
5819 clear_chars(g_coord, Columns - g_coord.X);
5820 else
5821 {
5822 set_console_color_rgb();
5823 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5824 vtp_printf("\033[0K");
5825
5826 gotoxy(save.X + 1, save.Y + 1);
5827 g_coord = save;
5828 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829}
5830
5831
5832/*
5833 * Scroll the scroll region up by `cLines' lines
5834 */
5835 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005836scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837{
5838 COORD oldcoord = g_coord;
5839
5840 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5841 delete_lines(cLines);
5842
5843 g_coord = oldcoord;
5844}
5845
5846
5847/*
5848 * Set the scroll region
5849 */
5850 static void
5851set_scroll_region(
5852 unsigned left,
5853 unsigned top,
5854 unsigned right,
5855 unsigned bottom)
5856{
5857 if (left >= right
5858 || top >= bottom
5859 || right > (unsigned) Columns - 1
5860 || bottom > (unsigned) Rows - 1)
5861 return;
5862
5863 g_srScrollRegion.Left = left;
5864 g_srScrollRegion.Top = top;
5865 g_srScrollRegion.Right = right;
5866 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005867
5868 if (USE_VTP)
5869 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005870}
5871
5872
5873/*
5874 * Insert `cLines' lines at the current cursor position
5875 */
5876 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005877insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878{
5879 SMALL_RECT source;
5880 COORD dest;
5881 CHAR_INFO fill;
5882
5883 dest.X = 0;
5884 dest.Y = g_coord.Y + cLines;
5885
5886 source.Left = 0;
5887 source.Top = g_coord.Y;
5888 source.Right = g_srScrollRegion.Right;
5889 source.Bottom = g_srScrollRegion.Bottom - cLines;
5890
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005891 if (!USE_VTP)
5892 {
5893 fill.Char.AsciiChar = ' ';
5894 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005895
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005896 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5897 }
5898 else
5899 {
5900 set_console_color_rgb();
5901
5902 gotoxy(1, source.Top + 1);
5903 vtp_printf("\033[%dT", cLines);
5904 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005905
5906 /* Here we have to deal with a win32 console flake: If the scroll
5907 * region looks like abc and we scroll c to a and fill with d we get
5908 * cbd... if we scroll block c one line at a time to a, we get cdd...
5909 * vim expects cdd consistently... So we have to deal with that
5910 * here... (this also occurs scrolling the same way in the other
5911 * direction). */
5912
5913 if (source.Bottom < dest.Y)
5914 {
5915 COORD coord;
5916
5917 coord.X = 0;
5918 coord.Y = source.Bottom;
5919 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5920 }
5921}
5922
5923
5924/*
5925 * Delete `cLines' lines at the current cursor position
5926 */
5927 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005928delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929{
5930 SMALL_RECT source;
5931 COORD dest;
5932 CHAR_INFO fill;
5933 int nb;
5934
5935 dest.X = 0;
5936 dest.Y = g_coord.Y;
5937
5938 source.Left = 0;
5939 source.Top = g_coord.Y + cLines;
5940 source.Right = g_srScrollRegion.Right;
5941 source.Bottom = g_srScrollRegion.Bottom;
5942
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005943 if (!USE_VTP)
5944 {
5945 fill.Char.AsciiChar = ' ';
5946 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005947
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005948 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5949 }
5950 else
5951 {
5952 set_console_color_rgb();
5953
5954 gotoxy(1, source.Top + 1);
5955 vtp_printf("\033[%dS", cLines);
5956 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005957
5958 /* Here we have to deal with a win32 console flake: If the scroll
5959 * region looks like abc and we scroll c to a and fill with d we get
5960 * cbd... if we scroll block c one line at a time to a, we get cdd...
5961 * vim expects cdd consistently... So we have to deal with that
5962 * here... (this also occurs scrolling the same way in the other
5963 * direction). */
5964
5965 nb = dest.Y + (source.Bottom - source.Top) + 1;
5966
5967 if (nb < source.Top)
5968 {
5969 COORD coord;
5970
5971 coord.X = 0;
5972 coord.Y = nb;
5973 clear_chars(coord, Columns * (source.Top - nb));
5974 }
5975}
5976
5977
5978/*
5979 * Set the cursor position
5980 */
5981 static void
5982gotoxy(
5983 unsigned x,
5984 unsigned y)
5985{
5986 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5987 return;
5988
5989 /* external cursor coords are 1-based; internal are 0-based */
5990 g_coord.X = x - 1;
5991 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005992
5993 if (!USE_VTP)
5994 SetConsoleCursorPosition(g_hConOut, g_coord);
5995 else
5996 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005997}
5998
5999
6000/*
6001 * Set the current text attribute = (foreground | background)
6002 * See ../doc/os_win32.txt for the numbers.
6003 */
6004 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006005textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006007 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008
6009 SetConsoleTextAttribute(g_hConOut, wAttr);
6010}
6011
6012
6013 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006014textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006015{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006016 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006017
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006018 if (!USE_VTP)
6019 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6020 else
6021 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022}
6023
6024
6025 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006026textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006028 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006029
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006030 if (!USE_VTP)
6031 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6032 else
6033 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034}
6035
6036
6037/*
6038 * restore the default text attribute (whatever we started with)
6039 */
6040 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006041normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006043 if (!USE_VTP)
6044 textattr(g_attrDefault);
6045 else
6046 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006047}
6048
6049
6050static WORD g_attrPreStandout = 0;
6051
6052/*
6053 * Make the text standout, by brightening it
6054 */
6055 static void
6056standout(void)
6057{
6058 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006059
Bram Moolenaar071d4272004-06-13 20:20:40 +00006060 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6061}
6062
6063
6064/*
6065 * Turn off standout mode
6066 */
6067 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006068standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069{
6070 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006072
6073 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006074}
6075
6076
6077/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006078 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006079 */
6080 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006081mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006082{
6083 char_u *p;
6084 int n;
6085
6086 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6087 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006088 if (
6089#ifdef FEAT_TERMGUICOLORS
6090 !p_tgc &&
6091#endif
6092 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006093 {
6094 p = T_ME + 2;
6095 n = getdigits(&p);
6096 if (*p == 'm' && n > 0)
6097 {
6098 cterm_normal_fg_color = (n & 0xf) + 1;
6099 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6100 }
6101 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006102#ifdef FEAT_TERMGUICOLORS
6103 cterm_normal_fg_gui_color = INVALCOLOR;
6104 cterm_normal_bg_gui_color = INVALCOLOR;
6105#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106}
6107
6108
6109/*
6110 * visual bell: flash the screen
6111 */
6112 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006113visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114{
6115 COORD coordOrigin = {0, 0};
6116 WORD attrFlash = ~g_attrCurrent & 0xff;
6117
6118 DWORD dwDummy;
6119 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6120
6121 if (oldattrs == NULL)
6122 return;
6123 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6124 coordOrigin, &dwDummy);
6125 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6126 coordOrigin, &dwDummy);
6127
6128 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006129 if (!USE_VTP)
6130 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131 coordOrigin, &dwDummy);
6132 vim_free(oldattrs);
6133}
6134
6135
6136/*
6137 * Make the cursor visible or invisible
6138 */
6139 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006140cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141{
6142 s_cursor_visible = fVisible;
6143#ifdef MCH_CURSOR_SHAPE
6144 mch_update_cursor();
6145#endif
6146}
6147
6148
6149/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006150 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006151 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006153 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006155 char_u *pchBuf,
6156 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157{
6158 COORD coord = g_coord;
6159 DWORD written;
6160
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006161#ifdef FEAT_MBYTE
6162 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6163 {
6164 static WCHAR *unicodebuf = NULL;
6165 static int unibuflen = 0;
6166 int length;
6167 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006169 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6170 if (unicodebuf == NULL || length > unibuflen)
6171 {
6172 vim_free(unicodebuf);
6173 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6174 unibuflen = length;
6175 }
6176 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6177 unicodebuf, unibuflen);
6178
6179 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006180
6181 if (!USE_VTP)
6182 {
6183 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6184 coord, &written);
6185 /* When writing fails or didn't write a single character, pretend one
6186 * character was written, otherwise we get stuck. */
6187 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6188 coord, &cchwritten) == 0
6189 || cchwritten == 0)
6190 cchwritten = 1;
6191 }
6192 else
6193 {
6194 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6195 NULL) == 0 || cchwritten == 0)
6196 cchwritten = 1;
6197 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006198
6199 if (cchwritten == length)
6200 {
6201 written = cbToWrite;
6202 g_coord.X += (SHORT)cells;
6203 }
6204 else
6205 {
6206 char_u *p = pchBuf;
6207 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006208 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006209 written = p - pchBuf;
6210 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6211 }
6212 }
6213 else
6214#endif
6215 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006216 if (!USE_VTP)
6217 {
6218 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6219 coord, &written);
6220 /* When writing fails or didn't write a single character, pretend one
6221 * character was written, otherwise we get stuck. */
6222 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6223 coord, &written) == 0
6224 || written == 0)
6225 written = 1;
6226 }
6227 else
6228 {
6229 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6230 NULL) == 0 || written == 0)
6231 written = 1;
6232 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006233
6234 g_coord.X += (SHORT) written;
6235 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236
6237 while (g_coord.X > g_srScrollRegion.Right)
6238 {
6239 g_coord.X -= (SHORT) Columns;
6240 if (g_coord.Y < g_srScrollRegion.Bottom)
6241 g_coord.Y++;
6242 }
6243
6244 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6245
6246 return written;
6247}
6248
6249
6250/*
6251 * mch_write(): write the output buffer to the screen, translating ESC
6252 * sequences into calls to console output routines.
6253 */
6254 void
6255mch_write(
6256 char_u *s,
6257 int len)
6258{
6259 s[len] = NUL;
6260
6261 if (!term_console)
6262 {
6263 write(1, s, (unsigned)len);
6264 return;
6265 }
6266
6267 /* translate ESC | sequences into faked bios calls */
6268 while (len--)
6269 {
6270 /* optimization: use one single write_chars for runs of text,
6271 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006272 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273
6274 if (p_wd)
6275 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006276 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006277 if (prefix != 0)
6278 prefix = 1;
6279 }
6280
6281 if (prefix != 0)
6282 {
6283 DWORD nWritten;
6284
6285 nWritten = write_chars(s, prefix);
6286#ifdef MCH_WRITE_DUMP
6287 if (fdDump)
6288 {
6289 fputc('>', fdDump);
6290 fwrite(s, sizeof(char_u), nWritten, fdDump);
6291 fputs("<\n", fdDump);
6292 }
6293#endif
6294 len -= (nWritten - 1);
6295 s += nWritten;
6296 }
6297 else if (s[0] == '\n')
6298 {
6299 /* \n, newline: go to the beginning of the next line or scroll */
6300 if (g_coord.Y == g_srScrollRegion.Bottom)
6301 {
6302 scroll(1);
6303 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6304 }
6305 else
6306 {
6307 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6308 }
6309#ifdef MCH_WRITE_DUMP
6310 if (fdDump)
6311 fputs("\\n\n", fdDump);
6312#endif
6313 s++;
6314 }
6315 else if (s[0] == '\r')
6316 {
6317 /* \r, carriage return: go to beginning of line */
6318 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6319#ifdef MCH_WRITE_DUMP
6320 if (fdDump)
6321 fputs("\\r\n", fdDump);
6322#endif
6323 s++;
6324 }
6325 else if (s[0] == '\b')
6326 {
6327 /* \b, backspace: move cursor one position left */
6328 if (g_coord.X > g_srScrollRegion.Left)
6329 g_coord.X--;
6330 else if (g_coord.Y > g_srScrollRegion.Top)
6331 {
6332 g_coord.X = g_srScrollRegion.Right;
6333 g_coord.Y--;
6334 }
6335 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6336#ifdef MCH_WRITE_DUMP
6337 if (fdDump)
6338 fputs("\\b\n", fdDump);
6339#endif
6340 s++;
6341 }
6342 else if (s[0] == '\a')
6343 {
6344 /* \a, bell */
6345 MessageBeep(0xFFFFFFFF);
6346#ifdef MCH_WRITE_DUMP
6347 if (fdDump)
6348 fputs("\\a\n", fdDump);
6349#endif
6350 s++;
6351 }
6352 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6353 {
6354#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006355 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006356#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006357 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006358 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359
6360 switch (s[2])
6361 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362 case '0': case '1': case '2': case '3': case '4':
6363 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006364 p = s + 1;
6365 do
6366 {
6367 ++p;
6368 args[argc] = getdigits(&p);
6369 argc += (argc < 15) ? 1 : 0;
6370 if (p > s + len)
6371 break;
6372 } while (*p == ';');
6373
Bram Moolenaar071d4272004-06-13 20:20:40 +00006374 if (p > s + len)
6375 break;
6376
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006377 arg1 = args[0];
6378 arg2 = args[1];
6379 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006381 if (argc == 1 && args[0] == 0)
6382 normvideo();
6383 else if (argc == 1)
6384 {
6385 if (USE_VTP)
6386 textcolor((WORD) arg1);
6387 else
6388 textattr((WORD) arg1);
6389 }
6390 else if (USE_VTP)
6391 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006392 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006393 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006394 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006395 gotoxy(arg2, arg1);
6396 }
6397 else if (argc == 2 && *p == 'r')
6398 {
6399 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6400 }
6401 else if (argc == 1 && *p == 'A')
6402 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403 gotoxy(g_coord.X + 1,
6404 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6405 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006406 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407 {
6408 textbackground((WORD) arg1);
6409 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006410 else if (argc == 1 && *p == 'C')
6411 {
6412 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6413 g_coord.Y + 1);
6414 }
6415 else if (argc == 1 && *p == 'f')
6416 {
6417 textcolor((WORD) arg1);
6418 }
6419 else if (argc == 1 && *p == 'H')
6420 {
6421 gotoxy(1, arg1);
6422 }
6423 else if (argc == 1 && *p == 'L')
6424 {
6425 insert_lines(arg1);
6426 }
6427 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428 {
6429 delete_lines(arg1);
6430 }
6431
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006432 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006433 s = p + 1;
6434 break;
6435
Bram Moolenaar071d4272004-06-13 20:20:40 +00006436 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006437 gotoxy(g_coord.X + 1,
6438 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6439 goto got3;
6440
6441 case 'B':
6442 visual_bell();
6443 goto got3;
6444
6445 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006446 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6447 g_coord.Y + 1);
6448 goto got3;
6449
6450 case 'E':
6451 termcap_mode_end();
6452 goto got3;
6453
6454 case 'F':
6455 standout();
6456 goto got3;
6457
6458 case 'f':
6459 standend();
6460 goto got3;
6461
6462 case 'H':
6463 gotoxy(1, 1);
6464 goto got3;
6465
6466 case 'j':
6467 clear_to_end_of_display();
6468 goto got3;
6469
6470 case 'J':
6471 clear_screen();
6472 goto got3;
6473
6474 case 'K':
6475 clear_to_end_of_line();
6476 goto got3;
6477
6478 case 'L':
6479 insert_lines(1);
6480 goto got3;
6481
6482 case 'M':
6483 delete_lines(1);
6484 goto got3;
6485
6486 case 'S':
6487 termcap_mode_start();
6488 goto got3;
6489
6490 case 'V':
6491 cursor_visible(TRUE);
6492 goto got3;
6493
6494 case 'v':
6495 cursor_visible(FALSE);
6496 goto got3;
6497
6498 got3:
6499 s += 3;
6500 len -= 2;
6501 }
6502
6503#ifdef MCH_WRITE_DUMP
6504 if (fdDump)
6505 {
6506 fputs("ESC | ", fdDump);
6507 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6508 fputc('\n', fdDump);
6509 }
6510#endif
6511 }
6512 else
6513 {
6514 /* Write a single character */
6515 DWORD nWritten;
6516
6517 nWritten = write_chars(s, 1);
6518#ifdef MCH_WRITE_DUMP
6519 if (fdDump)
6520 {
6521 fputc('>', fdDump);
6522 fwrite(s, sizeof(char_u), nWritten, fdDump);
6523 fputs("<\n", fdDump);
6524 }
6525#endif
6526
6527 len -= (nWritten - 1);
6528 s += nWritten;
6529 }
6530 }
6531
6532#ifdef MCH_WRITE_DUMP
6533 if (fdDump)
6534 fflush(fdDump);
6535#endif
6536}
6537
6538#endif /* FEAT_GUI_W32 */
6539
6540
6541/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006542 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 */
6544 void
6545mch_delay(
6546 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006547 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548{
6549#ifdef FEAT_GUI_W32
6550 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006551#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006553# ifdef FEAT_MZSCHEME
6554 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6555 {
6556 int towait = p_mzq;
6557
6558 /* if msec is large enough, wait by portions in p_mzq */
6559 while (msec > 0)
6560 {
6561 mzvim_check_threads();
6562 if (msec < towait)
6563 towait = msec;
6564 Sleep(towait);
6565 msec -= towait;
6566 }
6567 }
6568 else
6569# endif
6570 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006572 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006573#endif
6574}
6575
6576
6577/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006578 * This version of remove is not scared by a readonly (backup) file.
6579 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580 * Return 0 for success, -1 for failure.
6581 */
6582 int
6583mch_remove(char_u *name)
6584{
6585#ifdef FEAT_MBYTE
6586 WCHAR *wn = NULL;
6587 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006588#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589
Bram Moolenaar203258c2016-01-17 22:15:16 +01006590 /*
6591 * On Windows, deleting a directory's symbolic link is done by
6592 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6593 */
6594 if (mch_isdir(name) && mch_is_symbolic_link(name))
6595 return mch_rmdir(name);
6596
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006597 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6598
6599#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6601 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006602 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603 if (wn != NULL)
6604 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 n = DeleteFileW(wn) ? 0 : -1;
6606 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006607 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608 }
6609 }
6610#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006611 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612}
6613
6614
6615/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006616 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 */
6618 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006619mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620{
6621#ifndef FEAT_GUI_W32 /* never used */
6622 if (g_fCtrlCPressed || g_fCBrkPressed)
6623 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006624 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6626 got_int = TRUE;
6627 }
6628#endif
6629}
6630
Bram Moolenaaree273972016-01-02 21:11:51 +01006631/* physical RAM to leave for the OS */
6632#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006633
6634/*
6635 * How much main memory in KiB that can be used by VIM.
6636 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006637 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006638mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006639{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006640 MEMORYSTATUSEX ms;
6641
Bram Moolenaaree273972016-01-02 21:11:51 +01006642 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006643 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6644 * what fits in 32 bits. But it's not always available. */
6645 ms.dwLength = sizeof(MEMORYSTATUSEX);
6646 GlobalMemoryStatusEx(&ms);
6647 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006648 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006649 /* Process address space fits in physical RAM, use all of it. */
6650 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006651 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006652 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006653 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006654 /* Catch old NT box or perverse hardware setup. */
6655 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006656 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006657 /* Use physical RAM less reserve for OS + data. */
6658 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006659}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006660
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661#ifdef FEAT_MBYTE
6662/*
6663 * Same code as below, but with wide functions and no comments.
6664 * Return 0 for success, non-zero for failure.
6665 */
6666 int
6667mch_wrename(WCHAR *wold, WCHAR *wnew)
6668{
6669 WCHAR *p;
6670 int i;
6671 WCHAR szTempFile[_MAX_PATH + 1];
6672 WCHAR szNewPath[_MAX_PATH + 1];
6673 HANDLE hf;
6674
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006675 p = wold;
6676 for (i = 0; wold[i] != NUL; ++i)
6677 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6678 && wold[i + 1] != 0)
6679 p = wold + i + 1;
6680 if ((int)(wold + i - p) < 8 || p[6] != '~')
6681 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682
6683 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6684 return -1;
6685 *p = NUL;
6686
6687 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6688 return -2;
6689
6690 if (!DeleteFileW(szTempFile))
6691 return -3;
6692
6693 if (!MoveFileW(wold, szTempFile))
6694 return -4;
6695
6696 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6697 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6698 return -5;
6699 if (!CloseHandle(hf))
6700 return -6;
6701
6702 if (!MoveFileW(szTempFile, wnew))
6703 {
6704 (void)MoveFileW(szTempFile, wold);
6705 return -7;
6706 }
6707
6708 DeleteFileW(szTempFile);
6709
6710 if (!DeleteFileW(wold))
6711 return -8;
6712
6713 return 0;
6714}
6715#endif
6716
6717
6718/*
6719 * mch_rename() works around a bug in rename (aka MoveFile) in
6720 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6721 * file whose short file name is "FOO.BAR" (its long file name will
6722 * be correct: "foo.bar~"). Because a file can be accessed by
6723 * either its SFN or its LFN, "foo.bar" has effectively been
6724 * renamed to "foo.bar", which is not at all what was wanted. This
6725 * seems to happen only when renaming files with three-character
6726 * extensions by appending a suffix that does not include ".".
6727 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6728 *
6729 * There is another problem, which isn't really a bug but isn't right either:
6730 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6731 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6732 * service pack 6. Doesn't seem to happen on Windows 98.
6733 *
6734 * Like rename(), returns 0 upon success, non-zero upon failure.
6735 * Should probably set errno appropriately when errors occur.
6736 */
6737 int
6738mch_rename(
6739 const char *pszOldFile,
6740 const char *pszNewFile)
6741{
6742 char szTempFile[_MAX_PATH+1];
6743 char szNewPath[_MAX_PATH+1];
6744 char *pszFilePart;
6745 HANDLE hf;
6746#ifdef FEAT_MBYTE
6747 WCHAR *wold = NULL;
6748 WCHAR *wnew = NULL;
6749 int retval = -1;
6750
6751 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6752 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006753 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6754 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755 if (wold != NULL && wnew != NULL)
6756 retval = mch_wrename(wold, wnew);
6757 vim_free(wold);
6758 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006759 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760 }
6761#endif
6762
6763 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006764 * No need to play tricks unless the file name contains a "~" as the
6765 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006767 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6768 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6769 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770
6771 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6772 * a directory, no error is returned and pszFilePart will be NULL. */
6773 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6774 || pszFilePart == NULL)
6775 return -1;
6776 *pszFilePart = NUL;
6777
6778 /* Get (and create) a unique temporary file name in directory of new file */
6779 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6780 return -2;
6781
6782 /* blow the temp file away */
6783 if (!DeleteFile(szTempFile))
6784 return -3;
6785
6786 /* rename old file to the temp file */
6787 if (!MoveFile(pszOldFile, szTempFile))
6788 return -4;
6789
6790 /* now create an empty file called pszOldFile; this prevents the operating
6791 * system using pszOldFile as an alias (SFN) if we're renaming within the
6792 * same directory. For example, we're editing a file called
6793 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6794 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6795 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006796 * cause all sorts of problems later in buf_write(). So, we create an
6797 * empty file called filena~1.txt and the system will have to find some
6798 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799 */
6800 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6801 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6802 return -5;
6803 if (!CloseHandle(hf))
6804 return -6;
6805
6806 /* rename the temp file to the new file */
6807 if (!MoveFile(szTempFile, pszNewFile))
6808 {
6809 /* Renaming failed. Rename the file back to its old name, so that it
6810 * looks like nothing happened. */
6811 (void)MoveFile(szTempFile, pszOldFile);
6812
6813 return -7;
6814 }
6815
6816 /* Seems to be left around on Novell filesystems */
6817 DeleteFile(szTempFile);
6818
6819 /* finally, remove the empty old file */
6820 if (!DeleteFile(pszOldFile))
6821 return -8;
6822
6823 return 0; /* success */
6824}
6825
6826/*
6827 * Get the default shell for the current hardware platform
6828 */
6829 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006830default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006832 PlatformId();
6833
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006834 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835}
6836
6837/*
6838 * mch_access() extends access() to do more detailed check on network drives.
6839 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6840 */
6841 int
6842mch_access(char *n, int p)
6843{
6844 HANDLE hFile;
6845 DWORD am;
6846 int retval = -1; /* default: fail */
6847#ifdef FEAT_MBYTE
6848 WCHAR *wn = NULL;
6849
6850 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006851 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852#endif
6853
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006854 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 {
6856 char TempName[_MAX_PATH + 16] = "";
6857#ifdef FEAT_MBYTE
6858 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6859#endif
6860
6861 if (p & R_OK)
6862 {
6863 /* Read check is performed by seeing if we can do a find file on
6864 * the directory for any file. */
6865#ifdef FEAT_MBYTE
6866 if (wn != NULL)
6867 {
6868 int i;
6869 WIN32_FIND_DATAW d;
6870
6871 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6872 TempNameW[i] = wn[i];
6873 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6874 TempNameW[i++] = '\\';
6875 TempNameW[i++] = '*';
6876 TempNameW[i++] = 0;
6877
6878 hFile = FindFirstFileW(TempNameW, &d);
6879 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006880 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 else
6882 (void)FindClose(hFile);
6883 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006884 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885#endif
6886 {
6887 char *pch;
6888 WIN32_FIND_DATA d;
6889
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006890 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891 pch = TempName + STRLEN(TempName) - 1;
6892 if (*pch != '\\' && *pch != '/')
6893 *++pch = '\\';
6894 *++pch = '*';
6895 *++pch = NUL;
6896
6897 hFile = FindFirstFile(TempName, &d);
6898 if (hFile == INVALID_HANDLE_VALUE)
6899 goto getout;
6900 (void)FindClose(hFile);
6901 }
6902 }
6903
6904 if (p & W_OK)
6905 {
6906 /* Trying to create a temporary file in the directory should catch
6907 * directories on read-only network shares. However, in
6908 * directories whose ACL allows writes but denies deletes will end
6909 * up keeping the temporary file :-(. */
6910#ifdef FEAT_MBYTE
6911 if (wn != NULL)
6912 {
6913 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006914 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 else
6916 DeleteFileW(TempNameW);
6917 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006918 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919#endif
6920 {
6921 if (!GetTempFileName(n, "VIM", 0, TempName))
6922 goto getout;
6923 mch_remove((char_u *)TempName);
6924 }
6925 }
6926 }
6927 else
6928 {
6929 /* Trying to open the file for the required access does ACL, read-only
6930 * network share, and file attribute checks. */
6931 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6932 | ((p & R_OK) ? GENERIC_READ : 0);
6933#ifdef FEAT_MBYTE
6934 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006936 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937#endif
6938 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6939 if (hFile == INVALID_HANDLE_VALUE)
6940 goto getout;
6941 CloseHandle(hFile);
6942 }
6943
6944 retval = 0; /* success */
6945getout:
6946#ifdef FEAT_MBYTE
6947 vim_free(wn);
6948#endif
6949 return retval;
6950}
6951
6952#if defined(FEAT_MBYTE) || defined(PROTO)
6953/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006954 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955 */
6956 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006957mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006958{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006959 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6960# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961 WCHAR *wn;
6962 int f;
6963
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006964 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006965 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006966 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006967 if (wn != NULL)
6968 {
6969 f = _wopen(wn, flags, mode);
6970 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006971 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972 }
6973 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006974# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006976 /* open() can open a file which name is longer than _MAX_PATH bytes
6977 * and shorter than _MAX_PATH characters successfully, but sometimes it
6978 * causes unexpected error in another part. We make it an error explicitly
6979 * here. */
6980 if (strlen(name) >= _MAX_PATH)
6981 return -1;
6982
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983 return open(name, flags, mode);
6984}
6985
6986/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006987 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006988 */
6989 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006990mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006991{
6992 WCHAR *wn, *wm;
6993 FILE *f = NULL;
6994
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006995 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006996 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006997# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006998 /* Work around an annoying assertion in the Microsoft debug CRT
6999 * when mode's text/binary setting doesn't match _get_fmode(). */
7000 char newMode = mode[strlen(mode) - 1];
7001 int oldMode = 0;
7002
7003 _get_fmode(&oldMode);
7004 if (newMode == 't')
7005 _set_fmode(_O_TEXT);
7006 else if (newMode == 'b')
7007 _set_fmode(_O_BINARY);
7008# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007009 wn = enc_to_utf16((char_u *)name, NULL);
7010 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 if (wn != NULL && wm != NULL)
7012 f = _wfopen(wn, wm);
7013 vim_free(wn);
7014 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007015
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007016# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007017 _set_fmode(oldMode);
7018# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007019 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020 }
7021
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007022 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7023 * and shorter than _MAX_PATH characters successfully, but sometimes it
7024 * causes unexpected error in another part. We make it an error explicitly
7025 * here. */
7026 if (strlen(name) >= _MAX_PATH)
7027 return NULL;
7028
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029 return fopen(name, mode);
7030}
7031#endif
7032
7033#ifdef FEAT_MBYTE
7034/*
7035 * SUB STREAM (aka info stream) handling:
7036 *
7037 * NTFS can have sub streams for each file. Normal contents of file is
7038 * stored in the main stream, and extra contents (author information and
7039 * title and so on) can be stored in sub stream. After Windows 2000, user
7040 * can access and store those informations in sub streams via explorer's
7041 * property menuitem in right click menu. Those informations in sub streams
7042 * were lost when copying only the main stream. So we have to copy sub
7043 * streams.
7044 *
7045 * Incomplete explanation:
7046 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7047 * More useful info and an example:
7048 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7049 */
7050
7051/*
7052 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7053 * and write to stream "substream" of file "to".
7054 * Errors are ignored.
7055 */
7056 static void
7057copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7058{
7059 HANDLE hTo;
7060 WCHAR *to_name;
7061
7062 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7063 wcscpy(to_name, to);
7064 wcscat(to_name, substream);
7065
7066 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7067 FILE_ATTRIBUTE_NORMAL, NULL);
7068 if (hTo != INVALID_HANDLE_VALUE)
7069 {
7070 long done;
7071 DWORD todo;
7072 DWORD readcnt, written;
7073 char buf[4096];
7074
7075 /* Copy block of bytes at a time. Abort when something goes wrong. */
7076 for (done = 0; done < len; done += written)
7077 {
7078 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007079 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7080 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7082 FALSE, FALSE, context)
7083 || readcnt != todo
7084 || !WriteFile(hTo, buf, todo, &written, NULL)
7085 || written != todo)
7086 break;
7087 }
7088 CloseHandle(hTo);
7089 }
7090
7091 free(to_name);
7092}
7093
7094/*
7095 * Copy info streams from file "from" to file "to".
7096 */
7097 static void
7098copy_infostreams(char_u *from, char_u *to)
7099{
7100 WCHAR *fromw;
7101 WCHAR *tow;
7102 HANDLE sh;
7103 WIN32_STREAM_ID sid;
7104 int headersize;
7105 WCHAR streamname[_MAX_PATH];
7106 DWORD readcount;
7107 void *context = NULL;
7108 DWORD lo, hi;
7109 int len;
7110
7111 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007112 fromw = enc_to_utf16(from, NULL);
7113 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114 if (fromw != NULL && tow != NULL)
7115 {
7116 /* Open the file for reading. */
7117 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7118 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7119 if (sh != INVALID_HANDLE_VALUE)
7120 {
7121 /* Use BackupRead() to find the info streams. Repeat until we
7122 * have done them all.*/
7123 for (;;)
7124 {
7125 /* Get the header to find the length of the stream name. If
7126 * the "readcount" is zero we have done all info streams. */
7127 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007128 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7130 &readcount, FALSE, FALSE, &context)
7131 || readcount == 0)
7132 break;
7133
7134 /* We only deal with streams that have a name. The normal
7135 * file data appears to be without a name, even though docs
7136 * suggest it is called "::$DATA". */
7137 if (sid.dwStreamNameSize > 0)
7138 {
7139 /* Read the stream name. */
7140 if (!BackupRead(sh, (LPBYTE)streamname,
7141 sid.dwStreamNameSize,
7142 &readcount, FALSE, FALSE, &context))
7143 break;
7144
7145 /* Copy an info stream with a name ":anything:$DATA".
7146 * Skip "::$DATA", it has no stream name (examples suggest
7147 * it might be used for the normal file contents).
7148 * Note that BackupRead() counts bytes, but the name is in
7149 * wide characters. */
7150 len = readcount / sizeof(WCHAR);
7151 streamname[len] = 0;
7152 if (len > 7 && wcsicmp(streamname + len - 6,
7153 L":$DATA") == 0)
7154 {
7155 streamname[len - 6] = 0;
7156 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007157 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 }
7159 }
7160
7161 /* Advance to the next stream. We might try seeking too far,
7162 * but BackupSeek() doesn't skip over stream borders, thus
7163 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007164 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007165 &lo, &hi, &context);
7166 }
7167
7168 /* Clear the context. */
7169 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7170
7171 CloseHandle(sh);
7172 }
7173 }
7174 vim_free(fromw);
7175 vim_free(tow);
7176}
7177#endif
7178
7179/*
7180 * Copy file attributes from file "from" to file "to".
7181 * For Windows NT and later we copy info streams.
7182 * Always returns zero, errors are ignored.
7183 */
7184 int
7185mch_copy_file_attribute(char_u *from, char_u *to)
7186{
7187#ifdef FEAT_MBYTE
7188 /* File streams only work on Windows NT and later. */
7189 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007190 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007191#endif
7192 return 0;
7193}
7194
7195#if defined(MYRESETSTKOFLW) || defined(PROTO)
7196/*
7197 * Recreate a destroyed stack guard page in win32.
7198 * Written by Benjamin Peterson.
7199 */
7200
7201/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007202#define MIN_STACK_WINNT 2
7203
7204/*
7205 * This function does the same thing as _resetstkoflw(), which is only
7206 * available in DevStudio .net and later.
7207 * Returns 0 for failure, 1 for success.
7208 */
7209 int
7210myresetstkoflw(void)
7211{
7212 BYTE *pStackPtr;
7213 BYTE *pGuardPage;
7214 BYTE *pStackBase;
7215 BYTE *pLowestPossiblePage;
7216 MEMORY_BASIC_INFORMATION mbi;
7217 SYSTEM_INFO si;
7218 DWORD nPageSize;
7219 DWORD dummy;
7220
Bram Moolenaar071d4272004-06-13 20:20:40 +00007221 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007222
7223 /* We need to know the system page size. */
7224 GetSystemInfo(&si);
7225 nPageSize = si.dwPageSize;
7226
7227 /* ...and the current stack pointer */
7228 pStackPtr = (BYTE*)_alloca(1);
7229
7230 /* ...and the base of the stack. */
7231 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7232 return 0;
7233 pStackBase = (BYTE*)mbi.AllocationBase;
7234
7235 /* ...and the page thats min_stack_req pages away from stack base; this is
7236 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007237 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007240 /* We want the first committed page in the stack Start at the stack
7241 * base and move forward through memory until we find a committed block.
7242 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007243 BYTE *pBlock = pStackBase;
7244
Bram Moolenaara466c992005-07-09 21:03:22 +00007245 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246 {
7247 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7248 return 0;
7249
7250 pBlock += mbi.RegionSize;
7251
7252 if (mbi.State & MEM_COMMIT)
7253 break;
7254 }
7255
7256 /* mbi now describes the first committed block in the stack. */
7257 if (mbi.Protect & PAGE_GUARD)
7258 return 1;
7259
7260 /* decide where the guard page should start */
7261 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7262 pGuardPage = pLowestPossiblePage;
7263 else
7264 pGuardPage = (BYTE*)mbi.BaseAddress;
7265
7266 /* allocate the guard page */
7267 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7268 return 0;
7269
7270 /* apply the guard attribute to the page */
7271 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7272 &dummy))
7273 return 0;
7274 }
7275
7276 return 1;
7277}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007278#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007279
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007280
7281#if defined(FEAT_MBYTE) || defined(PROTO)
7282/*
7283 * The command line arguments in UCS2
7284 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007285static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007286static LPWSTR *ArglistW = NULL;
7287static int global_argc = 0;
7288static char **global_argv;
7289
7290static int used_file_argc = 0; /* last argument in global_argv[] used
7291 for the argument list. */
7292static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7293 command line arguments added to
7294 the argument list */
7295static int used_file_count = 0; /* nr of entries in used_file_indexes */
7296static int used_file_literal = FALSE; /* take file names literally */
7297static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007298static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007299static int used_alist_count = 0;
7300
7301
7302/*
7303 * Get the command line arguments. Unicode version.
7304 * Returns argc. Zero when something fails.
7305 */
7306 int
7307get_cmd_argsW(char ***argvp)
7308{
7309 char **argv = NULL;
7310 int argc = 0;
7311 int i;
7312
Bram Moolenaar14993322014-09-09 12:25:33 +02007313 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007314 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7315 if (ArglistW != NULL)
7316 {
7317 argv = malloc((nArgsW + 1) * sizeof(char *));
7318 if (argv != NULL)
7319 {
7320 argc = nArgsW;
7321 argv[argc] = NULL;
7322 for (i = 0; i < argc; ++i)
7323 {
7324 int len;
7325
7326 /* Convert each Unicode argument to the current codepage. */
7327 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007328 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007329 (LPSTR *)&argv[i], &len, 0, 0);
7330 if (argv[i] == NULL)
7331 {
7332 /* Out of memory, clear everything. */
7333 while (i > 0)
7334 free(argv[--i]);
7335 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007336 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007337 argc = 0;
7338 }
7339 }
7340 }
7341 }
7342
7343 global_argc = argc;
7344 global_argv = argv;
7345 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007346 {
7347 if (used_file_indexes != NULL)
7348 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007349 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007350 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007351
7352 if (argvp != NULL)
7353 *argvp = argv;
7354 return argc;
7355}
7356
7357 void
7358free_cmd_argsW(void)
7359{
7360 if (ArglistW != NULL)
7361 {
7362 GlobalFree(ArglistW);
7363 ArglistW = NULL;
7364 }
7365}
7366
7367/*
7368 * Remember "name" is an argument that was added to the argument list.
7369 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7370 * is called.
7371 */
7372 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007373used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007374{
7375 int i;
7376
7377 if (used_file_indexes == NULL)
7378 return;
7379 for (i = used_file_argc + 1; i < global_argc; ++i)
7380 if (STRCMP(global_argv[i], name) == 0)
7381 {
7382 used_file_argc = i;
7383 used_file_indexes[used_file_count++] = i;
7384 break;
7385 }
7386 used_file_literal = literal;
7387 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007388 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007389}
7390
7391/*
7392 * Remember the length of the argument list as it was. If it changes then we
7393 * leave it alone when 'encoding' is set.
7394 */
7395 void
7396set_alist_count(void)
7397{
7398 used_alist_count = GARGCOUNT;
7399}
7400
7401/*
7402 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7403 * has been changed while starting up. Use the UCS-2 command line arguments
7404 * and convert them to 'encoding'.
7405 */
7406 void
7407fix_arg_enc(void)
7408{
7409 int i;
7410 int idx;
7411 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007412 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007413
7414 /* Safety checks:
7415 * - if argument count differs between the wide and non-wide argument
7416 * list, something must be wrong.
7417 * - the file name arguments must have been located.
7418 * - the length of the argument list wasn't changed by the user.
7419 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007420 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007421 || ArglistW == NULL
7422 || used_file_indexes == NULL
7423 || used_file_count == 0
7424 || used_alist_count != GARGCOUNT)
7425 return;
7426
Bram Moolenaar86b68352004-12-27 21:59:20 +00007427 /* Remember the buffer numbers for the arguments. */
7428 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7429 if (fnum_list == NULL)
7430 return; /* out of memory */
7431 for (i = 0; i < GARGCOUNT; ++i)
7432 fnum_list[i] = GARGLIST[i].ae_fnum;
7433
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007434 /* Clear the argument list. Make room for the new arguments. */
7435 alist_clear(&global_alist);
7436 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007437 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007438
7439 for (i = 0; i < used_file_count; ++i)
7440 {
7441 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007442 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007443 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007444 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007445 int literal = used_file_literal;
7446
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007447#ifdef FEAT_DIFF
7448 /* When using diff mode may need to concatenate file name to
7449 * directory name. Just like it's done in main(). */
7450 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7451 && !mch_isdir(alist_name(&GARGLIST[0])))
7452 {
7453 char_u *r;
7454
7455 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7456 if (r != NULL)
7457 {
7458 vim_free(str);
7459 str = r;
7460 }
7461 }
7462#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007463 /* Re-use the old buffer by renaming it. When not using literal
7464 * names it's done by alist_expand() below. */
7465 if (used_file_literal)
7466 buf_set_name(fnum_list[i], str);
7467
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007468 /* Check backtick literal. backtick literal is already expanded in
7469 * main.c, so this part add str as literal. */
7470 if (literal == FALSE)
7471 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007472 size_t len = STRLEN(str);
7473
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007474 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7475 literal = TRUE;
7476 }
7477 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007478 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007479 }
7480
7481 if (!used_file_literal)
7482 {
7483 /* Now expand wildcards in the arguments. */
7484 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7485 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007486 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7487 * Also, unset wildignore to not be influenced by this option.
7488 * The arguments specified in command-line should be kept even if
7489 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007490 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007491 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007492 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007493 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007494 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007495 }
7496
7497 /* If wildcard expansion failed, we are editing the first file of the
7498 * arglist and there is no file name: Edit the first argument now. */
7499 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7500 {
7501 do_cmdline_cmd((char_u *)":rewind");
7502 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007503 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007504 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007505
7506 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007507}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007509
7510 int
7511mch_setenv(char *var, char *value, int x)
7512{
7513 char_u *envbuf;
7514
7515 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7516 if (envbuf == NULL)
7517 return -1;
7518
7519 sprintf((char *)envbuf, "%s=%s", var, value);
7520
7521#ifdef FEAT_MBYTE
7522 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7523 {
7524 WCHAR *p = enc_to_utf16(envbuf, NULL);
7525
7526 vim_free(envbuf);
7527 if (p == NULL)
7528 return -1;
7529 _wputenv(p);
7530# ifdef libintl_wputenv
7531 libintl_wputenv(p);
7532# endif
7533 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7534 vim_free(p);
7535 }
7536 else
7537#endif
7538 {
7539 _putenv((char *)envbuf);
7540# ifdef libintl_putenv
7541 libintl_putenv((char *)envbuf);
7542# endif
7543 /* Unlike Un*x systems, we can free the string for _putenv(). */
7544 vim_free(envbuf);
7545 }
7546
7547 return 0;
7548}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007549
7550#ifndef FEAT_GUI_W32
7551
7552/*
7553 * Support for 256 colors and 24-bit colors was added in Windows 10
7554 * version 1703 (Creators update).
7555 */
7556# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7557
7558 static void
7559vtp_init(void)
7560{
7561 DWORD ver, mode;
7562 HMODULE hKerneldll;
7563 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7564
7565 ver = get_build_number();
7566 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7567 GetConsoleMode(g_hConOut, &mode);
7568 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7569 if (SetConsoleMode(g_hConOut, mode) == 0)
7570 vtp_working = 0;
7571
7572 /* Use functions supported from Vista */
7573 hKerneldll = GetModuleHandle("kernel32.dll");
7574 if (hKerneldll != NULL)
7575 {
7576 pGetConsoleScreenBufferInfoEx =
7577 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7578 hKerneldll, "GetConsoleScreenBufferInfoEx");
7579 pSetConsoleScreenBufferInfoEx =
7580 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7581 hKerneldll, "SetConsoleScreenBufferInfoEx");
7582 if (pGetConsoleScreenBufferInfoEx != NULL
7583 && pSetConsoleScreenBufferInfoEx != NULL)
7584 has_csbiex = TRUE;
7585 }
7586
7587 csbi.cbSize = sizeof(csbi);
7588 if (has_csbiex)
7589 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7590 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[0];
7591 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[7];
7592
7593 set_console_color_rgb();
7594}
7595
7596 static void
7597vtp_exit(void)
7598{
7599 reset_console_color_rgb();
7600}
7601
7602 static int
7603vtp_printf(
7604 char *format,
7605 ...)
7606{
7607 char_u buf[100];
7608 va_list list;
7609 DWORD result;
7610
7611 va_start(list, format);
7612 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7613 va_end(list);
7614 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7615 return (int)result;
7616}
7617
7618 static void
7619vtp_sgr_bulk(
7620 int arg)
7621{
7622 int args[1];
7623
7624 args[0] = arg;
7625 vtp_sgr_bulks(1, args);
7626}
7627
7628 static void
7629vtp_sgr_bulks(
7630 int argc,
7631 int *args
7632)
7633{
7634 /* 2('\033[') + 4('255.') * 16 + NUL */
7635 char_u buf[2 + (4 * 16) + 1];
7636 char_u *p;
7637 int i;
7638
7639 p = buf;
7640 *p++ = '\033';
7641 *p++ = '[';
7642
7643 for (i = 0; i < argc; ++i)
7644 {
7645 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7646 *p++ = ';';
7647 }
7648 p--;
7649 *p++ = 'm';
7650 *p = NUL;
7651 vtp_printf((char *)buf);
7652}
7653
7654 static void
7655set_console_color_rgb(void)
7656{
7657# ifdef FEAT_TERMGUICOLORS
7658 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7659 int id;
7660 guicolor_T fg = INVALCOLOR;
7661 guicolor_T bg = INVALCOLOR;
7662
7663 if (!USE_VTP)
7664 return;
7665
7666 id = syn_name2id((char_u *)"Normal");
7667 if (id > 0)
7668 syn_id2colors(id, &fg, &bg);
7669 if (fg == INVALCOLOR)
7670 fg = 0xc0c0c0; /* white text */
7671 if (bg == INVALCOLOR)
7672 bg = 0x000000; /* black background */
7673 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7674 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7675
7676 csbi.cbSize = sizeof(csbi);
7677 if (has_csbiex)
7678 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7679
7680 csbi.cbSize = sizeof(csbi);
7681 csbi.srWindow.Right += 1;
7682 csbi.srWindow.Bottom += 1;
7683 csbi.ColorTable[0] = (COLORREF)bg;
7684 csbi.ColorTable[7] = (COLORREF)fg;
7685 if (has_csbiex)
7686 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7687# endif
7688}
7689
7690 static void
7691reset_console_color_rgb(void)
7692{
7693# ifdef FEAT_TERMGUICOLORS
7694 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7695
7696 csbi.cbSize = sizeof(csbi);
7697 if (has_csbiex)
7698 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7699
7700 csbi.cbSize = sizeof(csbi);
7701 csbi.srWindow.Right += 1;
7702 csbi.srWindow.Bottom += 1;
7703 csbi.ColorTable[0] = (COLORREF)save_console_bg_rgb;
7704 csbi.ColorTable[7] = (COLORREF)save_console_fg_rgb;
7705 if (has_csbiex)
7706 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7707# endif
7708}
7709
7710 void
7711control_console_color_rgb(void)
7712{
7713 if (USE_VTP)
7714 set_console_color_rgb();
7715 else
7716 reset_console_color_rgb();
7717}
7718
7719 int
7720has_vtp_working(void)
7721{
7722 return vtp_working;
7723}
7724
7725 int
7726use_vtp(void)
7727{
7728 return USE_VTP;
7729}
7730
7731#endif