blob: 0de3d6493e021bf176290ca29ead115e926c825c [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
53#ifdef __MINGW32__
54# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
55# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
56# endif
57# ifndef RIGHTMOST_BUTTON_PRESSED
58# define RIGHTMOST_BUTTON_PRESSED 0x0002
59# endif
60# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
61# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
62# endif
63# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
64# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
65# endif
66# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
67# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
68# endif
69
70/*
71 * EventFlags
72 */
73# ifndef MOUSE_MOVED
74# define MOUSE_MOVED 0x0001
75# endif
76# ifndef DOUBLE_CLICK
77# define DOUBLE_CLICK 0x0002
78# endif
79#endif
80
81/* Record all output and all keyboard & mouse input */
82/* #define MCH_WRITE_DUMP */
83
84#ifdef MCH_WRITE_DUMP
85FILE* fdDump = NULL;
86#endif
87
88/*
89 * When generating prototypes for Win32 on Unix, these lines make the syntax
90 * errors disappear. They do not need to be correct.
91 */
92#ifdef PROTO
93#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000094typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000095typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000096typedef int ACCESS_MASK;
97typedef int BOOL;
98typedef int COLORREF;
99typedef int CONSOLE_CURSOR_INFO;
100typedef int COORD;
101typedef int DWORD;
102typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100103typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000104typedef int HDC;
105typedef int HFONT;
106typedef int HICON;
107typedef int HINSTANCE;
108typedef int HWND;
109typedef int INPUT_RECORD;
110typedef int KEY_EVENT_RECORD;
111typedef int LOGFONT;
112typedef int LPBOOL;
113typedef int LPCTSTR;
114typedef int LPDWORD;
115typedef int LPSTR;
116typedef int LPTSTR;
117typedef int LPVOID;
118typedef int MOUSE_EVENT_RECORD;
119typedef int PACL;
120typedef int PDWORD;
121typedef int PHANDLE;
122typedef int PRINTDLG;
123typedef int PSECURITY_DESCRIPTOR;
124typedef int PSID;
125typedef int SECURITY_INFORMATION;
126typedef int SHORT;
127typedef int SMALL_RECT;
128typedef int TEXTMETRIC;
129typedef int TOKEN_INFORMATION_CLASS;
130typedef int TRUSTEE;
131typedef int WORD;
132typedef int WCHAR;
133typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100134typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200135typedef int SE_OBJECT_TYPE;
136typedef int PSNSECINFO;
137typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100138typedef int STARTUPINFO;
139typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200140typedef int LPSECURITY_ATTRIBUTES;
141# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142#endif
143
144#ifndef FEAT_GUI_W32
145/* Undocumented API in kernel32.dll needed to work around dead key bug in
146 * console-mode applications in NT 4.0. If you switch keyboard layouts
147 * in a console app to a layout that includes dead keys and then hit a
148 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
149 * and Michael Dietrich for helping me figure out this workaround.
150 */
151
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100152/* WINAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
153#ifndef WINAPI
154# define WINAPI __stdcall
Bram Moolenaar071d4272004-06-13 20:20:40 +0000155#endif
156#if defined(__BORLANDC__)
157typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
158#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100159typedef BOOL (WINAPI *PFNGCKLN)(LPSTR);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000161static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000162#endif
163
164#if defined(__BORLANDC__)
165/* Strangely Borland uses a non-standard name. */
166# define wcsicmp(a, b) wcscmpi((a), (b))
167#endif
168
Bram Moolenaar82881492012-11-20 16:53:39 +0100169#ifndef PROTO
170
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200171/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200172#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100173LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200174BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
175BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
176BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
177#endif
178
Bram Moolenaar82881492012-11-20 16:53:39 +0100179#endif /* PROTO */
180
Bram Moolenaar071d4272004-06-13 20:20:40 +0000181#ifndef FEAT_GUI_W32
182/* Win32 Console handles for input and output */
183static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
184static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
185
186/* Win32 Screen buffer,coordinate,console I/O information */
187static SMALL_RECT g_srScrollRegion;
188static COORD g_coord; /* 0-based, but external coords are 1-based */
189
190/* The attribute of the screen when the editor was started */
191static WORD g_attrDefault = 7; /* lightgray text on black background */
192static WORD g_attrCurrent;
193
194static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
195static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
196static int g_fForceExit = FALSE; /* set when forcefully exiting */
197
198static void termcap_mode_start(void);
199static void termcap_mode_end(void);
200static void clear_chars(COORD coord, DWORD n);
201static void clear_screen(void);
202static void clear_to_end_of_display(void);
203static void clear_to_end_of_line(void);
204static void scroll(unsigned cLines);
205static void set_scroll_region(unsigned left, unsigned top,
206 unsigned right, unsigned bottom);
207static void insert_lines(unsigned cLines);
208static void delete_lines(unsigned cLines);
209static void gotoxy(unsigned x, unsigned y);
210static void normvideo(void);
211static void textattr(WORD wAttr);
212static void textcolor(WORD wAttr);
213static void textbackground(WORD wAttr);
214static void standout(void);
215static void standend(void);
216static void visual_bell(void);
217static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200218static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000219static void create_conin(void);
220static int s_cursor_visible = TRUE;
221static int did_create_conin = FALSE;
222#else
223static int s_dont_use_vimrun = TRUE;
224static int need_vimrun_warning = FALSE;
225static char *vimrun_path = "vimrun ";
226#endif
227
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200228static int win32_getattrs(char_u *name);
229static int win32_setattrs(char_u *name, int attrs);
230static int win32_set_archive(char_u *name);
231
Bram Moolenaar071d4272004-06-13 20:20:40 +0000232#ifndef FEAT_GUI_W32
233static int suppress_winsize = 1; /* don't fiddle with console */
234#endif
235
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200236static char_u *exe_path = NULL;
237
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100238static BOOL win8_or_later = FALSE;
239
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100240#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100241/*
242 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100243 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100244 */
245 static BOOL
246read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100247 HANDLE hInput,
248 INPUT_RECORD *lpBuffer,
249 DWORD nLength,
250 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100251{
252 enum
253 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100254 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100255 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100256 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100257 static DWORD s_dwIndex = 0;
258 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100259 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100260 int head;
261 int tail;
262 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100263
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200264 if (nLength == -2)
265 return (s_dwMax > 0) ? TRUE : FALSE;
266
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100267 if (!win8_or_later)
268 {
269 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200270 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
271 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100272 }
273
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100274 if (s_dwMax == 0)
275 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100276 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200277 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
278 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100279 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100280 s_dwIndex = 0;
281 s_dwMax = dwEvents;
282 if (dwEvents == 0)
283 {
284 *lpEvents = 0;
285 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100286 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100287
288 if (s_dwMax > 1)
289 {
290 head = 0;
291 tail = s_dwMax - 1;
292 while (head != tail)
293 {
294 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
295 && s_irCache[head + 1].EventType
296 == WINDOW_BUFFER_SIZE_EVENT)
297 {
298 /* Remove duplicate event to avoid flicker. */
299 for (i = head; i < tail; ++i)
300 s_irCache[i] = s_irCache[i + 1];
301 --tail;
302 continue;
303 }
304 head++;
305 }
306 s_dwMax = tail + 1;
307 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100308 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100309
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100310 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200311 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100312 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100313 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100314 return TRUE;
315}
316
317/*
318 * Version of PeekConsoleInput() that works with IME.
319 */
320 static BOOL
321peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100322 HANDLE hInput,
323 INPUT_RECORD *lpBuffer,
324 DWORD nLength,
325 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100327 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100328}
329
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100330# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200331 static DWORD
332msg_wait_for_multiple_objects(
333 DWORD nCount,
334 LPHANDLE pHandles,
335 BOOL fWaitAll,
336 DWORD dwMilliseconds,
337 DWORD dwWakeMask)
338{
339 if (read_console_input(NULL, NULL, -2, NULL))
340 return WAIT_OBJECT_0;
341 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
342 dwMilliseconds, dwWakeMask);
343}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100344# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200345
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100346# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200347 static DWORD
348wait_for_single_object(
349 HANDLE hHandle,
350 DWORD dwMilliseconds)
351{
352 if (read_console_input(NULL, NULL, -2, NULL))
353 return WAIT_OBJECT_0;
354 return WaitForSingleObject(hHandle, dwMilliseconds);
355}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100356# endif
357#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200358
Bram Moolenaar071d4272004-06-13 20:20:40 +0000359 static void
360get_exe_name(void)
361{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100362 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
363 * as the maximum length that works (plus a NUL byte). */
364#define MAX_ENV_PATH_LEN 8192
365 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200366 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367
368 if (exe_name == NULL)
369 {
370 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100371 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000372 if (*temp != NUL)
373 exe_name = FullName_save((char_u *)temp, FALSE);
374 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000375
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200376 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000377 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200378 exe_path = vim_strnsave(exe_name,
379 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200380 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000381 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200382 /* Append our starting directory to $PATH, so that when doing
383 * "!xxd" it's found in our starting directory. Needed because
384 * SearchPath() also looks there. */
385 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100386 if (p == NULL
387 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200388 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100389 if (p == NULL || *p == NUL)
390 temp[0] = NUL;
391 else
392 {
393 STRCPY(temp, p);
394 STRCAT(temp, ";");
395 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200396 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100397 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200398 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000399 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000400 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401}
402
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200403/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100404 * Unescape characters in "p" that appear in "escaped".
405 */
406 static void
407unescape_shellxquote(char_u *p, char_u *escaped)
408{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100409 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100410 int n;
411
412 while (*p != NUL)
413 {
414 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
415 mch_memmove(p, p + 1, l--);
416#ifdef FEAT_MBYTE
417 n = (*mb_ptr2len)(p);
418#else
419 n = 1;
420#endif
421 p += n;
422 l -= n;
423 }
424}
425
426/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 * Load library "name".
428 */
429 HINSTANCE
430vimLoadLib(char *name)
431{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200432 HINSTANCE dll = NULL;
433 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200434
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200435 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
436 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200437 if (exe_path == NULL)
438 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200439 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200440 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200441#ifdef FEAT_MBYTE
442 WCHAR old_dirw[MAXPATHL];
443
444 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
445 {
446 /* Change directory to where the executable is, both to make
447 * sure we find a .dll there and to avoid looking for a .dll
448 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100449 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200450 dll = LoadLibrary(name);
451 SetCurrentDirectoryW(old_dirw);
452 return dll;
453 }
454 /* Retry with non-wide function (for Windows 98). */
455 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
456#endif
457 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
458 {
459 /* Change directory to where the executable is, both to make
460 * sure we find a .dll there and to avoid looking for a .dll
461 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100462 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200463 dll = LoadLibrary(name);
464 SetCurrentDirectory(old_dir);
465 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200466 }
467 return dll;
468}
469
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
471# ifndef GETTEXT_DLL
472# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100473# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200475/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000476static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200477static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000478static char *null_libintl_textdomain(const char *);
479static char *null_libintl_bindtextdomain(const char *, const char *);
480static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000483char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200484char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
485 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000486char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
487char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000488 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000489char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
490 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491
492 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100493dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000494{
495 int i;
496 static struct
497 {
498 char *name;
499 FARPROC *ptr;
500 } libintl_entry[] =
501 {
502 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200503 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000504 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
505 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
506 {NULL, NULL}
507 };
508
509 /* No need to initialize twice. */
510 if (hLibintlDLL)
511 return 1;
512 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100513 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100514#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100515 if (!hLibintlDLL)
516 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100517#endif
518 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200520 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200522 verbose_enter();
523 EMSG2(_(e_loadlib), GETTEXT_DLL);
524 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200526 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000527 }
528 for (i = 0; libintl_entry[i].name != NULL
529 && libintl_entry[i].ptr != NULL; ++i)
530 {
531 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
532 libintl_entry[i].name)) == NULL)
533 {
534 dyn_libintl_end();
535 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000536 {
537 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000538 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000539 verbose_leave();
540 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000541 return 0;
542 }
543 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000544
545 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000546 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000547 "bind_textdomain_codeset");
548 if (dyn_libintl_bind_textdomain_codeset == NULL)
549 dyn_libintl_bind_textdomain_codeset =
550 null_libintl_bind_textdomain_codeset;
551
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552 return 1;
553}
554
555 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100556dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000557{
558 if (hLibintlDLL)
559 FreeLibrary(hLibintlDLL);
560 hLibintlDLL = NULL;
561 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200562 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000563 dyn_libintl_textdomain = null_libintl_textdomain;
564 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000565 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000566}
567
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000568/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000570null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000571{
572 return (char*)msgid;
573}
574
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000575/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200577null_libintl_ngettext(
578 const char *msgid,
579 const char *msgid_plural,
580 unsigned long n)
581{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200582 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200583}
584
585/*ARGSUSED*/
586 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000587null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000588{
589 return NULL;
590}
591
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000592/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000593 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000594null_libintl_bind_textdomain_codeset(const char *domainname,
595 const char *codeset)
596{
597 return NULL;
598}
599
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000600/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000601 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000602null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603{
604 return NULL;
605}
606
607#endif /* DYNAMIC_GETTEXT */
608
609/* This symbol is not defined in older versions of the SDK or Visual C++ */
610
611#ifndef VER_PLATFORM_WIN32_WINDOWS
612# define VER_PLATFORM_WIN32_WINDOWS 1
613#endif
614
615DWORD g_PlatformId;
616
617#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100618# ifndef PROTO
619# include <aclapi.h>
620# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200621# ifndef PROTECTED_DACL_SECURITY_INFORMATION
622# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
623# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100624
Bram Moolenaar071d4272004-06-13 20:20:40 +0000625/*
626 * These are needed to dynamically load the ADVAPI DLL, which is not
627 * implemented under Windows 95 (and causes VIM to crash)
628 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200629typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200631typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
633 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200634# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200635typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200636 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200637typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200638 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
639 PSECURITY_DESCRIPTOR *);
640# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641
642static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
643static PSNSECINFO pSetNamedSecurityInfo;
644static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200645# ifdef FEAT_MBYTE
646static PSNSECINFOW pSetNamedSecurityInfoW;
647static PGNSECINFOW pGetNamedSecurityInfoW;
648# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000649#endif
650
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200651typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
652
653static BOOL allowPiping = FALSE;
654static PSETHANDLEINFORMATION pSetHandleInformation;
655
Bram Moolenaar27515922013-06-29 15:36:26 +0200656#ifdef HAVE_ACL
657/*
658 * Enables or disables the specified privilege.
659 */
660 static BOOL
661win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
662{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100663 BOOL bResult;
664 LUID luid;
665 HANDLE hToken;
666 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200667
668 if (!OpenProcessToken(GetCurrentProcess(),
669 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
670 return FALSE;
671
672 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
673 {
674 CloseHandle(hToken);
675 return FALSE;
676 }
677
Bram Moolenaar45500912014-07-09 20:51:07 +0200678 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200679 tokenPrivileges.Privileges[0].Luid = luid;
680 tokenPrivileges.Privileges[0].Attributes = bEnable ?
681 SE_PRIVILEGE_ENABLED : 0;
682
683 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
684 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
685
686 CloseHandle(hToken);
687
688 return bResult && GetLastError() == ERROR_SUCCESS;
689}
690#endif
691
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692/*
693 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
694 * VER_PLATFORM_WIN32_WINDOWS (Win95).
695 */
696 void
697PlatformId(void)
698{
699 static int done = FALSE;
700
701 if (!done)
702 {
703 OSVERSIONINFO ovi;
704
705 ovi.dwOSVersionInfoSize = sizeof(ovi);
706 GetVersionEx(&ovi);
707
708 g_PlatformId = ovi.dwPlatformId;
709
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100710 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
711 || ovi.dwMajorVersion > 6)
712 win8_or_later = TRUE;
713
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714#ifdef HAVE_ACL
715 /*
716 * Load the ADVAPI runtime if we are on anything
717 * other than Windows 95
718 */
719 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
720 {
721 /*
722 * do this load. Problems: Doesn't unload at end of run (this is
723 * theoretically okay, since Windows should unload it when VIM
724 * terminates). Should we be using the 'mch_libcall' routines?
725 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
726 * time we verify security...
727 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200728 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000729 if (advapi_lib != NULL)
730 {
731 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
732 "SetNamedSecurityInfoA");
733 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
734 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200735# ifdef FEAT_MBYTE
736 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
737 "SetNamedSecurityInfoW");
738 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
739 "GetNamedSecurityInfoW");
740# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200742 || pGetNamedSecurityInfo == NULL
743# ifdef FEAT_MBYTE
744 || pSetNamedSecurityInfoW == NULL
745 || pGetNamedSecurityInfoW == NULL
746# endif
747 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 {
749 /* If we can't get the function addresses, set advapi_lib
750 * to NULL so that we don't use them. */
751 FreeLibrary(advapi_lib);
752 advapi_lib = NULL;
753 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200754 /* Enable privilege for getting or setting SACLs. */
755 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000756 }
757 }
758#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200759 /*
760 * If we are on windows NT, try to load the pipe functions, only
761 * available from Win2K.
762 */
763 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
764 {
765 HANDLE kernel32 = GetModuleHandle("kernel32");
766 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
767 kernel32, "SetHandleInformation");
768
769 allowPiping = pSetHandleInformation != NULL;
770 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771 done = TRUE;
772 }
773}
774
775/*
776 * Return TRUE when running on Windows 95 (or 98 or ME).
777 * Only to be used after mch_init().
778 */
779 int
780mch_windows95(void)
781{
782 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
783}
784
785#ifdef FEAT_GUI_W32
786/*
787 * Used to work around the "can't do synchronous spawn"
788 * problem on Win32s, without resorting to Universal Thunk.
789 */
790static int old_num_windows;
791static int num_windows;
792
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000793/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794 static BOOL CALLBACK
795win32ssynch_cb(HWND hwnd, LPARAM lparam)
796{
797 num_windows++;
798 return TRUE;
799}
800#endif
801
802#ifndef FEAT_GUI_W32
803
804#define SHIFT (SHIFT_PRESSED)
805#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
806#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
807#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
808
809
810/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
811 * We map function keys to their ANSI terminal equivalents, as produced
812 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
813 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
814 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
815 * combinations of function/arrow/etc keys.
816 */
817
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000818static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819{
820 WORD wVirtKey;
821 BOOL fAnsiKey;
822 int chAlone;
823 int chShift;
824 int chCtrl;
825 int chAlt;
826} VirtKeyMap[] =
827{
828
829/* Key ANSI alone shift ctrl alt */
830 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
831
832 { VK_F1, TRUE, ';', 'T', '^', 'h', },
833 { VK_F2, TRUE, '<', 'U', '_', 'i', },
834 { VK_F3, TRUE, '=', 'V', '`', 'j', },
835 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
836 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
837 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
838 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
839 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
840 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
841 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
842 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
843 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
844
845 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
846 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
847 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
848 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
849 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
850 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
851 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
852 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
853 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
854 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
855
856 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
857
858#if 0
859 /* Most people don't have F13-F20, but what the hell... */
860 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
861 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
862 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
863 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
864 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
865 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
866 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
867 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
868#endif
869 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
870 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
871 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
872 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
873
874 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
875 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
876 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
877 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
878 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
879 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
880 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
881 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
882 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
883 /* Sorry, out of number space! <negri>*/
884 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
885
886};
887
888
889#ifdef _MSC_VER
890// The ToAscii bug destroys several registers. Need to turn off optimization
891// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000892# pragma warning(push)
893# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894# pragma optimize("", off)
895#endif
896
897#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200898# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200900# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901#endif
902
903/* The return code indicates key code size. */
904 static int
905#ifdef __BORLANDC__
906 __stdcall
907#endif
908win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000909 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910{
911 UINT uMods = pker->dwControlKeyState;
912 static int s_iIsDead = 0;
913 static WORD awAnsiCode[2];
914 static BYTE abKeystate[256];
915
916
917 if (s_iIsDead == 2)
918 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200919 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920 s_iIsDead = 0;
921 return 1;
922 }
923
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200924 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925 return 1;
926
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200927 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928
929 // Should only be non-NULL on NT 4.0
930 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
931 {
932 CHAR szKLID[KL_NAMELENGTH];
933
934 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
935 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
936 }
937
938 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200939 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940
941 if (uMods & SHIFT_PRESSED)
942 abKeystate[VK_SHIFT] = 0x80;
943 if (uMods & CAPSLOCK_ON)
944 abKeystate[VK_CAPITAL] = 1;
945
946 if ((uMods & ALT_GR) == ALT_GR)
947 {
948 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
949 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
950 }
951
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200952 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
953 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954
955 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200956 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957
958 return s_iIsDead;
959}
960
961#ifdef _MSC_VER
962/* MUST switch optimization on again here, otherwise a call to
963 * decode_key_event() may crash (e.g. when hitting caps-lock) */
964# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000965# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966
967# if (_MSC_VER < 1100)
968/* MUST turn off global optimisation for this next function, or
969 * pressing ctrl-minus in insert mode crashes Vim when built with
970 * VC4.1. -- negri. */
971# pragma optimize("g", off)
972# endif
973#endif
974
975static BOOL g_fJustGotFocus = FALSE;
976
977/*
978 * Decode a KEY_EVENT into one or two keystrokes
979 */
980 static BOOL
981decode_key_event(
982 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200983 WCHAR *pch,
984 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985 int *pmodifiers,
986 BOOL fDoPost)
987{
988 int i;
989 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
990
991 *pch = *pch2 = NUL;
992 g_fJustGotFocus = FALSE;
993
994 /* ignore key up events */
995 if (!pker->bKeyDown)
996 return FALSE;
997
998 /* ignore some keystrokes */
999 switch (pker->wVirtualKeyCode)
1000 {
1001 /* modifiers */
1002 case VK_SHIFT:
1003 case VK_CONTROL:
1004 case VK_MENU: /* Alt key */
1005 return FALSE;
1006
1007 default:
1008 break;
1009 }
1010
1011 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001012 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 {
1014 /* Ctrl-6 is Ctrl-^ */
1015 if (pker->wVirtualKeyCode == '6')
1016 {
1017 *pch = Ctrl_HAT;
1018 return TRUE;
1019 }
1020 /* Ctrl-2 is Ctrl-@ */
1021 else if (pker->wVirtualKeyCode == '2')
1022 {
1023 *pch = NUL;
1024 return TRUE;
1025 }
1026 /* Ctrl-- is Ctrl-_ */
1027 else if (pker->wVirtualKeyCode == 0xBD)
1028 {
1029 *pch = Ctrl__;
1030 return TRUE;
1031 }
1032 }
1033
1034 /* Shift-TAB */
1035 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1036 {
1037 *pch = K_NUL;
1038 *pch2 = '\017';
1039 return TRUE;
1040 }
1041
1042 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1043 {
1044 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1045 {
1046 if (nModifs == 0)
1047 *pch = VirtKeyMap[i].chAlone;
1048 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1049 *pch = VirtKeyMap[i].chShift;
1050 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1051 *pch = VirtKeyMap[i].chCtrl;
1052 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1053 *pch = VirtKeyMap[i].chAlt;
1054
1055 if (*pch != 0)
1056 {
1057 if (VirtKeyMap[i].fAnsiKey)
1058 {
1059 *pch2 = *pch;
1060 *pch = K_NUL;
1061 }
1062
1063 return TRUE;
1064 }
1065 }
1066 }
1067
1068 i = win32_kbd_patch_key(pker);
1069
1070 if (i < 0)
1071 *pch = NUL;
1072 else
1073 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001074 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075
1076 if (pmodifiers != NULL)
1077 {
1078 /* Pass on the ALT key as a modifier, but only when not combined
1079 * with CTRL (which is ALTGR). */
1080 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1081 *pmodifiers |= MOD_MASK_ALT;
1082
1083 /* Pass on SHIFT only for special keys, because we don't know when
1084 * it's already included with the character. */
1085 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1086 *pmodifiers |= MOD_MASK_SHIFT;
1087
1088 /* Pass on CTRL only for non-special keys, because we don't know
1089 * when it's already included with the character. And not when
1090 * combined with ALT (which is ALTGR). */
1091 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1092 && *pch >= 0x20 && *pch < 0x80)
1093 *pmodifiers |= MOD_MASK_CTRL;
1094 }
1095 }
1096
1097 return (*pch != NUL);
1098}
1099
1100#ifdef _MSC_VER
1101# pragma optimize("", on)
1102#endif
1103
1104#endif /* FEAT_GUI_W32 */
1105
1106
1107#ifdef FEAT_MOUSE
1108
1109/*
1110 * For the GUI the mouse handling is in gui_w32.c.
1111 */
1112# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001113/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001115mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116{
1117}
1118# else
1119static int g_fMouseAvail = FALSE; /* mouse present */
1120static int g_fMouseActive = FALSE; /* mouse enabled */
1121static int g_nMouseClick = -1; /* mouse status */
1122static int g_xMouse; /* mouse x coordinate */
1123static int g_yMouse; /* mouse y coordinate */
1124
1125/*
1126 * Enable or disable mouse input
1127 */
1128 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001129mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130{
1131 DWORD cmodein;
1132
1133 if (!g_fMouseAvail)
1134 return;
1135
1136 g_fMouseActive = on;
1137 GetConsoleMode(g_hConIn, &cmodein);
1138
1139 if (g_fMouseActive)
1140 cmodein |= ENABLE_MOUSE_INPUT;
1141 else
1142 cmodein &= ~ENABLE_MOUSE_INPUT;
1143
1144 SetConsoleMode(g_hConIn, cmodein);
1145}
1146
Bram Moolenaar071d4272004-06-13 20:20:40 +00001147/*
1148 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1149 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1150 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1151 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1152 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1153 * and we return the mouse position in g_xMouse and g_yMouse.
1154 *
1155 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1156 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1157 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1158 *
1159 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1160 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1161 *
1162 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1163 * moves, even if it stays within the same character cell. We ignore
1164 * all MOUSE_MOVED messages if the position hasn't really changed, and
1165 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1166 * we're only interested in MOUSE_DRAG).
1167 *
1168 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1169 * 2-button mouses by pressing the left & right buttons simultaneously.
1170 * In practice, it's almost impossible to click both at the same time,
1171 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1172 * in such cases, if the user is clicking quickly.
1173 */
1174 static BOOL
1175decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001176 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177{
1178 static int s_nOldButton = -1;
1179 static int s_nOldMouseClick = -1;
1180 static int s_xOldMouse = -1;
1181 static int s_yOldMouse = -1;
1182 static linenr_T s_old_topline = 0;
1183#ifdef FEAT_DIFF
1184 static int s_old_topfill = 0;
1185#endif
1186 static int s_cClicks = 1;
1187 static BOOL s_fReleased = TRUE;
1188 static DWORD s_dwLastClickTime = 0;
1189 static BOOL s_fNextIsMiddle = FALSE;
1190
1191 static DWORD cButtons = 0; /* number of buttons supported */
1192
1193 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1194 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1195 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1196 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1197
1198 int nButton;
1199
1200 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1201 cButtons = 2;
1202
1203 if (!g_fMouseAvail || !g_fMouseActive)
1204 {
1205 g_nMouseClick = -1;
1206 return FALSE;
1207 }
1208
1209 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1210 if (g_fJustGotFocus)
1211 {
1212 g_fJustGotFocus = FALSE;
1213 return FALSE;
1214 }
1215
1216 /* unprocessed mouse click? */
1217 if (g_nMouseClick != -1)
1218 return TRUE;
1219
1220 nButton = -1;
1221 g_xMouse = pmer->dwMousePosition.X;
1222 g_yMouse = pmer->dwMousePosition.Y;
1223
1224 if (pmer->dwEventFlags == MOUSE_MOVED)
1225 {
1226 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1227 * events even when the mouse moves only within a char cell.) */
1228 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1229 return FALSE;
1230 }
1231
1232 /* If no buttons are pressed... */
1233 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1234 {
1235 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1236 if (s_fReleased)
1237 return FALSE;
1238
1239 nButton = MOUSE_RELEASE;
1240 s_fReleased = TRUE;
1241 }
1242 else /* one or more buttons pressed */
1243 {
1244 /* on a 2-button mouse, hold down left and right buttons
1245 * simultaneously to get MIDDLE. */
1246
1247 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1248 {
1249 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1250
1251 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001252 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001253 if (dwLR == LEFT || dwLR == RIGHT)
1254 {
1255 for (;;)
1256 {
1257 /* wait a short time for next input event */
1258 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1259 != WAIT_OBJECT_0)
1260 break;
1261 else
1262 {
1263 DWORD cRecords = 0;
1264 INPUT_RECORD ir;
1265 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1266
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001267 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001268
1269 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1270 || !(pmer2->dwButtonState & LEFT_RIGHT))
1271 break;
1272 else
1273 {
1274 if (pmer2->dwEventFlags != MOUSE_MOVED)
1275 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001276 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277
1278 return decode_mouse_event(pmer2);
1279 }
1280 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1281 s_yOldMouse == pmer2->dwMousePosition.Y)
1282 {
1283 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001284 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285
1286 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001287 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001288
1289 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1290 break;
1291 }
1292 else
1293 break;
1294 }
1295 }
1296 }
1297 }
1298 }
1299
1300 if (s_fNextIsMiddle)
1301 {
1302 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1303 ? MOUSE_DRAG : MOUSE_MIDDLE;
1304 s_fNextIsMiddle = FALSE;
1305 }
1306 else if (cButtons == 2 &&
1307 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1308 {
1309 nButton = MOUSE_MIDDLE;
1310
1311 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1312 {
1313 s_fNextIsMiddle = TRUE;
1314 nButton = MOUSE_RELEASE;
1315 }
1316 }
1317 else if ((pmer->dwButtonState & LEFT) == LEFT)
1318 nButton = MOUSE_LEFT;
1319 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1320 nButton = MOUSE_MIDDLE;
1321 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1322 nButton = MOUSE_RIGHT;
1323
1324 if (! s_fReleased && ! s_fNextIsMiddle
1325 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1326 return FALSE;
1327
1328 s_fReleased = s_fNextIsMiddle;
1329 }
1330
1331 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1332 {
1333 /* button pressed or released, without mouse moving */
1334 if (nButton != -1 && nButton != MOUSE_RELEASE)
1335 {
1336 DWORD dwCurrentTime = GetTickCount();
1337
1338 if (s_xOldMouse != g_xMouse
1339 || s_yOldMouse != g_yMouse
1340 || s_nOldButton != nButton
1341 || s_old_topline != curwin->w_topline
1342#ifdef FEAT_DIFF
1343 || s_old_topfill != curwin->w_topfill
1344#endif
1345 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1346 {
1347 s_cClicks = 1;
1348 }
1349 else if (++s_cClicks > 4)
1350 {
1351 s_cClicks = 1;
1352 }
1353
1354 s_dwLastClickTime = dwCurrentTime;
1355 }
1356 }
1357 else if (pmer->dwEventFlags == MOUSE_MOVED)
1358 {
1359 if (nButton != -1 && nButton != MOUSE_RELEASE)
1360 nButton = MOUSE_DRAG;
1361
1362 s_cClicks = 1;
1363 }
1364
1365 if (nButton == -1)
1366 return FALSE;
1367
1368 if (nButton != MOUSE_RELEASE)
1369 s_nOldButton = nButton;
1370
1371 g_nMouseClick = nButton;
1372
1373 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1374 g_nMouseClick |= MOUSE_SHIFT;
1375 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1376 g_nMouseClick |= MOUSE_CTRL;
1377 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1378 g_nMouseClick |= MOUSE_ALT;
1379
1380 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1381 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1382
1383 /* only pass on interesting (i.e., different) mouse events */
1384 if (s_xOldMouse == g_xMouse
1385 && s_yOldMouse == g_yMouse
1386 && s_nOldMouseClick == g_nMouseClick)
1387 {
1388 g_nMouseClick = -1;
1389 return FALSE;
1390 }
1391
1392 s_xOldMouse = g_xMouse;
1393 s_yOldMouse = g_yMouse;
1394 s_old_topline = curwin->w_topline;
1395#ifdef FEAT_DIFF
1396 s_old_topfill = curwin->w_topfill;
1397#endif
1398 s_nOldMouseClick = g_nMouseClick;
1399
1400 return TRUE;
1401}
1402
1403# endif /* FEAT_GUI_W32 */
1404#endif /* FEAT_MOUSE */
1405
1406
1407#ifdef MCH_CURSOR_SHAPE
1408/*
1409 * Set the shape of the cursor.
1410 * 'thickness' can be from 1 (thin) to 99 (block)
1411 */
1412 static void
1413mch_set_cursor_shape(int thickness)
1414{
1415 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1416 ConsoleCursorInfo.dwSize = thickness;
1417 ConsoleCursorInfo.bVisible = s_cursor_visible;
1418
1419 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1420 if (s_cursor_visible)
1421 SetConsoleCursorPosition(g_hConOut, g_coord);
1422}
1423
1424 void
1425mch_update_cursor(void)
1426{
1427 int idx;
1428 int thickness;
1429
1430 /*
1431 * How the cursor is drawn depends on the current mode.
1432 */
1433 idx = get_shape_idx(FALSE);
1434
1435 if (shape_table[idx].shape == SHAPE_BLOCK)
1436 thickness = 99; /* 100 doesn't work on W95 */
1437 else
1438 thickness = shape_table[idx].percentage;
1439 mch_set_cursor_shape(thickness);
1440}
1441#endif
1442
1443#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1444/*
1445 * Handle FOCUS_EVENT.
1446 */
1447 static void
1448handle_focus_event(INPUT_RECORD ir)
1449{
1450 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1451 ui_focus_change((int)g_fJustGotFocus);
1452}
1453
1454/*
1455 * Wait until console input from keyboard or mouse is available,
1456 * or the time is up.
1457 * Return TRUE if something is available FALSE if not.
1458 */
1459 static int
1460WaitForChar(long msec)
1461{
1462 DWORD dwNow = 0, dwEndTime = 0;
1463 INPUT_RECORD ir;
1464 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001465 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001466#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001467 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001468#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469
1470 if (msec > 0)
1471 /* Wait until the specified time has elapsed. */
1472 dwEndTime = GetTickCount() + msec;
1473 else if (msec < 0)
1474 /* Wait forever. */
1475 dwEndTime = INFINITE;
1476
1477 /* We need to loop until the end of the time period, because
1478 * we might get multiple unusable mouse events in that time.
1479 */
1480 for (;;)
1481 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001482#ifdef MESSAGE_QUEUE
1483 parse_queued_messages();
1484#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001485#ifdef FEAT_MZSCHEME
1486 mzvim_check_threads();
1487#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488#ifdef FEAT_CLIENTSERVER
1489 serverProcessPendingMessages();
1490#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001491
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492 if (0
1493#ifdef FEAT_MOUSE
1494 || g_nMouseClick != -1
1495#endif
1496#ifdef FEAT_CLIENTSERVER
1497 || input_available()
1498#endif
1499 )
1500 return TRUE;
1501
1502 if (msec > 0)
1503 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001504 /* If the specified wait time has passed, return. Beware that
1505 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001507 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001508 break;
1509 }
1510 if (msec != 0)
1511 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001512 DWORD dwWaitTime = dwEndTime - dwNow;
1513
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001514#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar9186a272016-02-23 19:34:01 +01001515 /* Check channel while waiting input. */
1516 if (dwWaitTime > 100)
1517 dwWaitTime = 100;
1518#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001519#ifdef FEAT_MZSCHEME
1520 if (mzthreads_allowed() && p_mzq > 0
1521 && (msec < 0 || (long)dwWaitTime > p_mzq))
1522 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1523#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001524#ifdef FEAT_TIMERS
1525 {
1526 long due_time;
1527
1528 /* When waiting very briefly don't trigger timers. */
1529 if (dwWaitTime > 10)
1530 {
1531 /* Trigger timers and then get the time in msec until the
1532 * next one is due. Wait up to that time. */
1533 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001534 if (typebuf.tb_change_cnt != tb_change_cnt)
1535 {
1536 /* timer may have used feedkeys() */
1537 return FALSE;
1538 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001539 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1540 dwWaitTime = due_time;
1541 }
1542 }
1543#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544#ifdef FEAT_CLIENTSERVER
1545 /* Wait for either an event on the console input or a message in
1546 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001547 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001548 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001550 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551#endif
1552 continue;
1553 }
1554
1555 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001556 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557
1558#ifdef FEAT_MBYTE_IME
1559 if (State & CMDLINE && msg_row == Rows - 1)
1560 {
1561 CONSOLE_SCREEN_BUFFER_INFO csbi;
1562
1563 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1564 {
1565 if (csbi.dwCursorPosition.Y != msg_row)
1566 {
1567 /* The screen is now messed up, must redraw the
1568 * command line and later all the windows. */
1569 redraw_all_later(CLEAR);
1570 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1571 redrawcmd();
1572 }
1573 }
1574 }
1575#endif
1576
1577 if (cRecords > 0)
1578 {
1579 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1580 {
1581#ifdef FEAT_MBYTE_IME
1582 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1583 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001584 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1586 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001587 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588 continue;
1589 }
1590#endif
1591 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1592 NULL, FALSE))
1593 return TRUE;
1594 }
1595
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001596 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597
1598 if (ir.EventType == FOCUS_EVENT)
1599 handle_focus_event(ir);
1600 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1601 shell_resized();
1602#ifdef FEAT_MOUSE
1603 else if (ir.EventType == MOUSE_EVENT
1604 && decode_mouse_event(&ir.Event.MouseEvent))
1605 return TRUE;
1606#endif
1607 }
1608 else if (msec == 0)
1609 break;
1610 }
1611
1612#ifdef FEAT_CLIENTSERVER
1613 /* Something might have been received while we were waiting. */
1614 if (input_available())
1615 return TRUE;
1616#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001617
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 return FALSE;
1619}
1620
1621#ifndef FEAT_GUI_MSWIN
1622/*
1623 * return non-zero if a character is available
1624 */
1625 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001626mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627{
1628 return WaitForChar(0L);
1629}
1630#endif
1631
1632/*
1633 * Create the console input. Used when reading stdin doesn't work.
1634 */
1635 static void
1636create_conin(void)
1637{
1638 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1639 FILE_SHARE_READ|FILE_SHARE_WRITE,
1640 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001641 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 did_create_conin = TRUE;
1643}
1644
1645/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001646 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001648 static WCHAR
1649tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001651 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652
1653 for (;;)
1654 {
1655 INPUT_RECORD ir;
1656 DWORD cRecords = 0;
1657
1658#ifdef FEAT_CLIENTSERVER
1659 (void)WaitForChar(-1L);
1660 if (input_available())
1661 return 0;
1662# ifdef FEAT_MOUSE
1663 if (g_nMouseClick != -1)
1664 return 0;
1665# endif
1666#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001667 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 {
1669 if (did_create_conin)
1670 read_error_exit();
1671 create_conin();
1672 continue;
1673 }
1674
1675 if (ir.EventType == KEY_EVENT)
1676 {
1677 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1678 pmodifiers, TRUE))
1679 return ch;
1680 }
1681 else if (ir.EventType == FOCUS_EVENT)
1682 handle_focus_event(ir);
1683 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1684 shell_resized();
1685#ifdef FEAT_MOUSE
1686 else if (ir.EventType == MOUSE_EVENT)
1687 {
1688 if (decode_mouse_event(&ir.Event.MouseEvent))
1689 return 0;
1690 }
1691#endif
1692 }
1693}
1694#endif /* !FEAT_GUI_W32 */
1695
1696
1697/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001698 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699 * Get one or more characters from the keyboard or the mouse.
1700 * If time == 0, do not wait for characters.
1701 * If time == n, wait a short time for characters.
1702 * If time == -1, wait forever for characters.
1703 * Returns the number of characters read into buf.
1704 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001705/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 int
1707mch_inchar(
1708 char_u *buf,
1709 int maxlen,
1710 long time,
1711 int tb_change_cnt)
1712{
1713#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1714
1715 int len;
1716 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717#define TYPEAHEADLEN 20
1718 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1719 static int typeaheadlen = 0;
1720
1721 /* First use any typeahead that was kept because "buf" was too small. */
1722 if (typeaheadlen > 0)
1723 goto theend;
1724
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 if (time >= 0)
1726 {
1727 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001728 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 }
1730 else /* time == -1, wait forever */
1731 {
1732 mch_set_winsize_now(); /* Allow winsize changes from now on */
1733
Bram Moolenaar3918c952005-03-15 22:34:55 +00001734 /*
1735 * If there is no character available within 2 seconds (default)
1736 * write the autoscript file to disk. Or cause the CursorHold event
1737 * to be triggered.
1738 */
1739 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001740 {
1741#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001742 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001744 buf[0] = K_SPECIAL;
1745 buf[1] = KS_EXTRA;
1746 buf[2] = (int)KE_CURSORHOLD;
1747 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001748 }
1749#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001750 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001751 }
1752 }
1753
1754 /*
1755 * Try to read as many characters as there are, until the buffer is full.
1756 */
1757
1758 /* we will get at least one key. Get more if they are available. */
1759 g_fCBrkPressed = FALSE;
1760
1761#ifdef MCH_WRITE_DUMP
1762 if (fdDump)
1763 fputc('[', fdDump);
1764#endif
1765
1766 /* Keep looping until there is something in the typeahead buffer and more
1767 * to get and still room in the buffer (up to two bytes for a char and
1768 * three bytes for a modifier). */
1769 while ((typeaheadlen == 0 || WaitForChar(0L))
1770 && typeaheadlen + 5 <= TYPEAHEADLEN)
1771 {
1772 if (typebuf_changed(tb_change_cnt))
1773 {
1774 /* "buf" may be invalid now if a client put something in the
1775 * typeahead buffer and "buf" is in the typeahead buffer. */
1776 typeaheadlen = 0;
1777 break;
1778 }
1779#ifdef FEAT_MOUSE
1780 if (g_nMouseClick != -1)
1781 {
1782# ifdef MCH_WRITE_DUMP
1783 if (fdDump)
1784 fprintf(fdDump, "{%02x @ %d, %d}",
1785 g_nMouseClick, g_xMouse, g_yMouse);
1786# endif
1787 typeahead[typeaheadlen++] = ESC + 128;
1788 typeahead[typeaheadlen++] = 'M';
1789 typeahead[typeaheadlen++] = g_nMouseClick;
1790 typeahead[typeaheadlen++] = g_xMouse + '!';
1791 typeahead[typeaheadlen++] = g_yMouse + '!';
1792 g_nMouseClick = -1;
1793 }
1794 else
1795#endif
1796 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001797 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 int modifiers = 0;
1799
1800 c = tgetch(&modifiers, &ch2);
1801
1802 if (typebuf_changed(tb_change_cnt))
1803 {
1804 /* "buf" may be invalid now if a client put something in the
1805 * typeahead buffer and "buf" is in the typeahead buffer. */
1806 typeaheadlen = 0;
1807 break;
1808 }
1809
1810 if (c == Ctrl_C && ctrl_c_interrupts)
1811 {
1812#if defined(FEAT_CLIENTSERVER)
1813 trash_input_buf();
1814#endif
1815 got_int = TRUE;
1816 }
1817
1818#ifdef FEAT_MOUSE
1819 if (g_nMouseClick == -1)
1820#endif
1821 {
1822 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001823 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001824
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001825#ifdef FEAT_MBYTE
1826 if (ch2 == NUL)
1827 {
1828 int i;
1829 char_u *p;
1830 WCHAR ch[2];
1831
1832 ch[0] = c;
1833 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1834 {
1835 ch[1] = tgetch(&modifiers, &ch2);
1836 n++;
1837 }
1838 p = utf16_to_enc(ch, &n);
1839 if (p != NULL)
1840 {
1841 for (i = 0; i < n; i++)
1842 typeahead[typeaheadlen + i] = p[i];
1843 vim_free(p);
1844 }
1845 }
1846 else
1847#endif
1848 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001849 if (ch2 != NUL)
1850 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001851 typeahead[typeaheadlen + n] = 3;
1852 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001853 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855
Bram Moolenaar45500912014-07-09 20:51:07 +02001856 if (conv)
1857 {
1858 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001859
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001860 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001861 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001862 char_u *e = typeahead + TYPEAHEADLEN;
1863
1864 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001865 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001866 if (*p == K_NUL)
1867 {
1868 ++p;
1869 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1870 *p = 3;
1871 ++n;
1872 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001873 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001874 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001875 }
1876 }
1877
Bram Moolenaar071d4272004-06-13 20:20:40 +00001878 /* Use the ALT key to set the 8th bit of the character
1879 * when it's one byte, the 8th bit isn't set yet and not
1880 * using a double-byte encoding (would become a lead
1881 * byte). */
1882 if ((modifiers & MOD_MASK_ALT)
1883 && n == 1
1884 && (typeahead[typeaheadlen] & 0x80) == 0
1885#ifdef FEAT_MBYTE
1886 && !enc_dbcs
1887#endif
1888 )
1889 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001890#ifdef FEAT_MBYTE
1891 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1892 typeahead + typeaheadlen);
1893#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001895#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001896 modifiers &= ~MOD_MASK_ALT;
1897 }
1898
1899 if (modifiers != 0)
1900 {
1901 /* Prepend modifiers to the character. */
1902 mch_memmove(typeahead + typeaheadlen + 3,
1903 typeahead + typeaheadlen, n);
1904 typeahead[typeaheadlen++] = K_SPECIAL;
1905 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1906 typeahead[typeaheadlen++] = modifiers;
1907 }
1908
1909 typeaheadlen += n;
1910
1911#ifdef MCH_WRITE_DUMP
1912 if (fdDump)
1913 fputc(c, fdDump);
1914#endif
1915 }
1916 }
1917 }
1918
1919#ifdef MCH_WRITE_DUMP
1920 if (fdDump)
1921 {
1922 fputs("]\n", fdDump);
1923 fflush(fdDump);
1924 }
1925#endif
1926
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927theend:
1928 /* Move typeahead to "buf", as much as fits. */
1929 len = 0;
1930 while (len < maxlen && typeaheadlen > 0)
1931 {
1932 buf[len++] = typeahead[0];
1933 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1934 }
1935 return len;
1936
1937#else /* FEAT_GUI_W32 */
1938 return 0;
1939#endif /* FEAT_GUI_W32 */
1940}
1941
Bram Moolenaar82881492012-11-20 16:53:39 +01001942#ifndef PROTO
1943# ifndef __MINGW32__
1944# include <shellapi.h> /* required for FindExecutable() */
1945# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001946#endif
1947
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001948/*
1949 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001950 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001951 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001953executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001955 char *dum;
1956 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001957 char *curpath, *newpath;
1958 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001960#ifdef FEAT_MBYTE
1961 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001963 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001964 WCHAR fnamew[_MAX_PATH];
1965 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001966 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001967
1968 if (p != NULL)
1969 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001970 wcurpath = _wgetenv(L"PATH");
1971 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1972 * sizeof(WCHAR));
1973 if (wnewpath == NULL)
1974 return FALSE;
1975 wcscpy(wnewpath, L".;");
1976 wcscat(wnewpath, wcurpath);
1977 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1978 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001979 vim_free(p);
1980 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1981 {
1982 if (n == 0)
1983 return FALSE;
1984 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1985 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001986 if (path != NULL)
1987 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001988 return TRUE;
1989 }
1990 /* Retry with non-wide function (for Windows 98). */
1991 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001993#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001994
1995 curpath = getenv("PATH");
1996 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1997 if (newpath == NULL)
1998 return FALSE;
1999 STRCPY(newpath, ".;");
2000 STRCAT(newpath, curpath);
2001 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2002 vim_free(newpath);
2003 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002004 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002005 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002006 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002007 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002008 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002009 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010}
2011
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002012#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002013 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002014/*
2015 * Bad parameter handler.
2016 *
2017 * Certain MS CRT functions will intentionally crash when passed invalid
2018 * parameters to highlight possible security holes. Setting this function as
2019 * the bad parameter handler will prevent the crash.
2020 *
2021 * In debug builds the parameters contain CRT information that might help track
2022 * down the source of a problem, but in non-debug builds the arguments are all
2023 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2024 * worth allowing these to make debugging of issues easier.
2025 */
2026 static void
2027bad_param_handler(const wchar_t *expression,
2028 const wchar_t *function,
2029 const wchar_t *file,
2030 unsigned int line,
2031 uintptr_t pReserved)
2032{
2033}
2034
2035# define SET_INVALID_PARAM_HANDLER \
2036 ((void)_set_invalid_parameter_handler(bad_param_handler))
2037#else
2038# define SET_INVALID_PARAM_HANDLER
2039#endif
2040
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041#ifdef FEAT_GUI_W32
2042
2043/*
2044 * GUI version of mch_init().
2045 */
2046 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002047mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048{
2049#ifndef __MINGW32__
2050 extern int _fmode;
2051#endif
2052
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002053 /* Silently handle invalid parameters to CRT functions */
2054 SET_INVALID_PARAM_HANDLER;
2055
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056 /* Let critical errors result in a failure, not in a dialog box. Required
2057 * for the timestamp test to work on removed floppies. */
2058 SetErrorMode(SEM_FAILCRITICALERRORS);
2059
2060 _fmode = O_BINARY; /* we do our own CR-LF translation */
2061
2062 /* Specify window size. Is there a place to get the default from? */
2063 Rows = 25;
2064 Columns = 80;
2065
2066 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 {
2068 char_u vimrun_location[_MAX_PATH + 4];
2069
2070 /* First try in same directory as gvim.exe */
2071 STRCPY(vimrun_location, exe_name);
2072 STRCPY(gettail(vimrun_location), "vimrun.exe");
2073 if (mch_getperm(vimrun_location) >= 0)
2074 {
2075 if (*skiptowhite(vimrun_location) != NUL)
2076 {
2077 /* Enclose path with white space in double quotes. */
2078 mch_memmove(vimrun_location + 1, vimrun_location,
2079 STRLEN(vimrun_location) + 1);
2080 *vimrun_location = '"';
2081 STRCPY(gettail(vimrun_location), "vimrun\" ");
2082 }
2083 else
2084 STRCPY(gettail(vimrun_location), "vimrun ");
2085
2086 vimrun_path = (char *)vim_strsave(vimrun_location);
2087 s_dont_use_vimrun = FALSE;
2088 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002089 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 s_dont_use_vimrun = FALSE;
2091
2092 /* Don't give the warning for a missing vimrun.exe right now, but only
2093 * when vimrun was supposed to be used. Don't bother people that do
2094 * not need vimrun.exe. */
2095 if (s_dont_use_vimrun)
2096 need_vimrun_warning = TRUE;
2097 }
2098
2099 /*
2100 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2101 * Otherwise the default "findstr /n" is used.
2102 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002103 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002104 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2105
2106#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002107 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108#endif
2109}
2110
2111
2112#else /* FEAT_GUI_W32 */
2113
2114#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2115#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2116
2117/*
2118 * ClearConsoleBuffer()
2119 * Description:
2120 * Clears the entire contents of the console screen buffer, using the
2121 * specified attribute.
2122 * Returns:
2123 * TRUE on success
2124 */
2125 static BOOL
2126ClearConsoleBuffer(WORD wAttribute)
2127{
2128 CONSOLE_SCREEN_BUFFER_INFO csbi;
2129 COORD coord;
2130 DWORD NumCells, dummy;
2131
2132 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2133 return FALSE;
2134
2135 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2136 coord.X = 0;
2137 coord.Y = 0;
2138 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2139 coord, &dummy))
2140 {
2141 return FALSE;
2142 }
2143 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2144 coord, &dummy))
2145 {
2146 return FALSE;
2147 }
2148
2149 return TRUE;
2150}
2151
2152/*
2153 * FitConsoleWindow()
2154 * Description:
2155 * Checks if the console window will fit within given buffer dimensions.
2156 * Also, if requested, will shrink the window to fit.
2157 * Returns:
2158 * TRUE on success
2159 */
2160 static BOOL
2161FitConsoleWindow(
2162 COORD dwBufferSize,
2163 BOOL WantAdjust)
2164{
2165 CONSOLE_SCREEN_BUFFER_INFO csbi;
2166 COORD dwWindowSize;
2167 BOOL NeedAdjust = FALSE;
2168
2169 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2170 {
2171 /*
2172 * A buffer resize will fail if the current console window does
2173 * not lie completely within that buffer. To avoid this, we might
2174 * have to move and possibly shrink the window.
2175 */
2176 if (csbi.srWindow.Right >= dwBufferSize.X)
2177 {
2178 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2179 if (dwWindowSize.X > dwBufferSize.X)
2180 dwWindowSize.X = dwBufferSize.X;
2181 csbi.srWindow.Right = dwBufferSize.X - 1;
2182 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2183 NeedAdjust = TRUE;
2184 }
2185 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2186 {
2187 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2188 if (dwWindowSize.Y > dwBufferSize.Y)
2189 dwWindowSize.Y = dwBufferSize.Y;
2190 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2191 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2192 NeedAdjust = TRUE;
2193 }
2194 if (NeedAdjust && WantAdjust)
2195 {
2196 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2197 return FALSE;
2198 }
2199 return TRUE;
2200 }
2201
2202 return FALSE;
2203}
2204
2205typedef struct ConsoleBufferStruct
2206{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002207 BOOL IsValid;
2208 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002209 PCHAR_INFO Buffer;
2210 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211} ConsoleBuffer;
2212
2213/*
2214 * SaveConsoleBuffer()
2215 * Description:
2216 * Saves important information about the console buffer, including the
2217 * actual buffer contents. The saved information is suitable for later
2218 * restoration by RestoreConsoleBuffer().
2219 * Returns:
2220 * TRUE if all information was saved; FALSE otherwise
2221 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2222 */
2223 static BOOL
2224SaveConsoleBuffer(
2225 ConsoleBuffer *cb)
2226{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002227 DWORD NumCells;
2228 COORD BufferCoord;
2229 SMALL_RECT ReadRegion;
2230 WORD Y, Y_incr;
2231
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 if (cb == NULL)
2233 return FALSE;
2234
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002235 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236 {
2237 cb->IsValid = FALSE;
2238 return FALSE;
2239 }
2240 cb->IsValid = TRUE;
2241
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002242 /*
2243 * Allocate a buffer large enough to hold the entire console screen
2244 * buffer. If this ConsoleBuffer structure has already been initialized
2245 * with a buffer of the correct size, then just use that one.
2246 */
2247 if (!cb->IsValid || cb->Buffer == NULL ||
2248 cb->BufferSize.X != cb->Info.dwSize.X ||
2249 cb->BufferSize.Y != cb->Info.dwSize.Y)
2250 {
2251 cb->BufferSize.X = cb->Info.dwSize.X;
2252 cb->BufferSize.Y = cb->Info.dwSize.Y;
2253 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2254 vim_free(cb->Buffer);
2255 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2256 if (cb->Buffer == NULL)
2257 return FALSE;
2258 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259
2260 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002261 * We will now copy the console screen buffer into our buffer.
2262 * ReadConsoleOutput() seems to be limited as far as how much you
2263 * can read at a time. Empirically, this number seems to be about
2264 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2265 * in chunks until it is all copied. The chunks will all have the
2266 * same horizontal characteristics, so initialize them now. The
2267 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002269 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002270 ReadRegion.Left = 0;
2271 ReadRegion.Right = cb->Info.dwSize.X - 1;
2272 Y_incr = 12000 / cb->Info.dwSize.X;
2273 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002275 /*
2276 * Read into position (0, Y) in our buffer.
2277 */
2278 BufferCoord.Y = Y;
2279 /*
2280 * Read the region whose top left corner is (0, Y) and whose bottom
2281 * right corner is (width - 1, Y + Y_incr - 1). This should define
2282 * a region of size width by Y_incr. Don't worry if this region is
2283 * too large for the remaining buffer; it will be cropped.
2284 */
2285 ReadRegion.Top = Y;
2286 ReadRegion.Bottom = Y + Y_incr - 1;
2287 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2288 cb->Buffer, /* our buffer */
2289 cb->BufferSize, /* dimensions of our buffer */
2290 BufferCoord, /* offset in our buffer */
2291 &ReadRegion)) /* region to save */
2292 {
2293 vim_free(cb->Buffer);
2294 cb->Buffer = NULL;
2295 return FALSE;
2296 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297 }
2298
2299 return TRUE;
2300}
2301
2302/*
2303 * RestoreConsoleBuffer()
2304 * Description:
2305 * Restores important information about the console buffer, including the
2306 * actual buffer contents, if desired. The information to restore is in
2307 * the same format used by SaveConsoleBuffer().
2308 * Returns:
2309 * TRUE on success
2310 */
2311 static BOOL
2312RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002313 ConsoleBuffer *cb,
2314 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002316 COORD BufferCoord;
2317 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318
2319 if (cb == NULL || !cb->IsValid)
2320 return FALSE;
2321
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002322 /*
2323 * Before restoring the buffer contents, clear the current buffer, and
2324 * restore the cursor position and window information. Doing this now
2325 * prevents old buffer contents from "flashing" onto the screen.
2326 */
2327 if (RestoreScreen)
2328 ClearConsoleBuffer(cb->Info.wAttributes);
2329
2330 FitConsoleWindow(cb->Info.dwSize, TRUE);
2331 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2332 return FALSE;
2333 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2334 return FALSE;
2335
2336 if (!RestoreScreen)
2337 {
2338 /*
2339 * No need to restore the screen buffer contents, so we're done.
2340 */
2341 return TRUE;
2342 }
2343
2344 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2345 return FALSE;
2346 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2347 return FALSE;
2348
2349 /*
2350 * Restore the screen buffer contents.
2351 */
2352 if (cb->Buffer != NULL)
2353 {
2354 BufferCoord.X = 0;
2355 BufferCoord.Y = 0;
2356 WriteRegion.Left = 0;
2357 WriteRegion.Top = 0;
2358 WriteRegion.Right = cb->Info.dwSize.X - 1;
2359 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2360 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2361 cb->Buffer, /* our buffer */
2362 cb->BufferSize, /* dimensions of our buffer */
2363 BufferCoord, /* offset in our buffer */
2364 &WriteRegion)) /* region to restore */
2365 {
2366 return FALSE;
2367 }
2368 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369
2370 return TRUE;
2371}
2372
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002373#define FEAT_RESTORE_ORIG_SCREEN
2374#ifdef FEAT_RESTORE_ORIG_SCREEN
2375static ConsoleBuffer g_cbOrig = { 0 };
2376#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377static ConsoleBuffer g_cbNonTermcap = { 0 };
2378static ConsoleBuffer g_cbTermcap = { 0 };
2379
2380#ifdef FEAT_TITLE
2381#ifdef __BORLANDC__
2382typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2383#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002384typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385#endif
2386char g_szOrigTitle[256] = { 0 };
2387HWND g_hWnd = NULL; /* also used in os_mswin.c */
2388static HICON g_hOrigIconSmall = NULL;
2389static HICON g_hOrigIcon = NULL;
2390static HICON g_hVimIcon = NULL;
2391static BOOL g_fCanChangeIcon = FALSE;
2392
2393/* ICON* are not defined in VC++ 4.0 */
2394#ifndef ICON_SMALL
2395#define ICON_SMALL 0
2396#endif
2397#ifndef ICON_BIG
2398#define ICON_BIG 1
2399#endif
2400/*
2401 * GetConsoleIcon()
2402 * Description:
2403 * Attempts to retrieve the small icon and/or the big icon currently in
2404 * use by a given window.
2405 * Returns:
2406 * TRUE on success
2407 */
2408 static BOOL
2409GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002410 HWND hWnd,
2411 HICON *phIconSmall,
2412 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413{
2414 if (hWnd == NULL)
2415 return FALSE;
2416
2417 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002418 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2419 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002421 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2422 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 return TRUE;
2424}
2425
2426/*
2427 * SetConsoleIcon()
2428 * Description:
2429 * Attempts to change the small icon and/or the big icon currently in
2430 * use by a given window.
2431 * Returns:
2432 * TRUE on success
2433 */
2434 static BOOL
2435SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002436 HWND hWnd,
2437 HICON hIconSmall,
2438 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440 if (hWnd == NULL)
2441 return FALSE;
2442
2443 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002444 SendMessage(hWnd, WM_SETICON,
2445 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002447 SendMessage(hWnd, WM_SETICON,
2448 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002449 return TRUE;
2450}
2451
2452/*
2453 * SaveConsoleTitleAndIcon()
2454 * Description:
2455 * Saves the current console window title in g_szOrigTitle, for later
2456 * restoration. Also, attempts to obtain a handle to the console window,
2457 * and use it to save the small and big icons currently in use by the
2458 * console window. This is not always possible on some versions of Windows;
2459 * nor is it possible when running Vim remotely using Telnet (since the
2460 * console window the user sees is owned by a remote process).
2461 */
2462 static void
2463SaveConsoleTitleAndIcon(void)
2464{
2465 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2466
2467 /* Save the original title. */
2468 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2469 return;
2470
2471 /*
2472 * Obtain a handle to the console window using GetConsoleWindow() from
2473 * KERNEL32.DLL; we need to handle in order to change the window icon.
2474 * This function only exists on NT-based Windows, starting with Windows
2475 * 2000. On older operating systems, we can't change the window icon
2476 * anyway.
2477 */
2478 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2479 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2480 "GetConsoleWindow")) != NULL)
2481 {
2482 g_hWnd = (*GetConsoleWindowProc)();
2483 }
2484 if (g_hWnd == NULL)
2485 return;
2486
2487 /* Save the original console window icon. */
2488 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2489 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2490 return;
2491
2492 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002493 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002494 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 if (g_hVimIcon != NULL)
2496 g_fCanChangeIcon = TRUE;
2497}
2498#endif
2499
2500static int g_fWindInitCalled = FALSE;
2501static int g_fTermcapMode = FALSE;
2502static CONSOLE_CURSOR_INFO g_cci;
2503static DWORD g_cmodein = 0;
2504static DWORD g_cmodeout = 0;
2505
2506/*
2507 * non-GUI version of mch_init().
2508 */
2509 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002510mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002512#ifndef FEAT_RESTORE_ORIG_SCREEN
2513 CONSOLE_SCREEN_BUFFER_INFO csbi;
2514#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515#ifndef __MINGW32__
2516 extern int _fmode;
2517#endif
2518
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002519 /* Silently handle invalid parameters to CRT functions */
2520 SET_INVALID_PARAM_HANDLER;
2521
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 /* Let critical errors result in a failure, not in a dialog box. Required
2523 * for the timestamp test to work on removed floppies. */
2524 SetErrorMode(SEM_FAILCRITICALERRORS);
2525
2526 _fmode = O_BINARY; /* we do our own CR-LF translation */
2527 out_flush();
2528
2529 /* Obtain handles for the standard Console I/O devices */
2530 if (read_cmd_fd == 0)
2531 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2532 else
2533 create_conin();
2534 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2535
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002536#ifdef FEAT_RESTORE_ORIG_SCREEN
2537 /* Save the initial console buffer for later restoration */
2538 SaveConsoleBuffer(&g_cbOrig);
2539 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2540#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002542 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2543 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2544#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 if (cterm_normal_fg_color == 0)
2546 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2547 if (cterm_normal_bg_color == 0)
2548 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2549
2550 /* set termcap codes to current text attributes */
2551 update_tcap(g_attrCurrent);
2552
2553 GetConsoleCursorInfo(g_hConOut, &g_cci);
2554 GetConsoleMode(g_hConIn, &g_cmodein);
2555 GetConsoleMode(g_hConOut, &g_cmodeout);
2556
2557#ifdef FEAT_TITLE
2558 SaveConsoleTitleAndIcon();
2559 /*
2560 * Set both the small and big icons of the console window to Vim's icon.
2561 * Note that Vim presently only has one size of icon (32x32), but it
2562 * automatically gets scaled down to 16x16 when setting the small icon.
2563 */
2564 if (g_fCanChangeIcon)
2565 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2566#endif
2567
2568 ui_get_shellsize();
2569
2570#ifdef MCH_WRITE_DUMP
2571 fdDump = fopen("dump", "wt");
2572
2573 if (fdDump)
2574 {
2575 time_t t;
2576
2577 time(&t);
2578 fputs(ctime(&t), fdDump);
2579 fflush(fdDump);
2580 }
2581#endif
2582
2583 g_fWindInitCalled = TRUE;
2584
2585#ifdef FEAT_MOUSE
2586 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2587#endif
2588
2589#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002590 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591#endif
2592
2593 /* This will be NULL on anything but NT 4.0 */
2594 s_pfnGetConsoleKeyboardLayoutName =
2595 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2596 "GetConsoleKeyboardLayoutNameA");
2597}
2598
2599/*
2600 * non-GUI version of mch_exit().
2601 * Shut down and exit with status `r'
2602 * Careful: mch_exit() may be called before mch_init()!
2603 */
2604 void
2605mch_exit(int r)
2606{
2607 stoptermcap();
2608
2609 if (g_fWindInitCalled)
2610 settmode(TMODE_COOK);
2611
2612 ml_close_all(TRUE); /* remove all memfiles */
2613
2614 if (g_fWindInitCalled)
2615 {
2616#ifdef FEAT_TITLE
2617 mch_restore_title(3);
2618 /*
2619 * Restore both the small and big icons of the console window to
2620 * what they were at startup. Don't do this when the window is
2621 * closed, Vim would hang here.
2622 */
2623 if (g_fCanChangeIcon && !g_fForceExit)
2624 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2625#endif
2626
2627#ifdef MCH_WRITE_DUMP
2628 if (fdDump)
2629 {
2630 time_t t;
2631
2632 time(&t);
2633 fputs(ctime(&t), fdDump);
2634 fclose(fdDump);
2635 }
2636 fdDump = NULL;
2637#endif
2638 }
2639
2640 SetConsoleCursorInfo(g_hConOut, &g_cci);
2641 SetConsoleMode(g_hConIn, g_cmodein);
2642 SetConsoleMode(g_hConOut, g_cmodeout);
2643
2644#ifdef DYNAMIC_GETTEXT
2645 dyn_libintl_end();
2646#endif
2647
2648 exit(r);
2649}
2650#endif /* !FEAT_GUI_W32 */
2651
Bram Moolenaar071d4272004-06-13 20:20:40 +00002652/*
2653 * Do we have an interactive window?
2654 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002655/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002656 int
2657mch_check_win(
2658 int argc,
2659 char **argv)
2660{
2661 get_exe_name();
2662
2663#ifdef FEAT_GUI_W32
2664 return OK; /* GUI always has a tty */
2665#else
2666 if (isatty(1))
2667 return OK;
2668 return FAIL;
2669#endif
2670}
2671
2672
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002673#ifdef FEAT_MBYTE
2674/*
2675 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2676 * if it already exists. When "len" is > 0, also expand short to long
2677 * filenames.
2678 * Return FAIL if wide functions are not available, OK otherwise.
2679 * NOTE: much of this is identical to fname_case(), keep in sync!
2680 */
2681 static int
2682fname_casew(
2683 WCHAR *name,
2684 int len)
2685{
2686 WCHAR szTrueName[_MAX_PATH + 2];
2687 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2688 WCHAR *ptrue, *ptruePrev;
2689 WCHAR *porig, *porigPrev;
2690 int flen;
2691 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002692 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002693 int c;
2694 int slen;
2695
2696 flen = (int)wcslen(name);
2697 if (flen > _MAX_PATH)
2698 return OK;
2699
2700 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2701
2702 /* Build the new name in szTrueName[] one component at a time. */
2703 porig = name;
2704 ptrue = szTrueName;
2705
2706 if (iswalpha(porig[0]) && porig[1] == L':')
2707 {
2708 /* copy leading drive letter */
2709 *ptrue++ = *porig++;
2710 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002711 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002712 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002713
2714 while (*porig != NUL)
2715 {
2716 /* copy \ characters */
2717 while (*porig == psepc)
2718 *ptrue++ = *porig++;
2719
2720 ptruePrev = ptrue;
2721 porigPrev = porig;
2722 while (*porig != NUL && *porig != psepc)
2723 {
2724 *ptrue++ = *porig++;
2725 }
2726 *ptrue = NUL;
2727
2728 /* To avoid a slow failure append "\*" when searching a directory,
2729 * server or network share. */
2730 wcscpy(szTrueNameTemp, szTrueName);
2731 slen = (int)wcslen(szTrueNameTemp);
2732 if (*porig == psepc && slen + 2 < _MAX_PATH)
2733 wcscpy(szTrueNameTemp + slen, L"\\*");
2734
2735 /* Skip "", "." and "..". */
2736 if (ptrue > ptruePrev
2737 && (ptruePrev[0] != L'.'
2738 || (ptruePrev[1] != NUL
2739 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2740 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2741 != INVALID_HANDLE_VALUE)
2742 {
2743 c = *porig;
2744 *porig = NUL;
2745
2746 /* Only use the match when it's the same name (ignoring case) or
2747 * expansion is allowed and there is a match with the short name
2748 * and there is enough room. */
2749 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2750 || (len > 0
2751 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2752 && (int)(ptruePrev - szTrueName)
2753 + (int)wcslen(fb.cFileName) < len)))
2754 {
2755 wcscpy(ptruePrev, fb.cFileName);
2756
2757 /* Look for exact match and prefer it if found. Must be a
2758 * long name, otherwise there would be only one match. */
2759 while (FindNextFileW(hFind, &fb))
2760 {
2761 if (*fb.cAlternateFileName != NUL
2762 && (wcscoll(porigPrev, fb.cFileName) == 0
2763 || (len > 0
2764 && (_wcsicoll(porigPrev,
2765 fb.cAlternateFileName) == 0
2766 && (int)(ptruePrev - szTrueName)
2767 + (int)wcslen(fb.cFileName) < len))))
2768 {
2769 wcscpy(ptruePrev, fb.cFileName);
2770 break;
2771 }
2772 }
2773 }
2774 FindClose(hFind);
2775 *porig = c;
2776 ptrue = ptruePrev + wcslen(ptruePrev);
2777 }
2778 else if (hFind == INVALID_HANDLE_VALUE
2779 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2780 return FAIL;
2781 }
2782
2783 wcscpy(name, szTrueName);
2784 return OK;
2785}
2786#endif
2787
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788/*
2789 * fname_case(): Set the case of the file name, if it already exists.
2790 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002791 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792 */
2793 void
2794fname_case(
2795 char_u *name,
2796 int len)
2797{
2798 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002799 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 char *ptrue, *ptruePrev;
2801 char *porig, *porigPrev;
2802 int flen;
2803 WIN32_FIND_DATA fb;
2804 HANDLE hFind;
2805 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002806 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002808 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002809 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810 return;
2811
2812 slash_adjust(name);
2813
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002814#ifdef FEAT_MBYTE
2815 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2816 {
2817 WCHAR *p = enc_to_utf16(name, NULL);
2818
2819 if (p != NULL)
2820 {
2821 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002822 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002823
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002824 wcsncpy(buf, p, _MAX_PATH);
2825 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002826 vim_free(p);
2827
2828 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2829 {
2830 q = utf16_to_enc(buf, NULL);
2831 if (q != NULL)
2832 {
2833 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2834 vim_free(q);
2835 return;
2836 }
2837 }
2838 }
2839 /* Retry with non-wide function (for Windows 98). */
2840 }
2841#endif
2842
2843 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2844 * So we should check this after calling wide function. */
2845 if (flen > _MAX_PATH)
2846 return;
2847
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002849 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850 ptrue = szTrueName;
2851
2852 if (isalpha(porig[0]) && porig[1] == ':')
2853 {
2854 /* copy leading drive letter */
2855 *ptrue++ = *porig++;
2856 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002858 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859
2860 while (*porig != NUL)
2861 {
2862 /* copy \ characters */
2863 while (*porig == psepc)
2864 *ptrue++ = *porig++;
2865
2866 ptruePrev = ptrue;
2867 porigPrev = porig;
2868 while (*porig != NUL && *porig != psepc)
2869 {
2870#ifdef FEAT_MBYTE
2871 int l;
2872
2873 if (enc_dbcs)
2874 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002875 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876 while (--l >= 0)
2877 *ptrue++ = *porig++;
2878 }
2879 else
2880#endif
2881 *ptrue++ = *porig++;
2882 }
2883 *ptrue = NUL;
2884
Bram Moolenaar464c9252010-10-13 20:37:41 +02002885 /* To avoid a slow failure append "\*" when searching a directory,
2886 * server or network share. */
2887 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002888 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002889 if (*porig == psepc && slen + 2 < _MAX_PATH)
2890 STRCPY(szTrueNameTemp + slen, "\\*");
2891
Bram Moolenaar071d4272004-06-13 20:20:40 +00002892 /* Skip "", "." and "..". */
2893 if (ptrue > ptruePrev
2894 && (ptruePrev[0] != '.'
2895 || (ptruePrev[1] != NUL
2896 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002897 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 != INVALID_HANDLE_VALUE)
2899 {
2900 c = *porig;
2901 *porig = NUL;
2902
2903 /* Only use the match when it's the same name (ignoring case) or
2904 * expansion is allowed and there is a match with the short name
2905 * and there is enough room. */
2906 if (_stricoll(porigPrev, fb.cFileName) == 0
2907 || (len > 0
2908 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2909 && (int)(ptruePrev - szTrueName)
2910 + (int)strlen(fb.cFileName) < len)))
2911 {
2912 STRCPY(ptruePrev, fb.cFileName);
2913
2914 /* Look for exact match and prefer it if found. Must be a
2915 * long name, otherwise there would be only one match. */
2916 while (FindNextFile(hFind, &fb))
2917 {
2918 if (*fb.cAlternateFileName != NUL
2919 && (strcoll(porigPrev, fb.cFileName) == 0
2920 || (len > 0
2921 && (_stricoll(porigPrev,
2922 fb.cAlternateFileName) == 0
2923 && (int)(ptruePrev - szTrueName)
2924 + (int)strlen(fb.cFileName) < len))))
2925 {
2926 STRCPY(ptruePrev, fb.cFileName);
2927 break;
2928 }
2929 }
2930 }
2931 FindClose(hFind);
2932 *porig = c;
2933 ptrue = ptruePrev + strlen(ptruePrev);
2934 }
2935 }
2936
2937 STRCPY(name, szTrueName);
2938}
2939
2940
2941/*
2942 * Insert user name in s[len].
2943 */
2944 int
2945mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002946 char_u *s,
2947 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002949 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 DWORD cch = sizeof szUserName;
2951
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002952#ifdef FEAT_MBYTE
2953 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2954 {
2955 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2956 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2957
2958 if (GetUserNameW(wszUserName, &wcch))
2959 {
2960 char_u *p = utf16_to_enc(wszUserName, NULL);
2961
2962 if (p != NULL)
2963 {
2964 vim_strncpy(s, p, len - 1);
2965 vim_free(p);
2966 return OK;
2967 }
2968 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002969 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2970 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002971 /* Retry with non-wide function (for Windows 98). */
2972 }
2973#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 if (GetUserName(szUserName, &cch))
2975 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002976 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977 return OK;
2978 }
2979 s[0] = NUL;
2980 return FAIL;
2981}
2982
2983
2984/*
2985 * Insert host name in s[len].
2986 */
2987 void
2988mch_get_host_name(
2989 char_u *s,
2990 int len)
2991{
2992 DWORD cch = len;
2993
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002994#ifdef FEAT_MBYTE
2995 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2996 {
2997 WCHAR wszHostName[256 + 1];
2998 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2999
3000 if (GetComputerNameW(wszHostName, &wcch))
3001 {
3002 char_u *p = utf16_to_enc(wszHostName, NULL);
3003
3004 if (p != NULL)
3005 {
3006 vim_strncpy(s, p, len - 1);
3007 vim_free(p);
3008 return;
3009 }
3010 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003011 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3012 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003013 /* Retry with non-wide function (for Windows 98). */
3014 }
3015#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003016 if (!GetComputerName((LPSTR)s, &cch))
3017 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018}
3019
3020
3021/*
3022 * return process ID
3023 */
3024 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003025mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026{
3027 return (long)GetCurrentProcessId();
3028}
3029
3030
3031/*
3032 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3033 * Return OK for success, FAIL for failure.
3034 */
3035 int
3036mch_dirname(
3037 char_u *buf,
3038 int len)
3039{
3040 /*
3041 * Originally this was:
3042 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3043 * But the Win32s known bug list says that getcwd() doesn't work
3044 * so use the Win32 system call instead. <Negri>
3045 */
3046#ifdef FEAT_MBYTE
3047 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3048 {
3049 WCHAR wbuf[_MAX_PATH + 1];
3050
3051 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3052 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003053 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054
3055 if (p != NULL)
3056 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003057 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058 vim_free(p);
3059 return OK;
3060 }
3061 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003062 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3063 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 /* Retry with non-wide function (for Windows 98). */
3065 }
3066#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003067 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068}
3069
3070/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003071 * Get file permissions for "name".
3072 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073 */
3074 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003075mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003077 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003078 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003080 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003081 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082}
3083
3084
3085/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003086 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003087 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003088 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 */
3090 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003091mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003093 long n = -1;
3094
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095#ifdef FEAT_MBYTE
3096 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3097 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003098 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099
3100 if (p != NULL)
3101 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003102 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003103 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003104 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003105 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106 /* Retry with non-wide function (for Windows 98). */
3107 }
3108 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003109 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003111 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003112 if (n == -1)
3113 return FAIL;
3114
3115 win32_set_archive(name);
3116
3117 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118}
3119
3120/*
3121 * Set hidden flag for "name".
3122 */
3123 void
3124mch_hide(char_u *name)
3125{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003126 int attrs = win32_getattrs(name);
3127 if (attrs == -1)
3128 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003130 attrs |= FILE_ATTRIBUTE_HIDDEN;
3131 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003132}
3133
3134/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003135 * Return TRUE if file "name" exists and is hidden.
3136 */
3137 int
3138mch_ishidden(char_u *name)
3139{
3140 int f = win32_getattrs(name);
3141
3142 if (f == -1)
3143 return FALSE; /* file does not exist at all */
3144
3145 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3146}
3147
3148/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149 * return TRUE if "name" is a directory
3150 * return FALSE if "name" is not a directory or upon error
3151 */
3152 int
3153mch_isdir(char_u *name)
3154{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003155 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156
3157 if (f == -1)
3158 return FALSE; /* file does not exist at all */
3159
3160 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3161}
3162
3163/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003164 * return TRUE if "name" is a directory, NOT a symlink to a directory
3165 * return FALSE if "name" is not a directory
3166 * return FALSE for error
3167 */
3168 int
3169mch_isrealdir(char_u *name)
3170{
3171 return mch_isdir(name) && !mch_is_symbolic_link(name);
3172}
3173
3174/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003175 * Create directory "name".
3176 * Return 0 on success, -1 on error.
3177 */
3178 int
3179mch_mkdir(char_u *name)
3180{
3181#ifdef FEAT_MBYTE
3182 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3183 {
3184 WCHAR *p;
3185 int retval;
3186
3187 p = enc_to_utf16(name, NULL);
3188 if (p == NULL)
3189 return -1;
3190 retval = _wmkdir(p);
3191 vim_free(p);
3192 return retval;
3193 }
3194#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003195 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003196}
3197
3198/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003199 * Delete directory "name".
3200 * Return 0 on success, -1 on error.
3201 */
3202 int
3203mch_rmdir(char_u *name)
3204{
3205#ifdef FEAT_MBYTE
3206 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3207 {
3208 WCHAR *p;
3209 int retval;
3210
3211 p = enc_to_utf16(name, NULL);
3212 if (p == NULL)
3213 return -1;
3214 retval = _wrmdir(p);
3215 vim_free(p);
3216 return retval;
3217 }
3218#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003219 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003220}
3221
3222/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003223 * Return TRUE if file "fname" has more than one link.
3224 */
3225 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003226mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003227{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003228 BY_HANDLE_FILE_INFORMATION info;
3229
3230 return win32_fileinfo(fname, &info) == FILEINFO_OK
3231 && info.nNumberOfLinks > 1;
3232}
3233
3234/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003235 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003236 */
3237 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003238mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003239{
3240 HANDLE hFind;
3241 int res = FALSE;
3242 WIN32_FIND_DATAA findDataA;
3243 DWORD fileFlags = 0, reparseTag = 0;
3244#ifdef FEAT_MBYTE
3245 WCHAR *wn = NULL;
3246 WIN32_FIND_DATAW findDataW;
3247
3248 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003249 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003250 if (wn != NULL)
3251 {
3252 hFind = FindFirstFileW(wn, &findDataW);
3253 vim_free(wn);
3254 if (hFind == INVALID_HANDLE_VALUE
3255 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3256 {
3257 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003258 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003259 if (hFind != INVALID_HANDLE_VALUE)
3260 {
3261 fileFlags = findDataA.dwFileAttributes;
3262 reparseTag = findDataA.dwReserved0;
3263 }
3264 }
3265 else
3266 {
3267 fileFlags = findDataW.dwFileAttributes;
3268 reparseTag = findDataW.dwReserved0;
3269 }
3270 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003271 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003272#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003273 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003274 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003275 if (hFind != INVALID_HANDLE_VALUE)
3276 {
3277 fileFlags = findDataA.dwFileAttributes;
3278 reparseTag = findDataA.dwReserved0;
3279 }
3280 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003281
3282 if (hFind != INVALID_HANDLE_VALUE)
3283 FindClose(hFind);
3284
3285 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003286 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3287 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003288 res = TRUE;
3289
3290 return res;
3291}
3292
3293/*
3294 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3295 * link.
3296 */
3297 int
3298mch_is_linked(char_u *fname)
3299{
3300 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3301 return TRUE;
3302 return FALSE;
3303}
3304
3305/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003306 * Get the by-handle-file-information for "fname".
3307 * Returns FILEINFO_OK when OK.
3308 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3309 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3310 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3311 */
3312 int
3313win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3314{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003315 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003316 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003317#ifdef FEAT_MBYTE
3318 WCHAR *wn = NULL;
3319
3320 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003321 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003322 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003323 if (wn == NULL)
3324 res = FILEINFO_ENC_FAIL;
3325 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003326 if (wn != NULL)
3327 {
3328 hFile = CreateFileW(wn, /* file name */
3329 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003330 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003331 NULL, /* security descriptor */
3332 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003333 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003334 NULL); /* handle to template file */
3335 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003336 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003337 {
3338 /* Retry with non-wide function (for Windows 98). */
3339 vim_free(wn);
3340 wn = NULL;
3341 }
3342 }
3343 if (wn == NULL)
3344#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003345 hFile = CreateFile((LPCSTR)fname, /* file name */
3346 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003347 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003348 NULL, /* security descriptor */
3349 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003350 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003351 NULL); /* handle to template file */
3352
3353 if (hFile != INVALID_HANDLE_VALUE)
3354 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003355 if (GetFileInformationByHandle(hFile, info) != 0)
3356 res = FILEINFO_OK;
3357 else
3358 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003359 CloseHandle(hFile);
3360 }
3361
3362#ifdef FEAT_MBYTE
3363 vim_free(wn);
3364#endif
3365 return res;
3366}
3367
3368/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003369 * get file attributes for `name'
3370 * -1 : error
3371 * else FILE_ATTRIBUTE_* defined in winnt.h
3372 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003373 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003374win32_getattrs(char_u *name)
3375{
3376 int attr;
3377#ifdef FEAT_MBYTE
3378 WCHAR *p = NULL;
3379
3380 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3381 p = enc_to_utf16(name, NULL);
3382
3383 if (p != NULL)
3384 {
3385 attr = GetFileAttributesW(p);
3386 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3387 {
3388 /* Retry with non-wide function (for Windows 98). */
3389 vim_free(p);
3390 p = NULL;
3391 }
3392 }
3393 if (p == NULL)
3394#endif
3395 attr = GetFileAttributes((char *)name);
3396#ifdef FEAT_MBYTE
3397 vim_free(p);
3398#endif
3399 return attr;
3400}
3401
3402/*
3403 * set file attributes for `name' to `attrs'
3404 *
3405 * return -1 for failure, 0 otherwise
3406 */
3407 static
3408 int
3409win32_setattrs(char_u *name, int attrs)
3410{
3411 int res;
3412#ifdef FEAT_MBYTE
3413 WCHAR *p = NULL;
3414
3415 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3416 p = enc_to_utf16(name, NULL);
3417
3418 if (p != NULL)
3419 {
3420 res = SetFileAttributesW(p, attrs);
3421 if (res == FALSE
3422 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3423 {
3424 /* Retry with non-wide function (for Windows 98). */
3425 vim_free(p);
3426 p = NULL;
3427 }
3428 }
3429 if (p == NULL)
3430#endif
3431 res = SetFileAttributes((char *)name, attrs);
3432#ifdef FEAT_MBYTE
3433 vim_free(p);
3434#endif
3435 return res ? 0 : -1;
3436}
3437
3438/*
3439 * Set archive flag for "name".
3440 */
3441 static
3442 int
3443win32_set_archive(char_u *name)
3444{
3445 int attrs = win32_getattrs(name);
3446 if (attrs == -1)
3447 return -1;
3448
3449 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3450 return win32_setattrs(name, attrs);
3451}
3452
3453/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454 * Return TRUE if file or directory "name" is writable (not readonly).
3455 * Strange semantics of Win32: a readonly directory is writable, but you can't
3456 * delete a file. Let's say this means it is writable.
3457 */
3458 int
3459mch_writable(char_u *name)
3460{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003461 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003463 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3464 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465}
3466
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467/*
3468 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003469 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470 * Return -1 if unknown.
3471 */
3472 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003473mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003475 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003476 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003477 char_u *p;
3478
3479 if (len >= _MAX_PATH) /* safety check */
3480 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003481 if (!use_path)
3482 {
3483 /* TODO: check if file is really executable. */
3484 return mch_getperm(name) != -1 && !mch_isdir(name);
3485 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003486
3487 /* If there already is an extension try using the name directly. Also do
3488 * this with a Unix-shell like 'shell'. */
3489 if (vim_strchr(gettail(name), '.') != NULL
3490 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003491 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003492 return TRUE;
3493
3494 /*
3495 * Loop over all extensions in $PATHEXT.
3496 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003497 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003498 p = mch_getenv("PATHEXT");
3499 if (p == NULL)
3500 p = (char_u *)".com;.exe;.bat;.cmd";
3501 while (*p)
3502 {
3503 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3504 {
3505 /* A single "." means no extension is added. */
3506 buf[len] = NUL;
3507 ++p;
3508 if (*p)
3509 ++p;
3510 }
3511 else
3512 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003513 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003514 return TRUE;
3515 }
3516 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518
3519/*
3520 * Check what "name" is:
3521 * NODE_NORMAL: file or directory (or doesn't exist)
3522 * NODE_WRITABLE: writable device, socket, fifo, etc.
3523 * NODE_OTHER: non-writable things
3524 */
3525 int
3526mch_nodetype(char_u *name)
3527{
3528 HANDLE hFile;
3529 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003530#ifdef FEAT_MBYTE
3531 WCHAR *wn = NULL;
3532#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533
Bram Moolenaar043545e2006-10-10 16:44:07 +00003534 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3535 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3536 * here. */
3537 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3538 return NODE_WRITABLE;
3539
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003540#ifdef FEAT_MBYTE
3541 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3542 {
3543 wn = enc_to_utf16(name, NULL);
3544 if (wn != NULL)
3545 {
3546 hFile = CreateFileW(wn, /* file name */
3547 GENERIC_WRITE, /* access mode */
3548 0, /* share mode */
3549 NULL, /* security descriptor */
3550 OPEN_EXISTING, /* creation disposition */
3551 0, /* file attributes */
3552 NULL); /* handle to template file */
3553 if (hFile == INVALID_HANDLE_VALUE
3554 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3555 {
3556 /* Retry with non-wide function (for Windows 98). */
3557 vim_free(wn);
3558 wn = NULL;
3559 }
3560 }
3561 }
3562 if (wn == NULL)
3563#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003564 hFile = CreateFile((LPCSTR)name, /* file name */
3565 GENERIC_WRITE, /* access mode */
3566 0, /* share mode */
3567 NULL, /* security descriptor */
3568 OPEN_EXISTING, /* creation disposition */
3569 0, /* file attributes */
3570 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003571
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003572#ifdef FEAT_MBYTE
3573 vim_free(wn);
3574#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 if (hFile == INVALID_HANDLE_VALUE)
3576 return NODE_NORMAL;
3577
3578 type = GetFileType(hFile);
3579 CloseHandle(hFile);
3580 if (type == FILE_TYPE_CHAR)
3581 return NODE_WRITABLE;
3582 if (type == FILE_TYPE_DISK)
3583 return NODE_NORMAL;
3584 return NODE_OTHER;
3585}
3586
3587#ifdef HAVE_ACL
3588struct my_acl
3589{
3590 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3591 PSID pSidOwner;
3592 PSID pSidGroup;
3593 PACL pDacl;
3594 PACL pSacl;
3595};
3596#endif
3597
3598/*
3599 * Return a pointer to the ACL of file "fname" in allocated memory.
3600 * Return NULL if the ACL is not available for whatever reason.
3601 */
3602 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003603mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604{
3605#ifndef HAVE_ACL
3606 return (vim_acl_T)NULL;
3607#else
3608 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003609 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610
3611 /* This only works on Windows NT and 2000. */
3612 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3613 {
3614 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3615 if (p != NULL)
3616 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003617# ifdef FEAT_MBYTE
3618 WCHAR *wn = NULL;
3619
3620 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3621 wn = enc_to_utf16(fname, NULL);
3622 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003623 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003624 /* Try to retrieve the entire security descriptor. */
3625 err = pGetNamedSecurityInfoW(
3626 wn, // Abstract filename
3627 SE_FILE_OBJECT, // File Object
3628 OWNER_SECURITY_INFORMATION |
3629 GROUP_SECURITY_INFORMATION |
3630 DACL_SECURITY_INFORMATION |
3631 SACL_SECURITY_INFORMATION,
3632 &p->pSidOwner, // Ownership information.
3633 &p->pSidGroup, // Group membership.
3634 &p->pDacl, // Discretionary information.
3635 &p->pSacl, // For auditing purposes.
3636 &p->pSecurityDescriptor);
3637 if (err == ERROR_ACCESS_DENIED ||
3638 err == ERROR_PRIVILEGE_NOT_HELD)
3639 {
3640 /* Retrieve only DACL. */
3641 (void)pGetNamedSecurityInfoW(
3642 wn,
3643 SE_FILE_OBJECT,
3644 DACL_SECURITY_INFORMATION,
3645 NULL,
3646 NULL,
3647 &p->pDacl,
3648 NULL,
3649 &p->pSecurityDescriptor);
3650 }
3651 if (p->pSecurityDescriptor == NULL)
3652 {
3653 mch_free_acl((vim_acl_T)p);
3654 p = NULL;
3655 }
3656 vim_free(wn);
3657 }
3658 else
3659# endif
3660 {
3661 /* Try to retrieve the entire security descriptor. */
3662 err = pGetNamedSecurityInfo(
3663 (LPSTR)fname, // Abstract filename
3664 SE_FILE_OBJECT, // File Object
3665 OWNER_SECURITY_INFORMATION |
3666 GROUP_SECURITY_INFORMATION |
3667 DACL_SECURITY_INFORMATION |
3668 SACL_SECURITY_INFORMATION,
3669 &p->pSidOwner, // Ownership information.
3670 &p->pSidGroup, // Group membership.
3671 &p->pDacl, // Discretionary information.
3672 &p->pSacl, // For auditing purposes.
3673 &p->pSecurityDescriptor);
3674 if (err == ERROR_ACCESS_DENIED ||
3675 err == ERROR_PRIVILEGE_NOT_HELD)
3676 {
3677 /* Retrieve only DACL. */
3678 (void)pGetNamedSecurityInfo(
3679 (LPSTR)fname,
3680 SE_FILE_OBJECT,
3681 DACL_SECURITY_INFORMATION,
3682 NULL,
3683 NULL,
3684 &p->pDacl,
3685 NULL,
3686 &p->pSecurityDescriptor);
3687 }
3688 if (p->pSecurityDescriptor == NULL)
3689 {
3690 mch_free_acl((vim_acl_T)p);
3691 p = NULL;
3692 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693 }
3694 }
3695 }
3696
3697 return (vim_acl_T)p;
3698#endif
3699}
3700
Bram Moolenaar27515922013-06-29 15:36:26 +02003701#ifdef HAVE_ACL
3702/*
3703 * Check if "acl" contains inherited ACE.
3704 */
3705 static BOOL
3706is_acl_inherited(PACL acl)
3707{
3708 DWORD i;
3709 ACL_SIZE_INFORMATION acl_info;
3710 PACCESS_ALLOWED_ACE ace;
3711
3712 acl_info.AceCount = 0;
3713 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3714 for (i = 0; i < acl_info.AceCount; i++)
3715 {
3716 GetAce(acl, i, (LPVOID *)&ace);
3717 if (ace->Header.AceFlags & INHERITED_ACE)
3718 return TRUE;
3719 }
3720 return FALSE;
3721}
3722#endif
3723
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724/*
3725 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3726 * Errors are ignored.
3727 * This must only be called with "acl" equal to what mch_get_acl() returned.
3728 */
3729 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003730mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731{
3732#ifdef HAVE_ACL
3733 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003734 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003735
3736 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003737 {
3738# ifdef FEAT_MBYTE
3739 WCHAR *wn = NULL;
3740# endif
3741
3742 /* Set security flags */
3743 if (p->pSidOwner)
3744 sec_info |= OWNER_SECURITY_INFORMATION;
3745 if (p->pSidGroup)
3746 sec_info |= GROUP_SECURITY_INFORMATION;
3747 if (p->pDacl)
3748 {
3749 sec_info |= DACL_SECURITY_INFORMATION;
3750 /* Do not inherit its parent's DACL.
3751 * If the DACL is inherited, Cygwin permissions would be changed.
3752 */
3753 if (!is_acl_inherited(p->pDacl))
3754 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3755 }
3756 if (p->pSacl)
3757 sec_info |= SACL_SECURITY_INFORMATION;
3758
3759# ifdef FEAT_MBYTE
3760 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3761 wn = enc_to_utf16(fname, NULL);
3762 if (wn != NULL)
3763 {
3764 (void)pSetNamedSecurityInfoW(
3765 wn, // Abstract filename
3766 SE_FILE_OBJECT, // File Object
3767 sec_info,
3768 p->pSidOwner, // Ownership information.
3769 p->pSidGroup, // Group membership.
3770 p->pDacl, // Discretionary information.
3771 p->pSacl // For auditing purposes.
3772 );
3773 vim_free(wn);
3774 }
3775 else
3776# endif
3777 {
3778 (void)pSetNamedSecurityInfo(
3779 (LPSTR)fname, // Abstract filename
3780 SE_FILE_OBJECT, // File Object
3781 sec_info,
3782 p->pSidOwner, // Ownership information.
3783 p->pSidGroup, // Group membership.
3784 p->pDacl, // Discretionary information.
3785 p->pSacl // For auditing purposes.
3786 );
3787 }
3788 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789#endif
3790}
3791
3792 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003793mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794{
3795#ifdef HAVE_ACL
3796 struct my_acl *p = (struct my_acl *)acl;
3797
3798 if (p != NULL)
3799 {
3800 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3801 vim_free(p);
3802 }
3803#endif
3804}
3805
3806#ifndef FEAT_GUI_W32
3807
3808/*
3809 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3810 */
3811 static BOOL WINAPI
3812handler_routine(
3813 DWORD dwCtrlType)
3814{
3815 switch (dwCtrlType)
3816 {
3817 case CTRL_C_EVENT:
3818 if (ctrl_c_interrupts)
3819 g_fCtrlCPressed = TRUE;
3820 return TRUE;
3821
3822 case CTRL_BREAK_EVENT:
3823 g_fCBrkPressed = TRUE;
3824 return TRUE;
3825
3826 /* fatal events: shut down gracefully */
3827 case CTRL_CLOSE_EVENT:
3828 case CTRL_LOGOFF_EVENT:
3829 case CTRL_SHUTDOWN_EVENT:
3830 windgoto((int)Rows - 1, 0);
3831 g_fForceExit = TRUE;
3832
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003833 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 (dwCtrlType == CTRL_CLOSE_EVENT
3835 ? _("close")
3836 : dwCtrlType == CTRL_LOGOFF_EVENT
3837 ? _("logoff")
3838 : _("shutdown")));
3839#ifdef DEBUG
3840 OutputDebugString(IObuff);
3841#endif
3842
3843 preserve_exit(); /* output IObuff, preserve files and exit */
3844
3845 return TRUE; /* not reached */
3846
3847 default:
3848 return FALSE;
3849 }
3850}
3851
3852
3853/*
3854 * set the tty in (raw) ? "raw" : "cooked" mode
3855 */
3856 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003857mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003858{
3859 DWORD cmodein;
3860 DWORD cmodeout;
3861 BOOL bEnableHandler;
3862
3863 GetConsoleMode(g_hConIn, &cmodein);
3864 GetConsoleMode(g_hConOut, &cmodeout);
3865 if (tmode == TMODE_RAW)
3866 {
3867 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3868 ENABLE_ECHO_INPUT);
3869#ifdef FEAT_MOUSE
3870 if (g_fMouseActive)
3871 cmodein |= ENABLE_MOUSE_INPUT;
3872#endif
3873 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3874 bEnableHandler = TRUE;
3875 }
3876 else /* cooked */
3877 {
3878 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3879 ENABLE_ECHO_INPUT);
3880 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3881 bEnableHandler = FALSE;
3882 }
3883 SetConsoleMode(g_hConIn, cmodein);
3884 SetConsoleMode(g_hConOut, cmodeout);
3885 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3886
3887#ifdef MCH_WRITE_DUMP
3888 if (fdDump)
3889 {
3890 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3891 tmode == TMODE_RAW ? "raw" :
3892 tmode == TMODE_COOK ? "cooked" : "normal",
3893 cmodein, cmodeout);
3894 fflush(fdDump);
3895 }
3896#endif
3897}
3898
3899
3900/*
3901 * Get the size of the current window in `Rows' and `Columns'
3902 * Return OK when size could be determined, FAIL otherwise.
3903 */
3904 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003905mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906{
3907 CONSOLE_SCREEN_BUFFER_INFO csbi;
3908
3909 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3910 {
3911 /*
3912 * For some reason, we are trying to get the screen dimensions
3913 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3914 * variables are really intended to mean the size of Vim screen
3915 * while in termcap mode.
3916 */
3917 Rows = g_cbTermcap.Info.dwSize.Y;
3918 Columns = g_cbTermcap.Info.dwSize.X;
3919 }
3920 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3921 {
3922 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3923 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3924 }
3925 else
3926 {
3927 Rows = 25;
3928 Columns = 80;
3929 }
3930 return OK;
3931}
3932
3933/*
3934 * Set a console window to `xSize' * `ySize'
3935 */
3936 static void
3937ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003938 HANDLE hConsole,
3939 int xSize,
3940 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003941{
3942 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3943 SMALL_RECT srWindowRect; /* hold the new console size */
3944 COORD coordScreen;
3945
3946#ifdef MCH_WRITE_DUMP
3947 if (fdDump)
3948 {
3949 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3950 fflush(fdDump);
3951 }
3952#endif
3953
3954 /* get the largest size we can size the console window to */
3955 coordScreen = GetLargestConsoleWindowSize(hConsole);
3956
3957 /* define the new console window size and scroll position */
3958 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3959 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3960 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3961
3962 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3963 {
3964 int sx, sy;
3965
3966 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3967 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3968 if (sy < ySize || sx < xSize)
3969 {
3970 /*
3971 * Increasing number of lines/columns, do buffer first.
3972 * Use the maximal size in x and y direction.
3973 */
3974 if (sy < ySize)
3975 coordScreen.Y = ySize;
3976 else
3977 coordScreen.Y = sy;
3978 if (sx < xSize)
3979 coordScreen.X = xSize;
3980 else
3981 coordScreen.X = sx;
3982 SetConsoleScreenBufferSize(hConsole, coordScreen);
3983 }
3984 }
3985
3986 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3987 {
3988#ifdef MCH_WRITE_DUMP
3989 if (fdDump)
3990 {
3991 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3992 GetLastError());
3993 fflush(fdDump);
3994 }
3995#endif
3996 }
3997
3998 /* define the new console buffer size */
3999 coordScreen.X = xSize;
4000 coordScreen.Y = ySize;
4001
4002 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4003 {
4004#ifdef MCH_WRITE_DUMP
4005 if (fdDump)
4006 {
4007 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4008 GetLastError());
4009 fflush(fdDump);
4010 }
4011#endif
4012 }
4013}
4014
4015
4016/*
4017 * Set the console window to `Rows' * `Columns'
4018 */
4019 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004020mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004021{
4022 COORD coordScreen;
4023
4024 /* Don't change window size while still starting up */
4025 if (suppress_winsize != 0)
4026 {
4027 suppress_winsize = 2;
4028 return;
4029 }
4030
4031 if (term_console)
4032 {
4033 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4034
4035 /* Clamp Rows and Columns to reasonable values */
4036 if (Rows > coordScreen.Y)
4037 Rows = coordScreen.Y;
4038 if (Columns > coordScreen.X)
4039 Columns = coordScreen.X;
4040
4041 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4042 }
4043}
4044
4045/*
4046 * Rows and/or Columns has changed.
4047 */
4048 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004049mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004050{
4051 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4052}
4053
4054
4055/*
4056 * Called when started up, to set the winsize that was delayed.
4057 */
4058 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004059mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004060{
4061 if (suppress_winsize == 2)
4062 {
4063 suppress_winsize = 0;
4064 mch_set_shellsize();
4065 shell_resized();
4066 }
4067 suppress_winsize = 0;
4068}
4069#endif /* FEAT_GUI_W32 */
4070
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004071 static BOOL
4072vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004073 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004074 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004075 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004076 STARTUPINFO *si,
4077 PROCESS_INFORMATION *pi)
4078{
4079# ifdef FEAT_MBYTE
4080 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4081 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004082 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004083
4084 if (wcmd != NULL)
4085 {
4086 BOOL ret;
4087 ret = CreateProcessW(
4088 NULL, /* Executable name */
4089 wcmd, /* Command to execute */
4090 NULL, /* Process security attributes */
4091 NULL, /* Thread security attributes */
4092 inherit_handles, /* Inherit handles */
4093 flags, /* Creation flags */
4094 NULL, /* Environment */
4095 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004096 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004097 pi); /* Process information */
4098 vim_free(wcmd);
4099 return ret;
4100 }
4101 }
4102#endif
4103 return CreateProcess(
4104 NULL, /* Executable name */
4105 cmd, /* Command to execute */
4106 NULL, /* Process security attributes */
4107 NULL, /* Thread security attributes */
4108 inherit_handles, /* Inherit handles */
4109 flags, /* Creation flags */
4110 NULL, /* Environment */
4111 NULL, /* Current directory */
4112 si, /* Startup information */
4113 pi); /* Process information */
4114}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115
4116
4117#if defined(FEAT_GUI_W32) || defined(PROTO)
4118
4119/*
4120 * Specialised version of system() for Win32 GUI mode.
4121 * This version proceeds as follows:
4122 * 1. Create a console window for use by the subprocess
4123 * 2. Run the subprocess (it gets the allocated console by default)
4124 * 3. Wait for the subprocess to terminate and get its exit code
4125 * 4. Prompt the user to press a key to close the console window
4126 */
4127 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004128mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129{
4130 STARTUPINFO si;
4131 PROCESS_INFORMATION pi;
4132 DWORD ret = 0;
4133 HWND hwnd = GetFocus();
4134
4135 si.cb = sizeof(si);
4136 si.lpReserved = NULL;
4137 si.lpDesktop = NULL;
4138 si.lpTitle = NULL;
4139 si.dwFlags = STARTF_USESHOWWINDOW;
4140 /*
4141 * It's nicer to run a filter command in a minimized window, but in
4142 * Windows 95 this makes the command MUCH slower. We can't do it under
4143 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004144 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145 */
Bram Moolenaar78c7e272016-08-25 23:19:29 +02004146 if ((options & SHELL_DOOUT) && !mch_windows95())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004147 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148 else
4149 si.wShowWindow = SW_SHOWNORMAL;
4150 si.cbReserved2 = 0;
4151 si.lpReserved2 = NULL;
4152
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004153 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 * When the "c:\\" is left out it works OK...? */
4155 if (mch_windows95()
4156 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4157 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4158 cmd += 3;
4159
4160 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004161 vim_create_process(cmd, FALSE,
4162 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163
4164 /* Wait for the command to terminate before continuing */
4165 if (g_PlatformId != VER_PLATFORM_WIN32s)
4166 {
4167#ifdef FEAT_GUI
4168 int delay = 1;
4169
4170 /* Keep updating the window while waiting for the shell to finish. */
4171 for (;;)
4172 {
4173 MSG msg;
4174
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004175 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176 {
4177 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004178 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004179 delay = 1;
4180 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 }
4182 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4183 break;
4184
4185 /* We start waiting for a very short time and then increase it, so
4186 * that we respond quickly when the process is quick, and don't
4187 * consume too much overhead when it's slow. */
4188 if (delay < 50)
4189 delay += 10;
4190 }
4191#else
4192 WaitForSingleObject(pi.hProcess, INFINITE);
4193#endif
4194
4195 /* Get the command exit code */
4196 GetExitCodeProcess(pi.hProcess, &ret);
4197 }
4198 else
4199 {
4200 /*
4201 * This ugly code is the only quick way of performing
4202 * a synchronous spawn under Win32s. Yuk.
4203 */
4204 num_windows = 0;
4205 EnumWindows(win32ssynch_cb, 0);
4206 old_num_windows = num_windows;
4207 do
4208 {
4209 Sleep(1000);
4210 num_windows = 0;
4211 EnumWindows(win32ssynch_cb, 0);
4212 } while (num_windows == old_num_windows);
4213 ret = 0;
4214 }
4215
4216 /* Close the handles to the subprocess, so that it goes away */
4217 CloseHandle(pi.hThread);
4218 CloseHandle(pi.hProcess);
4219
4220 /* Try to get input focus back. Doesn't always work though. */
4221 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4222
4223 return ret;
4224}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004225
4226/*
4227 * Thread launched by the gui to send the current buffer data to the
4228 * process. This way avoid to hang up vim totally if the children
4229 * process take a long time to process the lines.
4230 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004231 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004232sub_process_writer(LPVOID param)
4233{
4234 HANDLE g_hChildStd_IN_Wr = param;
4235 linenr_T lnum = curbuf->b_op_start.lnum;
4236 DWORD len = 0;
4237 DWORD l;
4238 char_u *lp = ml_get(lnum);
4239 char_u *s;
4240 int written = 0;
4241
4242 for (;;)
4243 {
4244 l = (DWORD)STRLEN(lp + written);
4245 if (l == 0)
4246 len = 0;
4247 else if (lp[written] == NL)
4248 {
4249 /* NL -> NUL translation */
4250 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4251 }
4252 else
4253 {
4254 s = vim_strchr(lp + written, NL);
4255 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4256 s == NULL ? l : (DWORD)(s - (lp + written)),
4257 &len, NULL);
4258 }
4259 if (len == (int)l)
4260 {
4261 /* Finished a line, add a NL, unless this line should not have
4262 * one. */
4263 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004264 || (!curbuf->b_p_bin
4265 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004266 || (lnum != curbuf->b_no_eol_lnum
4267 && (lnum != curbuf->b_ml.ml_line_count
4268 || curbuf->b_p_eol)))
4269 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004270 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004271 }
4272
4273 ++lnum;
4274 if (lnum > curbuf->b_op_end.lnum)
4275 break;
4276
4277 lp = ml_get(lnum);
4278 written = 0;
4279 }
4280 else if (len > 0)
4281 written += len;
4282 }
4283
4284 /* finished all the lines, close pipe */
4285 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004286 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287}
4288
4289
4290# define BUFLEN 100 /* length for buffer, stolen from unix version */
4291
4292/*
4293 * This function read from the children's stdout and write the
4294 * data on screen or in the buffer accordingly.
4295 */
4296 static void
4297dump_pipe(int options,
4298 HANDLE g_hChildStd_OUT_Rd,
4299 garray_T *ga,
4300 char_u buffer[],
4301 DWORD *buffer_off)
4302{
4303 DWORD availableBytes = 0;
4304 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004305 int ret;
4306 DWORD len;
4307 DWORD toRead;
4308 int repeatCount;
4309
4310 /* we query the pipe to see if there is any data to read
4311 * to avoid to perform a blocking read */
4312 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4313 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004314 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004315 NULL, /* number of read bytes */
4316 &availableBytes, /* available bytes total */
4317 NULL); /* byteLeft */
4318
4319 repeatCount = 0;
4320 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004321 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004322 {
4323 repeatCount++;
4324 toRead =
4325# ifdef FEAT_MBYTE
4326 (DWORD)(BUFLEN - *buffer_off);
4327# else
4328 (DWORD)BUFLEN;
4329# endif
4330 toRead = availableBytes < toRead ? availableBytes : toRead;
4331 ReadFile(g_hChildStd_OUT_Rd, buffer
4332# ifdef FEAT_MBYTE
4333 + *buffer_off, toRead
4334# else
4335 , toRead
4336# endif
4337 , &len, NULL);
4338
4339 /* If we haven't read anything, there is a problem */
4340 if (len == 0)
4341 break;
4342
4343 availableBytes -= len;
4344
4345 if (options & SHELL_READ)
4346 {
4347 /* Do NUL -> NL translation, append NL separated
4348 * lines to the current buffer. */
4349 for (i = 0; i < len; ++i)
4350 {
4351 if (buffer[i] == NL)
4352 append_ga_line(ga);
4353 else if (buffer[i] == NUL)
4354 ga_append(ga, NL);
4355 else
4356 ga_append(ga, buffer[i]);
4357 }
4358 }
4359# ifdef FEAT_MBYTE
4360 else if (has_mbyte)
4361 {
4362 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004363 int c;
4364 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004365
4366 len += *buffer_off;
4367 buffer[len] = NUL;
4368
4369 /* Check if the last character in buffer[] is
4370 * incomplete, keep these bytes for the next
4371 * round. */
4372 for (p = buffer; p < buffer + len; p += l)
4373 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004374 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004375 if (l == 0)
4376 l = 1; /* NUL byte? */
4377 else if (MB_BYTE2LEN(*p) != l)
4378 break;
4379 }
4380 if (p == buffer) /* no complete character */
4381 {
4382 /* avoid getting stuck at an illegal byte */
4383 if (len >= 12)
4384 ++p;
4385 else
4386 {
4387 *buffer_off = len;
4388 return;
4389 }
4390 }
4391 c = *p;
4392 *p = NUL;
4393 msg_puts(buffer);
4394 if (p < buffer + len)
4395 {
4396 *p = c;
4397 *buffer_off = (DWORD)((buffer + len) - p);
4398 mch_memmove(buffer, p, *buffer_off);
4399 return;
4400 }
4401 *buffer_off = 0;
4402 }
4403# endif /* FEAT_MBYTE */
4404 else
4405 {
4406 buffer[len] = NUL;
4407 msg_puts(buffer);
4408 }
4409
4410 windgoto(msg_row, msg_col);
4411 cursor_on();
4412 out_flush();
4413 }
4414}
4415
4416/*
4417 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4418 * for communication and doesn't open any new window.
4419 */
4420 static int
4421mch_system_piped(char *cmd, int options)
4422{
4423 STARTUPINFO si;
4424 PROCESS_INFORMATION pi;
4425 DWORD ret = 0;
4426
4427 HANDLE g_hChildStd_IN_Rd = NULL;
4428 HANDLE g_hChildStd_IN_Wr = NULL;
4429 HANDLE g_hChildStd_OUT_Rd = NULL;
4430 HANDLE g_hChildStd_OUT_Wr = NULL;
4431
4432 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4433 DWORD len;
4434
4435 /* buffer used to receive keys */
4436 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4437 int ta_len = 0; /* valid bytes in ta_buf[] */
4438
4439 DWORD i;
4440 int c;
4441 int noread_cnt = 0;
4442 garray_T ga;
4443 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004444 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004445 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004446
4447 SECURITY_ATTRIBUTES saAttr;
4448
4449 /* Set the bInheritHandle flag so pipe handles are inherited. */
4450 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4451 saAttr.bInheritHandle = TRUE;
4452 saAttr.lpSecurityDescriptor = NULL;
4453
4454 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4455 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4456 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4457 /* Create a pipe for the child process's STDIN. */
4458 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4459 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4460 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4461 {
4462 CloseHandle(g_hChildStd_IN_Rd);
4463 CloseHandle(g_hChildStd_IN_Wr);
4464 CloseHandle(g_hChildStd_OUT_Rd);
4465 CloseHandle(g_hChildStd_OUT_Wr);
4466 MSG_PUTS(_("\nCannot create pipes\n"));
4467 }
4468
4469 si.cb = sizeof(si);
4470 si.lpReserved = NULL;
4471 si.lpDesktop = NULL;
4472 si.lpTitle = NULL;
4473 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4474
4475 /* set-up our file redirection */
4476 si.hStdError = g_hChildStd_OUT_Wr;
4477 si.hStdOutput = g_hChildStd_OUT_Wr;
4478 si.hStdInput = g_hChildStd_IN_Rd;
4479 si.wShowWindow = SW_HIDE;
4480 si.cbReserved2 = 0;
4481 si.lpReserved2 = NULL;
4482
4483 if (options & SHELL_READ)
4484 ga_init2(&ga, 1, BUFLEN);
4485
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004486 if (cmd != NULL)
4487 {
4488 p = (char *)vim_strsave((char_u *)cmd);
4489 if (p != NULL)
4490 unescape_shellxquote((char_u *)p, p_sxe);
4491 else
4492 p = cmd;
4493 }
4494
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004495 /* Now, run the command.
4496 * About "Inherit handles" being TRUE: this command can be litigious,
4497 * handle inheritance was deactivated for pending temp file, but, if we
4498 * deactivate it, the pipes don't work for some reason. */
4499 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004500
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004501 if (p != cmd)
4502 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004503
4504 /* Close our unused side of the pipes */
4505 CloseHandle(g_hChildStd_IN_Rd);
4506 CloseHandle(g_hChildStd_OUT_Wr);
4507
4508 if (options & SHELL_WRITE)
4509 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004510 HANDLE thread = (HANDLE)
4511 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004512 0, /* default stack size */
4513 sub_process_writer, /* function to be executed */
4514 g_hChildStd_IN_Wr, /* parameter */
4515 0, /* creation flag, start immediately */
4516 NULL); /* we don't care about thread id */
4517 CloseHandle(thread);
4518 g_hChildStd_IN_Wr = NULL;
4519 }
4520
4521 /* Keep updating the window while waiting for the shell to finish. */
4522 for (;;)
4523 {
4524 MSG msg;
4525
Bram Moolenaar175d0702013-12-11 18:36:33 +01004526 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004527 {
4528 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004529 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004530 }
4531
4532 /* write pipe information in the window */
4533 if ((options & (SHELL_READ|SHELL_WRITE))
4534# ifdef FEAT_GUI
4535 || gui.in_use
4536# endif
4537 )
4538 {
4539 len = 0;
4540 if (!(options & SHELL_EXPAND)
4541 && ((options &
4542 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4543 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4544# ifdef FEAT_GUI
4545 || gui.in_use
4546# endif
4547 )
4548 && (ta_len > 0 || noread_cnt > 4))
4549 {
4550 if (ta_len == 0)
4551 {
4552 /* Get extra characters when we don't have any. Reset the
4553 * counter and timer. */
4554 noread_cnt = 0;
4555# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4556 gettimeofday(&start_tv, NULL);
4557# endif
4558 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4559 }
4560 if (ta_len > 0 || len > 0)
4561 {
4562 /*
4563 * For pipes: Check for CTRL-C: send interrupt signal to
4564 * child. Check for CTRL-D: EOF, close pipe to child.
4565 */
4566 if (len == 1 && cmd != NULL)
4567 {
4568 if (ta_buf[ta_len] == Ctrl_C)
4569 {
4570 /* Learn what exit code is expected, for
4571 * now put 9 as SIGKILL */
4572 TerminateProcess(pi.hProcess, 9);
4573 }
4574 if (ta_buf[ta_len] == Ctrl_D)
4575 {
4576 CloseHandle(g_hChildStd_IN_Wr);
4577 g_hChildStd_IN_Wr = NULL;
4578 }
4579 }
4580
4581 /* replace K_BS by <BS> and K_DEL by <DEL> */
4582 for (i = ta_len; i < ta_len + len; ++i)
4583 {
4584 if (ta_buf[i] == CSI && len - i > 2)
4585 {
4586 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4587 if (c == K_DEL || c == K_KDEL || c == K_BS)
4588 {
4589 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4590 (size_t)(len - i - 2));
4591 if (c == K_DEL || c == K_KDEL)
4592 ta_buf[i] = DEL;
4593 else
4594 ta_buf[i] = Ctrl_H;
4595 len -= 2;
4596 }
4597 }
4598 else if (ta_buf[i] == '\r')
4599 ta_buf[i] = '\n';
4600# ifdef FEAT_MBYTE
4601 if (has_mbyte)
4602 i += (*mb_ptr2len_len)(ta_buf + i,
4603 ta_len + len - i) - 1;
4604# endif
4605 }
4606
4607 /*
4608 * For pipes: echo the typed characters. For a pty this
4609 * does not seem to work.
4610 */
4611 for (i = ta_len; i < ta_len + len; ++i)
4612 {
4613 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4614 msg_putchar(ta_buf[i]);
4615# ifdef FEAT_MBYTE
4616 else if (has_mbyte)
4617 {
4618 int l = (*mb_ptr2len)(ta_buf + i);
4619
4620 msg_outtrans_len(ta_buf + i, l);
4621 i += l - 1;
4622 }
4623# endif
4624 else
4625 msg_outtrans_len(ta_buf + i, 1);
4626 }
4627 windgoto(msg_row, msg_col);
4628 out_flush();
4629
4630 ta_len += len;
4631
4632 /*
4633 * Write the characters to the child, unless EOF has been
4634 * typed for pipes. Write one character at a time, to
4635 * avoid losing too much typeahead. When writing buffer
4636 * lines, drop the typed characters (only check for
4637 * CTRL-C).
4638 */
4639 if (options & SHELL_WRITE)
4640 ta_len = 0;
4641 else if (g_hChildStd_IN_Wr != NULL)
4642 {
4643 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4644 1, &len, NULL);
4645 // if we are typing in, we want to keep things reactive
4646 delay = 1;
4647 if (len > 0)
4648 {
4649 ta_len -= len;
4650 mch_memmove(ta_buf, ta_buf + len, ta_len);
4651 }
4652 }
4653 }
4654 }
4655 }
4656
4657 if (ta_len)
4658 ui_inchar_undo(ta_buf, ta_len);
4659
4660 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4661 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004662 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004663 break;
4664 }
4665
4666 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004667 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004668
4669 /* We start waiting for a very short time and then increase it, so
4670 * that we respond quickly when the process is quick, and don't
4671 * consume too much overhead when it's slow. */
4672 if (delay < 50)
4673 delay += 10;
4674 }
4675
4676 /* Close the pipe */
4677 CloseHandle(g_hChildStd_OUT_Rd);
4678 if (g_hChildStd_IN_Wr != NULL)
4679 CloseHandle(g_hChildStd_IN_Wr);
4680
4681 WaitForSingleObject(pi.hProcess, INFINITE);
4682
4683 /* Get the command exit code */
4684 GetExitCodeProcess(pi.hProcess, &ret);
4685
4686 if (options & SHELL_READ)
4687 {
4688 if (ga.ga_len > 0)
4689 {
4690 append_ga_line(&ga);
4691 /* remember that the NL was missing */
4692 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4693 }
4694 else
4695 curbuf->b_no_eol_lnum = 0;
4696 ga_clear(&ga);
4697 }
4698
4699 /* Close the handles to the subprocess, so that it goes away */
4700 CloseHandle(pi.hThread);
4701 CloseHandle(pi.hProcess);
4702
4703 return ret;
4704}
4705
4706 static int
4707mch_system(char *cmd, int options)
4708{
4709 /* if we can pipe and the shelltemp option is off */
4710 if (allowPiping && !p_stmp)
4711 return mch_system_piped(cmd, options);
4712 else
4713 return mch_system_classic(cmd, options);
4714}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004715#else
4716
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004717# ifdef FEAT_MBYTE
4718 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004719mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004720{
4721 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4722 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004723 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004724 if (wcmd != NULL)
4725 {
4726 int ret = _wsystem(wcmd);
4727 vim_free(wcmd);
4728 return ret;
4729 }
4730 }
4731 return system(cmd);
4732}
4733# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004734# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004735# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004736
4737#endif
4738
4739/*
4740 * Either execute a command by calling the shell or start a new shell
4741 */
4742 int
4743mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004744 char_u *cmd,
4745 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004746{
4747 int x = 0;
4748 int tmode = cur_tmode;
4749#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004750 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004751# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004752 int did_set_title = FALSE;
4753
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004754 /* Change the title to reflect that we are in a subshell. */
4755 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4756 {
4757 WCHAR szShellTitle[512];
4758
4759 if (GetConsoleTitleW(szShellTitle,
4760 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4761 {
4762 if (cmd == NULL)
4763 wcscat(szShellTitle, L" :sh");
4764 else
4765 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004766 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004767
4768 if (wn != NULL)
4769 {
4770 wcscat(szShellTitle, L" - !");
4771 if ((wcslen(szShellTitle) + wcslen(wn) <
4772 sizeof(szShellTitle)/sizeof(WCHAR)))
4773 wcscat(szShellTitle, wn);
4774 SetConsoleTitleW(szShellTitle);
4775 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004776 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004777 }
4778 }
4779 }
4780 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004781 if (!did_set_title)
4782# endif
4783 /* Change the title to reflect that we are in a subshell. */
4784 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004786 if (cmd == NULL)
4787 strcat(szShellTitle, " :sh");
4788 else
4789 {
4790 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004791 if ((strlen(szShellTitle) + strlen((char *)cmd)
4792 < sizeof(szShellTitle)))
4793 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004794 }
4795 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004796 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797#endif
4798
4799 out_flush();
4800
4801#ifdef MCH_WRITE_DUMP
4802 if (fdDump)
4803 {
4804 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4805 fflush(fdDump);
4806 }
4807#endif
4808
4809 /*
4810 * Catch all deadly signals while running the external command, because a
4811 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4812 */
4813 signal(SIGINT, SIG_IGN);
4814#if defined(__GNUC__) && !defined(__MINGW32__)
4815 signal(SIGKILL, SIG_IGN);
4816#else
4817 signal(SIGBREAK, SIG_IGN);
4818#endif
4819 signal(SIGILL, SIG_IGN);
4820 signal(SIGFPE, SIG_IGN);
4821 signal(SIGSEGV, SIG_IGN);
4822 signal(SIGTERM, SIG_IGN);
4823 signal(SIGABRT, SIG_IGN);
4824
4825 if (options & SHELL_COOKED)
4826 settmode(TMODE_COOK); /* set to normal mode */
4827
4828 if (cmd == NULL)
4829 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004830 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831 }
4832 else
4833 {
4834 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004835 char_u *newcmd = NULL;
4836 char_u *cmdbase = cmd;
4837 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004838
4839 /* Skip a leading ", ( and "(. */
4840 if (*cmdbase == '"' )
4841 ++cmdbase;
4842 if (*cmdbase == '(')
4843 ++cmdbase;
4844
4845 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4846 {
4847 STARTUPINFO si;
4848 PROCESS_INFORMATION pi;
4849 DWORD flags = CREATE_NEW_CONSOLE;
4850 char_u *p;
4851
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004852 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004853 si.cb = sizeof(si);
4854 si.lpReserved = NULL;
4855 si.lpDesktop = NULL;
4856 si.lpTitle = NULL;
4857 si.dwFlags = 0;
4858 si.cbReserved2 = 0;
4859 si.lpReserved2 = NULL;
4860
4861 cmdbase = skipwhite(cmdbase + 5);
4862 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4863 && vim_iswhite(cmdbase[4]))
4864 {
4865 cmdbase = skipwhite(cmdbase + 4);
4866 si.dwFlags = STARTF_USESHOWWINDOW;
4867 si.wShowWindow = SW_SHOWMINNOACTIVE;
4868 }
4869 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4870 && vim_iswhite(cmdbase[2]))
4871 {
4872 cmdbase = skipwhite(cmdbase + 2);
4873 flags = CREATE_NO_WINDOW;
4874 si.dwFlags = STARTF_USESTDHANDLES;
4875 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004876 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004877 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004878 NULL, // Security att.
4879 OPEN_EXISTING, // Open flags
4880 FILE_ATTRIBUTE_NORMAL, // File att.
4881 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004882 si.hStdOutput = si.hStdInput;
4883 si.hStdError = si.hStdInput;
4884 }
4885
4886 /* Remove a trailing ", ) and )" if they have a match
4887 * at the start of the command. */
4888 if (cmdbase > cmd)
4889 {
4890 p = cmdbase + STRLEN(cmdbase);
4891 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4892 *--p = NUL;
4893 if (p > cmdbase && p[-1] == ')'
4894 && (*cmd =='(' || cmd[1] == '('))
4895 *--p = NUL;
4896 }
4897
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004898 newcmd = cmdbase;
4899 unescape_shellxquote(cmdbase, p_sxe);
4900
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004901 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004902 * If creating new console, arguments are passed to the
4903 * 'cmd.exe' as-is. If it's not, arguments are not treated
4904 * correctly for current 'cmd.exe'. So unescape characters in
4905 * shellxescape except '|' for avoiding to be treated as
4906 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004907 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004908 if (flags != CREATE_NEW_CONSOLE)
4909 {
4910 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004911 char_u *cmd_shell = mch_getenv("COMSPEC");
4912
4913 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004914 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004915
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004916 subcmd = vim_strsave_escaped_ext(cmdbase,
4917 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004918 if (subcmd != NULL)
4919 {
4920 /* make "cmd.exe /c arguments" */
4921 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004922 newcmd = lalloc(cmdlen, TRUE);
4923 if (newcmd != NULL)
4924 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004925 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004926 else
4927 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004928 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004929 }
4930 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004931
4932 /*
4933 * Now, start the command as a process, so that it doesn't
4934 * inherit our handles which causes unpleasant dangling swap
4935 * files if we exit before the spawned process
4936 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004937 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004938 x = 0;
4939 else
4940 {
4941 x = -1;
4942#ifdef FEAT_GUI_W32
4943 EMSG(_("E371: Command not found"));
4944#endif
4945 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004946
4947 if (newcmd != cmdbase)
4948 vim_free(newcmd);
4949
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004950 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004951 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004952 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004953 CloseHandle(si.hStdInput);
4954 }
4955 /* Close the handles to the subprocess, so that it goes away */
4956 CloseHandle(pi.hThread);
4957 CloseHandle(pi.hProcess);
4958 }
4959 else
4960 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004961 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004963 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004965 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4966
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004967 newcmd = lalloc(cmdlen, TRUE);
4968 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004969 {
4970#if defined(FEAT_GUI_W32)
4971 if (need_vimrun_warning)
4972 {
4973 MessageBox(NULL,
4974 _("VIMRUN.EXE not found in your $PATH.\n"
4975 "External commands will not pause after completion.\n"
4976 "See :help win32-vimrun for more information."),
4977 _("Vim Warning"),
4978 MB_ICONWARNING);
4979 need_vimrun_warning = FALSE;
4980 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004981 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 /* Use vimrun to execute the command. It opens a console
4983 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004984 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985 vimrun_path,
4986 (msg_silent != 0 || (options & SHELL_DOOUT))
4987 ? "-s " : "",
4988 p_sh, p_shcf, cmd);
4989 else
4990#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004991 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004992 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004994 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004996 }
4997 }
4998
4999 if (tmode == TMODE_RAW)
5000 settmode(TMODE_RAW); /* set to raw mode */
5001
5002 /* Print the return value, unless "vimrun" was used. */
5003 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5004#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005005 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
5006 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007#endif
5008 )
5009 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005010 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011 msg_putchar('\n');
5012 }
5013#ifdef FEAT_TITLE
5014 resettitle();
5015#endif
5016
5017 signal(SIGINT, SIG_DFL);
5018#if defined(__GNUC__) && !defined(__MINGW32__)
5019 signal(SIGKILL, SIG_DFL);
5020#else
5021 signal(SIGBREAK, SIG_DFL);
5022#endif
5023 signal(SIGILL, SIG_DFL);
5024 signal(SIGFPE, SIG_DFL);
5025 signal(SIGSEGV, SIG_DFL);
5026 signal(SIGTERM, SIG_DFL);
5027 signal(SIGABRT, SIG_DFL);
5028
5029 return x;
5030}
5031
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005032#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005033 static HANDLE
5034job_io_file_open(
5035 char_u *fname,
5036 DWORD dwDesiredAccess,
5037 DWORD dwShareMode,
5038 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5039 DWORD dwCreationDisposition,
5040 DWORD dwFlagsAndAttributes)
5041{
5042 HANDLE h;
5043# ifdef FEAT_MBYTE
5044 WCHAR *wn = NULL;
5045 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5046 {
5047 wn = enc_to_utf16(fname, NULL);
5048 if (wn != NULL)
5049 {
5050 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5051 lpSecurityAttributes, dwCreationDisposition,
5052 dwFlagsAndAttributes, NULL);
5053 vim_free(wn);
5054 if (h == INVALID_HANDLE_VALUE
5055 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5056 wn = NULL;
5057 }
5058 }
5059 if (wn == NULL)
5060# endif
5061
5062 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5063 lpSecurityAttributes, dwCreationDisposition,
5064 dwFlagsAndAttributes, NULL);
5065 return h;
5066}
5067
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005068 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005069mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005070{
5071 STARTUPINFO si;
5072 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005073 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005074 SECURITY_ATTRIBUTES saAttr;
5075 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005076 HANDLE ifd[2];
5077 HANDLE ofd[2];
5078 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005079
5080 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5081 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5082 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5083 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5084 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5085 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5086 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5087
5088 if (use_out_for_err && use_null_for_out)
5089 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005090
5091 ifd[0] = INVALID_HANDLE_VALUE;
5092 ifd[1] = INVALID_HANDLE_VALUE;
5093 ofd[0] = INVALID_HANDLE_VALUE;
5094 ofd[1] = INVALID_HANDLE_VALUE;
5095 efd[0] = INVALID_HANDLE_VALUE;
5096 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005097
Bram Moolenaar76467df2016-02-12 19:30:26 +01005098 jo = CreateJobObject(NULL, NULL);
5099 if (jo == NULL)
5100 {
5101 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005102 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005103 }
5104
5105 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005106 ZeroMemory(&si, sizeof(si));
5107 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005108 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005109 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005110
Bram Moolenaard8070362016-02-15 21:56:54 +01005111 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5112 saAttr.bInheritHandle = TRUE;
5113 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005114
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005115 if (use_file_for_in)
5116 {
5117 char_u *fname = options->jo_io_name[PART_IN];
5118
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005119 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5120 FILE_SHARE_READ | FILE_SHARE_WRITE,
5121 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5122 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005123 {
5124 EMSG2(_(e_notopen), fname);
5125 goto failed;
5126 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005127 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005128 else if (!use_null_for_in &&
5129 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5130 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005131 goto failed;
5132
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005133 if (use_file_for_out)
5134 {
5135 char_u *fname = options->jo_io_name[PART_OUT];
5136
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005137 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5138 FILE_SHARE_READ | FILE_SHARE_WRITE,
5139 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5140 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005141 {
5142 EMSG2(_(e_notopen), fname);
5143 goto failed;
5144 }
5145 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005146 else if (!use_null_for_out &&
5147 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5148 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005149 goto failed;
5150
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005151 if (use_file_for_err)
5152 {
5153 char_u *fname = options->jo_io_name[PART_ERR];
5154
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005155 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5156 FILE_SHARE_READ | FILE_SHARE_WRITE,
5157 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5158 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005159 {
5160 EMSG2(_(e_notopen), fname);
5161 goto failed;
5162 }
5163 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005164 else if (!use_out_for_err && !use_null_for_err &&
5165 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005166 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005167 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005168
Bram Moolenaard8070362016-02-15 21:56:54 +01005169 si.dwFlags |= STARTF_USESTDHANDLES;
5170 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005171 si.hStdOutput = ofd[1];
5172 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5173
5174 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5175 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005176 if (options->jo_set & JO_CHANNEL)
5177 {
5178 channel = options->jo_channel;
5179 if (channel != NULL)
5180 ++channel->ch_refcount;
5181 }
5182 else
5183 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005184 if (channel == NULL)
5185 goto failed;
5186 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005187
5188 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005189 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005190 CREATE_DEFAULT_ERROR_MODE |
5191 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005192 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005193 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005194 {
5195 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005196 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005197 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005198 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005199
5200 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005201 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005202 /* if failing, switch the way to terminate
5203 * process with TerminateProcess. */
5204 CloseHandle(jo);
5205 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005206 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005207 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005208 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005209 job->jv_proc_info = pi;
5210 job->jv_job_object = jo;
5211 job->jv_status = JOB_STARTED;
5212
Bram Moolenaar94d01912016-03-08 13:48:51 +01005213 if (!use_file_for_in)
5214 CloseHandle(ifd[0]);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005215 if (!use_file_for_out)
5216 CloseHandle(ofd[1]);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005217 if (!use_out_for_err && !use_file_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005218 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005219
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005220 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005221 if (channel != NULL)
5222 {
5223 channel_set_pipes(channel,
5224 use_file_for_in || use_null_for_in
5225 ? INVALID_FD : (sock_T)ifd[1],
5226 use_file_for_out || use_null_for_out
5227 ? INVALID_FD : (sock_T)ofd[0],
5228 use_out_for_err || use_file_for_err || use_null_for_err
5229 ? INVALID_FD : (sock_T)efd[0]);
5230 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005231 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005232 return;
5233
5234failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005235 CloseHandle(ifd[0]);
5236 CloseHandle(ofd[0]);
5237 CloseHandle(efd[0]);
5238 CloseHandle(ifd[1]);
5239 CloseHandle(ofd[1]);
5240 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005241 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005242}
5243
5244 char *
5245mch_job_status(job_T *job)
5246{
5247 DWORD dwExitCode = 0;
5248
Bram Moolenaar76467df2016-02-12 19:30:26 +01005249 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5250 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005251 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005252 job->jv_status = JOB_ENDED;
Bram Moolenaareab089d2016-02-21 19:32:02 +01005253 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005254 return "dead";
5255 }
5256 return "run";
5257}
5258
5259 int
5260mch_stop_job(job_T *job, char_u *how)
5261{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005262 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005263
Bram Moolenaar923d9262016-02-25 20:56:01 +01005264 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005265 {
5266 if (job->jv_job_object != NULL)
5267 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5268 else
5269 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5270 }
5271
5272 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5273 return FAIL;
5274 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005275 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5276 job->jv_proc_info.dwProcessId)
5277 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005278 FreeConsole();
5279 return ret;
5280}
5281
5282/*
5283 * Clear the data related to "job".
5284 */
5285 void
5286mch_clear_job(job_T *job)
5287{
5288 if (job->jv_status != JOB_FAILED)
5289 {
5290 if (job->jv_job_object != NULL)
5291 CloseHandle(job->jv_job_object);
5292 CloseHandle(job->jv_proc_info.hProcess);
5293 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005294}
5295#endif
5296
Bram Moolenaar071d4272004-06-13 20:20:40 +00005297
5298#ifndef FEAT_GUI_W32
5299
5300/*
5301 * Start termcap mode
5302 */
5303 static void
5304termcap_mode_start(void)
5305{
5306 DWORD cmodein;
5307
5308 if (g_fTermcapMode)
5309 return;
5310
5311 SaveConsoleBuffer(&g_cbNonTermcap);
5312
5313 if (g_cbTermcap.IsValid)
5314 {
5315 /*
5316 * We've been in termcap mode before. Restore certain screen
5317 * characteristics, including the buffer size and the window
5318 * size. Since we will be redrawing the screen, we don't need
5319 * to restore the actual contents of the buffer.
5320 */
5321 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5322 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5323 Rows = g_cbTermcap.Info.dwSize.Y;
5324 Columns = g_cbTermcap.Info.dwSize.X;
5325 }
5326 else
5327 {
5328 /*
5329 * This is our first time entering termcap mode. Clear the console
5330 * screen buffer, and resize the buffer to match the current window
5331 * size. We will use this as the size of our editing environment.
5332 */
5333 ClearConsoleBuffer(g_attrCurrent);
5334 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5335 }
5336
5337#ifdef FEAT_TITLE
5338 resettitle();
5339#endif
5340
5341 GetConsoleMode(g_hConIn, &cmodein);
5342#ifdef FEAT_MOUSE
5343 if (g_fMouseActive)
5344 cmodein |= ENABLE_MOUSE_INPUT;
5345 else
5346 cmodein &= ~ENABLE_MOUSE_INPUT;
5347#endif
5348 cmodein |= ENABLE_WINDOW_INPUT;
5349 SetConsoleMode(g_hConIn, cmodein);
5350
5351 redraw_later_clear();
5352 g_fTermcapMode = TRUE;
5353}
5354
5355
5356/*
5357 * End termcap mode
5358 */
5359 static void
5360termcap_mode_end(void)
5361{
5362 DWORD cmodein;
5363 ConsoleBuffer *cb;
5364 COORD coord;
5365 DWORD dwDummy;
5366
5367 if (!g_fTermcapMode)
5368 return;
5369
5370 SaveConsoleBuffer(&g_cbTermcap);
5371
5372 GetConsoleMode(g_hConIn, &cmodein);
5373 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5374 SetConsoleMode(g_hConIn, cmodein);
5375
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005376#ifdef FEAT_RESTORE_ORIG_SCREEN
5377 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5378#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005379 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005380#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005381 RestoreConsoleBuffer(cb, p_rs);
5382 SetConsoleCursorInfo(g_hConOut, &g_cci);
5383
5384 if (p_rs || exiting)
5385 {
5386 /*
5387 * Clear anything that happens to be on the current line.
5388 */
5389 coord.X = 0;
5390 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5391 FillConsoleOutputCharacter(g_hConOut, ' ',
5392 cb->Info.dwSize.X, coord, &dwDummy);
5393 /*
5394 * The following is just for aesthetics. If we are exiting without
5395 * restoring the screen, then we want to have a prompt string
5396 * appear at the bottom line. However, the command interpreter
5397 * seems to always advance the cursor one line before displaying
5398 * the prompt string, which causes the screen to scroll. To
5399 * counter this, move the cursor up one line before exiting.
5400 */
5401 if (exiting && !p_rs)
5402 coord.Y--;
5403 /*
5404 * Position the cursor at the leftmost column of the desired row.
5405 */
5406 SetConsoleCursorPosition(g_hConOut, coord);
5407 }
5408
5409 g_fTermcapMode = FALSE;
5410}
5411#endif /* FEAT_GUI_W32 */
5412
5413
5414#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005415/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005416 void
5417mch_write(
5418 char_u *s,
5419 int len)
5420{
5421 /* never used */
5422}
5423
5424#else
5425
5426/*
5427 * clear `n' chars, starting from `coord'
5428 */
5429 static void
5430clear_chars(
5431 COORD coord,
5432 DWORD n)
5433{
5434 DWORD dwDummy;
5435
5436 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5437 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5438}
5439
5440
5441/*
5442 * Clear the screen
5443 */
5444 static void
5445clear_screen(void)
5446{
5447 g_coord.X = g_coord.Y = 0;
5448 clear_chars(g_coord, Rows * Columns);
5449}
5450
5451
5452/*
5453 * Clear to end of display
5454 */
5455 static void
5456clear_to_end_of_display(void)
5457{
5458 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5459 * Columns + (Columns - g_coord.X));
5460}
5461
5462
5463/*
5464 * Clear to end of line
5465 */
5466 static void
5467clear_to_end_of_line(void)
5468{
5469 clear_chars(g_coord, Columns - g_coord.X);
5470}
5471
5472
5473/*
5474 * Scroll the scroll region up by `cLines' lines
5475 */
5476 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005477scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005478{
5479 COORD oldcoord = g_coord;
5480
5481 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5482 delete_lines(cLines);
5483
5484 g_coord = oldcoord;
5485}
5486
5487
5488/*
5489 * Set the scroll region
5490 */
5491 static void
5492set_scroll_region(
5493 unsigned left,
5494 unsigned top,
5495 unsigned right,
5496 unsigned bottom)
5497{
5498 if (left >= right
5499 || top >= bottom
5500 || right > (unsigned) Columns - 1
5501 || bottom > (unsigned) Rows - 1)
5502 return;
5503
5504 g_srScrollRegion.Left = left;
5505 g_srScrollRegion.Top = top;
5506 g_srScrollRegion.Right = right;
5507 g_srScrollRegion.Bottom = bottom;
5508}
5509
5510
5511/*
5512 * Insert `cLines' lines at the current cursor position
5513 */
5514 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005515insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005516{
5517 SMALL_RECT source;
5518 COORD dest;
5519 CHAR_INFO fill;
5520
5521 dest.X = 0;
5522 dest.Y = g_coord.Y + cLines;
5523
5524 source.Left = 0;
5525 source.Top = g_coord.Y;
5526 source.Right = g_srScrollRegion.Right;
5527 source.Bottom = g_srScrollRegion.Bottom - cLines;
5528
5529 fill.Char.AsciiChar = ' ';
5530 fill.Attributes = g_attrCurrent;
5531
5532 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5533
5534 /* Here we have to deal with a win32 console flake: If the scroll
5535 * region looks like abc and we scroll c to a and fill with d we get
5536 * cbd... if we scroll block c one line at a time to a, we get cdd...
5537 * vim expects cdd consistently... So we have to deal with that
5538 * here... (this also occurs scrolling the same way in the other
5539 * direction). */
5540
5541 if (source.Bottom < dest.Y)
5542 {
5543 COORD coord;
5544
5545 coord.X = 0;
5546 coord.Y = source.Bottom;
5547 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5548 }
5549}
5550
5551
5552/*
5553 * Delete `cLines' lines at the current cursor position
5554 */
5555 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005556delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005557{
5558 SMALL_RECT source;
5559 COORD dest;
5560 CHAR_INFO fill;
5561 int nb;
5562
5563 dest.X = 0;
5564 dest.Y = g_coord.Y;
5565
5566 source.Left = 0;
5567 source.Top = g_coord.Y + cLines;
5568 source.Right = g_srScrollRegion.Right;
5569 source.Bottom = g_srScrollRegion.Bottom;
5570
5571 fill.Char.AsciiChar = ' ';
5572 fill.Attributes = g_attrCurrent;
5573
5574 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5575
5576 /* Here we have to deal with a win32 console flake: If the scroll
5577 * region looks like abc and we scroll c to a and fill with d we get
5578 * cbd... if we scroll block c one line at a time to a, we get cdd...
5579 * vim expects cdd consistently... So we have to deal with that
5580 * here... (this also occurs scrolling the same way in the other
5581 * direction). */
5582
5583 nb = dest.Y + (source.Bottom - source.Top) + 1;
5584
5585 if (nb < source.Top)
5586 {
5587 COORD coord;
5588
5589 coord.X = 0;
5590 coord.Y = nb;
5591 clear_chars(coord, Columns * (source.Top - nb));
5592 }
5593}
5594
5595
5596/*
5597 * Set the cursor position
5598 */
5599 static void
5600gotoxy(
5601 unsigned x,
5602 unsigned y)
5603{
5604 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5605 return;
5606
5607 /* external cursor coords are 1-based; internal are 0-based */
5608 g_coord.X = x - 1;
5609 g_coord.Y = y - 1;
5610 SetConsoleCursorPosition(g_hConOut, g_coord);
5611}
5612
5613
5614/*
5615 * Set the current text attribute = (foreground | background)
5616 * See ../doc/os_win32.txt for the numbers.
5617 */
5618 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005619textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005621 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005622
5623 SetConsoleTextAttribute(g_hConOut, wAttr);
5624}
5625
5626
5627 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005628textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005629{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005630 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631
5632 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5633}
5634
5635
5636 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005637textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005639 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005640
5641 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5642}
5643
5644
5645/*
5646 * restore the default text attribute (whatever we started with)
5647 */
5648 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005649normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650{
5651 textattr(g_attrDefault);
5652}
5653
5654
5655static WORD g_attrPreStandout = 0;
5656
5657/*
5658 * Make the text standout, by brightening it
5659 */
5660 static void
5661standout(void)
5662{
5663 g_attrPreStandout = g_attrCurrent;
5664 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5665}
5666
5667
5668/*
5669 * Turn off standout mode
5670 */
5671 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005672standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673{
5674 if (g_attrPreStandout)
5675 {
5676 textattr(g_attrPreStandout);
5677 g_attrPreStandout = 0;
5678 }
5679}
5680
5681
5682/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005683 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005684 */
5685 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005686mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005687{
5688 char_u *p;
5689 int n;
5690
5691 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5692 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5693 if (T_ME[0] == ESC && T_ME[1] == '|')
5694 {
5695 p = T_ME + 2;
5696 n = getdigits(&p);
5697 if (*p == 'm' && n > 0)
5698 {
5699 cterm_normal_fg_color = (n & 0xf) + 1;
5700 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5701 }
5702 }
5703}
5704
5705
5706/*
5707 * visual bell: flash the screen
5708 */
5709 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005710visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711{
5712 COORD coordOrigin = {0, 0};
5713 WORD attrFlash = ~g_attrCurrent & 0xff;
5714
5715 DWORD dwDummy;
5716 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5717
5718 if (oldattrs == NULL)
5719 return;
5720 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5721 coordOrigin, &dwDummy);
5722 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5723 coordOrigin, &dwDummy);
5724
5725 Sleep(15); /* wait for 15 msec */
5726 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5727 coordOrigin, &dwDummy);
5728 vim_free(oldattrs);
5729}
5730
5731
5732/*
5733 * Make the cursor visible or invisible
5734 */
5735 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005736cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005737{
5738 s_cursor_visible = fVisible;
5739#ifdef MCH_CURSOR_SHAPE
5740 mch_update_cursor();
5741#endif
5742}
5743
5744
5745/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005746 * write `cbToWrite' bytes in `pchBuf' to the screen
5747 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005749 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005751 char_u *pchBuf,
5752 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005753{
5754 COORD coord = g_coord;
5755 DWORD written;
5756
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005757#ifdef FEAT_MBYTE
5758 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5759 {
5760 static WCHAR *unicodebuf = NULL;
5761 static int unibuflen = 0;
5762 int length;
5763 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005764
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005765 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5766 if (unicodebuf == NULL || length > unibuflen)
5767 {
5768 vim_free(unicodebuf);
5769 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5770 unibuflen = length;
5771 }
5772 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5773 unicodebuf, unibuflen);
5774
5775 cells = mb_string2cells(pchBuf, cbToWrite);
5776 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5777 coord, &written);
5778 /* When writing fails or didn't write a single character, pretend one
5779 * character was written, otherwise we get stuck. */
5780 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5781 coord, &cchwritten) == 0
5782 || cchwritten == 0)
5783 cchwritten = 1;
5784
5785 if (cchwritten == length)
5786 {
5787 written = cbToWrite;
5788 g_coord.X += (SHORT)cells;
5789 }
5790 else
5791 {
5792 char_u *p = pchBuf;
5793 for (n = 0; n < cchwritten; n++)
5794 mb_cptr_adv(p);
5795 written = p - pchBuf;
5796 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5797 }
5798 }
5799 else
5800#endif
5801 {
5802 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5803 coord, &written);
5804 /* When writing fails or didn't write a single character, pretend one
5805 * character was written, otherwise we get stuck. */
5806 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5807 coord, &written) == 0
5808 || written == 0)
5809 written = 1;
5810
5811 g_coord.X += (SHORT) written;
5812 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005813
5814 while (g_coord.X > g_srScrollRegion.Right)
5815 {
5816 g_coord.X -= (SHORT) Columns;
5817 if (g_coord.Y < g_srScrollRegion.Bottom)
5818 g_coord.Y++;
5819 }
5820
5821 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5822
5823 return written;
5824}
5825
5826
5827/*
5828 * mch_write(): write the output buffer to the screen, translating ESC
5829 * sequences into calls to console output routines.
5830 */
5831 void
5832mch_write(
5833 char_u *s,
5834 int len)
5835{
5836 s[len] = NUL;
5837
5838 if (!term_console)
5839 {
5840 write(1, s, (unsigned)len);
5841 return;
5842 }
5843
5844 /* translate ESC | sequences into faked bios calls */
5845 while (len--)
5846 {
5847 /* optimization: use one single write_chars for runs of text,
5848 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005849 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850
5851 if (p_wd)
5852 {
5853 WaitForChar(p_wd);
5854 if (prefix != 0)
5855 prefix = 1;
5856 }
5857
5858 if (prefix != 0)
5859 {
5860 DWORD nWritten;
5861
5862 nWritten = write_chars(s, prefix);
5863#ifdef MCH_WRITE_DUMP
5864 if (fdDump)
5865 {
5866 fputc('>', fdDump);
5867 fwrite(s, sizeof(char_u), nWritten, fdDump);
5868 fputs("<\n", fdDump);
5869 }
5870#endif
5871 len -= (nWritten - 1);
5872 s += nWritten;
5873 }
5874 else if (s[0] == '\n')
5875 {
5876 /* \n, newline: go to the beginning of the next line or scroll */
5877 if (g_coord.Y == g_srScrollRegion.Bottom)
5878 {
5879 scroll(1);
5880 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5881 }
5882 else
5883 {
5884 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5885 }
5886#ifdef MCH_WRITE_DUMP
5887 if (fdDump)
5888 fputs("\\n\n", fdDump);
5889#endif
5890 s++;
5891 }
5892 else if (s[0] == '\r')
5893 {
5894 /* \r, carriage return: go to beginning of line */
5895 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5896#ifdef MCH_WRITE_DUMP
5897 if (fdDump)
5898 fputs("\\r\n", fdDump);
5899#endif
5900 s++;
5901 }
5902 else if (s[0] == '\b')
5903 {
5904 /* \b, backspace: move cursor one position left */
5905 if (g_coord.X > g_srScrollRegion.Left)
5906 g_coord.X--;
5907 else if (g_coord.Y > g_srScrollRegion.Top)
5908 {
5909 g_coord.X = g_srScrollRegion.Right;
5910 g_coord.Y--;
5911 }
5912 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5913#ifdef MCH_WRITE_DUMP
5914 if (fdDump)
5915 fputs("\\b\n", fdDump);
5916#endif
5917 s++;
5918 }
5919 else if (s[0] == '\a')
5920 {
5921 /* \a, bell */
5922 MessageBeep(0xFFFFFFFF);
5923#ifdef MCH_WRITE_DUMP
5924 if (fdDump)
5925 fputs("\\a\n", fdDump);
5926#endif
5927 s++;
5928 }
5929 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5930 {
5931#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005932 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005934 char_u *p;
5935 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936
5937 switch (s[2])
5938 {
5939 /* one or two numeric arguments, separated by ';' */
5940
5941 case '0': case '1': case '2': case '3': case '4':
5942 case '5': case '6': case '7': case '8': case '9':
5943 p = s + 2;
5944 arg1 = getdigits(&p); /* no check for length! */
5945 if (p > s + len)
5946 break;
5947
5948 if (*p == ';')
5949 {
5950 ++p;
5951 arg2 = getdigits(&p); /* no check for length! */
5952 if (p > s + len)
5953 break;
5954
5955 if (*p == 'H')
5956 gotoxy(arg2, arg1);
5957 else if (*p == 'r')
5958 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5959 }
5960 else if (*p == 'A')
5961 {
5962 /* move cursor up arg1 lines in same column */
5963 gotoxy(g_coord.X + 1,
5964 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5965 }
5966 else if (*p == 'C')
5967 {
5968 /* move cursor right arg1 columns in same line */
5969 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5970 g_coord.Y + 1);
5971 }
5972 else if (*p == 'H')
5973 {
5974 gotoxy(1, arg1);
5975 }
5976 else if (*p == 'L')
5977 {
5978 insert_lines(arg1);
5979 }
5980 else if (*p == 'm')
5981 {
5982 if (arg1 == 0)
5983 normvideo();
5984 else
5985 textattr((WORD) arg1);
5986 }
5987 else if (*p == 'f')
5988 {
5989 textcolor((WORD) arg1);
5990 }
5991 else if (*p == 'b')
5992 {
5993 textbackground((WORD) arg1);
5994 }
5995 else if (*p == 'M')
5996 {
5997 delete_lines(arg1);
5998 }
5999
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006000 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001 s = p + 1;
6002 break;
6003
6004
6005 /* Three-character escape sequences */
6006
6007 case 'A':
6008 /* move cursor up one line in same column */
6009 gotoxy(g_coord.X + 1,
6010 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6011 goto got3;
6012
6013 case 'B':
6014 visual_bell();
6015 goto got3;
6016
6017 case 'C':
6018 /* move cursor right one column in same line */
6019 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6020 g_coord.Y + 1);
6021 goto got3;
6022
6023 case 'E':
6024 termcap_mode_end();
6025 goto got3;
6026
6027 case 'F':
6028 standout();
6029 goto got3;
6030
6031 case 'f':
6032 standend();
6033 goto got3;
6034
6035 case 'H':
6036 gotoxy(1, 1);
6037 goto got3;
6038
6039 case 'j':
6040 clear_to_end_of_display();
6041 goto got3;
6042
6043 case 'J':
6044 clear_screen();
6045 goto got3;
6046
6047 case 'K':
6048 clear_to_end_of_line();
6049 goto got3;
6050
6051 case 'L':
6052 insert_lines(1);
6053 goto got3;
6054
6055 case 'M':
6056 delete_lines(1);
6057 goto got3;
6058
6059 case 'S':
6060 termcap_mode_start();
6061 goto got3;
6062
6063 case 'V':
6064 cursor_visible(TRUE);
6065 goto got3;
6066
6067 case 'v':
6068 cursor_visible(FALSE);
6069 goto got3;
6070
6071 got3:
6072 s += 3;
6073 len -= 2;
6074 }
6075
6076#ifdef MCH_WRITE_DUMP
6077 if (fdDump)
6078 {
6079 fputs("ESC | ", fdDump);
6080 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6081 fputc('\n', fdDump);
6082 }
6083#endif
6084 }
6085 else
6086 {
6087 /* Write a single character */
6088 DWORD nWritten;
6089
6090 nWritten = write_chars(s, 1);
6091#ifdef MCH_WRITE_DUMP
6092 if (fdDump)
6093 {
6094 fputc('>', fdDump);
6095 fwrite(s, sizeof(char_u), nWritten, fdDump);
6096 fputs("<\n", fdDump);
6097 }
6098#endif
6099
6100 len -= (nWritten - 1);
6101 s += nWritten;
6102 }
6103 }
6104
6105#ifdef MCH_WRITE_DUMP
6106 if (fdDump)
6107 fflush(fdDump);
6108#endif
6109}
6110
6111#endif /* FEAT_GUI_W32 */
6112
6113
6114/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006115 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006117/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118 void
6119mch_delay(
6120 long msec,
6121 int ignoreinput)
6122{
6123#ifdef FEAT_GUI_W32
6124 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006125#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006127# ifdef FEAT_MZSCHEME
6128 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6129 {
6130 int towait = p_mzq;
6131
6132 /* if msec is large enough, wait by portions in p_mzq */
6133 while (msec > 0)
6134 {
6135 mzvim_check_threads();
6136 if (msec < towait)
6137 towait = msec;
6138 Sleep(towait);
6139 msec -= towait;
6140 }
6141 }
6142 else
6143# endif
6144 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006145 else
6146 WaitForChar(msec);
6147#endif
6148}
6149
6150
6151/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006152 * This version of remove is not scared by a readonly (backup) file.
6153 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 * Return 0 for success, -1 for failure.
6155 */
6156 int
6157mch_remove(char_u *name)
6158{
6159#ifdef FEAT_MBYTE
6160 WCHAR *wn = NULL;
6161 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006162#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006163
Bram Moolenaar203258c2016-01-17 22:15:16 +01006164 /*
6165 * On Windows, deleting a directory's symbolic link is done by
6166 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6167 */
6168 if (mch_isdir(name) && mch_is_symbolic_link(name))
6169 return mch_rmdir(name);
6170
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006171 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6172
6173#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6175 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006176 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177 if (wn != NULL)
6178 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179 n = DeleteFileW(wn) ? 0 : -1;
6180 vim_free(wn);
6181 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6182 return n;
6183 /* Retry with non-wide function (for Windows 98). */
6184 }
6185 }
6186#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006187 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006188}
6189
6190
6191/*
6192 * check for an "interrupt signal": CTRL-break or CTRL-C
6193 */
6194 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006195mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196{
6197#ifndef FEAT_GUI_W32 /* never used */
6198 if (g_fCtrlCPressed || g_fCBrkPressed)
6199 {
6200 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6201 got_int = TRUE;
6202 }
6203#endif
6204}
6205
Bram Moolenaaree273972016-01-02 21:11:51 +01006206/* physical RAM to leave for the OS */
6207#define WINNT_RESERVE_BYTES (256*1024*1024)
6208#define WIN95_RESERVE_BYTES (8*1024*1024)
6209
6210/*
6211 * How much main memory in KiB that can be used by VIM.
6212 */
6213/*ARGSUSED*/
6214 long_u
6215mch_total_mem(int special)
6216{
6217 PlatformId();
6218#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6219 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6220 {
6221 MEMORYSTATUSEX ms;
6222
6223 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6224 * what fits in 32 bits. But it's not always available. */
6225 ms.dwLength = sizeof(MEMORYSTATUSEX);
6226 GlobalMemoryStatusEx(&ms);
6227 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6228 {
6229 /* Process address space fits in physical RAM, use all of it. */
6230 return (long_u)(ms.ullAvailVirtual / 1024);
6231 }
6232 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6233 {
6234 /* Catch old NT box or perverse hardware setup. */
6235 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6236 }
6237 /* Use physical RAM less reserve for OS + data. */
6238 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6239 }
6240 else
6241#endif
6242 {
6243 /* Pre-XP or 95 OS handling. */
6244 MEMORYSTATUS ms;
6245 long_u os_reserve_bytes;
6246
6247 ms.dwLength = sizeof(MEMORYSTATUS);
6248 GlobalMemoryStatus(&ms);
6249 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6250 {
6251 /* Process address space fits in physical RAM, use all of it. */
6252 return (long_u)(ms.dwAvailVirtual / 1024);
6253 }
6254 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6255 ? WINNT_RESERVE_BYTES
6256 : WIN95_RESERVE_BYTES;
6257 if (ms.dwTotalPhys <= os_reserve_bytes)
6258 {
6259 /* Catch old boxes or perverse hardware setup. */
6260 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6261 }
6262 /* Use physical RAM less reserve for OS + data. */
6263 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6264 }
6265}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267#ifdef FEAT_MBYTE
6268/*
6269 * Same code as below, but with wide functions and no comments.
6270 * Return 0 for success, non-zero for failure.
6271 */
6272 int
6273mch_wrename(WCHAR *wold, WCHAR *wnew)
6274{
6275 WCHAR *p;
6276 int i;
6277 WCHAR szTempFile[_MAX_PATH + 1];
6278 WCHAR szNewPath[_MAX_PATH + 1];
6279 HANDLE hf;
6280
6281 if (!mch_windows95())
6282 {
6283 p = wold;
6284 for (i = 0; wold[i] != NUL; ++i)
6285 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6286 && wold[i + 1] != 0)
6287 p = wold + i + 1;
6288 if ((int)(wold + i - p) < 8 || p[6] != '~')
6289 return (MoveFileW(wold, wnew) == 0);
6290 }
6291
6292 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6293 return -1;
6294 *p = NUL;
6295
6296 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6297 return -2;
6298
6299 if (!DeleteFileW(szTempFile))
6300 return -3;
6301
6302 if (!MoveFileW(wold, szTempFile))
6303 return -4;
6304
6305 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6306 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6307 return -5;
6308 if (!CloseHandle(hf))
6309 return -6;
6310
6311 if (!MoveFileW(szTempFile, wnew))
6312 {
6313 (void)MoveFileW(szTempFile, wold);
6314 return -7;
6315 }
6316
6317 DeleteFileW(szTempFile);
6318
6319 if (!DeleteFileW(wold))
6320 return -8;
6321
6322 return 0;
6323}
6324#endif
6325
6326
6327/*
6328 * mch_rename() works around a bug in rename (aka MoveFile) in
6329 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6330 * file whose short file name is "FOO.BAR" (its long file name will
6331 * be correct: "foo.bar~"). Because a file can be accessed by
6332 * either its SFN or its LFN, "foo.bar" has effectively been
6333 * renamed to "foo.bar", which is not at all what was wanted. This
6334 * seems to happen only when renaming files with three-character
6335 * extensions by appending a suffix that does not include ".".
6336 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6337 *
6338 * There is another problem, which isn't really a bug but isn't right either:
6339 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6340 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6341 * service pack 6. Doesn't seem to happen on Windows 98.
6342 *
6343 * Like rename(), returns 0 upon success, non-zero upon failure.
6344 * Should probably set errno appropriately when errors occur.
6345 */
6346 int
6347mch_rename(
6348 const char *pszOldFile,
6349 const char *pszNewFile)
6350{
6351 char szTempFile[_MAX_PATH+1];
6352 char szNewPath[_MAX_PATH+1];
6353 char *pszFilePart;
6354 HANDLE hf;
6355#ifdef FEAT_MBYTE
6356 WCHAR *wold = NULL;
6357 WCHAR *wnew = NULL;
6358 int retval = -1;
6359
6360 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6361 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006362 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6363 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364 if (wold != NULL && wnew != NULL)
6365 retval = mch_wrename(wold, wnew);
6366 vim_free(wold);
6367 vim_free(wnew);
6368 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6369 return retval;
6370 /* Retry with non-wide function (for Windows 98). */
6371 }
6372#endif
6373
6374 /*
6375 * No need to play tricks if not running Windows 95, unless the file name
6376 * contains a "~" as the seventh character.
6377 */
6378 if (!mch_windows95())
6379 {
6380 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6381 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6382 return rename(pszOldFile, pszNewFile);
6383 }
6384
6385 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6386 * a directory, no error is returned and pszFilePart will be NULL. */
6387 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6388 || pszFilePart == NULL)
6389 return -1;
6390 *pszFilePart = NUL;
6391
6392 /* Get (and create) a unique temporary file name in directory of new file */
6393 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6394 return -2;
6395
6396 /* blow the temp file away */
6397 if (!DeleteFile(szTempFile))
6398 return -3;
6399
6400 /* rename old file to the temp file */
6401 if (!MoveFile(pszOldFile, szTempFile))
6402 return -4;
6403
6404 /* now create an empty file called pszOldFile; this prevents the operating
6405 * system using pszOldFile as an alias (SFN) if we're renaming within the
6406 * same directory. For example, we're editing a file called
6407 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6408 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6409 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006410 * cause all sorts of problems later in buf_write(). So, we create an
6411 * empty file called filena~1.txt and the system will have to find some
6412 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413 */
6414 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6415 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6416 return -5;
6417 if (!CloseHandle(hf))
6418 return -6;
6419
6420 /* rename the temp file to the new file */
6421 if (!MoveFile(szTempFile, pszNewFile))
6422 {
6423 /* Renaming failed. Rename the file back to its old name, so that it
6424 * looks like nothing happened. */
6425 (void)MoveFile(szTempFile, pszOldFile);
6426
6427 return -7;
6428 }
6429
6430 /* Seems to be left around on Novell filesystems */
6431 DeleteFile(szTempFile);
6432
6433 /* finally, remove the empty old file */
6434 if (!DeleteFile(pszOldFile))
6435 return -8;
6436
6437 return 0; /* success */
6438}
6439
6440/*
6441 * Get the default shell for the current hardware platform
6442 */
6443 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006444default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006445{
6446 char* psz = NULL;
6447
6448 PlatformId();
6449
6450 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6451 psz = "cmd.exe";
6452 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6453 psz = "command.com";
6454
6455 return psz;
6456}
6457
6458/*
6459 * mch_access() extends access() to do more detailed check on network drives.
6460 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6461 */
6462 int
6463mch_access(char *n, int p)
6464{
6465 HANDLE hFile;
6466 DWORD am;
6467 int retval = -1; /* default: fail */
6468#ifdef FEAT_MBYTE
6469 WCHAR *wn = NULL;
6470
6471 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006472 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006473#endif
6474
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006475 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476 {
6477 char TempName[_MAX_PATH + 16] = "";
6478#ifdef FEAT_MBYTE
6479 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6480#endif
6481
6482 if (p & R_OK)
6483 {
6484 /* Read check is performed by seeing if we can do a find file on
6485 * the directory for any file. */
6486#ifdef FEAT_MBYTE
6487 if (wn != NULL)
6488 {
6489 int i;
6490 WIN32_FIND_DATAW d;
6491
6492 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6493 TempNameW[i] = wn[i];
6494 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6495 TempNameW[i++] = '\\';
6496 TempNameW[i++] = '*';
6497 TempNameW[i++] = 0;
6498
6499 hFile = FindFirstFileW(TempNameW, &d);
6500 if (hFile == INVALID_HANDLE_VALUE)
6501 {
6502 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6503 goto getout;
6504
6505 /* Retry with non-wide function (for Windows 98). */
6506 vim_free(wn);
6507 wn = NULL;
6508 }
6509 else
6510 (void)FindClose(hFile);
6511 }
6512 if (wn == NULL)
6513#endif
6514 {
6515 char *pch;
6516 WIN32_FIND_DATA d;
6517
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006518 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 pch = TempName + STRLEN(TempName) - 1;
6520 if (*pch != '\\' && *pch != '/')
6521 *++pch = '\\';
6522 *++pch = '*';
6523 *++pch = NUL;
6524
6525 hFile = FindFirstFile(TempName, &d);
6526 if (hFile == INVALID_HANDLE_VALUE)
6527 goto getout;
6528 (void)FindClose(hFile);
6529 }
6530 }
6531
6532 if (p & W_OK)
6533 {
6534 /* Trying to create a temporary file in the directory should catch
6535 * directories on read-only network shares. However, in
6536 * directories whose ACL allows writes but denies deletes will end
6537 * up keeping the temporary file :-(. */
6538#ifdef FEAT_MBYTE
6539 if (wn != NULL)
6540 {
6541 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6542 {
6543 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6544 goto getout;
6545
6546 /* Retry with non-wide function (for Windows 98). */
6547 vim_free(wn);
6548 wn = NULL;
6549 }
6550 else
6551 DeleteFileW(TempNameW);
6552 }
6553 if (wn == NULL)
6554#endif
6555 {
6556 if (!GetTempFileName(n, "VIM", 0, TempName))
6557 goto getout;
6558 mch_remove((char_u *)TempName);
6559 }
6560 }
6561 }
6562 else
6563 {
6564 /* Trying to open the file for the required access does ACL, read-only
6565 * network share, and file attribute checks. */
6566 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6567 | ((p & R_OK) ? GENERIC_READ : 0);
6568#ifdef FEAT_MBYTE
6569 if (wn != NULL)
6570 {
6571 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6572 if (hFile == INVALID_HANDLE_VALUE
6573 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6574 {
6575 /* Retry with non-wide function (for Windows 98). */
6576 vim_free(wn);
6577 wn = NULL;
6578 }
6579 }
6580 if (wn == NULL)
6581#endif
6582 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6583 if (hFile == INVALID_HANDLE_VALUE)
6584 goto getout;
6585 CloseHandle(hFile);
6586 }
6587
6588 retval = 0; /* success */
6589getout:
6590#ifdef FEAT_MBYTE
6591 vim_free(wn);
6592#endif
6593 return retval;
6594}
6595
6596#if defined(FEAT_MBYTE) || defined(PROTO)
6597/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006598 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 */
6600 int
6601mch_open(char *name, int flags, int mode)
6602{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006603 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6604# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 WCHAR *wn;
6606 int f;
6607
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006608 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006609 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006610 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006611 if (wn != NULL)
6612 {
6613 f = _wopen(wn, flags, mode);
6614 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006615 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616 return f;
6617 /* Retry with non-wide function (for Windows 98). Can't use
6618 * GetLastError() here and it's unclear what errno gets set to if
6619 * the _wopen() fails for missing wide functions. */
6620 }
6621 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006622# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006624 /* open() can open a file which name is longer than _MAX_PATH bytes
6625 * and shorter than _MAX_PATH characters successfully, but sometimes it
6626 * causes unexpected error in another part. We make it an error explicitly
6627 * here. */
6628 if (strlen(name) >= _MAX_PATH)
6629 return -1;
6630
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 return open(name, flags, mode);
6632}
6633
6634/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006635 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636 */
6637 FILE *
6638mch_fopen(char *name, char *mode)
6639{
6640 WCHAR *wn, *wm;
6641 FILE *f = NULL;
6642
6643 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6644# ifdef __BORLANDC__
6645 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6646 && g_PlatformId == VER_PLATFORM_WIN32_NT
6647# endif
6648 )
6649 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006650# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006651 /* Work around an annoying assertion in the Microsoft debug CRT
6652 * when mode's text/binary setting doesn't match _get_fmode(). */
6653 char newMode = mode[strlen(mode) - 1];
6654 int oldMode = 0;
6655
6656 _get_fmode(&oldMode);
6657 if (newMode == 't')
6658 _set_fmode(_O_TEXT);
6659 else if (newMode == 'b')
6660 _set_fmode(_O_BINARY);
6661# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006662 wn = enc_to_utf16((char_u *)name, NULL);
6663 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664 if (wn != NULL && wm != NULL)
6665 f = _wfopen(wn, wm);
6666 vim_free(wn);
6667 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006668
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006669# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006670 _set_fmode(oldMode);
6671# endif
6672
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006673 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674 return f;
6675 /* Retry with non-wide function (for Windows 98). Can't use
6676 * GetLastError() here and it's unclear what errno gets set to if
6677 * the _wfopen() fails for missing wide functions. */
6678 }
6679
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006680 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6681 * and shorter than _MAX_PATH characters successfully, but sometimes it
6682 * causes unexpected error in another part. We make it an error explicitly
6683 * here. */
6684 if (strlen(name) >= _MAX_PATH)
6685 return NULL;
6686
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 return fopen(name, mode);
6688}
6689#endif
6690
6691#ifdef FEAT_MBYTE
6692/*
6693 * SUB STREAM (aka info stream) handling:
6694 *
6695 * NTFS can have sub streams for each file. Normal contents of file is
6696 * stored in the main stream, and extra contents (author information and
6697 * title and so on) can be stored in sub stream. After Windows 2000, user
6698 * can access and store those informations in sub streams via explorer's
6699 * property menuitem in right click menu. Those informations in sub streams
6700 * were lost when copying only the main stream. So we have to copy sub
6701 * streams.
6702 *
6703 * Incomplete explanation:
6704 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6705 * More useful info and an example:
6706 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6707 */
6708
6709/*
6710 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6711 * and write to stream "substream" of file "to".
6712 * Errors are ignored.
6713 */
6714 static void
6715copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6716{
6717 HANDLE hTo;
6718 WCHAR *to_name;
6719
6720 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6721 wcscpy(to_name, to);
6722 wcscat(to_name, substream);
6723
6724 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6725 FILE_ATTRIBUTE_NORMAL, NULL);
6726 if (hTo != INVALID_HANDLE_VALUE)
6727 {
6728 long done;
6729 DWORD todo;
6730 DWORD readcnt, written;
6731 char buf[4096];
6732
6733 /* Copy block of bytes at a time. Abort when something goes wrong. */
6734 for (done = 0; done < len; done += written)
6735 {
6736 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006737 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6738 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6740 FALSE, FALSE, context)
6741 || readcnt != todo
6742 || !WriteFile(hTo, buf, todo, &written, NULL)
6743 || written != todo)
6744 break;
6745 }
6746 CloseHandle(hTo);
6747 }
6748
6749 free(to_name);
6750}
6751
6752/*
6753 * Copy info streams from file "from" to file "to".
6754 */
6755 static void
6756copy_infostreams(char_u *from, char_u *to)
6757{
6758 WCHAR *fromw;
6759 WCHAR *tow;
6760 HANDLE sh;
6761 WIN32_STREAM_ID sid;
6762 int headersize;
6763 WCHAR streamname[_MAX_PATH];
6764 DWORD readcount;
6765 void *context = NULL;
6766 DWORD lo, hi;
6767 int len;
6768
6769 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006770 fromw = enc_to_utf16(from, NULL);
6771 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 if (fromw != NULL && tow != NULL)
6773 {
6774 /* Open the file for reading. */
6775 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6776 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6777 if (sh != INVALID_HANDLE_VALUE)
6778 {
6779 /* Use BackupRead() to find the info streams. Repeat until we
6780 * have done them all.*/
6781 for (;;)
6782 {
6783 /* Get the header to find the length of the stream name. If
6784 * the "readcount" is zero we have done all info streams. */
6785 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006786 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006787 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6788 &readcount, FALSE, FALSE, &context)
6789 || readcount == 0)
6790 break;
6791
6792 /* We only deal with streams that have a name. The normal
6793 * file data appears to be without a name, even though docs
6794 * suggest it is called "::$DATA". */
6795 if (sid.dwStreamNameSize > 0)
6796 {
6797 /* Read the stream name. */
6798 if (!BackupRead(sh, (LPBYTE)streamname,
6799 sid.dwStreamNameSize,
6800 &readcount, FALSE, FALSE, &context))
6801 break;
6802
6803 /* Copy an info stream with a name ":anything:$DATA".
6804 * Skip "::$DATA", it has no stream name (examples suggest
6805 * it might be used for the normal file contents).
6806 * Note that BackupRead() counts bytes, but the name is in
6807 * wide characters. */
6808 len = readcount / sizeof(WCHAR);
6809 streamname[len] = 0;
6810 if (len > 7 && wcsicmp(streamname + len - 6,
6811 L":$DATA") == 0)
6812 {
6813 streamname[len - 6] = 0;
6814 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006815 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 }
6817 }
6818
6819 /* Advance to the next stream. We might try seeking too far,
6820 * but BackupSeek() doesn't skip over stream borders, thus
6821 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006822 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823 &lo, &hi, &context);
6824 }
6825
6826 /* Clear the context. */
6827 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6828
6829 CloseHandle(sh);
6830 }
6831 }
6832 vim_free(fromw);
6833 vim_free(tow);
6834}
6835#endif
6836
6837/*
6838 * Copy file attributes from file "from" to file "to".
6839 * For Windows NT and later we copy info streams.
6840 * Always returns zero, errors are ignored.
6841 */
6842 int
6843mch_copy_file_attribute(char_u *from, char_u *to)
6844{
6845#ifdef FEAT_MBYTE
6846 /* File streams only work on Windows NT and later. */
6847 PlatformId();
6848 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6849 copy_infostreams(from, to);
6850#endif
6851 return 0;
6852}
6853
6854#if defined(MYRESETSTKOFLW) || defined(PROTO)
6855/*
6856 * Recreate a destroyed stack guard page in win32.
6857 * Written by Benjamin Peterson.
6858 */
6859
6860/* These magic numbers are from the MS header files */
6861#define MIN_STACK_WIN9X 17
6862#define MIN_STACK_WINNT 2
6863
6864/*
6865 * This function does the same thing as _resetstkoflw(), which is only
6866 * available in DevStudio .net and later.
6867 * Returns 0 for failure, 1 for success.
6868 */
6869 int
6870myresetstkoflw(void)
6871{
6872 BYTE *pStackPtr;
6873 BYTE *pGuardPage;
6874 BYTE *pStackBase;
6875 BYTE *pLowestPossiblePage;
6876 MEMORY_BASIC_INFORMATION mbi;
6877 SYSTEM_INFO si;
6878 DWORD nPageSize;
6879 DWORD dummy;
6880
6881 /* This code will not work on win32s. */
6882 PlatformId();
6883 if (g_PlatformId == VER_PLATFORM_WIN32s)
6884 return 0;
6885
6886 /* We need to know the system page size. */
6887 GetSystemInfo(&si);
6888 nPageSize = si.dwPageSize;
6889
6890 /* ...and the current stack pointer */
6891 pStackPtr = (BYTE*)_alloca(1);
6892
6893 /* ...and the base of the stack. */
6894 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6895 return 0;
6896 pStackBase = (BYTE*)mbi.AllocationBase;
6897
6898 /* ...and the page thats min_stack_req pages away from stack base; this is
6899 * the lowest page we could use. */
6900 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6901 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6902
6903 /* On Win95, we want the next page down from the end of the stack. */
6904 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6905 {
6906 /* Find the page that's only 1 page down from the page that the stack
6907 * ptr is in. */
6908 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6909 / (DWORD)nPageSize) - 1));
6910 if (pGuardPage < pLowestPossiblePage)
6911 return 0;
6912
6913 /* Apply the noaccess attribute to the page -- there's no guard
6914 * attribute in win95-type OSes. */
6915 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6916 return 0;
6917 }
6918 else
6919 {
6920 /* On NT, however, we want the first committed page in the stack Start
6921 * at the stack base and move forward through memory until we find a
6922 * committed block. */
6923 BYTE *pBlock = pStackBase;
6924
Bram Moolenaara466c992005-07-09 21:03:22 +00006925 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926 {
6927 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6928 return 0;
6929
6930 pBlock += mbi.RegionSize;
6931
6932 if (mbi.State & MEM_COMMIT)
6933 break;
6934 }
6935
6936 /* mbi now describes the first committed block in the stack. */
6937 if (mbi.Protect & PAGE_GUARD)
6938 return 1;
6939
6940 /* decide where the guard page should start */
6941 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6942 pGuardPage = pLowestPossiblePage;
6943 else
6944 pGuardPage = (BYTE*)mbi.BaseAddress;
6945
6946 /* allocate the guard page */
6947 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6948 return 0;
6949
6950 /* apply the guard attribute to the page */
6951 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6952 &dummy))
6953 return 0;
6954 }
6955
6956 return 1;
6957}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006958#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006960
6961#if defined(FEAT_MBYTE) || defined(PROTO)
6962/*
6963 * The command line arguments in UCS2
6964 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006965static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006966static LPWSTR *ArglistW = NULL;
6967static int global_argc = 0;
6968static char **global_argv;
6969
6970static int used_file_argc = 0; /* last argument in global_argv[] used
6971 for the argument list. */
6972static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6973 command line arguments added to
6974 the argument list */
6975static int used_file_count = 0; /* nr of entries in used_file_indexes */
6976static int used_file_literal = FALSE; /* take file names literally */
6977static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006978static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006979static int used_alist_count = 0;
6980
6981
6982/*
6983 * Get the command line arguments. Unicode version.
6984 * Returns argc. Zero when something fails.
6985 */
6986 int
6987get_cmd_argsW(char ***argvp)
6988{
6989 char **argv = NULL;
6990 int argc = 0;
6991 int i;
6992
Bram Moolenaar14993322014-09-09 12:25:33 +02006993 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006994 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6995 if (ArglistW != NULL)
6996 {
6997 argv = malloc((nArgsW + 1) * sizeof(char *));
6998 if (argv != NULL)
6999 {
7000 argc = nArgsW;
7001 argv[argc] = NULL;
7002 for (i = 0; i < argc; ++i)
7003 {
7004 int len;
7005
7006 /* Convert each Unicode argument to the current codepage. */
7007 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007008 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007009 (LPSTR *)&argv[i], &len, 0, 0);
7010 if (argv[i] == NULL)
7011 {
7012 /* Out of memory, clear everything. */
7013 while (i > 0)
7014 free(argv[--i]);
7015 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007016 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007017 argc = 0;
7018 }
7019 }
7020 }
7021 }
7022
7023 global_argc = argc;
7024 global_argv = argv;
7025 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007026 {
7027 if (used_file_indexes != NULL)
7028 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007029 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007030 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007031
7032 if (argvp != NULL)
7033 *argvp = argv;
7034 return argc;
7035}
7036
7037 void
7038free_cmd_argsW(void)
7039{
7040 if (ArglistW != NULL)
7041 {
7042 GlobalFree(ArglistW);
7043 ArglistW = NULL;
7044 }
7045}
7046
7047/*
7048 * Remember "name" is an argument that was added to the argument list.
7049 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7050 * is called.
7051 */
7052 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007053used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007054{
7055 int i;
7056
7057 if (used_file_indexes == NULL)
7058 return;
7059 for (i = used_file_argc + 1; i < global_argc; ++i)
7060 if (STRCMP(global_argv[i], name) == 0)
7061 {
7062 used_file_argc = i;
7063 used_file_indexes[used_file_count++] = i;
7064 break;
7065 }
7066 used_file_literal = literal;
7067 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007068 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007069}
7070
7071/*
7072 * Remember the length of the argument list as it was. If it changes then we
7073 * leave it alone when 'encoding' is set.
7074 */
7075 void
7076set_alist_count(void)
7077{
7078 used_alist_count = GARGCOUNT;
7079}
7080
7081/*
7082 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7083 * has been changed while starting up. Use the UCS-2 command line arguments
7084 * and convert them to 'encoding'.
7085 */
7086 void
7087fix_arg_enc(void)
7088{
7089 int i;
7090 int idx;
7091 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007092 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007093
7094 /* Safety checks:
7095 * - if argument count differs between the wide and non-wide argument
7096 * list, something must be wrong.
7097 * - the file name arguments must have been located.
7098 * - the length of the argument list wasn't changed by the user.
7099 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007100 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007101 || ArglistW == NULL
7102 || used_file_indexes == NULL
7103 || used_file_count == 0
7104 || used_alist_count != GARGCOUNT)
7105 return;
7106
Bram Moolenaar86b68352004-12-27 21:59:20 +00007107 /* Remember the buffer numbers for the arguments. */
7108 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7109 if (fnum_list == NULL)
7110 return; /* out of memory */
7111 for (i = 0; i < GARGCOUNT; ++i)
7112 fnum_list[i] = GARGLIST[i].ae_fnum;
7113
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007114 /* Clear the argument list. Make room for the new arguments. */
7115 alist_clear(&global_alist);
7116 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007117 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007118
7119 for (i = 0; i < used_file_count; ++i)
7120 {
7121 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007122 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007123 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007124 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007125#ifdef FEAT_DIFF
7126 /* When using diff mode may need to concatenate file name to
7127 * directory name. Just like it's done in main(). */
7128 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7129 && !mch_isdir(alist_name(&GARGLIST[0])))
7130 {
7131 char_u *r;
7132
7133 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7134 if (r != NULL)
7135 {
7136 vim_free(str);
7137 str = r;
7138 }
7139 }
7140#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007141 /* Re-use the old buffer by renaming it. When not using literal
7142 * names it's done by alist_expand() below. */
7143 if (used_file_literal)
7144 buf_set_name(fnum_list[i], str);
7145
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007146 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007147 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007148 }
7149
7150 if (!used_file_literal)
7151 {
7152 /* Now expand wildcards in the arguments. */
7153 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7154 * filename characters but are excluded from 'isfname' to make
7155 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7156 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007157 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007158 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7159 }
7160
7161 /* If wildcard expansion failed, we are editing the first file of the
7162 * arglist and there is no file name: Edit the first argument now. */
7163 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7164 {
7165 do_cmdline_cmd((char_u *)":rewind");
7166 if (GARGCOUNT == 1 && used_file_full_path)
7167 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7168 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007169
7170 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007171}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007172#endif