blob: 9fe43218d2c84db440f7578a4de756f182b470a5 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
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 Moolenaar071d4272004-06-13 20:20:40 +0000140#endif
141
142#ifndef FEAT_GUI_W32
143/* Undocumented API in kernel32.dll needed to work around dead key bug in
144 * console-mode applications in NT 4.0. If you switch keyboard layouts
145 * in a console app to a layout that includes dead keys and then hit a
146 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
147 * and Michael Dietrich for helping me figure out this workaround.
148 */
149
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100150/* WINAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
151#ifndef WINAPI
152# define WINAPI __stdcall
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153#endif
154#if defined(__BORLANDC__)
155typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
156#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100157typedef BOOL (WINAPI *PFNGCKLN)(LPSTR);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000159static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160#endif
161
162#if defined(__BORLANDC__)
163/* Strangely Borland uses a non-standard name. */
164# define wcsicmp(a, b) wcscmpi((a), (b))
165#endif
166
Bram Moolenaar82881492012-11-20 16:53:39 +0100167#ifndef PROTO
168
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200169/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200170#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100171LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200172BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
173BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
174BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
175#endif
176
Bram Moolenaar82881492012-11-20 16:53:39 +0100177#endif /* PROTO */
178
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179#ifndef FEAT_GUI_W32
180/* Win32 Console handles for input and output */
181static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
182static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
183
184/* Win32 Screen buffer,coordinate,console I/O information */
185static SMALL_RECT g_srScrollRegion;
186static COORD g_coord; /* 0-based, but external coords are 1-based */
187
188/* The attribute of the screen when the editor was started */
189static WORD g_attrDefault = 7; /* lightgray text on black background */
190static WORD g_attrCurrent;
191
192static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
193static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
194static int g_fForceExit = FALSE; /* set when forcefully exiting */
195
196static void termcap_mode_start(void);
197static void termcap_mode_end(void);
198static void clear_chars(COORD coord, DWORD n);
199static void clear_screen(void);
200static void clear_to_end_of_display(void);
201static void clear_to_end_of_line(void);
202static void scroll(unsigned cLines);
203static void set_scroll_region(unsigned left, unsigned top,
204 unsigned right, unsigned bottom);
205static void insert_lines(unsigned cLines);
206static void delete_lines(unsigned cLines);
207static void gotoxy(unsigned x, unsigned y);
208static void normvideo(void);
209static void textattr(WORD wAttr);
210static void textcolor(WORD wAttr);
211static void textbackground(WORD wAttr);
212static void standout(void);
213static void standend(void);
214static void visual_bell(void);
215static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200216static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000217static void create_conin(void);
218static int s_cursor_visible = TRUE;
219static int did_create_conin = FALSE;
220#else
221static int s_dont_use_vimrun = TRUE;
222static int need_vimrun_warning = FALSE;
223static char *vimrun_path = "vimrun ";
224#endif
225
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200226static int win32_getattrs(char_u *name);
227static int win32_setattrs(char_u *name, int attrs);
228static int win32_set_archive(char_u *name);
229
Bram Moolenaar071d4272004-06-13 20:20:40 +0000230#ifndef FEAT_GUI_W32
231static int suppress_winsize = 1; /* don't fiddle with console */
232#endif
233
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200234static char_u *exe_path = NULL;
235
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100236static BOOL win8_or_later = FALSE;
237
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100238#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100239/*
240 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100241 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100242 */
243 static BOOL
244read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100245 HANDLE hInput,
246 INPUT_RECORD *lpBuffer,
247 DWORD nLength,
248 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100249{
250 enum
251 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100252 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100253 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100254 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100255 static DWORD s_dwIndex = 0;
256 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100257 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100258 int head;
259 int tail;
260 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100261
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200262 if (nLength == -2)
263 return (s_dwMax > 0) ? TRUE : FALSE;
264
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100265 if (!win8_or_later)
266 {
267 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200268 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
269 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100270 }
271
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100272 if (s_dwMax == 0)
273 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100274 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200275 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
276 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100277 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100278 s_dwIndex = 0;
279 s_dwMax = dwEvents;
280 if (dwEvents == 0)
281 {
282 *lpEvents = 0;
283 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100284 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100285
286 if (s_dwMax > 1)
287 {
288 head = 0;
289 tail = s_dwMax - 1;
290 while (head != tail)
291 {
292 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
293 && s_irCache[head + 1].EventType
294 == WINDOW_BUFFER_SIZE_EVENT)
295 {
296 /* Remove duplicate event to avoid flicker. */
297 for (i = head; i < tail; ++i)
298 s_irCache[i] = s_irCache[i + 1];
299 --tail;
300 continue;
301 }
302 head++;
303 }
304 s_dwMax = tail + 1;
305 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100306 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100307
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100308 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200309 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100311 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100312 return TRUE;
313}
314
315/*
316 * Version of PeekConsoleInput() that works with IME.
317 */
318 static BOOL
319peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100320 HANDLE hInput,
321 INPUT_RECORD *lpBuffer,
322 DWORD nLength,
323 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100325 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326}
327
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100328# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200329 static DWORD
330msg_wait_for_multiple_objects(
331 DWORD nCount,
332 LPHANDLE pHandles,
333 BOOL fWaitAll,
334 DWORD dwMilliseconds,
335 DWORD dwWakeMask)
336{
337 if (read_console_input(NULL, NULL, -2, NULL))
338 return WAIT_OBJECT_0;
339 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
340 dwMilliseconds, dwWakeMask);
341}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100342# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200343
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100344# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200345 static DWORD
346wait_for_single_object(
347 HANDLE hHandle,
348 DWORD dwMilliseconds)
349{
350 if (read_console_input(NULL, NULL, -2, NULL))
351 return WAIT_OBJECT_0;
352 return WaitForSingleObject(hHandle, dwMilliseconds);
353}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100354# endif
355#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200356
Bram Moolenaar071d4272004-06-13 20:20:40 +0000357 static void
358get_exe_name(void)
359{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100360 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
361 * as the maximum length that works (plus a NUL byte). */
362#define MAX_ENV_PATH_LEN 8192
363 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200364 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365
366 if (exe_name == NULL)
367 {
368 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100369 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000370 if (*temp != NUL)
371 exe_name = FullName_save((char_u *)temp, FALSE);
372 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000373
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200374 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000375 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200376 exe_path = vim_strnsave(exe_name,
377 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200378 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000379 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200380 /* Append our starting directory to $PATH, so that when doing
381 * "!xxd" it's found in our starting directory. Needed because
382 * SearchPath() also looks there. */
383 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100384 if (p == NULL
385 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200386 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100387 if (p == NULL || *p == NUL)
388 temp[0] = NUL;
389 else
390 {
391 STRCPY(temp, p);
392 STRCAT(temp, ";");
393 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200394 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100395 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200396 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000397 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000398 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000399}
400
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200401/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100402 * Unescape characters in "p" that appear in "escaped".
403 */
404 static void
405unescape_shellxquote(char_u *p, char_u *escaped)
406{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100407 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100408 int n;
409
410 while (*p != NUL)
411 {
412 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
413 mch_memmove(p, p + 1, l--);
414#ifdef FEAT_MBYTE
415 n = (*mb_ptr2len)(p);
416#else
417 n = 1;
418#endif
419 p += n;
420 l -= n;
421 }
422}
423
424/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200425 * Load library "name".
426 */
427 HINSTANCE
428vimLoadLib(char *name)
429{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200430 HINSTANCE dll = NULL;
431 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200432
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200433 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
434 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 if (exe_path == NULL)
436 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200437 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200438 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200439#ifdef FEAT_MBYTE
440 WCHAR old_dirw[MAXPATHL];
441
442 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
443 {
444 /* Change directory to where the executable is, both to make
445 * sure we find a .dll there and to avoid looking for a .dll
446 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100447 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200448 dll = LoadLibrary(name);
449 SetCurrentDirectoryW(old_dirw);
450 return dll;
451 }
452 /* Retry with non-wide function (for Windows 98). */
453 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
454#endif
455 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
456 {
457 /* Change directory to where the executable is, both to make
458 * sure we find a .dll there and to avoid looking for a .dll
459 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100460 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200461 dll = LoadLibrary(name);
462 SetCurrentDirectory(old_dir);
463 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 }
465 return dll;
466}
467
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
469# ifndef GETTEXT_DLL
470# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100471# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200473/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000474static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200475static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000476static char *null_libintl_textdomain(const char *);
477static char *null_libintl_bindtextdomain(const char *, const char *);
478static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000481char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200482char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
483 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000484char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
485char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000487char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
488 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000489
490 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100491dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000492{
493 int i;
494 static struct
495 {
496 char *name;
497 FARPROC *ptr;
498 } libintl_entry[] =
499 {
500 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200501 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
503 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
504 {NULL, NULL}
505 };
506
507 /* No need to initialize twice. */
508 if (hLibintlDLL)
509 return 1;
510 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100511 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100512#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100513 if (!hLibintlDLL)
514 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100515#endif
516 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000517 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200518 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200520 verbose_enter();
521 EMSG2(_(e_loadlib), GETTEXT_DLL);
522 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200524 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525 }
526 for (i = 0; libintl_entry[i].name != NULL
527 && libintl_entry[i].ptr != NULL; ++i)
528 {
529 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
530 libintl_entry[i].name)) == NULL)
531 {
532 dyn_libintl_end();
533 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000534 {
535 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000537 verbose_leave();
538 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000539 return 0;
540 }
541 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000542
543 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000544 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000545 "bind_textdomain_codeset");
546 if (dyn_libintl_bind_textdomain_codeset == NULL)
547 dyn_libintl_bind_textdomain_codeset =
548 null_libintl_bind_textdomain_codeset;
549
Bram Moolenaar071d4272004-06-13 20:20:40 +0000550 return 1;
551}
552
553 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100554dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555{
556 if (hLibintlDLL)
557 FreeLibrary(hLibintlDLL);
558 hLibintlDLL = NULL;
559 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200560 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561 dyn_libintl_textdomain = null_libintl_textdomain;
562 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000563 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000564}
565
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000566/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000567 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000568null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569{
570 return (char*)msgid;
571}
572
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000573/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000574 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200575null_libintl_ngettext(
576 const char *msgid,
577 const char *msgid_plural,
578 unsigned long n)
579{
580 return n == 1 ? msgid : msgid_plural;
581}
582
583/*ARGSUSED*/
584 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000585null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000586{
587 return NULL;
588}
589
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000590/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000592null_libintl_bind_textdomain_codeset(const char *domainname,
593 const char *codeset)
594{
595 return NULL;
596}
597
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000598/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000599 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000600null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601{
602 return NULL;
603}
604
605#endif /* DYNAMIC_GETTEXT */
606
607/* This symbol is not defined in older versions of the SDK or Visual C++ */
608
609#ifndef VER_PLATFORM_WIN32_WINDOWS
610# define VER_PLATFORM_WIN32_WINDOWS 1
611#endif
612
613DWORD g_PlatformId;
614
615#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100616# ifndef PROTO
617# include <aclapi.h>
618# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200619# ifndef PROTECTED_DACL_SECURITY_INFORMATION
620# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
621# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100622
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623/*
624 * These are needed to dynamically load the ADVAPI DLL, which is not
625 * implemented under Windows 95 (and causes VIM to crash)
626 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200627typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000628 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200629typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
631 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200632# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200633typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200634 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200635typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200636 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
637 PSECURITY_DESCRIPTOR *);
638# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000639
640static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
641static PSNSECINFO pSetNamedSecurityInfo;
642static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200643# ifdef FEAT_MBYTE
644static PSNSECINFOW pSetNamedSecurityInfoW;
645static PGNSECINFOW pGetNamedSecurityInfoW;
646# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000647#endif
648
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200649typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
650
651static BOOL allowPiping = FALSE;
652static PSETHANDLEINFORMATION pSetHandleInformation;
653
Bram Moolenaar27515922013-06-29 15:36:26 +0200654#ifdef HAVE_ACL
655/*
656 * Enables or disables the specified privilege.
657 */
658 static BOOL
659win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
660{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100661 BOOL bResult;
662 LUID luid;
663 HANDLE hToken;
664 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200665
666 if (!OpenProcessToken(GetCurrentProcess(),
667 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
668 return FALSE;
669
670 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
671 {
672 CloseHandle(hToken);
673 return FALSE;
674 }
675
Bram Moolenaar45500912014-07-09 20:51:07 +0200676 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200677 tokenPrivileges.Privileges[0].Luid = luid;
678 tokenPrivileges.Privileges[0].Attributes = bEnable ?
679 SE_PRIVILEGE_ENABLED : 0;
680
681 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
682 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
683
684 CloseHandle(hToken);
685
686 return bResult && GetLastError() == ERROR_SUCCESS;
687}
688#endif
689
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690/*
691 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
692 * VER_PLATFORM_WIN32_WINDOWS (Win95).
693 */
694 void
695PlatformId(void)
696{
697 static int done = FALSE;
698
699 if (!done)
700 {
701 OSVERSIONINFO ovi;
702
703 ovi.dwOSVersionInfoSize = sizeof(ovi);
704 GetVersionEx(&ovi);
705
706 g_PlatformId = ovi.dwPlatformId;
707
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100708 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
709 || ovi.dwMajorVersion > 6)
710 win8_or_later = TRUE;
711
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712#ifdef HAVE_ACL
713 /*
714 * Load the ADVAPI runtime if we are on anything
715 * other than Windows 95
716 */
717 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
718 {
719 /*
720 * do this load. Problems: Doesn't unload at end of run (this is
721 * theoretically okay, since Windows should unload it when VIM
722 * terminates). Should we be using the 'mch_libcall' routines?
723 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
724 * time we verify security...
725 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200726 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727 if (advapi_lib != NULL)
728 {
729 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
730 "SetNamedSecurityInfoA");
731 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
732 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200733# ifdef FEAT_MBYTE
734 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
735 "SetNamedSecurityInfoW");
736 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
737 "GetNamedSecurityInfoW");
738# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200740 || pGetNamedSecurityInfo == NULL
741# ifdef FEAT_MBYTE
742 || pSetNamedSecurityInfoW == NULL
743 || pGetNamedSecurityInfoW == NULL
744# endif
745 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746 {
747 /* If we can't get the function addresses, set advapi_lib
748 * to NULL so that we don't use them. */
749 FreeLibrary(advapi_lib);
750 advapi_lib = NULL;
751 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200752 /* Enable privilege for getting or setting SACLs. */
753 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754 }
755 }
756#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200757 /*
758 * If we are on windows NT, try to load the pipe functions, only
759 * available from Win2K.
760 */
761 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
762 {
763 HANDLE kernel32 = GetModuleHandle("kernel32");
764 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
765 kernel32, "SetHandleInformation");
766
767 allowPiping = pSetHandleInformation != NULL;
768 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769 done = TRUE;
770 }
771}
772
773/*
774 * Return TRUE when running on Windows 95 (or 98 or ME).
775 * Only to be used after mch_init().
776 */
777 int
778mch_windows95(void)
779{
780 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
781}
782
783#ifdef FEAT_GUI_W32
784/*
785 * Used to work around the "can't do synchronous spawn"
786 * problem on Win32s, without resorting to Universal Thunk.
787 */
788static int old_num_windows;
789static int num_windows;
790
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000791/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792 static BOOL CALLBACK
793win32ssynch_cb(HWND hwnd, LPARAM lparam)
794{
795 num_windows++;
796 return TRUE;
797}
798#endif
799
800#ifndef FEAT_GUI_W32
801
802#define SHIFT (SHIFT_PRESSED)
803#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
804#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
805#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
806
807
808/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
809 * We map function keys to their ANSI terminal equivalents, as produced
810 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
811 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
812 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
813 * combinations of function/arrow/etc keys.
814 */
815
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000816static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817{
818 WORD wVirtKey;
819 BOOL fAnsiKey;
820 int chAlone;
821 int chShift;
822 int chCtrl;
823 int chAlt;
824} VirtKeyMap[] =
825{
826
827/* Key ANSI alone shift ctrl alt */
828 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
829
830 { VK_F1, TRUE, ';', 'T', '^', 'h', },
831 { VK_F2, TRUE, '<', 'U', '_', 'i', },
832 { VK_F3, TRUE, '=', 'V', '`', 'j', },
833 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
834 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
835 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
836 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
837 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
838 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
839 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
840 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
841 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
842
843 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
844 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
845 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
846 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
847 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
848 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
849 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
850 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
851 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
852 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
853
854 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
855
856#if 0
857 /* Most people don't have F13-F20, but what the hell... */
858 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
859 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
860 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
861 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
862 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
863 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
864 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
865 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
866#endif
867 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
868 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
869 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
870 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
871
872 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
873 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
874 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
875 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
876 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
877 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
878 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
879 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
880 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
881 /* Sorry, out of number space! <negri>*/
882 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
883
884};
885
886
887#ifdef _MSC_VER
888// The ToAscii bug destroys several registers. Need to turn off optimization
889// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000890# pragma warning(push)
891# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892# pragma optimize("", off)
893#endif
894
895#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200896# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200898# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899#endif
900
901/* The return code indicates key code size. */
902 static int
903#ifdef __BORLANDC__
904 __stdcall
905#endif
906win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000907 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908{
909 UINT uMods = pker->dwControlKeyState;
910 static int s_iIsDead = 0;
911 static WORD awAnsiCode[2];
912 static BYTE abKeystate[256];
913
914
915 if (s_iIsDead == 2)
916 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200917 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918 s_iIsDead = 0;
919 return 1;
920 }
921
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200922 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923 return 1;
924
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200925 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926
927 // Should only be non-NULL on NT 4.0
928 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
929 {
930 CHAR szKLID[KL_NAMELENGTH];
931
932 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
933 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
934 }
935
936 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200937 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938
939 if (uMods & SHIFT_PRESSED)
940 abKeystate[VK_SHIFT] = 0x80;
941 if (uMods & CAPSLOCK_ON)
942 abKeystate[VK_CAPITAL] = 1;
943
944 if ((uMods & ALT_GR) == ALT_GR)
945 {
946 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
947 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
948 }
949
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200950 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
951 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000952
953 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200954 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955
956 return s_iIsDead;
957}
958
959#ifdef _MSC_VER
960/* MUST switch optimization on again here, otherwise a call to
961 * decode_key_event() may crash (e.g. when hitting caps-lock) */
962# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000963# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964
965# if (_MSC_VER < 1100)
966/* MUST turn off global optimisation for this next function, or
967 * pressing ctrl-minus in insert mode crashes Vim when built with
968 * VC4.1. -- negri. */
969# pragma optimize("g", off)
970# endif
971#endif
972
973static BOOL g_fJustGotFocus = FALSE;
974
975/*
976 * Decode a KEY_EVENT into one or two keystrokes
977 */
978 static BOOL
979decode_key_event(
980 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200981 WCHAR *pch,
982 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983 int *pmodifiers,
984 BOOL fDoPost)
985{
986 int i;
987 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
988
989 *pch = *pch2 = NUL;
990 g_fJustGotFocus = FALSE;
991
992 /* ignore key up events */
993 if (!pker->bKeyDown)
994 return FALSE;
995
996 /* ignore some keystrokes */
997 switch (pker->wVirtualKeyCode)
998 {
999 /* modifiers */
1000 case VK_SHIFT:
1001 case VK_CONTROL:
1002 case VK_MENU: /* Alt key */
1003 return FALSE;
1004
1005 default:
1006 break;
1007 }
1008
1009 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001010 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001011 {
1012 /* Ctrl-6 is Ctrl-^ */
1013 if (pker->wVirtualKeyCode == '6')
1014 {
1015 *pch = Ctrl_HAT;
1016 return TRUE;
1017 }
1018 /* Ctrl-2 is Ctrl-@ */
1019 else if (pker->wVirtualKeyCode == '2')
1020 {
1021 *pch = NUL;
1022 return TRUE;
1023 }
1024 /* Ctrl-- is Ctrl-_ */
1025 else if (pker->wVirtualKeyCode == 0xBD)
1026 {
1027 *pch = Ctrl__;
1028 return TRUE;
1029 }
1030 }
1031
1032 /* Shift-TAB */
1033 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1034 {
1035 *pch = K_NUL;
1036 *pch2 = '\017';
1037 return TRUE;
1038 }
1039
1040 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1041 {
1042 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1043 {
1044 if (nModifs == 0)
1045 *pch = VirtKeyMap[i].chAlone;
1046 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1047 *pch = VirtKeyMap[i].chShift;
1048 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1049 *pch = VirtKeyMap[i].chCtrl;
1050 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1051 *pch = VirtKeyMap[i].chAlt;
1052
1053 if (*pch != 0)
1054 {
1055 if (VirtKeyMap[i].fAnsiKey)
1056 {
1057 *pch2 = *pch;
1058 *pch = K_NUL;
1059 }
1060
1061 return TRUE;
1062 }
1063 }
1064 }
1065
1066 i = win32_kbd_patch_key(pker);
1067
1068 if (i < 0)
1069 *pch = NUL;
1070 else
1071 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001072 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073
1074 if (pmodifiers != NULL)
1075 {
1076 /* Pass on the ALT key as a modifier, but only when not combined
1077 * with CTRL (which is ALTGR). */
1078 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1079 *pmodifiers |= MOD_MASK_ALT;
1080
1081 /* Pass on SHIFT only for special keys, because we don't know when
1082 * it's already included with the character. */
1083 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1084 *pmodifiers |= MOD_MASK_SHIFT;
1085
1086 /* Pass on CTRL only for non-special keys, because we don't know
1087 * when it's already included with the character. And not when
1088 * combined with ALT (which is ALTGR). */
1089 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1090 && *pch >= 0x20 && *pch < 0x80)
1091 *pmodifiers |= MOD_MASK_CTRL;
1092 }
1093 }
1094
1095 return (*pch != NUL);
1096}
1097
1098#ifdef _MSC_VER
1099# pragma optimize("", on)
1100#endif
1101
1102#endif /* FEAT_GUI_W32 */
1103
1104
1105#ifdef FEAT_MOUSE
1106
1107/*
1108 * For the GUI the mouse handling is in gui_w32.c.
1109 */
1110# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001111/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001113mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114{
1115}
1116# else
1117static int g_fMouseAvail = FALSE; /* mouse present */
1118static int g_fMouseActive = FALSE; /* mouse enabled */
1119static int g_nMouseClick = -1; /* mouse status */
1120static int g_xMouse; /* mouse x coordinate */
1121static int g_yMouse; /* mouse y coordinate */
1122
1123/*
1124 * Enable or disable mouse input
1125 */
1126 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001127mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128{
1129 DWORD cmodein;
1130
1131 if (!g_fMouseAvail)
1132 return;
1133
1134 g_fMouseActive = on;
1135 GetConsoleMode(g_hConIn, &cmodein);
1136
1137 if (g_fMouseActive)
1138 cmodein |= ENABLE_MOUSE_INPUT;
1139 else
1140 cmodein &= ~ENABLE_MOUSE_INPUT;
1141
1142 SetConsoleMode(g_hConIn, cmodein);
1143}
1144
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145/*
1146 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1147 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1148 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1149 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1150 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1151 * and we return the mouse position in g_xMouse and g_yMouse.
1152 *
1153 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1154 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1155 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1156 *
1157 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1158 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1159 *
1160 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1161 * moves, even if it stays within the same character cell. We ignore
1162 * all MOUSE_MOVED messages if the position hasn't really changed, and
1163 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1164 * we're only interested in MOUSE_DRAG).
1165 *
1166 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1167 * 2-button mouses by pressing the left & right buttons simultaneously.
1168 * In practice, it's almost impossible to click both at the same time,
1169 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1170 * in such cases, if the user is clicking quickly.
1171 */
1172 static BOOL
1173decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001174 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175{
1176 static int s_nOldButton = -1;
1177 static int s_nOldMouseClick = -1;
1178 static int s_xOldMouse = -1;
1179 static int s_yOldMouse = -1;
1180 static linenr_T s_old_topline = 0;
1181#ifdef FEAT_DIFF
1182 static int s_old_topfill = 0;
1183#endif
1184 static int s_cClicks = 1;
1185 static BOOL s_fReleased = TRUE;
1186 static DWORD s_dwLastClickTime = 0;
1187 static BOOL s_fNextIsMiddle = FALSE;
1188
1189 static DWORD cButtons = 0; /* number of buttons supported */
1190
1191 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1192 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1193 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1194 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1195
1196 int nButton;
1197
1198 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1199 cButtons = 2;
1200
1201 if (!g_fMouseAvail || !g_fMouseActive)
1202 {
1203 g_nMouseClick = -1;
1204 return FALSE;
1205 }
1206
1207 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1208 if (g_fJustGotFocus)
1209 {
1210 g_fJustGotFocus = FALSE;
1211 return FALSE;
1212 }
1213
1214 /* unprocessed mouse click? */
1215 if (g_nMouseClick != -1)
1216 return TRUE;
1217
1218 nButton = -1;
1219 g_xMouse = pmer->dwMousePosition.X;
1220 g_yMouse = pmer->dwMousePosition.Y;
1221
1222 if (pmer->dwEventFlags == MOUSE_MOVED)
1223 {
1224 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1225 * events even when the mouse moves only within a char cell.) */
1226 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1227 return FALSE;
1228 }
1229
1230 /* If no buttons are pressed... */
1231 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1232 {
1233 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1234 if (s_fReleased)
1235 return FALSE;
1236
1237 nButton = MOUSE_RELEASE;
1238 s_fReleased = TRUE;
1239 }
1240 else /* one or more buttons pressed */
1241 {
1242 /* on a 2-button mouse, hold down left and right buttons
1243 * simultaneously to get MIDDLE. */
1244
1245 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1246 {
1247 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1248
1249 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001250 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251 if (dwLR == LEFT || dwLR == RIGHT)
1252 {
1253 for (;;)
1254 {
1255 /* wait a short time for next input event */
1256 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1257 != WAIT_OBJECT_0)
1258 break;
1259 else
1260 {
1261 DWORD cRecords = 0;
1262 INPUT_RECORD ir;
1263 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1264
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001265 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266
1267 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1268 || !(pmer2->dwButtonState & LEFT_RIGHT))
1269 break;
1270 else
1271 {
1272 if (pmer2->dwEventFlags != MOUSE_MOVED)
1273 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001274 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001275
1276 return decode_mouse_event(pmer2);
1277 }
1278 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1279 s_yOldMouse == pmer2->dwMousePosition.Y)
1280 {
1281 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001282 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001283
1284 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001285 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286
1287 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1288 break;
1289 }
1290 else
1291 break;
1292 }
1293 }
1294 }
1295 }
1296 }
1297
1298 if (s_fNextIsMiddle)
1299 {
1300 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1301 ? MOUSE_DRAG : MOUSE_MIDDLE;
1302 s_fNextIsMiddle = FALSE;
1303 }
1304 else if (cButtons == 2 &&
1305 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1306 {
1307 nButton = MOUSE_MIDDLE;
1308
1309 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1310 {
1311 s_fNextIsMiddle = TRUE;
1312 nButton = MOUSE_RELEASE;
1313 }
1314 }
1315 else if ((pmer->dwButtonState & LEFT) == LEFT)
1316 nButton = MOUSE_LEFT;
1317 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1318 nButton = MOUSE_MIDDLE;
1319 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1320 nButton = MOUSE_RIGHT;
1321
1322 if (! s_fReleased && ! s_fNextIsMiddle
1323 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1324 return FALSE;
1325
1326 s_fReleased = s_fNextIsMiddle;
1327 }
1328
1329 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1330 {
1331 /* button pressed or released, without mouse moving */
1332 if (nButton != -1 && nButton != MOUSE_RELEASE)
1333 {
1334 DWORD dwCurrentTime = GetTickCount();
1335
1336 if (s_xOldMouse != g_xMouse
1337 || s_yOldMouse != g_yMouse
1338 || s_nOldButton != nButton
1339 || s_old_topline != curwin->w_topline
1340#ifdef FEAT_DIFF
1341 || s_old_topfill != curwin->w_topfill
1342#endif
1343 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1344 {
1345 s_cClicks = 1;
1346 }
1347 else if (++s_cClicks > 4)
1348 {
1349 s_cClicks = 1;
1350 }
1351
1352 s_dwLastClickTime = dwCurrentTime;
1353 }
1354 }
1355 else if (pmer->dwEventFlags == MOUSE_MOVED)
1356 {
1357 if (nButton != -1 && nButton != MOUSE_RELEASE)
1358 nButton = MOUSE_DRAG;
1359
1360 s_cClicks = 1;
1361 }
1362
1363 if (nButton == -1)
1364 return FALSE;
1365
1366 if (nButton != MOUSE_RELEASE)
1367 s_nOldButton = nButton;
1368
1369 g_nMouseClick = nButton;
1370
1371 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1372 g_nMouseClick |= MOUSE_SHIFT;
1373 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1374 g_nMouseClick |= MOUSE_CTRL;
1375 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1376 g_nMouseClick |= MOUSE_ALT;
1377
1378 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1379 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1380
1381 /* only pass on interesting (i.e., different) mouse events */
1382 if (s_xOldMouse == g_xMouse
1383 && s_yOldMouse == g_yMouse
1384 && s_nOldMouseClick == g_nMouseClick)
1385 {
1386 g_nMouseClick = -1;
1387 return FALSE;
1388 }
1389
1390 s_xOldMouse = g_xMouse;
1391 s_yOldMouse = g_yMouse;
1392 s_old_topline = curwin->w_topline;
1393#ifdef FEAT_DIFF
1394 s_old_topfill = curwin->w_topfill;
1395#endif
1396 s_nOldMouseClick = g_nMouseClick;
1397
1398 return TRUE;
1399}
1400
1401# endif /* FEAT_GUI_W32 */
1402#endif /* FEAT_MOUSE */
1403
1404
1405#ifdef MCH_CURSOR_SHAPE
1406/*
1407 * Set the shape of the cursor.
1408 * 'thickness' can be from 1 (thin) to 99 (block)
1409 */
1410 static void
1411mch_set_cursor_shape(int thickness)
1412{
1413 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1414 ConsoleCursorInfo.dwSize = thickness;
1415 ConsoleCursorInfo.bVisible = s_cursor_visible;
1416
1417 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1418 if (s_cursor_visible)
1419 SetConsoleCursorPosition(g_hConOut, g_coord);
1420}
1421
1422 void
1423mch_update_cursor(void)
1424{
1425 int idx;
1426 int thickness;
1427
1428 /*
1429 * How the cursor is drawn depends on the current mode.
1430 */
1431 idx = get_shape_idx(FALSE);
1432
1433 if (shape_table[idx].shape == SHAPE_BLOCK)
1434 thickness = 99; /* 100 doesn't work on W95 */
1435 else
1436 thickness = shape_table[idx].percentage;
1437 mch_set_cursor_shape(thickness);
1438}
1439#endif
1440
1441#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1442/*
1443 * Handle FOCUS_EVENT.
1444 */
1445 static void
1446handle_focus_event(INPUT_RECORD ir)
1447{
1448 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1449 ui_focus_change((int)g_fJustGotFocus);
1450}
1451
1452/*
1453 * Wait until console input from keyboard or mouse is available,
1454 * or the time is up.
1455 * Return TRUE if something is available FALSE if not.
1456 */
1457 static int
1458WaitForChar(long msec)
1459{
1460 DWORD dwNow = 0, dwEndTime = 0;
1461 INPUT_RECORD ir;
1462 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001463 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001464#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001465 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001466#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001467
1468 if (msec > 0)
1469 /* Wait until the specified time has elapsed. */
1470 dwEndTime = GetTickCount() + msec;
1471 else if (msec < 0)
1472 /* Wait forever. */
1473 dwEndTime = INFINITE;
1474
1475 /* We need to loop until the end of the time period, because
1476 * we might get multiple unusable mouse events in that time.
1477 */
1478 for (;;)
1479 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001480#ifdef MESSAGE_QUEUE
1481 parse_queued_messages();
1482#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001483#ifdef FEAT_MZSCHEME
1484 mzvim_check_threads();
1485#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486#ifdef FEAT_CLIENTSERVER
1487 serverProcessPendingMessages();
1488#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001489
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490 if (0
1491#ifdef FEAT_MOUSE
1492 || g_nMouseClick != -1
1493#endif
1494#ifdef FEAT_CLIENTSERVER
1495 || input_available()
1496#endif
1497 )
1498 return TRUE;
1499
1500 if (msec > 0)
1501 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001502 /* If the specified wait time has passed, return. Beware that
1503 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001505 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506 break;
1507 }
1508 if (msec != 0)
1509 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001510 DWORD dwWaitTime = dwEndTime - dwNow;
1511
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001512#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar9186a272016-02-23 19:34:01 +01001513 /* Check channel while waiting input. */
1514 if (dwWaitTime > 100)
1515 dwWaitTime = 100;
1516#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001517#ifdef FEAT_MZSCHEME
1518 if (mzthreads_allowed() && p_mzq > 0
1519 && (msec < 0 || (long)dwWaitTime > p_mzq))
1520 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1521#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001522#ifdef FEAT_TIMERS
1523 {
1524 long due_time;
1525
1526 /* When waiting very briefly don't trigger timers. */
1527 if (dwWaitTime > 10)
1528 {
1529 /* Trigger timers and then get the time in msec until the
1530 * next one is due. Wait up to that time. */
1531 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001532 if (typebuf.tb_change_cnt != tb_change_cnt)
1533 {
1534 /* timer may have used feedkeys() */
1535 return FALSE;
1536 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001537 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1538 dwWaitTime = due_time;
1539 }
1540 }
1541#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001542#ifdef FEAT_CLIENTSERVER
1543 /* Wait for either an event on the console input or a message in
1544 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001545 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001546 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001548 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549#endif
1550 continue;
1551 }
1552
1553 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001554 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555
1556#ifdef FEAT_MBYTE_IME
1557 if (State & CMDLINE && msg_row == Rows - 1)
1558 {
1559 CONSOLE_SCREEN_BUFFER_INFO csbi;
1560
1561 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1562 {
1563 if (csbi.dwCursorPosition.Y != msg_row)
1564 {
1565 /* The screen is now messed up, must redraw the
1566 * command line and later all the windows. */
1567 redraw_all_later(CLEAR);
1568 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1569 redrawcmd();
1570 }
1571 }
1572 }
1573#endif
1574
1575 if (cRecords > 0)
1576 {
1577 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1578 {
1579#ifdef FEAT_MBYTE_IME
1580 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1581 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001582 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1584 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001585 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586 continue;
1587 }
1588#endif
1589 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1590 NULL, FALSE))
1591 return TRUE;
1592 }
1593
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001594 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595
1596 if (ir.EventType == FOCUS_EVENT)
1597 handle_focus_event(ir);
1598 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1599 shell_resized();
1600#ifdef FEAT_MOUSE
1601 else if (ir.EventType == MOUSE_EVENT
1602 && decode_mouse_event(&ir.Event.MouseEvent))
1603 return TRUE;
1604#endif
1605 }
1606 else if (msec == 0)
1607 break;
1608 }
1609
1610#ifdef FEAT_CLIENTSERVER
1611 /* Something might have been received while we were waiting. */
1612 if (input_available())
1613 return TRUE;
1614#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001615
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616 return FALSE;
1617}
1618
1619#ifndef FEAT_GUI_MSWIN
1620/*
1621 * return non-zero if a character is available
1622 */
1623 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001624mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625{
1626 return WaitForChar(0L);
1627}
1628#endif
1629
1630/*
1631 * Create the console input. Used when reading stdin doesn't work.
1632 */
1633 static void
1634create_conin(void)
1635{
1636 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1637 FILE_SHARE_READ|FILE_SHARE_WRITE,
1638 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001639 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 did_create_conin = TRUE;
1641}
1642
1643/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001644 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001646 static WCHAR
1647tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001649 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650
1651 for (;;)
1652 {
1653 INPUT_RECORD ir;
1654 DWORD cRecords = 0;
1655
1656#ifdef FEAT_CLIENTSERVER
1657 (void)WaitForChar(-1L);
1658 if (input_available())
1659 return 0;
1660# ifdef FEAT_MOUSE
1661 if (g_nMouseClick != -1)
1662 return 0;
1663# endif
1664#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001665 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666 {
1667 if (did_create_conin)
1668 read_error_exit();
1669 create_conin();
1670 continue;
1671 }
1672
1673 if (ir.EventType == KEY_EVENT)
1674 {
1675 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1676 pmodifiers, TRUE))
1677 return ch;
1678 }
1679 else if (ir.EventType == FOCUS_EVENT)
1680 handle_focus_event(ir);
1681 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1682 shell_resized();
1683#ifdef FEAT_MOUSE
1684 else if (ir.EventType == MOUSE_EVENT)
1685 {
1686 if (decode_mouse_event(&ir.Event.MouseEvent))
1687 return 0;
1688 }
1689#endif
1690 }
1691}
1692#endif /* !FEAT_GUI_W32 */
1693
1694
1695/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001696 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697 * Get one or more characters from the keyboard or the mouse.
1698 * If time == 0, do not wait for characters.
1699 * If time == n, wait a short time for characters.
1700 * If time == -1, wait forever for characters.
1701 * Returns the number of characters read into buf.
1702 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001703/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704 int
1705mch_inchar(
1706 char_u *buf,
1707 int maxlen,
1708 long time,
1709 int tb_change_cnt)
1710{
1711#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1712
1713 int len;
1714 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715#define TYPEAHEADLEN 20
1716 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1717 static int typeaheadlen = 0;
1718
1719 /* First use any typeahead that was kept because "buf" was too small. */
1720 if (typeaheadlen > 0)
1721 goto theend;
1722
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 if (time >= 0)
1724 {
1725 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727 }
1728 else /* time == -1, wait forever */
1729 {
1730 mch_set_winsize_now(); /* Allow winsize changes from now on */
1731
Bram Moolenaar3918c952005-03-15 22:34:55 +00001732 /*
1733 * If there is no character available within 2 seconds (default)
1734 * write the autoscript file to disk. Or cause the CursorHold event
1735 * to be triggered.
1736 */
1737 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738 {
1739#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001740 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001741 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001742 buf[0] = K_SPECIAL;
1743 buf[1] = KS_EXTRA;
1744 buf[2] = (int)KE_CURSORHOLD;
1745 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 }
1747#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001748 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 }
1750 }
1751
1752 /*
1753 * Try to read as many characters as there are, until the buffer is full.
1754 */
1755
1756 /* we will get at least one key. Get more if they are available. */
1757 g_fCBrkPressed = FALSE;
1758
1759#ifdef MCH_WRITE_DUMP
1760 if (fdDump)
1761 fputc('[', fdDump);
1762#endif
1763
1764 /* Keep looping until there is something in the typeahead buffer and more
1765 * to get and still room in the buffer (up to two bytes for a char and
1766 * three bytes for a modifier). */
1767 while ((typeaheadlen == 0 || WaitForChar(0L))
1768 && typeaheadlen + 5 <= TYPEAHEADLEN)
1769 {
1770 if (typebuf_changed(tb_change_cnt))
1771 {
1772 /* "buf" may be invalid now if a client put something in the
1773 * typeahead buffer and "buf" is in the typeahead buffer. */
1774 typeaheadlen = 0;
1775 break;
1776 }
1777#ifdef FEAT_MOUSE
1778 if (g_nMouseClick != -1)
1779 {
1780# ifdef MCH_WRITE_DUMP
1781 if (fdDump)
1782 fprintf(fdDump, "{%02x @ %d, %d}",
1783 g_nMouseClick, g_xMouse, g_yMouse);
1784# endif
1785 typeahead[typeaheadlen++] = ESC + 128;
1786 typeahead[typeaheadlen++] = 'M';
1787 typeahead[typeaheadlen++] = g_nMouseClick;
1788 typeahead[typeaheadlen++] = g_xMouse + '!';
1789 typeahead[typeaheadlen++] = g_yMouse + '!';
1790 g_nMouseClick = -1;
1791 }
1792 else
1793#endif
1794 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001795 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 int modifiers = 0;
1797
1798 c = tgetch(&modifiers, &ch2);
1799
1800 if (typebuf_changed(tb_change_cnt))
1801 {
1802 /* "buf" may be invalid now if a client put something in the
1803 * typeahead buffer and "buf" is in the typeahead buffer. */
1804 typeaheadlen = 0;
1805 break;
1806 }
1807
1808 if (c == Ctrl_C && ctrl_c_interrupts)
1809 {
1810#if defined(FEAT_CLIENTSERVER)
1811 trash_input_buf();
1812#endif
1813 got_int = TRUE;
1814 }
1815
1816#ifdef FEAT_MOUSE
1817 if (g_nMouseClick == -1)
1818#endif
1819 {
1820 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001821 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001823#ifdef FEAT_MBYTE
1824 if (ch2 == NUL)
1825 {
1826 int i;
1827 char_u *p;
1828 WCHAR ch[2];
1829
1830 ch[0] = c;
1831 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1832 {
1833 ch[1] = tgetch(&modifiers, &ch2);
1834 n++;
1835 }
1836 p = utf16_to_enc(ch, &n);
1837 if (p != NULL)
1838 {
1839 for (i = 0; i < n; i++)
1840 typeahead[typeaheadlen + i] = p[i];
1841 vim_free(p);
1842 }
1843 }
1844 else
1845#endif
1846 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 if (ch2 != NUL)
1848 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001849 typeahead[typeaheadlen + n] = 3;
1850 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001851 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001853
Bram Moolenaar45500912014-07-09 20:51:07 +02001854 if (conv)
1855 {
1856 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001857
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001858 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001859 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001860 char_u *e = typeahead + TYPEAHEADLEN;
1861
1862 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001863 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001864 if (*p == K_NUL)
1865 {
1866 ++p;
1867 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1868 *p = 3;
1869 ++n;
1870 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001871 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001872 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001873 }
1874 }
1875
Bram Moolenaar071d4272004-06-13 20:20:40 +00001876 /* Use the ALT key to set the 8th bit of the character
1877 * when it's one byte, the 8th bit isn't set yet and not
1878 * using a double-byte encoding (would become a lead
1879 * byte). */
1880 if ((modifiers & MOD_MASK_ALT)
1881 && n == 1
1882 && (typeahead[typeaheadlen] & 0x80) == 0
1883#ifdef FEAT_MBYTE
1884 && !enc_dbcs
1885#endif
1886 )
1887 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001888#ifdef FEAT_MBYTE
1889 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1890 typeahead + typeaheadlen);
1891#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001893#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894 modifiers &= ~MOD_MASK_ALT;
1895 }
1896
1897 if (modifiers != 0)
1898 {
1899 /* Prepend modifiers to the character. */
1900 mch_memmove(typeahead + typeaheadlen + 3,
1901 typeahead + typeaheadlen, n);
1902 typeahead[typeaheadlen++] = K_SPECIAL;
1903 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1904 typeahead[typeaheadlen++] = modifiers;
1905 }
1906
1907 typeaheadlen += n;
1908
1909#ifdef MCH_WRITE_DUMP
1910 if (fdDump)
1911 fputc(c, fdDump);
1912#endif
1913 }
1914 }
1915 }
1916
1917#ifdef MCH_WRITE_DUMP
1918 if (fdDump)
1919 {
1920 fputs("]\n", fdDump);
1921 fflush(fdDump);
1922 }
1923#endif
1924
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925theend:
1926 /* Move typeahead to "buf", as much as fits. */
1927 len = 0;
1928 while (len < maxlen && typeaheadlen > 0)
1929 {
1930 buf[len++] = typeahead[0];
1931 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1932 }
1933 return len;
1934
1935#else /* FEAT_GUI_W32 */
1936 return 0;
1937#endif /* FEAT_GUI_W32 */
1938}
1939
Bram Moolenaar82881492012-11-20 16:53:39 +01001940#ifndef PROTO
1941# ifndef __MINGW32__
1942# include <shellapi.h> /* required for FindExecutable() */
1943# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944#endif
1945
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001946/*
1947 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001948 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001949 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001951executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001953 char *dum;
1954 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001955 char *curpath, *newpath;
1956 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001958#ifdef FEAT_MBYTE
1959 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001961 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001962 WCHAR fnamew[_MAX_PATH];
1963 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001964 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001965
1966 if (p != NULL)
1967 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001968 wcurpath = _wgetenv(L"PATH");
1969 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1970 * sizeof(WCHAR));
1971 if (wnewpath == NULL)
1972 return FALSE;
1973 wcscpy(wnewpath, L".;");
1974 wcscat(wnewpath, wcurpath);
1975 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1976 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001977 vim_free(p);
1978 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1979 {
1980 if (n == 0)
1981 return FALSE;
1982 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1983 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001984 if (path != NULL)
1985 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001986 return TRUE;
1987 }
1988 /* Retry with non-wide function (for Windows 98). */
1989 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001991#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001992
1993 curpath = getenv("PATH");
1994 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1995 if (newpath == NULL)
1996 return FALSE;
1997 STRCPY(newpath, ".;");
1998 STRCAT(newpath, curpath);
1999 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2000 vim_free(newpath);
2001 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002002 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002003 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002004 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002005 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002006 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002007 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008}
2009
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002010#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002011 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002012/*
2013 * Bad parameter handler.
2014 *
2015 * Certain MS CRT functions will intentionally crash when passed invalid
2016 * parameters to highlight possible security holes. Setting this function as
2017 * the bad parameter handler will prevent the crash.
2018 *
2019 * In debug builds the parameters contain CRT information that might help track
2020 * down the source of a problem, but in non-debug builds the arguments are all
2021 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2022 * worth allowing these to make debugging of issues easier.
2023 */
2024 static void
2025bad_param_handler(const wchar_t *expression,
2026 const wchar_t *function,
2027 const wchar_t *file,
2028 unsigned int line,
2029 uintptr_t pReserved)
2030{
2031}
2032
2033# define SET_INVALID_PARAM_HANDLER \
2034 ((void)_set_invalid_parameter_handler(bad_param_handler))
2035#else
2036# define SET_INVALID_PARAM_HANDLER
2037#endif
2038
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039#ifdef FEAT_GUI_W32
2040
2041/*
2042 * GUI version of mch_init().
2043 */
2044 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002045mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002046{
2047#ifndef __MINGW32__
2048 extern int _fmode;
2049#endif
2050
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002051 /* Silently handle invalid parameters to CRT functions */
2052 SET_INVALID_PARAM_HANDLER;
2053
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054 /* Let critical errors result in a failure, not in a dialog box. Required
2055 * for the timestamp test to work on removed floppies. */
2056 SetErrorMode(SEM_FAILCRITICALERRORS);
2057
2058 _fmode = O_BINARY; /* we do our own CR-LF translation */
2059
2060 /* Specify window size. Is there a place to get the default from? */
2061 Rows = 25;
2062 Columns = 80;
2063
2064 /* Look for 'vimrun' */
2065 if (!gui_is_win32s())
2066 {
2067 char_u vimrun_location[_MAX_PATH + 4];
2068
2069 /* First try in same directory as gvim.exe */
2070 STRCPY(vimrun_location, exe_name);
2071 STRCPY(gettail(vimrun_location), "vimrun.exe");
2072 if (mch_getperm(vimrun_location) >= 0)
2073 {
2074 if (*skiptowhite(vimrun_location) != NUL)
2075 {
2076 /* Enclose path with white space in double quotes. */
2077 mch_memmove(vimrun_location + 1, vimrun_location,
2078 STRLEN(vimrun_location) + 1);
2079 *vimrun_location = '"';
2080 STRCPY(gettail(vimrun_location), "vimrun\" ");
2081 }
2082 else
2083 STRCPY(gettail(vimrun_location), "vimrun ");
2084
2085 vimrun_path = (char *)vim_strsave(vimrun_location);
2086 s_dont_use_vimrun = FALSE;
2087 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002088 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089 s_dont_use_vimrun = FALSE;
2090
2091 /* Don't give the warning for a missing vimrun.exe right now, but only
2092 * when vimrun was supposed to be used. Don't bother people that do
2093 * not need vimrun.exe. */
2094 if (s_dont_use_vimrun)
2095 need_vimrun_warning = TRUE;
2096 }
2097
2098 /*
2099 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2100 * Otherwise the default "findstr /n" is used.
2101 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002102 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002103 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2104
2105#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002106 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002107#endif
2108}
2109
2110
2111#else /* FEAT_GUI_W32 */
2112
2113#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2114#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2115
2116/*
2117 * ClearConsoleBuffer()
2118 * Description:
2119 * Clears the entire contents of the console screen buffer, using the
2120 * specified attribute.
2121 * Returns:
2122 * TRUE on success
2123 */
2124 static BOOL
2125ClearConsoleBuffer(WORD wAttribute)
2126{
2127 CONSOLE_SCREEN_BUFFER_INFO csbi;
2128 COORD coord;
2129 DWORD NumCells, dummy;
2130
2131 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2132 return FALSE;
2133
2134 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2135 coord.X = 0;
2136 coord.Y = 0;
2137 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2138 coord, &dummy))
2139 {
2140 return FALSE;
2141 }
2142 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2143 coord, &dummy))
2144 {
2145 return FALSE;
2146 }
2147
2148 return TRUE;
2149}
2150
2151/*
2152 * FitConsoleWindow()
2153 * Description:
2154 * Checks if the console window will fit within given buffer dimensions.
2155 * Also, if requested, will shrink the window to fit.
2156 * Returns:
2157 * TRUE on success
2158 */
2159 static BOOL
2160FitConsoleWindow(
2161 COORD dwBufferSize,
2162 BOOL WantAdjust)
2163{
2164 CONSOLE_SCREEN_BUFFER_INFO csbi;
2165 COORD dwWindowSize;
2166 BOOL NeedAdjust = FALSE;
2167
2168 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2169 {
2170 /*
2171 * A buffer resize will fail if the current console window does
2172 * not lie completely within that buffer. To avoid this, we might
2173 * have to move and possibly shrink the window.
2174 */
2175 if (csbi.srWindow.Right >= dwBufferSize.X)
2176 {
2177 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2178 if (dwWindowSize.X > dwBufferSize.X)
2179 dwWindowSize.X = dwBufferSize.X;
2180 csbi.srWindow.Right = dwBufferSize.X - 1;
2181 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2182 NeedAdjust = TRUE;
2183 }
2184 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2185 {
2186 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2187 if (dwWindowSize.Y > dwBufferSize.Y)
2188 dwWindowSize.Y = dwBufferSize.Y;
2189 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2190 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2191 NeedAdjust = TRUE;
2192 }
2193 if (NeedAdjust && WantAdjust)
2194 {
2195 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2196 return FALSE;
2197 }
2198 return TRUE;
2199 }
2200
2201 return FALSE;
2202}
2203
2204typedef struct ConsoleBufferStruct
2205{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002206 BOOL IsValid;
2207 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002208 PCHAR_INFO Buffer;
2209 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210} ConsoleBuffer;
2211
2212/*
2213 * SaveConsoleBuffer()
2214 * Description:
2215 * Saves important information about the console buffer, including the
2216 * actual buffer contents. The saved information is suitable for later
2217 * restoration by RestoreConsoleBuffer().
2218 * Returns:
2219 * TRUE if all information was saved; FALSE otherwise
2220 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2221 */
2222 static BOOL
2223SaveConsoleBuffer(
2224 ConsoleBuffer *cb)
2225{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002226 DWORD NumCells;
2227 COORD BufferCoord;
2228 SMALL_RECT ReadRegion;
2229 WORD Y, Y_incr;
2230
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231 if (cb == NULL)
2232 return FALSE;
2233
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002234 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 {
2236 cb->IsValid = FALSE;
2237 return FALSE;
2238 }
2239 cb->IsValid = TRUE;
2240
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002241 /*
2242 * Allocate a buffer large enough to hold the entire console screen
2243 * buffer. If this ConsoleBuffer structure has already been initialized
2244 * with a buffer of the correct size, then just use that one.
2245 */
2246 if (!cb->IsValid || cb->Buffer == NULL ||
2247 cb->BufferSize.X != cb->Info.dwSize.X ||
2248 cb->BufferSize.Y != cb->Info.dwSize.Y)
2249 {
2250 cb->BufferSize.X = cb->Info.dwSize.X;
2251 cb->BufferSize.Y = cb->Info.dwSize.Y;
2252 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2253 vim_free(cb->Buffer);
2254 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2255 if (cb->Buffer == NULL)
2256 return FALSE;
2257 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258
2259 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002260 * We will now copy the console screen buffer into our buffer.
2261 * ReadConsoleOutput() seems to be limited as far as how much you
2262 * can read at a time. Empirically, this number seems to be about
2263 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2264 * in chunks until it is all copied. The chunks will all have the
2265 * same horizontal characteristics, so initialize them now. The
2266 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002267 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002268 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002269 ReadRegion.Left = 0;
2270 ReadRegion.Right = cb->Info.dwSize.X - 1;
2271 Y_incr = 12000 / cb->Info.dwSize.X;
2272 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002274 /*
2275 * Read into position (0, Y) in our buffer.
2276 */
2277 BufferCoord.Y = Y;
2278 /*
2279 * Read the region whose top left corner is (0, Y) and whose bottom
2280 * right corner is (width - 1, Y + Y_incr - 1). This should define
2281 * a region of size width by Y_incr. Don't worry if this region is
2282 * too large for the remaining buffer; it will be cropped.
2283 */
2284 ReadRegion.Top = Y;
2285 ReadRegion.Bottom = Y + Y_incr - 1;
2286 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2287 cb->Buffer, /* our buffer */
2288 cb->BufferSize, /* dimensions of our buffer */
2289 BufferCoord, /* offset in our buffer */
2290 &ReadRegion)) /* region to save */
2291 {
2292 vim_free(cb->Buffer);
2293 cb->Buffer = NULL;
2294 return FALSE;
2295 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296 }
2297
2298 return TRUE;
2299}
2300
2301/*
2302 * RestoreConsoleBuffer()
2303 * Description:
2304 * Restores important information about the console buffer, including the
2305 * actual buffer contents, if desired. The information to restore is in
2306 * the same format used by SaveConsoleBuffer().
2307 * Returns:
2308 * TRUE on success
2309 */
2310 static BOOL
2311RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002312 ConsoleBuffer *cb,
2313 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002315 COORD BufferCoord;
2316 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317
2318 if (cb == NULL || !cb->IsValid)
2319 return FALSE;
2320
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002321 /*
2322 * Before restoring the buffer contents, clear the current buffer, and
2323 * restore the cursor position and window information. Doing this now
2324 * prevents old buffer contents from "flashing" onto the screen.
2325 */
2326 if (RestoreScreen)
2327 ClearConsoleBuffer(cb->Info.wAttributes);
2328
2329 FitConsoleWindow(cb->Info.dwSize, TRUE);
2330 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2331 return FALSE;
2332 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2333 return FALSE;
2334
2335 if (!RestoreScreen)
2336 {
2337 /*
2338 * No need to restore the screen buffer contents, so we're done.
2339 */
2340 return TRUE;
2341 }
2342
2343 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2344 return FALSE;
2345 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2346 return FALSE;
2347
2348 /*
2349 * Restore the screen buffer contents.
2350 */
2351 if (cb->Buffer != NULL)
2352 {
2353 BufferCoord.X = 0;
2354 BufferCoord.Y = 0;
2355 WriteRegion.Left = 0;
2356 WriteRegion.Top = 0;
2357 WriteRegion.Right = cb->Info.dwSize.X - 1;
2358 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2359 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2360 cb->Buffer, /* our buffer */
2361 cb->BufferSize, /* dimensions of our buffer */
2362 BufferCoord, /* offset in our buffer */
2363 &WriteRegion)) /* region to restore */
2364 {
2365 return FALSE;
2366 }
2367 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368
2369 return TRUE;
2370}
2371
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002372#define FEAT_RESTORE_ORIG_SCREEN
2373#ifdef FEAT_RESTORE_ORIG_SCREEN
2374static ConsoleBuffer g_cbOrig = { 0 };
2375#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376static ConsoleBuffer g_cbNonTermcap = { 0 };
2377static ConsoleBuffer g_cbTermcap = { 0 };
2378
2379#ifdef FEAT_TITLE
2380#ifdef __BORLANDC__
2381typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2382#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002383typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384#endif
2385char g_szOrigTitle[256] = { 0 };
2386HWND g_hWnd = NULL; /* also used in os_mswin.c */
2387static HICON g_hOrigIconSmall = NULL;
2388static HICON g_hOrigIcon = NULL;
2389static HICON g_hVimIcon = NULL;
2390static BOOL g_fCanChangeIcon = FALSE;
2391
2392/* ICON* are not defined in VC++ 4.0 */
2393#ifndef ICON_SMALL
2394#define ICON_SMALL 0
2395#endif
2396#ifndef ICON_BIG
2397#define ICON_BIG 1
2398#endif
2399/*
2400 * GetConsoleIcon()
2401 * Description:
2402 * Attempts to retrieve the small icon and/or the big icon currently in
2403 * use by a given window.
2404 * Returns:
2405 * TRUE on success
2406 */
2407 static BOOL
2408GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002409 HWND hWnd,
2410 HICON *phIconSmall,
2411 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412{
2413 if (hWnd == NULL)
2414 return FALSE;
2415
2416 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002417 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2418 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002420 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2421 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 return TRUE;
2423}
2424
2425/*
2426 * SetConsoleIcon()
2427 * Description:
2428 * Attempts to change the small icon and/or the big icon currently in
2429 * use by a given window.
2430 * Returns:
2431 * TRUE on success
2432 */
2433 static BOOL
2434SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002435 HWND hWnd,
2436 HICON hIconSmall,
2437 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439 if (hWnd == NULL)
2440 return FALSE;
2441
2442 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002443 SendMessage(hWnd, WM_SETICON,
2444 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002446 SendMessage(hWnd, WM_SETICON,
2447 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 return TRUE;
2449}
2450
2451/*
2452 * SaveConsoleTitleAndIcon()
2453 * Description:
2454 * Saves the current console window title in g_szOrigTitle, for later
2455 * restoration. Also, attempts to obtain a handle to the console window,
2456 * and use it to save the small and big icons currently in use by the
2457 * console window. This is not always possible on some versions of Windows;
2458 * nor is it possible when running Vim remotely using Telnet (since the
2459 * console window the user sees is owned by a remote process).
2460 */
2461 static void
2462SaveConsoleTitleAndIcon(void)
2463{
2464 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2465
2466 /* Save the original title. */
2467 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2468 return;
2469
2470 /*
2471 * Obtain a handle to the console window using GetConsoleWindow() from
2472 * KERNEL32.DLL; we need to handle in order to change the window icon.
2473 * This function only exists on NT-based Windows, starting with Windows
2474 * 2000. On older operating systems, we can't change the window icon
2475 * anyway.
2476 */
2477 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2478 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2479 "GetConsoleWindow")) != NULL)
2480 {
2481 g_hWnd = (*GetConsoleWindowProc)();
2482 }
2483 if (g_hWnd == NULL)
2484 return;
2485
2486 /* Save the original console window icon. */
2487 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2488 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2489 return;
2490
2491 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002492 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002493 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 if (g_hVimIcon != NULL)
2495 g_fCanChangeIcon = TRUE;
2496}
2497#endif
2498
2499static int g_fWindInitCalled = FALSE;
2500static int g_fTermcapMode = FALSE;
2501static CONSOLE_CURSOR_INFO g_cci;
2502static DWORD g_cmodein = 0;
2503static DWORD g_cmodeout = 0;
2504
2505/*
2506 * non-GUI version of mch_init().
2507 */
2508 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002509mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002511#ifndef FEAT_RESTORE_ORIG_SCREEN
2512 CONSOLE_SCREEN_BUFFER_INFO csbi;
2513#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514#ifndef __MINGW32__
2515 extern int _fmode;
2516#endif
2517
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002518 /* Silently handle invalid parameters to CRT functions */
2519 SET_INVALID_PARAM_HANDLER;
2520
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521 /* Let critical errors result in a failure, not in a dialog box. Required
2522 * for the timestamp test to work on removed floppies. */
2523 SetErrorMode(SEM_FAILCRITICALERRORS);
2524
2525 _fmode = O_BINARY; /* we do our own CR-LF translation */
2526 out_flush();
2527
2528 /* Obtain handles for the standard Console I/O devices */
2529 if (read_cmd_fd == 0)
2530 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2531 else
2532 create_conin();
2533 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2534
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002535#ifdef FEAT_RESTORE_ORIG_SCREEN
2536 /* Save the initial console buffer for later restoration */
2537 SaveConsoleBuffer(&g_cbOrig);
2538 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2539#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002541 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2542 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2543#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 if (cterm_normal_fg_color == 0)
2545 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2546 if (cterm_normal_bg_color == 0)
2547 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2548
2549 /* set termcap codes to current text attributes */
2550 update_tcap(g_attrCurrent);
2551
2552 GetConsoleCursorInfo(g_hConOut, &g_cci);
2553 GetConsoleMode(g_hConIn, &g_cmodein);
2554 GetConsoleMode(g_hConOut, &g_cmodeout);
2555
2556#ifdef FEAT_TITLE
2557 SaveConsoleTitleAndIcon();
2558 /*
2559 * Set both the small and big icons of the console window to Vim's icon.
2560 * Note that Vim presently only has one size of icon (32x32), but it
2561 * automatically gets scaled down to 16x16 when setting the small icon.
2562 */
2563 if (g_fCanChangeIcon)
2564 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2565#endif
2566
2567 ui_get_shellsize();
2568
2569#ifdef MCH_WRITE_DUMP
2570 fdDump = fopen("dump", "wt");
2571
2572 if (fdDump)
2573 {
2574 time_t t;
2575
2576 time(&t);
2577 fputs(ctime(&t), fdDump);
2578 fflush(fdDump);
2579 }
2580#endif
2581
2582 g_fWindInitCalled = TRUE;
2583
2584#ifdef FEAT_MOUSE
2585 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2586#endif
2587
2588#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002589 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590#endif
2591
2592 /* This will be NULL on anything but NT 4.0 */
2593 s_pfnGetConsoleKeyboardLayoutName =
2594 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2595 "GetConsoleKeyboardLayoutNameA");
2596}
2597
2598/*
2599 * non-GUI version of mch_exit().
2600 * Shut down and exit with status `r'
2601 * Careful: mch_exit() may be called before mch_init()!
2602 */
2603 void
2604mch_exit(int r)
2605{
2606 stoptermcap();
2607
2608 if (g_fWindInitCalled)
2609 settmode(TMODE_COOK);
2610
2611 ml_close_all(TRUE); /* remove all memfiles */
2612
2613 if (g_fWindInitCalled)
2614 {
2615#ifdef FEAT_TITLE
2616 mch_restore_title(3);
2617 /*
2618 * Restore both the small and big icons of the console window to
2619 * what they were at startup. Don't do this when the window is
2620 * closed, Vim would hang here.
2621 */
2622 if (g_fCanChangeIcon && !g_fForceExit)
2623 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2624#endif
2625
2626#ifdef MCH_WRITE_DUMP
2627 if (fdDump)
2628 {
2629 time_t t;
2630
2631 time(&t);
2632 fputs(ctime(&t), fdDump);
2633 fclose(fdDump);
2634 }
2635 fdDump = NULL;
2636#endif
2637 }
2638
2639 SetConsoleCursorInfo(g_hConOut, &g_cci);
2640 SetConsoleMode(g_hConIn, g_cmodein);
2641 SetConsoleMode(g_hConOut, g_cmodeout);
2642
2643#ifdef DYNAMIC_GETTEXT
2644 dyn_libintl_end();
2645#endif
2646
2647 exit(r);
2648}
2649#endif /* !FEAT_GUI_W32 */
2650
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651/*
2652 * Do we have an interactive window?
2653 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002654/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002655 int
2656mch_check_win(
2657 int argc,
2658 char **argv)
2659{
2660 get_exe_name();
2661
2662#ifdef FEAT_GUI_W32
2663 return OK; /* GUI always has a tty */
2664#else
2665 if (isatty(1))
2666 return OK;
2667 return FAIL;
2668#endif
2669}
2670
2671
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002672#ifdef FEAT_MBYTE
2673/*
2674 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2675 * if it already exists. When "len" is > 0, also expand short to long
2676 * filenames.
2677 * Return FAIL if wide functions are not available, OK otherwise.
2678 * NOTE: much of this is identical to fname_case(), keep in sync!
2679 */
2680 static int
2681fname_casew(
2682 WCHAR *name,
2683 int len)
2684{
2685 WCHAR szTrueName[_MAX_PATH + 2];
2686 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2687 WCHAR *ptrue, *ptruePrev;
2688 WCHAR *porig, *porigPrev;
2689 int flen;
2690 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002691 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002692 int c;
2693 int slen;
2694
2695 flen = (int)wcslen(name);
2696 if (flen > _MAX_PATH)
2697 return OK;
2698
2699 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2700
2701 /* Build the new name in szTrueName[] one component at a time. */
2702 porig = name;
2703 ptrue = szTrueName;
2704
2705 if (iswalpha(porig[0]) && porig[1] == L':')
2706 {
2707 /* copy leading drive letter */
2708 *ptrue++ = *porig++;
2709 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002710 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002711 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002712
2713 while (*porig != NUL)
2714 {
2715 /* copy \ characters */
2716 while (*porig == psepc)
2717 *ptrue++ = *porig++;
2718
2719 ptruePrev = ptrue;
2720 porigPrev = porig;
2721 while (*porig != NUL && *porig != psepc)
2722 {
2723 *ptrue++ = *porig++;
2724 }
2725 *ptrue = NUL;
2726
2727 /* To avoid a slow failure append "\*" when searching a directory,
2728 * server or network share. */
2729 wcscpy(szTrueNameTemp, szTrueName);
2730 slen = (int)wcslen(szTrueNameTemp);
2731 if (*porig == psepc && slen + 2 < _MAX_PATH)
2732 wcscpy(szTrueNameTemp + slen, L"\\*");
2733
2734 /* Skip "", "." and "..". */
2735 if (ptrue > ptruePrev
2736 && (ptruePrev[0] != L'.'
2737 || (ptruePrev[1] != NUL
2738 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2739 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2740 != INVALID_HANDLE_VALUE)
2741 {
2742 c = *porig;
2743 *porig = NUL;
2744
2745 /* Only use the match when it's the same name (ignoring case) or
2746 * expansion is allowed and there is a match with the short name
2747 * and there is enough room. */
2748 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2749 || (len > 0
2750 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2751 && (int)(ptruePrev - szTrueName)
2752 + (int)wcslen(fb.cFileName) < len)))
2753 {
2754 wcscpy(ptruePrev, fb.cFileName);
2755
2756 /* Look for exact match and prefer it if found. Must be a
2757 * long name, otherwise there would be only one match. */
2758 while (FindNextFileW(hFind, &fb))
2759 {
2760 if (*fb.cAlternateFileName != NUL
2761 && (wcscoll(porigPrev, fb.cFileName) == 0
2762 || (len > 0
2763 && (_wcsicoll(porigPrev,
2764 fb.cAlternateFileName) == 0
2765 && (int)(ptruePrev - szTrueName)
2766 + (int)wcslen(fb.cFileName) < len))))
2767 {
2768 wcscpy(ptruePrev, fb.cFileName);
2769 break;
2770 }
2771 }
2772 }
2773 FindClose(hFind);
2774 *porig = c;
2775 ptrue = ptruePrev + wcslen(ptruePrev);
2776 }
2777 else if (hFind == INVALID_HANDLE_VALUE
2778 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2779 return FAIL;
2780 }
2781
2782 wcscpy(name, szTrueName);
2783 return OK;
2784}
2785#endif
2786
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787/*
2788 * fname_case(): Set the case of the file name, if it already exists.
2789 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002790 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791 */
2792 void
2793fname_case(
2794 char_u *name,
2795 int len)
2796{
2797 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002798 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002799 char *ptrue, *ptruePrev;
2800 char *porig, *porigPrev;
2801 int flen;
2802 WIN32_FIND_DATA fb;
2803 HANDLE hFind;
2804 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002805 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002806
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002807 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002808 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002809 return;
2810
2811 slash_adjust(name);
2812
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002813#ifdef FEAT_MBYTE
2814 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2815 {
2816 WCHAR *p = enc_to_utf16(name, NULL);
2817
2818 if (p != NULL)
2819 {
2820 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002821 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002822
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002823 wcsncpy(buf, p, _MAX_PATH);
2824 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002825 vim_free(p);
2826
2827 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2828 {
2829 q = utf16_to_enc(buf, NULL);
2830 if (q != NULL)
2831 {
2832 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2833 vim_free(q);
2834 return;
2835 }
2836 }
2837 }
2838 /* Retry with non-wide function (for Windows 98). */
2839 }
2840#endif
2841
2842 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2843 * So we should check this after calling wide function. */
2844 if (flen > _MAX_PATH)
2845 return;
2846
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002848 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849 ptrue = szTrueName;
2850
2851 if (isalpha(porig[0]) && porig[1] == ':')
2852 {
2853 /* copy leading drive letter */
2854 *ptrue++ = *porig++;
2855 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002857 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858
2859 while (*porig != NUL)
2860 {
2861 /* copy \ characters */
2862 while (*porig == psepc)
2863 *ptrue++ = *porig++;
2864
2865 ptruePrev = ptrue;
2866 porigPrev = porig;
2867 while (*porig != NUL && *porig != psepc)
2868 {
2869#ifdef FEAT_MBYTE
2870 int l;
2871
2872 if (enc_dbcs)
2873 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002874 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002875 while (--l >= 0)
2876 *ptrue++ = *porig++;
2877 }
2878 else
2879#endif
2880 *ptrue++ = *porig++;
2881 }
2882 *ptrue = NUL;
2883
Bram Moolenaar464c9252010-10-13 20:37:41 +02002884 /* To avoid a slow failure append "\*" when searching a directory,
2885 * server or network share. */
2886 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002887 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002888 if (*porig == psepc && slen + 2 < _MAX_PATH)
2889 STRCPY(szTrueNameTemp + slen, "\\*");
2890
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891 /* Skip "", "." and "..". */
2892 if (ptrue > ptruePrev
2893 && (ptruePrev[0] != '.'
2894 || (ptruePrev[1] != NUL
2895 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002896 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 != INVALID_HANDLE_VALUE)
2898 {
2899 c = *porig;
2900 *porig = NUL;
2901
2902 /* Only use the match when it's the same name (ignoring case) or
2903 * expansion is allowed and there is a match with the short name
2904 * and there is enough room. */
2905 if (_stricoll(porigPrev, fb.cFileName) == 0
2906 || (len > 0
2907 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2908 && (int)(ptruePrev - szTrueName)
2909 + (int)strlen(fb.cFileName) < len)))
2910 {
2911 STRCPY(ptruePrev, fb.cFileName);
2912
2913 /* Look for exact match and prefer it if found. Must be a
2914 * long name, otherwise there would be only one match. */
2915 while (FindNextFile(hFind, &fb))
2916 {
2917 if (*fb.cAlternateFileName != NUL
2918 && (strcoll(porigPrev, fb.cFileName) == 0
2919 || (len > 0
2920 && (_stricoll(porigPrev,
2921 fb.cAlternateFileName) == 0
2922 && (int)(ptruePrev - szTrueName)
2923 + (int)strlen(fb.cFileName) < len))))
2924 {
2925 STRCPY(ptruePrev, fb.cFileName);
2926 break;
2927 }
2928 }
2929 }
2930 FindClose(hFind);
2931 *porig = c;
2932 ptrue = ptruePrev + strlen(ptruePrev);
2933 }
2934 }
2935
2936 STRCPY(name, szTrueName);
2937}
2938
2939
2940/*
2941 * Insert user name in s[len].
2942 */
2943 int
2944mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002945 char_u *s,
2946 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002948 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949 DWORD cch = sizeof szUserName;
2950
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002951#ifdef FEAT_MBYTE
2952 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2953 {
2954 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2955 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2956
2957 if (GetUserNameW(wszUserName, &wcch))
2958 {
2959 char_u *p = utf16_to_enc(wszUserName, NULL);
2960
2961 if (p != NULL)
2962 {
2963 vim_strncpy(s, p, len - 1);
2964 vim_free(p);
2965 return OK;
2966 }
2967 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002968 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2969 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002970 /* Retry with non-wide function (for Windows 98). */
2971 }
2972#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973 if (GetUserName(szUserName, &cch))
2974 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002975 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002976 return OK;
2977 }
2978 s[0] = NUL;
2979 return FAIL;
2980}
2981
2982
2983/*
2984 * Insert host name in s[len].
2985 */
2986 void
2987mch_get_host_name(
2988 char_u *s,
2989 int len)
2990{
2991 DWORD cch = len;
2992
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002993#ifdef FEAT_MBYTE
2994 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2995 {
2996 WCHAR wszHostName[256 + 1];
2997 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2998
2999 if (GetComputerNameW(wszHostName, &wcch))
3000 {
3001 char_u *p = utf16_to_enc(wszHostName, NULL);
3002
3003 if (p != NULL)
3004 {
3005 vim_strncpy(s, p, len - 1);
3006 vim_free(p);
3007 return;
3008 }
3009 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003010 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3011 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003012 /* Retry with non-wide function (for Windows 98). */
3013 }
3014#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003015 if (!GetComputerName((LPSTR)s, &cch))
3016 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017}
3018
3019
3020/*
3021 * return process ID
3022 */
3023 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003024mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025{
3026 return (long)GetCurrentProcessId();
3027}
3028
3029
3030/*
3031 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3032 * Return OK for success, FAIL for failure.
3033 */
3034 int
3035mch_dirname(
3036 char_u *buf,
3037 int len)
3038{
3039 /*
3040 * Originally this was:
3041 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3042 * But the Win32s known bug list says that getcwd() doesn't work
3043 * so use the Win32 system call instead. <Negri>
3044 */
3045#ifdef FEAT_MBYTE
3046 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3047 {
3048 WCHAR wbuf[_MAX_PATH + 1];
3049
3050 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3051 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003052 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053
3054 if (p != NULL)
3055 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003056 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 vim_free(p);
3058 return OK;
3059 }
3060 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003061 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3062 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063 /* Retry with non-wide function (for Windows 98). */
3064 }
3065#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003066 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067}
3068
3069/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003070 * Get file permissions for "name".
3071 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 */
3073 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003074mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003076 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003077 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003079 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003080 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081}
3082
3083
3084/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003085 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003086 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003087 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088 */
3089 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003090mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003092 long n = -1;
3093
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094#ifdef FEAT_MBYTE
3095 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3096 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003097 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098
3099 if (p != NULL)
3100 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003101 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003103 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003104 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105 /* Retry with non-wide function (for Windows 98). */
3106 }
3107 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003108 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003109#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003110 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003111 if (n == -1)
3112 return FAIL;
3113
3114 win32_set_archive(name);
3115
3116 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117}
3118
3119/*
3120 * Set hidden flag for "name".
3121 */
3122 void
3123mch_hide(char_u *name)
3124{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003125 int attrs = win32_getattrs(name);
3126 if (attrs == -1)
3127 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003129 attrs |= FILE_ATTRIBUTE_HIDDEN;
3130 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131}
3132
3133/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003134 * Return TRUE if file "name" exists and is hidden.
3135 */
3136 int
3137mch_ishidden(char_u *name)
3138{
3139 int f = win32_getattrs(name);
3140
3141 if (f == -1)
3142 return FALSE; /* file does not exist at all */
3143
3144 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3145}
3146
3147/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003148 * return TRUE if "name" is a directory
3149 * return FALSE if "name" is not a directory or upon error
3150 */
3151 int
3152mch_isdir(char_u *name)
3153{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003154 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155
3156 if (f == -1)
3157 return FALSE; /* file does not exist at all */
3158
3159 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3160}
3161
3162/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003163 * return TRUE if "name" is a directory, NOT a symlink to a directory
3164 * return FALSE if "name" is not a directory
3165 * return FALSE for error
3166 */
3167 int
3168mch_isrealdir(char_u *name)
3169{
3170 return mch_isdir(name) && !mch_is_symbolic_link(name);
3171}
3172
3173/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003174 * Create directory "name".
3175 * Return 0 on success, -1 on error.
3176 */
3177 int
3178mch_mkdir(char_u *name)
3179{
3180#ifdef FEAT_MBYTE
3181 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3182 {
3183 WCHAR *p;
3184 int retval;
3185
3186 p = enc_to_utf16(name, NULL);
3187 if (p == NULL)
3188 return -1;
3189 retval = _wmkdir(p);
3190 vim_free(p);
3191 return retval;
3192 }
3193#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003194 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003195}
3196
3197/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003198 * Delete directory "name".
3199 * Return 0 on success, -1 on error.
3200 */
3201 int
3202mch_rmdir(char_u *name)
3203{
3204#ifdef FEAT_MBYTE
3205 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3206 {
3207 WCHAR *p;
3208 int retval;
3209
3210 p = enc_to_utf16(name, NULL);
3211 if (p == NULL)
3212 return -1;
3213 retval = _wrmdir(p);
3214 vim_free(p);
3215 return retval;
3216 }
3217#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003218 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003219}
3220
3221/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003222 * Return TRUE if file "fname" has more than one link.
3223 */
3224 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003225mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003226{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003227 BY_HANDLE_FILE_INFORMATION info;
3228
3229 return win32_fileinfo(fname, &info) == FILEINFO_OK
3230 && info.nNumberOfLinks > 1;
3231}
3232
3233/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003234 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003235 */
3236 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003237mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003238{
3239 HANDLE hFind;
3240 int res = FALSE;
3241 WIN32_FIND_DATAA findDataA;
3242 DWORD fileFlags = 0, reparseTag = 0;
3243#ifdef FEAT_MBYTE
3244 WCHAR *wn = NULL;
3245 WIN32_FIND_DATAW findDataW;
3246
3247 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003248 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003249 if (wn != NULL)
3250 {
3251 hFind = FindFirstFileW(wn, &findDataW);
3252 vim_free(wn);
3253 if (hFind == INVALID_HANDLE_VALUE
3254 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3255 {
3256 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003257 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003258 if (hFind != INVALID_HANDLE_VALUE)
3259 {
3260 fileFlags = findDataA.dwFileAttributes;
3261 reparseTag = findDataA.dwReserved0;
3262 }
3263 }
3264 else
3265 {
3266 fileFlags = findDataW.dwFileAttributes;
3267 reparseTag = findDataW.dwReserved0;
3268 }
3269 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003270 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003271#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003272 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003273 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003274 if (hFind != INVALID_HANDLE_VALUE)
3275 {
3276 fileFlags = findDataA.dwFileAttributes;
3277 reparseTag = findDataA.dwReserved0;
3278 }
3279 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003280
3281 if (hFind != INVALID_HANDLE_VALUE)
3282 FindClose(hFind);
3283
3284 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003285 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3286 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003287 res = TRUE;
3288
3289 return res;
3290}
3291
3292/*
3293 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3294 * link.
3295 */
3296 int
3297mch_is_linked(char_u *fname)
3298{
3299 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3300 return TRUE;
3301 return FALSE;
3302}
3303
3304/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003305 * Get the by-handle-file-information for "fname".
3306 * Returns FILEINFO_OK when OK.
3307 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3308 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3309 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3310 */
3311 int
3312win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3313{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003314 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003315 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003316#ifdef FEAT_MBYTE
3317 WCHAR *wn = NULL;
3318
3319 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003320 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003321 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003322 if (wn == NULL)
3323 res = FILEINFO_ENC_FAIL;
3324 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003325 if (wn != NULL)
3326 {
3327 hFile = CreateFileW(wn, /* file name */
3328 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003329 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003330 NULL, /* security descriptor */
3331 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003332 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003333 NULL); /* handle to template file */
3334 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003335 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003336 {
3337 /* Retry with non-wide function (for Windows 98). */
3338 vim_free(wn);
3339 wn = NULL;
3340 }
3341 }
3342 if (wn == NULL)
3343#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003344 hFile = CreateFile((LPCSTR)fname, /* file name */
3345 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003346 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003347 NULL, /* security descriptor */
3348 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003349 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003350 NULL); /* handle to template file */
3351
3352 if (hFile != INVALID_HANDLE_VALUE)
3353 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003354 if (GetFileInformationByHandle(hFile, info) != 0)
3355 res = FILEINFO_OK;
3356 else
3357 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003358 CloseHandle(hFile);
3359 }
3360
3361#ifdef FEAT_MBYTE
3362 vim_free(wn);
3363#endif
3364 return res;
3365}
3366
3367/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003368 * get file attributes for `name'
3369 * -1 : error
3370 * else FILE_ATTRIBUTE_* defined in winnt.h
3371 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003372 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003373win32_getattrs(char_u *name)
3374{
3375 int attr;
3376#ifdef FEAT_MBYTE
3377 WCHAR *p = NULL;
3378
3379 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3380 p = enc_to_utf16(name, NULL);
3381
3382 if (p != NULL)
3383 {
3384 attr = GetFileAttributesW(p);
3385 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3386 {
3387 /* Retry with non-wide function (for Windows 98). */
3388 vim_free(p);
3389 p = NULL;
3390 }
3391 }
3392 if (p == NULL)
3393#endif
3394 attr = GetFileAttributes((char *)name);
3395#ifdef FEAT_MBYTE
3396 vim_free(p);
3397#endif
3398 return attr;
3399}
3400
3401/*
3402 * set file attributes for `name' to `attrs'
3403 *
3404 * return -1 for failure, 0 otherwise
3405 */
3406 static
3407 int
3408win32_setattrs(char_u *name, int attrs)
3409{
3410 int res;
3411#ifdef FEAT_MBYTE
3412 WCHAR *p = NULL;
3413
3414 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3415 p = enc_to_utf16(name, NULL);
3416
3417 if (p != NULL)
3418 {
3419 res = SetFileAttributesW(p, attrs);
3420 if (res == FALSE
3421 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3422 {
3423 /* Retry with non-wide function (for Windows 98). */
3424 vim_free(p);
3425 p = NULL;
3426 }
3427 }
3428 if (p == NULL)
3429#endif
3430 res = SetFileAttributes((char *)name, attrs);
3431#ifdef FEAT_MBYTE
3432 vim_free(p);
3433#endif
3434 return res ? 0 : -1;
3435}
3436
3437/*
3438 * Set archive flag for "name".
3439 */
3440 static
3441 int
3442win32_set_archive(char_u *name)
3443{
3444 int attrs = win32_getattrs(name);
3445 if (attrs == -1)
3446 return -1;
3447
3448 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3449 return win32_setattrs(name, attrs);
3450}
3451
3452/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003453 * Return TRUE if file or directory "name" is writable (not readonly).
3454 * Strange semantics of Win32: a readonly directory is writable, but you can't
3455 * delete a file. Let's say this means it is writable.
3456 */
3457 int
3458mch_writable(char_u *name)
3459{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003460 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003462 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3463 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003464}
3465
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466/*
3467 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003468 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469 * Return -1 if unknown.
3470 */
3471 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003472mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003473{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003474 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003475 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003476 char_u *p;
3477
3478 if (len >= _MAX_PATH) /* safety check */
3479 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003480 if (!use_path)
3481 {
3482 /* TODO: check if file is really executable. */
3483 return mch_getperm(name) != -1 && !mch_isdir(name);
3484 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003485
3486 /* If there already is an extension try using the name directly. Also do
3487 * this with a Unix-shell like 'shell'. */
3488 if (vim_strchr(gettail(name), '.') != NULL
3489 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003490 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003491 return TRUE;
3492
3493 /*
3494 * Loop over all extensions in $PATHEXT.
3495 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003496 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003497 p = mch_getenv("PATHEXT");
3498 if (p == NULL)
3499 p = (char_u *)".com;.exe;.bat;.cmd";
3500 while (*p)
3501 {
3502 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3503 {
3504 /* A single "." means no extension is added. */
3505 buf[len] = NUL;
3506 ++p;
3507 if (*p)
3508 ++p;
3509 }
3510 else
3511 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003512 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003513 return TRUE;
3514 }
3515 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517
3518/*
3519 * Check what "name" is:
3520 * NODE_NORMAL: file or directory (or doesn't exist)
3521 * NODE_WRITABLE: writable device, socket, fifo, etc.
3522 * NODE_OTHER: non-writable things
3523 */
3524 int
3525mch_nodetype(char_u *name)
3526{
3527 HANDLE hFile;
3528 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003529#ifdef FEAT_MBYTE
3530 WCHAR *wn = NULL;
3531#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532
Bram Moolenaar043545e2006-10-10 16:44:07 +00003533 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3534 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3535 * here. */
3536 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3537 return NODE_WRITABLE;
3538
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003539#ifdef FEAT_MBYTE
3540 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3541 {
3542 wn = enc_to_utf16(name, NULL);
3543 if (wn != NULL)
3544 {
3545 hFile = CreateFileW(wn, /* file name */
3546 GENERIC_WRITE, /* access mode */
3547 0, /* share mode */
3548 NULL, /* security descriptor */
3549 OPEN_EXISTING, /* creation disposition */
3550 0, /* file attributes */
3551 NULL); /* handle to template file */
3552 if (hFile == INVALID_HANDLE_VALUE
3553 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3554 {
3555 /* Retry with non-wide function (for Windows 98). */
3556 vim_free(wn);
3557 wn = NULL;
3558 }
3559 }
3560 }
3561 if (wn == NULL)
3562#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003563 hFile = CreateFile((LPCSTR)name, /* file name */
3564 GENERIC_WRITE, /* access mode */
3565 0, /* share mode */
3566 NULL, /* security descriptor */
3567 OPEN_EXISTING, /* creation disposition */
3568 0, /* file attributes */
3569 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003570
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003571#ifdef FEAT_MBYTE
3572 vim_free(wn);
3573#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003574 if (hFile == INVALID_HANDLE_VALUE)
3575 return NODE_NORMAL;
3576
3577 type = GetFileType(hFile);
3578 CloseHandle(hFile);
3579 if (type == FILE_TYPE_CHAR)
3580 return NODE_WRITABLE;
3581 if (type == FILE_TYPE_DISK)
3582 return NODE_NORMAL;
3583 return NODE_OTHER;
3584}
3585
3586#ifdef HAVE_ACL
3587struct my_acl
3588{
3589 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3590 PSID pSidOwner;
3591 PSID pSidGroup;
3592 PACL pDacl;
3593 PACL pSacl;
3594};
3595#endif
3596
3597/*
3598 * Return a pointer to the ACL of file "fname" in allocated memory.
3599 * Return NULL if the ACL is not available for whatever reason.
3600 */
3601 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003602mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003603{
3604#ifndef HAVE_ACL
3605 return (vim_acl_T)NULL;
3606#else
3607 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003608 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609
3610 /* This only works on Windows NT and 2000. */
3611 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3612 {
3613 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3614 if (p != NULL)
3615 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003616# ifdef FEAT_MBYTE
3617 WCHAR *wn = NULL;
3618
3619 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3620 wn = enc_to_utf16(fname, NULL);
3621 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003622 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003623 /* Try to retrieve the entire security descriptor. */
3624 err = pGetNamedSecurityInfoW(
3625 wn, // Abstract filename
3626 SE_FILE_OBJECT, // File Object
3627 OWNER_SECURITY_INFORMATION |
3628 GROUP_SECURITY_INFORMATION |
3629 DACL_SECURITY_INFORMATION |
3630 SACL_SECURITY_INFORMATION,
3631 &p->pSidOwner, // Ownership information.
3632 &p->pSidGroup, // Group membership.
3633 &p->pDacl, // Discretionary information.
3634 &p->pSacl, // For auditing purposes.
3635 &p->pSecurityDescriptor);
3636 if (err == ERROR_ACCESS_DENIED ||
3637 err == ERROR_PRIVILEGE_NOT_HELD)
3638 {
3639 /* Retrieve only DACL. */
3640 (void)pGetNamedSecurityInfoW(
3641 wn,
3642 SE_FILE_OBJECT,
3643 DACL_SECURITY_INFORMATION,
3644 NULL,
3645 NULL,
3646 &p->pDacl,
3647 NULL,
3648 &p->pSecurityDescriptor);
3649 }
3650 if (p->pSecurityDescriptor == NULL)
3651 {
3652 mch_free_acl((vim_acl_T)p);
3653 p = NULL;
3654 }
3655 vim_free(wn);
3656 }
3657 else
3658# endif
3659 {
3660 /* Try to retrieve the entire security descriptor. */
3661 err = pGetNamedSecurityInfo(
3662 (LPSTR)fname, // Abstract filename
3663 SE_FILE_OBJECT, // File Object
3664 OWNER_SECURITY_INFORMATION |
3665 GROUP_SECURITY_INFORMATION |
3666 DACL_SECURITY_INFORMATION |
3667 SACL_SECURITY_INFORMATION,
3668 &p->pSidOwner, // Ownership information.
3669 &p->pSidGroup, // Group membership.
3670 &p->pDacl, // Discretionary information.
3671 &p->pSacl, // For auditing purposes.
3672 &p->pSecurityDescriptor);
3673 if (err == ERROR_ACCESS_DENIED ||
3674 err == ERROR_PRIVILEGE_NOT_HELD)
3675 {
3676 /* Retrieve only DACL. */
3677 (void)pGetNamedSecurityInfo(
3678 (LPSTR)fname,
3679 SE_FILE_OBJECT,
3680 DACL_SECURITY_INFORMATION,
3681 NULL,
3682 NULL,
3683 &p->pDacl,
3684 NULL,
3685 &p->pSecurityDescriptor);
3686 }
3687 if (p->pSecurityDescriptor == NULL)
3688 {
3689 mch_free_acl((vim_acl_T)p);
3690 p = NULL;
3691 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692 }
3693 }
3694 }
3695
3696 return (vim_acl_T)p;
3697#endif
3698}
3699
Bram Moolenaar27515922013-06-29 15:36:26 +02003700#ifdef HAVE_ACL
3701/*
3702 * Check if "acl" contains inherited ACE.
3703 */
3704 static BOOL
3705is_acl_inherited(PACL acl)
3706{
3707 DWORD i;
3708 ACL_SIZE_INFORMATION acl_info;
3709 PACCESS_ALLOWED_ACE ace;
3710
3711 acl_info.AceCount = 0;
3712 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3713 for (i = 0; i < acl_info.AceCount; i++)
3714 {
3715 GetAce(acl, i, (LPVOID *)&ace);
3716 if (ace->Header.AceFlags & INHERITED_ACE)
3717 return TRUE;
3718 }
3719 return FALSE;
3720}
3721#endif
3722
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723/*
3724 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3725 * Errors are ignored.
3726 * This must only be called with "acl" equal to what mch_get_acl() returned.
3727 */
3728 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003729mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730{
3731#ifdef HAVE_ACL
3732 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003733 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003734
3735 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003736 {
3737# ifdef FEAT_MBYTE
3738 WCHAR *wn = NULL;
3739# endif
3740
3741 /* Set security flags */
3742 if (p->pSidOwner)
3743 sec_info |= OWNER_SECURITY_INFORMATION;
3744 if (p->pSidGroup)
3745 sec_info |= GROUP_SECURITY_INFORMATION;
3746 if (p->pDacl)
3747 {
3748 sec_info |= DACL_SECURITY_INFORMATION;
3749 /* Do not inherit its parent's DACL.
3750 * If the DACL is inherited, Cygwin permissions would be changed.
3751 */
3752 if (!is_acl_inherited(p->pDacl))
3753 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3754 }
3755 if (p->pSacl)
3756 sec_info |= SACL_SECURITY_INFORMATION;
3757
3758# ifdef FEAT_MBYTE
3759 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3760 wn = enc_to_utf16(fname, NULL);
3761 if (wn != NULL)
3762 {
3763 (void)pSetNamedSecurityInfoW(
3764 wn, // Abstract filename
3765 SE_FILE_OBJECT, // File Object
3766 sec_info,
3767 p->pSidOwner, // Ownership information.
3768 p->pSidGroup, // Group membership.
3769 p->pDacl, // Discretionary information.
3770 p->pSacl // For auditing purposes.
3771 );
3772 vim_free(wn);
3773 }
3774 else
3775# endif
3776 {
3777 (void)pSetNamedSecurityInfo(
3778 (LPSTR)fname, // Abstract filename
3779 SE_FILE_OBJECT, // File Object
3780 sec_info,
3781 p->pSidOwner, // Ownership information.
3782 p->pSidGroup, // Group membership.
3783 p->pDacl, // Discretionary information.
3784 p->pSacl // For auditing purposes.
3785 );
3786 }
3787 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788#endif
3789}
3790
3791 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003792mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793{
3794#ifdef HAVE_ACL
3795 struct my_acl *p = (struct my_acl *)acl;
3796
3797 if (p != NULL)
3798 {
3799 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3800 vim_free(p);
3801 }
3802#endif
3803}
3804
3805#ifndef FEAT_GUI_W32
3806
3807/*
3808 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3809 */
3810 static BOOL WINAPI
3811handler_routine(
3812 DWORD dwCtrlType)
3813{
3814 switch (dwCtrlType)
3815 {
3816 case CTRL_C_EVENT:
3817 if (ctrl_c_interrupts)
3818 g_fCtrlCPressed = TRUE;
3819 return TRUE;
3820
3821 case CTRL_BREAK_EVENT:
3822 g_fCBrkPressed = TRUE;
3823 return TRUE;
3824
3825 /* fatal events: shut down gracefully */
3826 case CTRL_CLOSE_EVENT:
3827 case CTRL_LOGOFF_EVENT:
3828 case CTRL_SHUTDOWN_EVENT:
3829 windgoto((int)Rows - 1, 0);
3830 g_fForceExit = TRUE;
3831
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003832 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003833 (dwCtrlType == CTRL_CLOSE_EVENT
3834 ? _("close")
3835 : dwCtrlType == CTRL_LOGOFF_EVENT
3836 ? _("logoff")
3837 : _("shutdown")));
3838#ifdef DEBUG
3839 OutputDebugString(IObuff);
3840#endif
3841
3842 preserve_exit(); /* output IObuff, preserve files and exit */
3843
3844 return TRUE; /* not reached */
3845
3846 default:
3847 return FALSE;
3848 }
3849}
3850
3851
3852/*
3853 * set the tty in (raw) ? "raw" : "cooked" mode
3854 */
3855 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003856mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857{
3858 DWORD cmodein;
3859 DWORD cmodeout;
3860 BOOL bEnableHandler;
3861
3862 GetConsoleMode(g_hConIn, &cmodein);
3863 GetConsoleMode(g_hConOut, &cmodeout);
3864 if (tmode == TMODE_RAW)
3865 {
3866 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3867 ENABLE_ECHO_INPUT);
3868#ifdef FEAT_MOUSE
3869 if (g_fMouseActive)
3870 cmodein |= ENABLE_MOUSE_INPUT;
3871#endif
3872 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3873 bEnableHandler = TRUE;
3874 }
3875 else /* cooked */
3876 {
3877 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3878 ENABLE_ECHO_INPUT);
3879 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3880 bEnableHandler = FALSE;
3881 }
3882 SetConsoleMode(g_hConIn, cmodein);
3883 SetConsoleMode(g_hConOut, cmodeout);
3884 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3885
3886#ifdef MCH_WRITE_DUMP
3887 if (fdDump)
3888 {
3889 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3890 tmode == TMODE_RAW ? "raw" :
3891 tmode == TMODE_COOK ? "cooked" : "normal",
3892 cmodein, cmodeout);
3893 fflush(fdDump);
3894 }
3895#endif
3896}
3897
3898
3899/*
3900 * Get the size of the current window in `Rows' and `Columns'
3901 * Return OK when size could be determined, FAIL otherwise.
3902 */
3903 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003904mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905{
3906 CONSOLE_SCREEN_BUFFER_INFO csbi;
3907
3908 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3909 {
3910 /*
3911 * For some reason, we are trying to get the screen dimensions
3912 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3913 * variables are really intended to mean the size of Vim screen
3914 * while in termcap mode.
3915 */
3916 Rows = g_cbTermcap.Info.dwSize.Y;
3917 Columns = g_cbTermcap.Info.dwSize.X;
3918 }
3919 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3920 {
3921 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3922 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3923 }
3924 else
3925 {
3926 Rows = 25;
3927 Columns = 80;
3928 }
3929 return OK;
3930}
3931
3932/*
3933 * Set a console window to `xSize' * `ySize'
3934 */
3935 static void
3936ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003937 HANDLE hConsole,
3938 int xSize,
3939 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003940{
3941 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3942 SMALL_RECT srWindowRect; /* hold the new console size */
3943 COORD coordScreen;
3944
3945#ifdef MCH_WRITE_DUMP
3946 if (fdDump)
3947 {
3948 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3949 fflush(fdDump);
3950 }
3951#endif
3952
3953 /* get the largest size we can size the console window to */
3954 coordScreen = GetLargestConsoleWindowSize(hConsole);
3955
3956 /* define the new console window size and scroll position */
3957 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3958 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3959 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3960
3961 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3962 {
3963 int sx, sy;
3964
3965 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3966 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3967 if (sy < ySize || sx < xSize)
3968 {
3969 /*
3970 * Increasing number of lines/columns, do buffer first.
3971 * Use the maximal size in x and y direction.
3972 */
3973 if (sy < ySize)
3974 coordScreen.Y = ySize;
3975 else
3976 coordScreen.Y = sy;
3977 if (sx < xSize)
3978 coordScreen.X = xSize;
3979 else
3980 coordScreen.X = sx;
3981 SetConsoleScreenBufferSize(hConsole, coordScreen);
3982 }
3983 }
3984
3985 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3986 {
3987#ifdef MCH_WRITE_DUMP
3988 if (fdDump)
3989 {
3990 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3991 GetLastError());
3992 fflush(fdDump);
3993 }
3994#endif
3995 }
3996
3997 /* define the new console buffer size */
3998 coordScreen.X = xSize;
3999 coordScreen.Y = ySize;
4000
4001 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4002 {
4003#ifdef MCH_WRITE_DUMP
4004 if (fdDump)
4005 {
4006 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4007 GetLastError());
4008 fflush(fdDump);
4009 }
4010#endif
4011 }
4012}
4013
4014
4015/*
4016 * Set the console window to `Rows' * `Columns'
4017 */
4018 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004019mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020{
4021 COORD coordScreen;
4022
4023 /* Don't change window size while still starting up */
4024 if (suppress_winsize != 0)
4025 {
4026 suppress_winsize = 2;
4027 return;
4028 }
4029
4030 if (term_console)
4031 {
4032 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4033
4034 /* Clamp Rows and Columns to reasonable values */
4035 if (Rows > coordScreen.Y)
4036 Rows = coordScreen.Y;
4037 if (Columns > coordScreen.X)
4038 Columns = coordScreen.X;
4039
4040 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4041 }
4042}
4043
4044/*
4045 * Rows and/or Columns has changed.
4046 */
4047 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004048mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049{
4050 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4051}
4052
4053
4054/*
4055 * Called when started up, to set the winsize that was delayed.
4056 */
4057 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004058mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004059{
4060 if (suppress_winsize == 2)
4061 {
4062 suppress_winsize = 0;
4063 mch_set_shellsize();
4064 shell_resized();
4065 }
4066 suppress_winsize = 0;
4067}
4068#endif /* FEAT_GUI_W32 */
4069
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004070 static BOOL
4071vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004072 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004073 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004074 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004075 STARTUPINFO *si,
4076 PROCESS_INFORMATION *pi)
4077{
4078# ifdef FEAT_MBYTE
4079 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4080 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004081 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004082
4083 if (wcmd != NULL)
4084 {
4085 BOOL ret;
4086 ret = CreateProcessW(
4087 NULL, /* Executable name */
4088 wcmd, /* Command to execute */
4089 NULL, /* Process security attributes */
4090 NULL, /* Thread security attributes */
4091 inherit_handles, /* Inherit handles */
4092 flags, /* Creation flags */
4093 NULL, /* Environment */
4094 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004095 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004096 pi); /* Process information */
4097 vim_free(wcmd);
4098 return ret;
4099 }
4100 }
4101#endif
4102 return CreateProcess(
4103 NULL, /* Executable name */
4104 cmd, /* Command to execute */
4105 NULL, /* Process security attributes */
4106 NULL, /* Thread security attributes */
4107 inherit_handles, /* Inherit handles */
4108 flags, /* Creation flags */
4109 NULL, /* Environment */
4110 NULL, /* Current directory */
4111 si, /* Startup information */
4112 pi); /* Process information */
4113}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114
4115
4116#if defined(FEAT_GUI_W32) || defined(PROTO)
4117
4118/*
4119 * Specialised version of system() for Win32 GUI mode.
4120 * This version proceeds as follows:
4121 * 1. Create a console window for use by the subprocess
4122 * 2. Run the subprocess (it gets the allocated console by default)
4123 * 3. Wait for the subprocess to terminate and get its exit code
4124 * 4. Prompt the user to press a key to close the console window
4125 */
4126 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004127mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004128{
4129 STARTUPINFO si;
4130 PROCESS_INFORMATION pi;
4131 DWORD ret = 0;
4132 HWND hwnd = GetFocus();
4133
4134 si.cb = sizeof(si);
4135 si.lpReserved = NULL;
4136 si.lpDesktop = NULL;
4137 si.lpTitle = NULL;
4138 si.dwFlags = STARTF_USESHOWWINDOW;
4139 /*
4140 * It's nicer to run a filter command in a minimized window, but in
4141 * Windows 95 this makes the command MUCH slower. We can't do it under
4142 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004143 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 */
4145 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004146 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147 else
4148 si.wShowWindow = SW_SHOWNORMAL;
4149 si.cbReserved2 = 0;
4150 si.lpReserved2 = NULL;
4151
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004152 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 * When the "c:\\" is left out it works OK...? */
4154 if (mch_windows95()
4155 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4156 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4157 cmd += 3;
4158
4159 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004160 vim_create_process(cmd, FALSE,
4161 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004162
4163 /* Wait for the command to terminate before continuing */
4164 if (g_PlatformId != VER_PLATFORM_WIN32s)
4165 {
4166#ifdef FEAT_GUI
4167 int delay = 1;
4168
4169 /* Keep updating the window while waiting for the shell to finish. */
4170 for (;;)
4171 {
4172 MSG msg;
4173
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004174 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175 {
4176 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004177 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004178 delay = 1;
4179 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004180 }
4181 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4182 break;
4183
4184 /* We start waiting for a very short time and then increase it, so
4185 * that we respond quickly when the process is quick, and don't
4186 * consume too much overhead when it's slow. */
4187 if (delay < 50)
4188 delay += 10;
4189 }
4190#else
4191 WaitForSingleObject(pi.hProcess, INFINITE);
4192#endif
4193
4194 /* Get the command exit code */
4195 GetExitCodeProcess(pi.hProcess, &ret);
4196 }
4197 else
4198 {
4199 /*
4200 * This ugly code is the only quick way of performing
4201 * a synchronous spawn under Win32s. Yuk.
4202 */
4203 num_windows = 0;
4204 EnumWindows(win32ssynch_cb, 0);
4205 old_num_windows = num_windows;
4206 do
4207 {
4208 Sleep(1000);
4209 num_windows = 0;
4210 EnumWindows(win32ssynch_cb, 0);
4211 } while (num_windows == old_num_windows);
4212 ret = 0;
4213 }
4214
4215 /* Close the handles to the subprocess, so that it goes away */
4216 CloseHandle(pi.hThread);
4217 CloseHandle(pi.hProcess);
4218
4219 /* Try to get input focus back. Doesn't always work though. */
4220 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4221
4222 return ret;
4223}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004224
4225/*
4226 * Thread launched by the gui to send the current buffer data to the
4227 * process. This way avoid to hang up vim totally if the children
4228 * process take a long time to process the lines.
4229 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004230 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004231sub_process_writer(LPVOID param)
4232{
4233 HANDLE g_hChildStd_IN_Wr = param;
4234 linenr_T lnum = curbuf->b_op_start.lnum;
4235 DWORD len = 0;
4236 DWORD l;
4237 char_u *lp = ml_get(lnum);
4238 char_u *s;
4239 int written = 0;
4240
4241 for (;;)
4242 {
4243 l = (DWORD)STRLEN(lp + written);
4244 if (l == 0)
4245 len = 0;
4246 else if (lp[written] == NL)
4247 {
4248 /* NL -> NUL translation */
4249 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4250 }
4251 else
4252 {
4253 s = vim_strchr(lp + written, NL);
4254 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4255 s == NULL ? l : (DWORD)(s - (lp + written)),
4256 &len, NULL);
4257 }
4258 if (len == (int)l)
4259 {
4260 /* Finished a line, add a NL, unless this line should not have
4261 * one. */
4262 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004263 || (!curbuf->b_p_bin
4264 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004265 || (lnum != curbuf->b_no_eol_lnum
4266 && (lnum != curbuf->b_ml.ml_line_count
4267 || curbuf->b_p_eol)))
4268 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004269 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004270 }
4271
4272 ++lnum;
4273 if (lnum > curbuf->b_op_end.lnum)
4274 break;
4275
4276 lp = ml_get(lnum);
4277 written = 0;
4278 }
4279 else if (len > 0)
4280 written += len;
4281 }
4282
4283 /* finished all the lines, close pipe */
4284 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004285 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004286}
4287
4288
4289# define BUFLEN 100 /* length for buffer, stolen from unix version */
4290
4291/*
4292 * This function read from the children's stdout and write the
4293 * data on screen or in the buffer accordingly.
4294 */
4295 static void
4296dump_pipe(int options,
4297 HANDLE g_hChildStd_OUT_Rd,
4298 garray_T *ga,
4299 char_u buffer[],
4300 DWORD *buffer_off)
4301{
4302 DWORD availableBytes = 0;
4303 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004304 int ret;
4305 DWORD len;
4306 DWORD toRead;
4307 int repeatCount;
4308
4309 /* we query the pipe to see if there is any data to read
4310 * to avoid to perform a blocking read */
4311 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4312 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004313 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004314 NULL, /* number of read bytes */
4315 &availableBytes, /* available bytes total */
4316 NULL); /* byteLeft */
4317
4318 repeatCount = 0;
4319 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004320 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004321 {
4322 repeatCount++;
4323 toRead =
4324# ifdef FEAT_MBYTE
4325 (DWORD)(BUFLEN - *buffer_off);
4326# else
4327 (DWORD)BUFLEN;
4328# endif
4329 toRead = availableBytes < toRead ? availableBytes : toRead;
4330 ReadFile(g_hChildStd_OUT_Rd, buffer
4331# ifdef FEAT_MBYTE
4332 + *buffer_off, toRead
4333# else
4334 , toRead
4335# endif
4336 , &len, NULL);
4337
4338 /* If we haven't read anything, there is a problem */
4339 if (len == 0)
4340 break;
4341
4342 availableBytes -= len;
4343
4344 if (options & SHELL_READ)
4345 {
4346 /* Do NUL -> NL translation, append NL separated
4347 * lines to the current buffer. */
4348 for (i = 0; i < len; ++i)
4349 {
4350 if (buffer[i] == NL)
4351 append_ga_line(ga);
4352 else if (buffer[i] == NUL)
4353 ga_append(ga, NL);
4354 else
4355 ga_append(ga, buffer[i]);
4356 }
4357 }
4358# ifdef FEAT_MBYTE
4359 else if (has_mbyte)
4360 {
4361 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004362 int c;
4363 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004364
4365 len += *buffer_off;
4366 buffer[len] = NUL;
4367
4368 /* Check if the last character in buffer[] is
4369 * incomplete, keep these bytes for the next
4370 * round. */
4371 for (p = buffer; p < buffer + len; p += l)
4372 {
4373 l = mb_cptr2len(p);
4374 if (l == 0)
4375 l = 1; /* NUL byte? */
4376 else if (MB_BYTE2LEN(*p) != l)
4377 break;
4378 }
4379 if (p == buffer) /* no complete character */
4380 {
4381 /* avoid getting stuck at an illegal byte */
4382 if (len >= 12)
4383 ++p;
4384 else
4385 {
4386 *buffer_off = len;
4387 return;
4388 }
4389 }
4390 c = *p;
4391 *p = NUL;
4392 msg_puts(buffer);
4393 if (p < buffer + len)
4394 {
4395 *p = c;
4396 *buffer_off = (DWORD)((buffer + len) - p);
4397 mch_memmove(buffer, p, *buffer_off);
4398 return;
4399 }
4400 *buffer_off = 0;
4401 }
4402# endif /* FEAT_MBYTE */
4403 else
4404 {
4405 buffer[len] = NUL;
4406 msg_puts(buffer);
4407 }
4408
4409 windgoto(msg_row, msg_col);
4410 cursor_on();
4411 out_flush();
4412 }
4413}
4414
4415/*
4416 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4417 * for communication and doesn't open any new window.
4418 */
4419 static int
4420mch_system_piped(char *cmd, int options)
4421{
4422 STARTUPINFO si;
4423 PROCESS_INFORMATION pi;
4424 DWORD ret = 0;
4425
4426 HANDLE g_hChildStd_IN_Rd = NULL;
4427 HANDLE g_hChildStd_IN_Wr = NULL;
4428 HANDLE g_hChildStd_OUT_Rd = NULL;
4429 HANDLE g_hChildStd_OUT_Wr = NULL;
4430
4431 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4432 DWORD len;
4433
4434 /* buffer used to receive keys */
4435 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4436 int ta_len = 0; /* valid bytes in ta_buf[] */
4437
4438 DWORD i;
4439 int c;
4440 int noread_cnt = 0;
4441 garray_T ga;
4442 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004443 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004444 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004445
4446 SECURITY_ATTRIBUTES saAttr;
4447
4448 /* Set the bInheritHandle flag so pipe handles are inherited. */
4449 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4450 saAttr.bInheritHandle = TRUE;
4451 saAttr.lpSecurityDescriptor = NULL;
4452
4453 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4454 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4455 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4456 /* Create a pipe for the child process's STDIN. */
4457 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4458 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4459 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4460 {
4461 CloseHandle(g_hChildStd_IN_Rd);
4462 CloseHandle(g_hChildStd_IN_Wr);
4463 CloseHandle(g_hChildStd_OUT_Rd);
4464 CloseHandle(g_hChildStd_OUT_Wr);
4465 MSG_PUTS(_("\nCannot create pipes\n"));
4466 }
4467
4468 si.cb = sizeof(si);
4469 si.lpReserved = NULL;
4470 si.lpDesktop = NULL;
4471 si.lpTitle = NULL;
4472 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4473
4474 /* set-up our file redirection */
4475 si.hStdError = g_hChildStd_OUT_Wr;
4476 si.hStdOutput = g_hChildStd_OUT_Wr;
4477 si.hStdInput = g_hChildStd_IN_Rd;
4478 si.wShowWindow = SW_HIDE;
4479 si.cbReserved2 = 0;
4480 si.lpReserved2 = NULL;
4481
4482 if (options & SHELL_READ)
4483 ga_init2(&ga, 1, BUFLEN);
4484
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004485 if (cmd != NULL)
4486 {
4487 p = (char *)vim_strsave((char_u *)cmd);
4488 if (p != NULL)
4489 unescape_shellxquote((char_u *)p, p_sxe);
4490 else
4491 p = cmd;
4492 }
4493
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004494 /* Now, run the command.
4495 * About "Inherit handles" being TRUE: this command can be litigious,
4496 * handle inheritance was deactivated for pending temp file, but, if we
4497 * deactivate it, the pipes don't work for some reason. */
4498 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004499
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004500 if (p != cmd)
4501 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004502
4503 /* Close our unused side of the pipes */
4504 CloseHandle(g_hChildStd_IN_Rd);
4505 CloseHandle(g_hChildStd_OUT_Wr);
4506
4507 if (options & SHELL_WRITE)
4508 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004509 HANDLE thread = (HANDLE)
4510 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004511 0, /* default stack size */
4512 sub_process_writer, /* function to be executed */
4513 g_hChildStd_IN_Wr, /* parameter */
4514 0, /* creation flag, start immediately */
4515 NULL); /* we don't care about thread id */
4516 CloseHandle(thread);
4517 g_hChildStd_IN_Wr = NULL;
4518 }
4519
4520 /* Keep updating the window while waiting for the shell to finish. */
4521 for (;;)
4522 {
4523 MSG msg;
4524
Bram Moolenaar175d0702013-12-11 18:36:33 +01004525 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004526 {
4527 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004528 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004529 }
4530
4531 /* write pipe information in the window */
4532 if ((options & (SHELL_READ|SHELL_WRITE))
4533# ifdef FEAT_GUI
4534 || gui.in_use
4535# endif
4536 )
4537 {
4538 len = 0;
4539 if (!(options & SHELL_EXPAND)
4540 && ((options &
4541 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4542 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4543# ifdef FEAT_GUI
4544 || gui.in_use
4545# endif
4546 )
4547 && (ta_len > 0 || noread_cnt > 4))
4548 {
4549 if (ta_len == 0)
4550 {
4551 /* Get extra characters when we don't have any. Reset the
4552 * counter and timer. */
4553 noread_cnt = 0;
4554# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4555 gettimeofday(&start_tv, NULL);
4556# endif
4557 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4558 }
4559 if (ta_len > 0 || len > 0)
4560 {
4561 /*
4562 * For pipes: Check for CTRL-C: send interrupt signal to
4563 * child. Check for CTRL-D: EOF, close pipe to child.
4564 */
4565 if (len == 1 && cmd != NULL)
4566 {
4567 if (ta_buf[ta_len] == Ctrl_C)
4568 {
4569 /* Learn what exit code is expected, for
4570 * now put 9 as SIGKILL */
4571 TerminateProcess(pi.hProcess, 9);
4572 }
4573 if (ta_buf[ta_len] == Ctrl_D)
4574 {
4575 CloseHandle(g_hChildStd_IN_Wr);
4576 g_hChildStd_IN_Wr = NULL;
4577 }
4578 }
4579
4580 /* replace K_BS by <BS> and K_DEL by <DEL> */
4581 for (i = ta_len; i < ta_len + len; ++i)
4582 {
4583 if (ta_buf[i] == CSI && len - i > 2)
4584 {
4585 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4586 if (c == K_DEL || c == K_KDEL || c == K_BS)
4587 {
4588 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4589 (size_t)(len - i - 2));
4590 if (c == K_DEL || c == K_KDEL)
4591 ta_buf[i] = DEL;
4592 else
4593 ta_buf[i] = Ctrl_H;
4594 len -= 2;
4595 }
4596 }
4597 else if (ta_buf[i] == '\r')
4598 ta_buf[i] = '\n';
4599# ifdef FEAT_MBYTE
4600 if (has_mbyte)
4601 i += (*mb_ptr2len_len)(ta_buf + i,
4602 ta_len + len - i) - 1;
4603# endif
4604 }
4605
4606 /*
4607 * For pipes: echo the typed characters. For a pty this
4608 * does not seem to work.
4609 */
4610 for (i = ta_len; i < ta_len + len; ++i)
4611 {
4612 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4613 msg_putchar(ta_buf[i]);
4614# ifdef FEAT_MBYTE
4615 else if (has_mbyte)
4616 {
4617 int l = (*mb_ptr2len)(ta_buf + i);
4618
4619 msg_outtrans_len(ta_buf + i, l);
4620 i += l - 1;
4621 }
4622# endif
4623 else
4624 msg_outtrans_len(ta_buf + i, 1);
4625 }
4626 windgoto(msg_row, msg_col);
4627 out_flush();
4628
4629 ta_len += len;
4630
4631 /*
4632 * Write the characters to the child, unless EOF has been
4633 * typed for pipes. Write one character at a time, to
4634 * avoid losing too much typeahead. When writing buffer
4635 * lines, drop the typed characters (only check for
4636 * CTRL-C).
4637 */
4638 if (options & SHELL_WRITE)
4639 ta_len = 0;
4640 else if (g_hChildStd_IN_Wr != NULL)
4641 {
4642 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4643 1, &len, NULL);
4644 // if we are typing in, we want to keep things reactive
4645 delay = 1;
4646 if (len > 0)
4647 {
4648 ta_len -= len;
4649 mch_memmove(ta_buf, ta_buf + len, ta_len);
4650 }
4651 }
4652 }
4653 }
4654 }
4655
4656 if (ta_len)
4657 ui_inchar_undo(ta_buf, ta_len);
4658
4659 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4660 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004661 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004662 break;
4663 }
4664
4665 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004666 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004667
4668 /* We start waiting for a very short time and then increase it, so
4669 * that we respond quickly when the process is quick, and don't
4670 * consume too much overhead when it's slow. */
4671 if (delay < 50)
4672 delay += 10;
4673 }
4674
4675 /* Close the pipe */
4676 CloseHandle(g_hChildStd_OUT_Rd);
4677 if (g_hChildStd_IN_Wr != NULL)
4678 CloseHandle(g_hChildStd_IN_Wr);
4679
4680 WaitForSingleObject(pi.hProcess, INFINITE);
4681
4682 /* Get the command exit code */
4683 GetExitCodeProcess(pi.hProcess, &ret);
4684
4685 if (options & SHELL_READ)
4686 {
4687 if (ga.ga_len > 0)
4688 {
4689 append_ga_line(&ga);
4690 /* remember that the NL was missing */
4691 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4692 }
4693 else
4694 curbuf->b_no_eol_lnum = 0;
4695 ga_clear(&ga);
4696 }
4697
4698 /* Close the handles to the subprocess, so that it goes away */
4699 CloseHandle(pi.hThread);
4700 CloseHandle(pi.hProcess);
4701
4702 return ret;
4703}
4704
4705 static int
4706mch_system(char *cmd, int options)
4707{
4708 /* if we can pipe and the shelltemp option is off */
4709 if (allowPiping && !p_stmp)
4710 return mch_system_piped(cmd, options);
4711 else
4712 return mch_system_classic(cmd, options);
4713}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004714#else
4715
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004716# ifdef FEAT_MBYTE
4717 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004718mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004719{
4720 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4721 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004722 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004723 if (wcmd != NULL)
4724 {
4725 int ret = _wsystem(wcmd);
4726 vim_free(wcmd);
4727 return ret;
4728 }
4729 }
4730 return system(cmd);
4731}
4732# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004733# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004734# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735
4736#endif
4737
4738/*
4739 * Either execute a command by calling the shell or start a new shell
4740 */
4741 int
4742mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004743 char_u *cmd,
4744 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745{
4746 int x = 0;
4747 int tmode = cur_tmode;
4748#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004749 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004750# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004751 int did_set_title = FALSE;
4752
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004753 /* Change the title to reflect that we are in a subshell. */
4754 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4755 {
4756 WCHAR szShellTitle[512];
4757
4758 if (GetConsoleTitleW(szShellTitle,
4759 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4760 {
4761 if (cmd == NULL)
4762 wcscat(szShellTitle, L" :sh");
4763 else
4764 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004765 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004766
4767 if (wn != NULL)
4768 {
4769 wcscat(szShellTitle, L" - !");
4770 if ((wcslen(szShellTitle) + wcslen(wn) <
4771 sizeof(szShellTitle)/sizeof(WCHAR)))
4772 wcscat(szShellTitle, wn);
4773 SetConsoleTitleW(szShellTitle);
4774 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004775 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004776 }
4777 }
4778 }
4779 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004780 if (!did_set_title)
4781# endif
4782 /* Change the title to reflect that we are in a subshell. */
4783 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004784 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004785 if (cmd == NULL)
4786 strcat(szShellTitle, " :sh");
4787 else
4788 {
4789 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004790 if ((strlen(szShellTitle) + strlen((char *)cmd)
4791 < sizeof(szShellTitle)))
4792 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004793 }
4794 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004795 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004796#endif
4797
4798 out_flush();
4799
4800#ifdef MCH_WRITE_DUMP
4801 if (fdDump)
4802 {
4803 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4804 fflush(fdDump);
4805 }
4806#endif
4807
4808 /*
4809 * Catch all deadly signals while running the external command, because a
4810 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4811 */
4812 signal(SIGINT, SIG_IGN);
4813#if defined(__GNUC__) && !defined(__MINGW32__)
4814 signal(SIGKILL, SIG_IGN);
4815#else
4816 signal(SIGBREAK, SIG_IGN);
4817#endif
4818 signal(SIGILL, SIG_IGN);
4819 signal(SIGFPE, SIG_IGN);
4820 signal(SIGSEGV, SIG_IGN);
4821 signal(SIGTERM, SIG_IGN);
4822 signal(SIGABRT, SIG_IGN);
4823
4824 if (options & SHELL_COOKED)
4825 settmode(TMODE_COOK); /* set to normal mode */
4826
4827 if (cmd == NULL)
4828 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004829 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830 }
4831 else
4832 {
4833 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004834 char_u *newcmd = NULL;
4835 char_u *cmdbase = cmd;
4836 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004837
4838 /* Skip a leading ", ( and "(. */
4839 if (*cmdbase == '"' )
4840 ++cmdbase;
4841 if (*cmdbase == '(')
4842 ++cmdbase;
4843
4844 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4845 {
4846 STARTUPINFO si;
4847 PROCESS_INFORMATION pi;
4848 DWORD flags = CREATE_NEW_CONSOLE;
4849 char_u *p;
4850
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004851 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004852 si.cb = sizeof(si);
4853 si.lpReserved = NULL;
4854 si.lpDesktop = NULL;
4855 si.lpTitle = NULL;
4856 si.dwFlags = 0;
4857 si.cbReserved2 = 0;
4858 si.lpReserved2 = NULL;
4859
4860 cmdbase = skipwhite(cmdbase + 5);
4861 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4862 && vim_iswhite(cmdbase[4]))
4863 {
4864 cmdbase = skipwhite(cmdbase + 4);
4865 si.dwFlags = STARTF_USESHOWWINDOW;
4866 si.wShowWindow = SW_SHOWMINNOACTIVE;
4867 }
4868 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4869 && vim_iswhite(cmdbase[2]))
4870 {
4871 cmdbase = skipwhite(cmdbase + 2);
4872 flags = CREATE_NO_WINDOW;
4873 si.dwFlags = STARTF_USESTDHANDLES;
4874 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004875 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004876 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877 NULL, // Security att.
4878 OPEN_EXISTING, // Open flags
4879 FILE_ATTRIBUTE_NORMAL, // File att.
4880 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004881 si.hStdOutput = si.hStdInput;
4882 si.hStdError = si.hStdInput;
4883 }
4884
4885 /* Remove a trailing ", ) and )" if they have a match
4886 * at the start of the command. */
4887 if (cmdbase > cmd)
4888 {
4889 p = cmdbase + STRLEN(cmdbase);
4890 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4891 *--p = NUL;
4892 if (p > cmdbase && p[-1] == ')'
4893 && (*cmd =='(' || cmd[1] == '('))
4894 *--p = NUL;
4895 }
4896
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004897 newcmd = cmdbase;
4898 unescape_shellxquote(cmdbase, p_sxe);
4899
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004900 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004901 * If creating new console, arguments are passed to the
4902 * 'cmd.exe' as-is. If it's not, arguments are not treated
4903 * correctly for current 'cmd.exe'. So unescape characters in
4904 * shellxescape except '|' for avoiding to be treated as
4905 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004906 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004907 if (flags != CREATE_NEW_CONSOLE)
4908 {
4909 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004910 char_u *cmd_shell = mch_getenv("COMSPEC");
4911
4912 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004913 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004914
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004915 subcmd = vim_strsave_escaped_ext(cmdbase,
4916 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004917 if (subcmd != NULL)
4918 {
4919 /* make "cmd.exe /c arguments" */
4920 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004921 newcmd = lalloc(cmdlen, TRUE);
4922 if (newcmd != NULL)
4923 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004924 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004925 else
4926 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004927 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004928 }
4929 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004930
4931 /*
4932 * Now, start the command as a process, so that it doesn't
4933 * inherit our handles which causes unpleasant dangling swap
4934 * files if we exit before the spawned process
4935 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004936 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004937 x = 0;
4938 else
4939 {
4940 x = -1;
4941#ifdef FEAT_GUI_W32
4942 EMSG(_("E371: Command not found"));
4943#endif
4944 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004945
4946 if (newcmd != cmdbase)
4947 vim_free(newcmd);
4948
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004949 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004950 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004951 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004952 CloseHandle(si.hStdInput);
4953 }
4954 /* Close the handles to the subprocess, so that it goes away */
4955 CloseHandle(pi.hThread);
4956 CloseHandle(pi.hProcess);
4957 }
4958 else
4959 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004960 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004961#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004962 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004964 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4965
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004966 newcmd = lalloc(cmdlen, TRUE);
4967 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004968 {
4969#if defined(FEAT_GUI_W32)
4970 if (need_vimrun_warning)
4971 {
4972 MessageBox(NULL,
4973 _("VIMRUN.EXE not found in your $PATH.\n"
4974 "External commands will not pause after completion.\n"
4975 "See :help win32-vimrun for more information."),
4976 _("Vim Warning"),
4977 MB_ICONWARNING);
4978 need_vimrun_warning = FALSE;
4979 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004980 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004981 /* Use vimrun to execute the command. It opens a console
4982 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004983 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004984 vimrun_path,
4985 (msg_silent != 0 || (options & SHELL_DOOUT))
4986 ? "-s " : "",
4987 p_sh, p_shcf, cmd);
4988 else
4989#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004990 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004991 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004992 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004993 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004994 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995 }
4996 }
4997
4998 if (tmode == TMODE_RAW)
4999 settmode(TMODE_RAW); /* set to raw mode */
5000
5001 /* Print the return value, unless "vimrun" was used. */
5002 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5003#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005004 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
5005 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006#endif
5007 )
5008 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005009 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005010 msg_putchar('\n');
5011 }
5012#ifdef FEAT_TITLE
5013 resettitle();
5014#endif
5015
5016 signal(SIGINT, SIG_DFL);
5017#if defined(__GNUC__) && !defined(__MINGW32__)
5018 signal(SIGKILL, SIG_DFL);
5019#else
5020 signal(SIGBREAK, SIG_DFL);
5021#endif
5022 signal(SIGILL, SIG_DFL);
5023 signal(SIGFPE, SIG_DFL);
5024 signal(SIGSEGV, SIG_DFL);
5025 signal(SIGTERM, SIG_DFL);
5026 signal(SIGABRT, SIG_DFL);
5027
5028 return x;
5029}
5030
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005031#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005032 static HANDLE
5033job_io_file_open(
5034 char_u *fname,
5035 DWORD dwDesiredAccess,
5036 DWORD dwShareMode,
5037 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5038 DWORD dwCreationDisposition,
5039 DWORD dwFlagsAndAttributes)
5040{
5041 HANDLE h;
5042# ifdef FEAT_MBYTE
5043 WCHAR *wn = NULL;
5044 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5045 {
5046 wn = enc_to_utf16(fname, NULL);
5047 if (wn != NULL)
5048 {
5049 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5050 lpSecurityAttributes, dwCreationDisposition,
5051 dwFlagsAndAttributes, NULL);
5052 vim_free(wn);
5053 if (h == INVALID_HANDLE_VALUE
5054 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5055 wn = NULL;
5056 }
5057 }
5058 if (wn == NULL)
5059# endif
5060
5061 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5062 lpSecurityAttributes, dwCreationDisposition,
5063 dwFlagsAndAttributes, NULL);
5064 return h;
5065}
5066
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005067 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005068mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005069{
5070 STARTUPINFO si;
5071 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005072 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005073 SECURITY_ATTRIBUTES saAttr;
5074 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005075 HANDLE ifd[2];
5076 HANDLE ofd[2];
5077 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005078
5079 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5080 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5081 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5082 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5083 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5084 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5085 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5086
5087 if (use_out_for_err && use_null_for_out)
5088 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005089
5090 ifd[0] = INVALID_HANDLE_VALUE;
5091 ifd[1] = INVALID_HANDLE_VALUE;
5092 ofd[0] = INVALID_HANDLE_VALUE;
5093 ofd[1] = INVALID_HANDLE_VALUE;
5094 efd[0] = INVALID_HANDLE_VALUE;
5095 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005096
Bram Moolenaar76467df2016-02-12 19:30:26 +01005097 jo = CreateJobObject(NULL, NULL);
5098 if (jo == NULL)
5099 {
5100 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005101 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005102 }
5103
5104 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005105 ZeroMemory(&si, sizeof(si));
5106 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005107 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005108 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005109
Bram Moolenaard8070362016-02-15 21:56:54 +01005110 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5111 saAttr.bInheritHandle = TRUE;
5112 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005113
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005114 if (use_file_for_in)
5115 {
5116 char_u *fname = options->jo_io_name[PART_IN];
5117
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005118 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5119 FILE_SHARE_READ | FILE_SHARE_WRITE,
5120 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5121 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005122 {
5123 EMSG2(_(e_notopen), fname);
5124 goto failed;
5125 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005126 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005127 else if (!use_null_for_in &&
5128 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5129 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005130 goto failed;
5131
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005132 if (use_file_for_out)
5133 {
5134 char_u *fname = options->jo_io_name[PART_OUT];
5135
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005136 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5137 FILE_SHARE_READ | FILE_SHARE_WRITE,
5138 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5139 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005140 {
5141 EMSG2(_(e_notopen), fname);
5142 goto failed;
5143 }
5144 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005145 else if (!use_null_for_out &&
5146 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5147 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005148 goto failed;
5149
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005150 if (use_file_for_err)
5151 {
5152 char_u *fname = options->jo_io_name[PART_ERR];
5153
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005154 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5155 FILE_SHARE_READ | FILE_SHARE_WRITE,
5156 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5157 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005158 {
5159 EMSG2(_(e_notopen), fname);
5160 goto failed;
5161 }
5162 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005163 else if (!use_out_for_err && !use_null_for_err &&
5164 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005165 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005166 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005167
Bram Moolenaard8070362016-02-15 21:56:54 +01005168 si.dwFlags |= STARTF_USESTDHANDLES;
5169 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005170 si.hStdOutput = ofd[1];
5171 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5172
5173 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5174 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005175 if (options->jo_set & JO_CHANNEL)
5176 {
5177 channel = options->jo_channel;
5178 if (channel != NULL)
5179 ++channel->ch_refcount;
5180 }
5181 else
5182 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005183 if (channel == NULL)
5184 goto failed;
5185 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005186
5187 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005188 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005189 CREATE_DEFAULT_ERROR_MODE |
5190 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005191 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005192 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005193 {
5194 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005195 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005196 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005197 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005198
5199 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005200 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005201 /* if failing, switch the way to terminate
5202 * process with TerminateProcess. */
5203 CloseHandle(jo);
5204 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005205 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005206 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005207 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005208 job->jv_proc_info = pi;
5209 job->jv_job_object = jo;
5210 job->jv_status = JOB_STARTED;
5211
Bram Moolenaar94d01912016-03-08 13:48:51 +01005212 if (!use_file_for_in)
5213 CloseHandle(ifd[0]);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005214 if (!use_file_for_out)
5215 CloseHandle(ofd[1]);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005216 if (!use_out_for_err && !use_file_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005217 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005218
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005219 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005220 if (channel != NULL)
5221 {
5222 channel_set_pipes(channel,
5223 use_file_for_in || use_null_for_in
5224 ? INVALID_FD : (sock_T)ifd[1],
5225 use_file_for_out || use_null_for_out
5226 ? INVALID_FD : (sock_T)ofd[0],
5227 use_out_for_err || use_file_for_err || use_null_for_err
5228 ? INVALID_FD : (sock_T)efd[0]);
5229 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005230 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005231 return;
5232
5233failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005234 CloseHandle(ifd[0]);
5235 CloseHandle(ofd[0]);
5236 CloseHandle(efd[0]);
5237 CloseHandle(ifd[1]);
5238 CloseHandle(ofd[1]);
5239 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005240 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005241}
5242
5243 char *
5244mch_job_status(job_T *job)
5245{
5246 DWORD dwExitCode = 0;
5247
Bram Moolenaar76467df2016-02-12 19:30:26 +01005248 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5249 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005250 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005251 job->jv_status = JOB_ENDED;
Bram Moolenaareab089d2016-02-21 19:32:02 +01005252 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005253 return "dead";
5254 }
5255 return "run";
5256}
5257
5258 int
5259mch_stop_job(job_T *job, char_u *how)
5260{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005261 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005262
Bram Moolenaar923d9262016-02-25 20:56:01 +01005263 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005264 {
5265 if (job->jv_job_object != NULL)
5266 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5267 else
5268 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5269 }
5270
5271 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5272 return FAIL;
5273 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005274 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5275 job->jv_proc_info.dwProcessId)
5276 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005277 FreeConsole();
5278 return ret;
5279}
5280
5281/*
5282 * Clear the data related to "job".
5283 */
5284 void
5285mch_clear_job(job_T *job)
5286{
5287 if (job->jv_status != JOB_FAILED)
5288 {
5289 if (job->jv_job_object != NULL)
5290 CloseHandle(job->jv_job_object);
5291 CloseHandle(job->jv_proc_info.hProcess);
5292 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005293}
5294#endif
5295
Bram Moolenaar071d4272004-06-13 20:20:40 +00005296
5297#ifndef FEAT_GUI_W32
5298
5299/*
5300 * Start termcap mode
5301 */
5302 static void
5303termcap_mode_start(void)
5304{
5305 DWORD cmodein;
5306
5307 if (g_fTermcapMode)
5308 return;
5309
5310 SaveConsoleBuffer(&g_cbNonTermcap);
5311
5312 if (g_cbTermcap.IsValid)
5313 {
5314 /*
5315 * We've been in termcap mode before. Restore certain screen
5316 * characteristics, including the buffer size and the window
5317 * size. Since we will be redrawing the screen, we don't need
5318 * to restore the actual contents of the buffer.
5319 */
5320 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5321 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5322 Rows = g_cbTermcap.Info.dwSize.Y;
5323 Columns = g_cbTermcap.Info.dwSize.X;
5324 }
5325 else
5326 {
5327 /*
5328 * This is our first time entering termcap mode. Clear the console
5329 * screen buffer, and resize the buffer to match the current window
5330 * size. We will use this as the size of our editing environment.
5331 */
5332 ClearConsoleBuffer(g_attrCurrent);
5333 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5334 }
5335
5336#ifdef FEAT_TITLE
5337 resettitle();
5338#endif
5339
5340 GetConsoleMode(g_hConIn, &cmodein);
5341#ifdef FEAT_MOUSE
5342 if (g_fMouseActive)
5343 cmodein |= ENABLE_MOUSE_INPUT;
5344 else
5345 cmodein &= ~ENABLE_MOUSE_INPUT;
5346#endif
5347 cmodein |= ENABLE_WINDOW_INPUT;
5348 SetConsoleMode(g_hConIn, cmodein);
5349
5350 redraw_later_clear();
5351 g_fTermcapMode = TRUE;
5352}
5353
5354
5355/*
5356 * End termcap mode
5357 */
5358 static void
5359termcap_mode_end(void)
5360{
5361 DWORD cmodein;
5362 ConsoleBuffer *cb;
5363 COORD coord;
5364 DWORD dwDummy;
5365
5366 if (!g_fTermcapMode)
5367 return;
5368
5369 SaveConsoleBuffer(&g_cbTermcap);
5370
5371 GetConsoleMode(g_hConIn, &cmodein);
5372 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5373 SetConsoleMode(g_hConIn, cmodein);
5374
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005375#ifdef FEAT_RESTORE_ORIG_SCREEN
5376 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5377#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005378 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005379#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005380 RestoreConsoleBuffer(cb, p_rs);
5381 SetConsoleCursorInfo(g_hConOut, &g_cci);
5382
5383 if (p_rs || exiting)
5384 {
5385 /*
5386 * Clear anything that happens to be on the current line.
5387 */
5388 coord.X = 0;
5389 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5390 FillConsoleOutputCharacter(g_hConOut, ' ',
5391 cb->Info.dwSize.X, coord, &dwDummy);
5392 /*
5393 * The following is just for aesthetics. If we are exiting without
5394 * restoring the screen, then we want to have a prompt string
5395 * appear at the bottom line. However, the command interpreter
5396 * seems to always advance the cursor one line before displaying
5397 * the prompt string, which causes the screen to scroll. To
5398 * counter this, move the cursor up one line before exiting.
5399 */
5400 if (exiting && !p_rs)
5401 coord.Y--;
5402 /*
5403 * Position the cursor at the leftmost column of the desired row.
5404 */
5405 SetConsoleCursorPosition(g_hConOut, coord);
5406 }
5407
5408 g_fTermcapMode = FALSE;
5409}
5410#endif /* FEAT_GUI_W32 */
5411
5412
5413#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005414/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005415 void
5416mch_write(
5417 char_u *s,
5418 int len)
5419{
5420 /* never used */
5421}
5422
5423#else
5424
5425/*
5426 * clear `n' chars, starting from `coord'
5427 */
5428 static void
5429clear_chars(
5430 COORD coord,
5431 DWORD n)
5432{
5433 DWORD dwDummy;
5434
5435 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5436 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5437}
5438
5439
5440/*
5441 * Clear the screen
5442 */
5443 static void
5444clear_screen(void)
5445{
5446 g_coord.X = g_coord.Y = 0;
5447 clear_chars(g_coord, Rows * Columns);
5448}
5449
5450
5451/*
5452 * Clear to end of display
5453 */
5454 static void
5455clear_to_end_of_display(void)
5456{
5457 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5458 * Columns + (Columns - g_coord.X));
5459}
5460
5461
5462/*
5463 * Clear to end of line
5464 */
5465 static void
5466clear_to_end_of_line(void)
5467{
5468 clear_chars(g_coord, Columns - g_coord.X);
5469}
5470
5471
5472/*
5473 * Scroll the scroll region up by `cLines' lines
5474 */
5475 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005476scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005477{
5478 COORD oldcoord = g_coord;
5479
5480 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5481 delete_lines(cLines);
5482
5483 g_coord = oldcoord;
5484}
5485
5486
5487/*
5488 * Set the scroll region
5489 */
5490 static void
5491set_scroll_region(
5492 unsigned left,
5493 unsigned top,
5494 unsigned right,
5495 unsigned bottom)
5496{
5497 if (left >= right
5498 || top >= bottom
5499 || right > (unsigned) Columns - 1
5500 || bottom > (unsigned) Rows - 1)
5501 return;
5502
5503 g_srScrollRegion.Left = left;
5504 g_srScrollRegion.Top = top;
5505 g_srScrollRegion.Right = right;
5506 g_srScrollRegion.Bottom = bottom;
5507}
5508
5509
5510/*
5511 * Insert `cLines' lines at the current cursor position
5512 */
5513 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005514insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515{
5516 SMALL_RECT source;
5517 COORD dest;
5518 CHAR_INFO fill;
5519
5520 dest.X = 0;
5521 dest.Y = g_coord.Y + cLines;
5522
5523 source.Left = 0;
5524 source.Top = g_coord.Y;
5525 source.Right = g_srScrollRegion.Right;
5526 source.Bottom = g_srScrollRegion.Bottom - cLines;
5527
5528 fill.Char.AsciiChar = ' ';
5529 fill.Attributes = g_attrCurrent;
5530
5531 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5532
5533 /* Here we have to deal with a win32 console flake: If the scroll
5534 * region looks like abc and we scroll c to a and fill with d we get
5535 * cbd... if we scroll block c one line at a time to a, we get cdd...
5536 * vim expects cdd consistently... So we have to deal with that
5537 * here... (this also occurs scrolling the same way in the other
5538 * direction). */
5539
5540 if (source.Bottom < dest.Y)
5541 {
5542 COORD coord;
5543
5544 coord.X = 0;
5545 coord.Y = source.Bottom;
5546 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5547 }
5548}
5549
5550
5551/*
5552 * Delete `cLines' lines at the current cursor position
5553 */
5554 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005555delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556{
5557 SMALL_RECT source;
5558 COORD dest;
5559 CHAR_INFO fill;
5560 int nb;
5561
5562 dest.X = 0;
5563 dest.Y = g_coord.Y;
5564
5565 source.Left = 0;
5566 source.Top = g_coord.Y + cLines;
5567 source.Right = g_srScrollRegion.Right;
5568 source.Bottom = g_srScrollRegion.Bottom;
5569
5570 fill.Char.AsciiChar = ' ';
5571 fill.Attributes = g_attrCurrent;
5572
5573 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5574
5575 /* Here we have to deal with a win32 console flake: If the scroll
5576 * region looks like abc and we scroll c to a and fill with d we get
5577 * cbd... if we scroll block c one line at a time to a, we get cdd...
5578 * vim expects cdd consistently... So we have to deal with that
5579 * here... (this also occurs scrolling the same way in the other
5580 * direction). */
5581
5582 nb = dest.Y + (source.Bottom - source.Top) + 1;
5583
5584 if (nb < source.Top)
5585 {
5586 COORD coord;
5587
5588 coord.X = 0;
5589 coord.Y = nb;
5590 clear_chars(coord, Columns * (source.Top - nb));
5591 }
5592}
5593
5594
5595/*
5596 * Set the cursor position
5597 */
5598 static void
5599gotoxy(
5600 unsigned x,
5601 unsigned y)
5602{
5603 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5604 return;
5605
5606 /* external cursor coords are 1-based; internal are 0-based */
5607 g_coord.X = x - 1;
5608 g_coord.Y = y - 1;
5609 SetConsoleCursorPosition(g_hConOut, g_coord);
5610}
5611
5612
5613/*
5614 * Set the current text attribute = (foreground | background)
5615 * See ../doc/os_win32.txt for the numbers.
5616 */
5617 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005618textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005620 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621
5622 SetConsoleTextAttribute(g_hConOut, wAttr);
5623}
5624
5625
5626 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005627textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005629 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005630
5631 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5632}
5633
5634
5635 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005636textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005637{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005638 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639
5640 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5641}
5642
5643
5644/*
5645 * restore the default text attribute (whatever we started with)
5646 */
5647 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005648normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649{
5650 textattr(g_attrDefault);
5651}
5652
5653
5654static WORD g_attrPreStandout = 0;
5655
5656/*
5657 * Make the text standout, by brightening it
5658 */
5659 static void
5660standout(void)
5661{
5662 g_attrPreStandout = g_attrCurrent;
5663 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5664}
5665
5666
5667/*
5668 * Turn off standout mode
5669 */
5670 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005671standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672{
5673 if (g_attrPreStandout)
5674 {
5675 textattr(g_attrPreStandout);
5676 g_attrPreStandout = 0;
5677 }
5678}
5679
5680
5681/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005682 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005683 */
5684 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005685mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686{
5687 char_u *p;
5688 int n;
5689
5690 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5691 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5692 if (T_ME[0] == ESC && T_ME[1] == '|')
5693 {
5694 p = T_ME + 2;
5695 n = getdigits(&p);
5696 if (*p == 'm' && n > 0)
5697 {
5698 cterm_normal_fg_color = (n & 0xf) + 1;
5699 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5700 }
5701 }
5702}
5703
5704
5705/*
5706 * visual bell: flash the screen
5707 */
5708 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005709visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710{
5711 COORD coordOrigin = {0, 0};
5712 WORD attrFlash = ~g_attrCurrent & 0xff;
5713
5714 DWORD dwDummy;
5715 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5716
5717 if (oldattrs == NULL)
5718 return;
5719 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5720 coordOrigin, &dwDummy);
5721 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5722 coordOrigin, &dwDummy);
5723
5724 Sleep(15); /* wait for 15 msec */
5725 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5726 coordOrigin, &dwDummy);
5727 vim_free(oldattrs);
5728}
5729
5730
5731/*
5732 * Make the cursor visible or invisible
5733 */
5734 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005735cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005736{
5737 s_cursor_visible = fVisible;
5738#ifdef MCH_CURSOR_SHAPE
5739 mch_update_cursor();
5740#endif
5741}
5742
5743
5744/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005745 * write `cbToWrite' bytes in `pchBuf' to the screen
5746 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005747 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005748 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005749write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005750 char_u *pchBuf,
5751 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752{
5753 COORD coord = g_coord;
5754 DWORD written;
5755
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005756#ifdef FEAT_MBYTE
5757 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5758 {
5759 static WCHAR *unicodebuf = NULL;
5760 static int unibuflen = 0;
5761 int length;
5762 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005763
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005764 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5765 if (unicodebuf == NULL || length > unibuflen)
5766 {
5767 vim_free(unicodebuf);
5768 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5769 unibuflen = length;
5770 }
5771 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5772 unicodebuf, unibuflen);
5773
5774 cells = mb_string2cells(pchBuf, cbToWrite);
5775 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5776 coord, &written);
5777 /* When writing fails or didn't write a single character, pretend one
5778 * character was written, otherwise we get stuck. */
5779 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5780 coord, &cchwritten) == 0
5781 || cchwritten == 0)
5782 cchwritten = 1;
5783
5784 if (cchwritten == length)
5785 {
5786 written = cbToWrite;
5787 g_coord.X += (SHORT)cells;
5788 }
5789 else
5790 {
5791 char_u *p = pchBuf;
5792 for (n = 0; n < cchwritten; n++)
5793 mb_cptr_adv(p);
5794 written = p - pchBuf;
5795 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5796 }
5797 }
5798 else
5799#endif
5800 {
5801 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5802 coord, &written);
5803 /* When writing fails or didn't write a single character, pretend one
5804 * character was written, otherwise we get stuck. */
5805 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5806 coord, &written) == 0
5807 || written == 0)
5808 written = 1;
5809
5810 g_coord.X += (SHORT) written;
5811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005812
5813 while (g_coord.X > g_srScrollRegion.Right)
5814 {
5815 g_coord.X -= (SHORT) Columns;
5816 if (g_coord.Y < g_srScrollRegion.Bottom)
5817 g_coord.Y++;
5818 }
5819
5820 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5821
5822 return written;
5823}
5824
5825
5826/*
5827 * mch_write(): write the output buffer to the screen, translating ESC
5828 * sequences into calls to console output routines.
5829 */
5830 void
5831mch_write(
5832 char_u *s,
5833 int len)
5834{
5835 s[len] = NUL;
5836
5837 if (!term_console)
5838 {
5839 write(1, s, (unsigned)len);
5840 return;
5841 }
5842
5843 /* translate ESC | sequences into faked bios calls */
5844 while (len--)
5845 {
5846 /* optimization: use one single write_chars for runs of text,
5847 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005848 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005849
5850 if (p_wd)
5851 {
5852 WaitForChar(p_wd);
5853 if (prefix != 0)
5854 prefix = 1;
5855 }
5856
5857 if (prefix != 0)
5858 {
5859 DWORD nWritten;
5860
5861 nWritten = write_chars(s, prefix);
5862#ifdef MCH_WRITE_DUMP
5863 if (fdDump)
5864 {
5865 fputc('>', fdDump);
5866 fwrite(s, sizeof(char_u), nWritten, fdDump);
5867 fputs("<\n", fdDump);
5868 }
5869#endif
5870 len -= (nWritten - 1);
5871 s += nWritten;
5872 }
5873 else if (s[0] == '\n')
5874 {
5875 /* \n, newline: go to the beginning of the next line or scroll */
5876 if (g_coord.Y == g_srScrollRegion.Bottom)
5877 {
5878 scroll(1);
5879 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5880 }
5881 else
5882 {
5883 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5884 }
5885#ifdef MCH_WRITE_DUMP
5886 if (fdDump)
5887 fputs("\\n\n", fdDump);
5888#endif
5889 s++;
5890 }
5891 else if (s[0] == '\r')
5892 {
5893 /* \r, carriage return: go to beginning of line */
5894 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5895#ifdef MCH_WRITE_DUMP
5896 if (fdDump)
5897 fputs("\\r\n", fdDump);
5898#endif
5899 s++;
5900 }
5901 else if (s[0] == '\b')
5902 {
5903 /* \b, backspace: move cursor one position left */
5904 if (g_coord.X > g_srScrollRegion.Left)
5905 g_coord.X--;
5906 else if (g_coord.Y > g_srScrollRegion.Top)
5907 {
5908 g_coord.X = g_srScrollRegion.Right;
5909 g_coord.Y--;
5910 }
5911 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5912#ifdef MCH_WRITE_DUMP
5913 if (fdDump)
5914 fputs("\\b\n", fdDump);
5915#endif
5916 s++;
5917 }
5918 else if (s[0] == '\a')
5919 {
5920 /* \a, bell */
5921 MessageBeep(0xFFFFFFFF);
5922#ifdef MCH_WRITE_DUMP
5923 if (fdDump)
5924 fputs("\\a\n", fdDump);
5925#endif
5926 s++;
5927 }
5928 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5929 {
5930#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005931 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005933 char_u *p;
5934 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935
5936 switch (s[2])
5937 {
5938 /* one or two numeric arguments, separated by ';' */
5939
5940 case '0': case '1': case '2': case '3': case '4':
5941 case '5': case '6': case '7': case '8': case '9':
5942 p = s + 2;
5943 arg1 = getdigits(&p); /* no check for length! */
5944 if (p > s + len)
5945 break;
5946
5947 if (*p == ';')
5948 {
5949 ++p;
5950 arg2 = getdigits(&p); /* no check for length! */
5951 if (p > s + len)
5952 break;
5953
5954 if (*p == 'H')
5955 gotoxy(arg2, arg1);
5956 else if (*p == 'r')
5957 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5958 }
5959 else if (*p == 'A')
5960 {
5961 /* move cursor up arg1 lines in same column */
5962 gotoxy(g_coord.X + 1,
5963 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5964 }
5965 else if (*p == 'C')
5966 {
5967 /* move cursor right arg1 columns in same line */
5968 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5969 g_coord.Y + 1);
5970 }
5971 else if (*p == 'H')
5972 {
5973 gotoxy(1, arg1);
5974 }
5975 else if (*p == 'L')
5976 {
5977 insert_lines(arg1);
5978 }
5979 else if (*p == 'm')
5980 {
5981 if (arg1 == 0)
5982 normvideo();
5983 else
5984 textattr((WORD) arg1);
5985 }
5986 else if (*p == 'f')
5987 {
5988 textcolor((WORD) arg1);
5989 }
5990 else if (*p == 'b')
5991 {
5992 textbackground((WORD) arg1);
5993 }
5994 else if (*p == 'M')
5995 {
5996 delete_lines(arg1);
5997 }
5998
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005999 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006000 s = p + 1;
6001 break;
6002
6003
6004 /* Three-character escape sequences */
6005
6006 case 'A':
6007 /* move cursor up one line in same column */
6008 gotoxy(g_coord.X + 1,
6009 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6010 goto got3;
6011
6012 case 'B':
6013 visual_bell();
6014 goto got3;
6015
6016 case 'C':
6017 /* move cursor right one column in same line */
6018 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6019 g_coord.Y + 1);
6020 goto got3;
6021
6022 case 'E':
6023 termcap_mode_end();
6024 goto got3;
6025
6026 case 'F':
6027 standout();
6028 goto got3;
6029
6030 case 'f':
6031 standend();
6032 goto got3;
6033
6034 case 'H':
6035 gotoxy(1, 1);
6036 goto got3;
6037
6038 case 'j':
6039 clear_to_end_of_display();
6040 goto got3;
6041
6042 case 'J':
6043 clear_screen();
6044 goto got3;
6045
6046 case 'K':
6047 clear_to_end_of_line();
6048 goto got3;
6049
6050 case 'L':
6051 insert_lines(1);
6052 goto got3;
6053
6054 case 'M':
6055 delete_lines(1);
6056 goto got3;
6057
6058 case 'S':
6059 termcap_mode_start();
6060 goto got3;
6061
6062 case 'V':
6063 cursor_visible(TRUE);
6064 goto got3;
6065
6066 case 'v':
6067 cursor_visible(FALSE);
6068 goto got3;
6069
6070 got3:
6071 s += 3;
6072 len -= 2;
6073 }
6074
6075#ifdef MCH_WRITE_DUMP
6076 if (fdDump)
6077 {
6078 fputs("ESC | ", fdDump);
6079 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6080 fputc('\n', fdDump);
6081 }
6082#endif
6083 }
6084 else
6085 {
6086 /* Write a single character */
6087 DWORD nWritten;
6088
6089 nWritten = write_chars(s, 1);
6090#ifdef MCH_WRITE_DUMP
6091 if (fdDump)
6092 {
6093 fputc('>', fdDump);
6094 fwrite(s, sizeof(char_u), nWritten, fdDump);
6095 fputs("<\n", fdDump);
6096 }
6097#endif
6098
6099 len -= (nWritten - 1);
6100 s += nWritten;
6101 }
6102 }
6103
6104#ifdef MCH_WRITE_DUMP
6105 if (fdDump)
6106 fflush(fdDump);
6107#endif
6108}
6109
6110#endif /* FEAT_GUI_W32 */
6111
6112
6113/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006114 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006116/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117 void
6118mch_delay(
6119 long msec,
6120 int ignoreinput)
6121{
6122#ifdef FEAT_GUI_W32
6123 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006124#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006126# ifdef FEAT_MZSCHEME
6127 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6128 {
6129 int towait = p_mzq;
6130
6131 /* if msec is large enough, wait by portions in p_mzq */
6132 while (msec > 0)
6133 {
6134 mzvim_check_threads();
6135 if (msec < towait)
6136 towait = msec;
6137 Sleep(towait);
6138 msec -= towait;
6139 }
6140 }
6141 else
6142# endif
6143 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144 else
6145 WaitForChar(msec);
6146#endif
6147}
6148
6149
6150/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006151 * This version of remove is not scared by a readonly (backup) file.
6152 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006153 * Return 0 for success, -1 for failure.
6154 */
6155 int
6156mch_remove(char_u *name)
6157{
6158#ifdef FEAT_MBYTE
6159 WCHAR *wn = NULL;
6160 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006161#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162
Bram Moolenaar203258c2016-01-17 22:15:16 +01006163 /*
6164 * On Windows, deleting a directory's symbolic link is done by
6165 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6166 */
6167 if (mch_isdir(name) && mch_is_symbolic_link(name))
6168 return mch_rmdir(name);
6169
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006170 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6171
6172#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6174 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006175 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176 if (wn != NULL)
6177 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178 n = DeleteFileW(wn) ? 0 : -1;
6179 vim_free(wn);
6180 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6181 return n;
6182 /* Retry with non-wide function (for Windows 98). */
6183 }
6184 }
6185#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006186 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187}
6188
6189
6190/*
6191 * check for an "interrupt signal": CTRL-break or CTRL-C
6192 */
6193 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006194mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006195{
6196#ifndef FEAT_GUI_W32 /* never used */
6197 if (g_fCtrlCPressed || g_fCBrkPressed)
6198 {
6199 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6200 got_int = TRUE;
6201 }
6202#endif
6203}
6204
Bram Moolenaaree273972016-01-02 21:11:51 +01006205/* physical RAM to leave for the OS */
6206#define WINNT_RESERVE_BYTES (256*1024*1024)
6207#define WIN95_RESERVE_BYTES (8*1024*1024)
6208
6209/*
6210 * How much main memory in KiB that can be used by VIM.
6211 */
6212/*ARGSUSED*/
6213 long_u
6214mch_total_mem(int special)
6215{
6216 PlatformId();
6217#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6218 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6219 {
6220 MEMORYSTATUSEX ms;
6221
6222 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6223 * what fits in 32 bits. But it's not always available. */
6224 ms.dwLength = sizeof(MEMORYSTATUSEX);
6225 GlobalMemoryStatusEx(&ms);
6226 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6227 {
6228 /* Process address space fits in physical RAM, use all of it. */
6229 return (long_u)(ms.ullAvailVirtual / 1024);
6230 }
6231 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6232 {
6233 /* Catch old NT box or perverse hardware setup. */
6234 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6235 }
6236 /* Use physical RAM less reserve for OS + data. */
6237 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6238 }
6239 else
6240#endif
6241 {
6242 /* Pre-XP or 95 OS handling. */
6243 MEMORYSTATUS ms;
6244 long_u os_reserve_bytes;
6245
6246 ms.dwLength = sizeof(MEMORYSTATUS);
6247 GlobalMemoryStatus(&ms);
6248 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6249 {
6250 /* Process address space fits in physical RAM, use all of it. */
6251 return (long_u)(ms.dwAvailVirtual / 1024);
6252 }
6253 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6254 ? WINNT_RESERVE_BYTES
6255 : WIN95_RESERVE_BYTES;
6256 if (ms.dwTotalPhys <= os_reserve_bytes)
6257 {
6258 /* Catch old boxes or perverse hardware setup. */
6259 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6260 }
6261 /* Use physical RAM less reserve for OS + data. */
6262 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6263 }
6264}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266#ifdef FEAT_MBYTE
6267/*
6268 * Same code as below, but with wide functions and no comments.
6269 * Return 0 for success, non-zero for failure.
6270 */
6271 int
6272mch_wrename(WCHAR *wold, WCHAR *wnew)
6273{
6274 WCHAR *p;
6275 int i;
6276 WCHAR szTempFile[_MAX_PATH + 1];
6277 WCHAR szNewPath[_MAX_PATH + 1];
6278 HANDLE hf;
6279
6280 if (!mch_windows95())
6281 {
6282 p = wold;
6283 for (i = 0; wold[i] != NUL; ++i)
6284 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6285 && wold[i + 1] != 0)
6286 p = wold + i + 1;
6287 if ((int)(wold + i - p) < 8 || p[6] != '~')
6288 return (MoveFileW(wold, wnew) == 0);
6289 }
6290
6291 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6292 return -1;
6293 *p = NUL;
6294
6295 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6296 return -2;
6297
6298 if (!DeleteFileW(szTempFile))
6299 return -3;
6300
6301 if (!MoveFileW(wold, szTempFile))
6302 return -4;
6303
6304 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6305 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6306 return -5;
6307 if (!CloseHandle(hf))
6308 return -6;
6309
6310 if (!MoveFileW(szTempFile, wnew))
6311 {
6312 (void)MoveFileW(szTempFile, wold);
6313 return -7;
6314 }
6315
6316 DeleteFileW(szTempFile);
6317
6318 if (!DeleteFileW(wold))
6319 return -8;
6320
6321 return 0;
6322}
6323#endif
6324
6325
6326/*
6327 * mch_rename() works around a bug in rename (aka MoveFile) in
6328 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6329 * file whose short file name is "FOO.BAR" (its long file name will
6330 * be correct: "foo.bar~"). Because a file can be accessed by
6331 * either its SFN or its LFN, "foo.bar" has effectively been
6332 * renamed to "foo.bar", which is not at all what was wanted. This
6333 * seems to happen only when renaming files with three-character
6334 * extensions by appending a suffix that does not include ".".
6335 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6336 *
6337 * There is another problem, which isn't really a bug but isn't right either:
6338 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6339 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6340 * service pack 6. Doesn't seem to happen on Windows 98.
6341 *
6342 * Like rename(), returns 0 upon success, non-zero upon failure.
6343 * Should probably set errno appropriately when errors occur.
6344 */
6345 int
6346mch_rename(
6347 const char *pszOldFile,
6348 const char *pszNewFile)
6349{
6350 char szTempFile[_MAX_PATH+1];
6351 char szNewPath[_MAX_PATH+1];
6352 char *pszFilePart;
6353 HANDLE hf;
6354#ifdef FEAT_MBYTE
6355 WCHAR *wold = NULL;
6356 WCHAR *wnew = NULL;
6357 int retval = -1;
6358
6359 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6360 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006361 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6362 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 if (wold != NULL && wnew != NULL)
6364 retval = mch_wrename(wold, wnew);
6365 vim_free(wold);
6366 vim_free(wnew);
6367 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6368 return retval;
6369 /* Retry with non-wide function (for Windows 98). */
6370 }
6371#endif
6372
6373 /*
6374 * No need to play tricks if not running Windows 95, unless the file name
6375 * contains a "~" as the seventh character.
6376 */
6377 if (!mch_windows95())
6378 {
6379 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6380 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6381 return rename(pszOldFile, pszNewFile);
6382 }
6383
6384 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6385 * a directory, no error is returned and pszFilePart will be NULL. */
6386 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6387 || pszFilePart == NULL)
6388 return -1;
6389 *pszFilePart = NUL;
6390
6391 /* Get (and create) a unique temporary file name in directory of new file */
6392 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6393 return -2;
6394
6395 /* blow the temp file away */
6396 if (!DeleteFile(szTempFile))
6397 return -3;
6398
6399 /* rename old file to the temp file */
6400 if (!MoveFile(pszOldFile, szTempFile))
6401 return -4;
6402
6403 /* now create an empty file called pszOldFile; this prevents the operating
6404 * system using pszOldFile as an alias (SFN) if we're renaming within the
6405 * same directory. For example, we're editing a file called
6406 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6407 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6408 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006409 * cause all sorts of problems later in buf_write(). So, we create an
6410 * empty file called filena~1.txt and the system will have to find some
6411 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006412 */
6413 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6414 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6415 return -5;
6416 if (!CloseHandle(hf))
6417 return -6;
6418
6419 /* rename the temp file to the new file */
6420 if (!MoveFile(szTempFile, pszNewFile))
6421 {
6422 /* Renaming failed. Rename the file back to its old name, so that it
6423 * looks like nothing happened. */
6424 (void)MoveFile(szTempFile, pszOldFile);
6425
6426 return -7;
6427 }
6428
6429 /* Seems to be left around on Novell filesystems */
6430 DeleteFile(szTempFile);
6431
6432 /* finally, remove the empty old file */
6433 if (!DeleteFile(pszOldFile))
6434 return -8;
6435
6436 return 0; /* success */
6437}
6438
6439/*
6440 * Get the default shell for the current hardware platform
6441 */
6442 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006443default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444{
6445 char* psz = NULL;
6446
6447 PlatformId();
6448
6449 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6450 psz = "cmd.exe";
6451 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6452 psz = "command.com";
6453
6454 return psz;
6455}
6456
6457/*
6458 * mch_access() extends access() to do more detailed check on network drives.
6459 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6460 */
6461 int
6462mch_access(char *n, int p)
6463{
6464 HANDLE hFile;
6465 DWORD am;
6466 int retval = -1; /* default: fail */
6467#ifdef FEAT_MBYTE
6468 WCHAR *wn = NULL;
6469
6470 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006471 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472#endif
6473
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006474 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475 {
6476 char TempName[_MAX_PATH + 16] = "";
6477#ifdef FEAT_MBYTE
6478 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6479#endif
6480
6481 if (p & R_OK)
6482 {
6483 /* Read check is performed by seeing if we can do a find file on
6484 * the directory for any file. */
6485#ifdef FEAT_MBYTE
6486 if (wn != NULL)
6487 {
6488 int i;
6489 WIN32_FIND_DATAW d;
6490
6491 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6492 TempNameW[i] = wn[i];
6493 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6494 TempNameW[i++] = '\\';
6495 TempNameW[i++] = '*';
6496 TempNameW[i++] = 0;
6497
6498 hFile = FindFirstFileW(TempNameW, &d);
6499 if (hFile == INVALID_HANDLE_VALUE)
6500 {
6501 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6502 goto getout;
6503
6504 /* Retry with non-wide function (for Windows 98). */
6505 vim_free(wn);
6506 wn = NULL;
6507 }
6508 else
6509 (void)FindClose(hFile);
6510 }
6511 if (wn == NULL)
6512#endif
6513 {
6514 char *pch;
6515 WIN32_FIND_DATA d;
6516
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006517 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518 pch = TempName + STRLEN(TempName) - 1;
6519 if (*pch != '\\' && *pch != '/')
6520 *++pch = '\\';
6521 *++pch = '*';
6522 *++pch = NUL;
6523
6524 hFile = FindFirstFile(TempName, &d);
6525 if (hFile == INVALID_HANDLE_VALUE)
6526 goto getout;
6527 (void)FindClose(hFile);
6528 }
6529 }
6530
6531 if (p & W_OK)
6532 {
6533 /* Trying to create a temporary file in the directory should catch
6534 * directories on read-only network shares. However, in
6535 * directories whose ACL allows writes but denies deletes will end
6536 * up keeping the temporary file :-(. */
6537#ifdef FEAT_MBYTE
6538 if (wn != NULL)
6539 {
6540 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6541 {
6542 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6543 goto getout;
6544
6545 /* Retry with non-wide function (for Windows 98). */
6546 vim_free(wn);
6547 wn = NULL;
6548 }
6549 else
6550 DeleteFileW(TempNameW);
6551 }
6552 if (wn == NULL)
6553#endif
6554 {
6555 if (!GetTempFileName(n, "VIM", 0, TempName))
6556 goto getout;
6557 mch_remove((char_u *)TempName);
6558 }
6559 }
6560 }
6561 else
6562 {
6563 /* Trying to open the file for the required access does ACL, read-only
6564 * network share, and file attribute checks. */
6565 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6566 | ((p & R_OK) ? GENERIC_READ : 0);
6567#ifdef FEAT_MBYTE
6568 if (wn != NULL)
6569 {
6570 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6571 if (hFile == INVALID_HANDLE_VALUE
6572 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6573 {
6574 /* Retry with non-wide function (for Windows 98). */
6575 vim_free(wn);
6576 wn = NULL;
6577 }
6578 }
6579 if (wn == NULL)
6580#endif
6581 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6582 if (hFile == INVALID_HANDLE_VALUE)
6583 goto getout;
6584 CloseHandle(hFile);
6585 }
6586
6587 retval = 0; /* success */
6588getout:
6589#ifdef FEAT_MBYTE
6590 vim_free(wn);
6591#endif
6592 return retval;
6593}
6594
6595#if defined(FEAT_MBYTE) || defined(PROTO)
6596/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006597 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598 */
6599 int
6600mch_open(char *name, int flags, int mode)
6601{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006602 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6603# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604 WCHAR *wn;
6605 int f;
6606
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006607 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006609 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006610 if (wn != NULL)
6611 {
6612 f = _wopen(wn, flags, mode);
6613 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006614 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006615 return f;
6616 /* Retry with non-wide function (for Windows 98). Can't use
6617 * GetLastError() here and it's unclear what errno gets set to if
6618 * the _wopen() fails for missing wide functions. */
6619 }
6620 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006621# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006623 /* open() can open a file which name is longer than _MAX_PATH bytes
6624 * and shorter than _MAX_PATH characters successfully, but sometimes it
6625 * causes unexpected error in another part. We make it an error explicitly
6626 * here. */
6627 if (strlen(name) >= _MAX_PATH)
6628 return -1;
6629
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630 return open(name, flags, mode);
6631}
6632
6633/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006634 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006635 */
6636 FILE *
6637mch_fopen(char *name, char *mode)
6638{
6639 WCHAR *wn, *wm;
6640 FILE *f = NULL;
6641
6642 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6643# ifdef __BORLANDC__
6644 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6645 && g_PlatformId == VER_PLATFORM_WIN32_NT
6646# endif
6647 )
6648 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006649# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006650 /* Work around an annoying assertion in the Microsoft debug CRT
6651 * when mode's text/binary setting doesn't match _get_fmode(). */
6652 char newMode = mode[strlen(mode) - 1];
6653 int oldMode = 0;
6654
6655 _get_fmode(&oldMode);
6656 if (newMode == 't')
6657 _set_fmode(_O_TEXT);
6658 else if (newMode == 'b')
6659 _set_fmode(_O_BINARY);
6660# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006661 wn = enc_to_utf16((char_u *)name, NULL);
6662 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 if (wn != NULL && wm != NULL)
6664 f = _wfopen(wn, wm);
6665 vim_free(wn);
6666 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006667
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006668# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006669 _set_fmode(oldMode);
6670# endif
6671
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006672 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673 return f;
6674 /* Retry with non-wide function (for Windows 98). Can't use
6675 * GetLastError() here and it's unclear what errno gets set to if
6676 * the _wfopen() fails for missing wide functions. */
6677 }
6678
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006679 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6680 * and shorter than _MAX_PATH characters successfully, but sometimes it
6681 * causes unexpected error in another part. We make it an error explicitly
6682 * here. */
6683 if (strlen(name) >= _MAX_PATH)
6684 return NULL;
6685
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 return fopen(name, mode);
6687}
6688#endif
6689
6690#ifdef FEAT_MBYTE
6691/*
6692 * SUB STREAM (aka info stream) handling:
6693 *
6694 * NTFS can have sub streams for each file. Normal contents of file is
6695 * stored in the main stream, and extra contents (author information and
6696 * title and so on) can be stored in sub stream. After Windows 2000, user
6697 * can access and store those informations in sub streams via explorer's
6698 * property menuitem in right click menu. Those informations in sub streams
6699 * were lost when copying only the main stream. So we have to copy sub
6700 * streams.
6701 *
6702 * Incomplete explanation:
6703 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6704 * More useful info and an example:
6705 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6706 */
6707
6708/*
6709 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6710 * and write to stream "substream" of file "to".
6711 * Errors are ignored.
6712 */
6713 static void
6714copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6715{
6716 HANDLE hTo;
6717 WCHAR *to_name;
6718
6719 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6720 wcscpy(to_name, to);
6721 wcscat(to_name, substream);
6722
6723 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6724 FILE_ATTRIBUTE_NORMAL, NULL);
6725 if (hTo != INVALID_HANDLE_VALUE)
6726 {
6727 long done;
6728 DWORD todo;
6729 DWORD readcnt, written;
6730 char buf[4096];
6731
6732 /* Copy block of bytes at a time. Abort when something goes wrong. */
6733 for (done = 0; done < len; done += written)
6734 {
6735 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006736 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6737 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6739 FALSE, FALSE, context)
6740 || readcnt != todo
6741 || !WriteFile(hTo, buf, todo, &written, NULL)
6742 || written != todo)
6743 break;
6744 }
6745 CloseHandle(hTo);
6746 }
6747
6748 free(to_name);
6749}
6750
6751/*
6752 * Copy info streams from file "from" to file "to".
6753 */
6754 static void
6755copy_infostreams(char_u *from, char_u *to)
6756{
6757 WCHAR *fromw;
6758 WCHAR *tow;
6759 HANDLE sh;
6760 WIN32_STREAM_ID sid;
6761 int headersize;
6762 WCHAR streamname[_MAX_PATH];
6763 DWORD readcount;
6764 void *context = NULL;
6765 DWORD lo, hi;
6766 int len;
6767
6768 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006769 fromw = enc_to_utf16(from, NULL);
6770 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 if (fromw != NULL && tow != NULL)
6772 {
6773 /* Open the file for reading. */
6774 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6775 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6776 if (sh != INVALID_HANDLE_VALUE)
6777 {
6778 /* Use BackupRead() to find the info streams. Repeat until we
6779 * have done them all.*/
6780 for (;;)
6781 {
6782 /* Get the header to find the length of the stream name. If
6783 * the "readcount" is zero we have done all info streams. */
6784 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006785 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6787 &readcount, FALSE, FALSE, &context)
6788 || readcount == 0)
6789 break;
6790
6791 /* We only deal with streams that have a name. The normal
6792 * file data appears to be without a name, even though docs
6793 * suggest it is called "::$DATA". */
6794 if (sid.dwStreamNameSize > 0)
6795 {
6796 /* Read the stream name. */
6797 if (!BackupRead(sh, (LPBYTE)streamname,
6798 sid.dwStreamNameSize,
6799 &readcount, FALSE, FALSE, &context))
6800 break;
6801
6802 /* Copy an info stream with a name ":anything:$DATA".
6803 * Skip "::$DATA", it has no stream name (examples suggest
6804 * it might be used for the normal file contents).
6805 * Note that BackupRead() counts bytes, but the name is in
6806 * wide characters. */
6807 len = readcount / sizeof(WCHAR);
6808 streamname[len] = 0;
6809 if (len > 7 && wcsicmp(streamname + len - 6,
6810 L":$DATA") == 0)
6811 {
6812 streamname[len - 6] = 0;
6813 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006814 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815 }
6816 }
6817
6818 /* Advance to the next stream. We might try seeking too far,
6819 * but BackupSeek() doesn't skip over stream borders, thus
6820 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006821 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822 &lo, &hi, &context);
6823 }
6824
6825 /* Clear the context. */
6826 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6827
6828 CloseHandle(sh);
6829 }
6830 }
6831 vim_free(fromw);
6832 vim_free(tow);
6833}
6834#endif
6835
6836/*
6837 * Copy file attributes from file "from" to file "to".
6838 * For Windows NT and later we copy info streams.
6839 * Always returns zero, errors are ignored.
6840 */
6841 int
6842mch_copy_file_attribute(char_u *from, char_u *to)
6843{
6844#ifdef FEAT_MBYTE
6845 /* File streams only work on Windows NT and later. */
6846 PlatformId();
6847 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6848 copy_infostreams(from, to);
6849#endif
6850 return 0;
6851}
6852
6853#if defined(MYRESETSTKOFLW) || defined(PROTO)
6854/*
6855 * Recreate a destroyed stack guard page in win32.
6856 * Written by Benjamin Peterson.
6857 */
6858
6859/* These magic numbers are from the MS header files */
6860#define MIN_STACK_WIN9X 17
6861#define MIN_STACK_WINNT 2
6862
6863/*
6864 * This function does the same thing as _resetstkoflw(), which is only
6865 * available in DevStudio .net and later.
6866 * Returns 0 for failure, 1 for success.
6867 */
6868 int
6869myresetstkoflw(void)
6870{
6871 BYTE *pStackPtr;
6872 BYTE *pGuardPage;
6873 BYTE *pStackBase;
6874 BYTE *pLowestPossiblePage;
6875 MEMORY_BASIC_INFORMATION mbi;
6876 SYSTEM_INFO si;
6877 DWORD nPageSize;
6878 DWORD dummy;
6879
6880 /* This code will not work on win32s. */
6881 PlatformId();
6882 if (g_PlatformId == VER_PLATFORM_WIN32s)
6883 return 0;
6884
6885 /* We need to know the system page size. */
6886 GetSystemInfo(&si);
6887 nPageSize = si.dwPageSize;
6888
6889 /* ...and the current stack pointer */
6890 pStackPtr = (BYTE*)_alloca(1);
6891
6892 /* ...and the base of the stack. */
6893 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6894 return 0;
6895 pStackBase = (BYTE*)mbi.AllocationBase;
6896
6897 /* ...and the page thats min_stack_req pages away from stack base; this is
6898 * the lowest page we could use. */
6899 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6900 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6901
6902 /* On Win95, we want the next page down from the end of the stack. */
6903 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6904 {
6905 /* Find the page that's only 1 page down from the page that the stack
6906 * ptr is in. */
6907 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6908 / (DWORD)nPageSize) - 1));
6909 if (pGuardPage < pLowestPossiblePage)
6910 return 0;
6911
6912 /* Apply the noaccess attribute to the page -- there's no guard
6913 * attribute in win95-type OSes. */
6914 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6915 return 0;
6916 }
6917 else
6918 {
6919 /* On NT, however, we want the first committed page in the stack Start
6920 * at the stack base and move forward through memory until we find a
6921 * committed block. */
6922 BYTE *pBlock = pStackBase;
6923
Bram Moolenaara466c992005-07-09 21:03:22 +00006924 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 {
6926 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6927 return 0;
6928
6929 pBlock += mbi.RegionSize;
6930
6931 if (mbi.State & MEM_COMMIT)
6932 break;
6933 }
6934
6935 /* mbi now describes the first committed block in the stack. */
6936 if (mbi.Protect & PAGE_GUARD)
6937 return 1;
6938
6939 /* decide where the guard page should start */
6940 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6941 pGuardPage = pLowestPossiblePage;
6942 else
6943 pGuardPage = (BYTE*)mbi.BaseAddress;
6944
6945 /* allocate the guard page */
6946 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6947 return 0;
6948
6949 /* apply the guard attribute to the page */
6950 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6951 &dummy))
6952 return 0;
6953 }
6954
6955 return 1;
6956}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006957#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006958
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006959
6960#if defined(FEAT_MBYTE) || defined(PROTO)
6961/*
6962 * The command line arguments in UCS2
6963 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006964static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006965static LPWSTR *ArglistW = NULL;
6966static int global_argc = 0;
6967static char **global_argv;
6968
6969static int used_file_argc = 0; /* last argument in global_argv[] used
6970 for the argument list. */
6971static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6972 command line arguments added to
6973 the argument list */
6974static int used_file_count = 0; /* nr of entries in used_file_indexes */
6975static int used_file_literal = FALSE; /* take file names literally */
6976static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006977static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006978static int used_alist_count = 0;
6979
6980
6981/*
6982 * Get the command line arguments. Unicode version.
6983 * Returns argc. Zero when something fails.
6984 */
6985 int
6986get_cmd_argsW(char ***argvp)
6987{
6988 char **argv = NULL;
6989 int argc = 0;
6990 int i;
6991
Bram Moolenaar14993322014-09-09 12:25:33 +02006992 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006993 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6994 if (ArglistW != NULL)
6995 {
6996 argv = malloc((nArgsW + 1) * sizeof(char *));
6997 if (argv != NULL)
6998 {
6999 argc = nArgsW;
7000 argv[argc] = NULL;
7001 for (i = 0; i < argc; ++i)
7002 {
7003 int len;
7004
7005 /* Convert each Unicode argument to the current codepage. */
7006 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007007 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007008 (LPSTR *)&argv[i], &len, 0, 0);
7009 if (argv[i] == NULL)
7010 {
7011 /* Out of memory, clear everything. */
7012 while (i > 0)
7013 free(argv[--i]);
7014 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007015 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007016 argc = 0;
7017 }
7018 }
7019 }
7020 }
7021
7022 global_argc = argc;
7023 global_argv = argv;
7024 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007025 {
7026 if (used_file_indexes != NULL)
7027 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007028 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007029 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007030
7031 if (argvp != NULL)
7032 *argvp = argv;
7033 return argc;
7034}
7035
7036 void
7037free_cmd_argsW(void)
7038{
7039 if (ArglistW != NULL)
7040 {
7041 GlobalFree(ArglistW);
7042 ArglistW = NULL;
7043 }
7044}
7045
7046/*
7047 * Remember "name" is an argument that was added to the argument list.
7048 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7049 * is called.
7050 */
7051 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007052used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007053{
7054 int i;
7055
7056 if (used_file_indexes == NULL)
7057 return;
7058 for (i = used_file_argc + 1; i < global_argc; ++i)
7059 if (STRCMP(global_argv[i], name) == 0)
7060 {
7061 used_file_argc = i;
7062 used_file_indexes[used_file_count++] = i;
7063 break;
7064 }
7065 used_file_literal = literal;
7066 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007067 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007068}
7069
7070/*
7071 * Remember the length of the argument list as it was. If it changes then we
7072 * leave it alone when 'encoding' is set.
7073 */
7074 void
7075set_alist_count(void)
7076{
7077 used_alist_count = GARGCOUNT;
7078}
7079
7080/*
7081 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7082 * has been changed while starting up. Use the UCS-2 command line arguments
7083 * and convert them to 'encoding'.
7084 */
7085 void
7086fix_arg_enc(void)
7087{
7088 int i;
7089 int idx;
7090 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007091 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007092
7093 /* Safety checks:
7094 * - if argument count differs between the wide and non-wide argument
7095 * list, something must be wrong.
7096 * - the file name arguments must have been located.
7097 * - the length of the argument list wasn't changed by the user.
7098 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007099 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007100 || ArglistW == NULL
7101 || used_file_indexes == NULL
7102 || used_file_count == 0
7103 || used_alist_count != GARGCOUNT)
7104 return;
7105
Bram Moolenaar86b68352004-12-27 21:59:20 +00007106 /* Remember the buffer numbers for the arguments. */
7107 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7108 if (fnum_list == NULL)
7109 return; /* out of memory */
7110 for (i = 0; i < GARGCOUNT; ++i)
7111 fnum_list[i] = GARGLIST[i].ae_fnum;
7112
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007113 /* Clear the argument list. Make room for the new arguments. */
7114 alist_clear(&global_alist);
7115 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007116 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007117
7118 for (i = 0; i < used_file_count; ++i)
7119 {
7120 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007121 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007122 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007123 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007124#ifdef FEAT_DIFF
7125 /* When using diff mode may need to concatenate file name to
7126 * directory name. Just like it's done in main(). */
7127 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7128 && !mch_isdir(alist_name(&GARGLIST[0])))
7129 {
7130 char_u *r;
7131
7132 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7133 if (r != NULL)
7134 {
7135 vim_free(str);
7136 str = r;
7137 }
7138 }
7139#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007140 /* Re-use the old buffer by renaming it. When not using literal
7141 * names it's done by alist_expand() below. */
7142 if (used_file_literal)
7143 buf_set_name(fnum_list[i], str);
7144
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007145 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007146 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007147 }
7148
7149 if (!used_file_literal)
7150 {
7151 /* Now expand wildcards in the arguments. */
7152 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7153 * filename characters but are excluded from 'isfname' to make
7154 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7155 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007156 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007157 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7158 }
7159
7160 /* If wildcard expansion failed, we are editing the first file of the
7161 * arglist and there is no file name: Edit the first argument now. */
7162 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7163 {
7164 do_cmdline_cmd((char_u *)":rewind");
7165 if (GARGCOUNT == 1 && used_file_full_path)
7166 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7167 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007168
7169 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007170}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171#endif