blob: 2773953a6bb273448e5388085d84bca4ecd5ab52 [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{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200580 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200581}
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' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 {
2066 char_u vimrun_location[_MAX_PATH + 4];
2067
2068 /* First try in same directory as gvim.exe */
2069 STRCPY(vimrun_location, exe_name);
2070 STRCPY(gettail(vimrun_location), "vimrun.exe");
2071 if (mch_getperm(vimrun_location) >= 0)
2072 {
2073 if (*skiptowhite(vimrun_location) != NUL)
2074 {
2075 /* Enclose path with white space in double quotes. */
2076 mch_memmove(vimrun_location + 1, vimrun_location,
2077 STRLEN(vimrun_location) + 1);
2078 *vimrun_location = '"';
2079 STRCPY(gettail(vimrun_location), "vimrun\" ");
2080 }
2081 else
2082 STRCPY(gettail(vimrun_location), "vimrun ");
2083
2084 vimrun_path = (char *)vim_strsave(vimrun_location);
2085 s_dont_use_vimrun = FALSE;
2086 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002087 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002088 s_dont_use_vimrun = FALSE;
2089
2090 /* Don't give the warning for a missing vimrun.exe right now, but only
2091 * when vimrun was supposed to be used. Don't bother people that do
2092 * not need vimrun.exe. */
2093 if (s_dont_use_vimrun)
2094 need_vimrun_warning = TRUE;
2095 }
2096
2097 /*
2098 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2099 * Otherwise the default "findstr /n" is used.
2100 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002101 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002102 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2103
2104#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002105 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106#endif
2107}
2108
2109
2110#else /* FEAT_GUI_W32 */
2111
2112#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2113#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2114
2115/*
2116 * ClearConsoleBuffer()
2117 * Description:
2118 * Clears the entire contents of the console screen buffer, using the
2119 * specified attribute.
2120 * Returns:
2121 * TRUE on success
2122 */
2123 static BOOL
2124ClearConsoleBuffer(WORD wAttribute)
2125{
2126 CONSOLE_SCREEN_BUFFER_INFO csbi;
2127 COORD coord;
2128 DWORD NumCells, dummy;
2129
2130 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2131 return FALSE;
2132
2133 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2134 coord.X = 0;
2135 coord.Y = 0;
2136 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2137 coord, &dummy))
2138 {
2139 return FALSE;
2140 }
2141 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2142 coord, &dummy))
2143 {
2144 return FALSE;
2145 }
2146
2147 return TRUE;
2148}
2149
2150/*
2151 * FitConsoleWindow()
2152 * Description:
2153 * Checks if the console window will fit within given buffer dimensions.
2154 * Also, if requested, will shrink the window to fit.
2155 * Returns:
2156 * TRUE on success
2157 */
2158 static BOOL
2159FitConsoleWindow(
2160 COORD dwBufferSize,
2161 BOOL WantAdjust)
2162{
2163 CONSOLE_SCREEN_BUFFER_INFO csbi;
2164 COORD dwWindowSize;
2165 BOOL NeedAdjust = FALSE;
2166
2167 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2168 {
2169 /*
2170 * A buffer resize will fail if the current console window does
2171 * not lie completely within that buffer. To avoid this, we might
2172 * have to move and possibly shrink the window.
2173 */
2174 if (csbi.srWindow.Right >= dwBufferSize.X)
2175 {
2176 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2177 if (dwWindowSize.X > dwBufferSize.X)
2178 dwWindowSize.X = dwBufferSize.X;
2179 csbi.srWindow.Right = dwBufferSize.X - 1;
2180 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2181 NeedAdjust = TRUE;
2182 }
2183 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2184 {
2185 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2186 if (dwWindowSize.Y > dwBufferSize.Y)
2187 dwWindowSize.Y = dwBufferSize.Y;
2188 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2189 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2190 NeedAdjust = TRUE;
2191 }
2192 if (NeedAdjust && WantAdjust)
2193 {
2194 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2195 return FALSE;
2196 }
2197 return TRUE;
2198 }
2199
2200 return FALSE;
2201}
2202
2203typedef struct ConsoleBufferStruct
2204{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002205 BOOL IsValid;
2206 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002207 PCHAR_INFO Buffer;
2208 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209} ConsoleBuffer;
2210
2211/*
2212 * SaveConsoleBuffer()
2213 * Description:
2214 * Saves important information about the console buffer, including the
2215 * actual buffer contents. The saved information is suitable for later
2216 * restoration by RestoreConsoleBuffer().
2217 * Returns:
2218 * TRUE if all information was saved; FALSE otherwise
2219 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2220 */
2221 static BOOL
2222SaveConsoleBuffer(
2223 ConsoleBuffer *cb)
2224{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002225 DWORD NumCells;
2226 COORD BufferCoord;
2227 SMALL_RECT ReadRegion;
2228 WORD Y, Y_incr;
2229
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 if (cb == NULL)
2231 return FALSE;
2232
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002233 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002234 {
2235 cb->IsValid = FALSE;
2236 return FALSE;
2237 }
2238 cb->IsValid = TRUE;
2239
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002240 /*
2241 * Allocate a buffer large enough to hold the entire console screen
2242 * buffer. If this ConsoleBuffer structure has already been initialized
2243 * with a buffer of the correct size, then just use that one.
2244 */
2245 if (!cb->IsValid || cb->Buffer == NULL ||
2246 cb->BufferSize.X != cb->Info.dwSize.X ||
2247 cb->BufferSize.Y != cb->Info.dwSize.Y)
2248 {
2249 cb->BufferSize.X = cb->Info.dwSize.X;
2250 cb->BufferSize.Y = cb->Info.dwSize.Y;
2251 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2252 vim_free(cb->Buffer);
2253 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2254 if (cb->Buffer == NULL)
2255 return FALSE;
2256 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257
2258 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002259 * We will now copy the console screen buffer into our buffer.
2260 * ReadConsoleOutput() seems to be limited as far as how much you
2261 * can read at a time. Empirically, this number seems to be about
2262 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2263 * in chunks until it is all copied. The chunks will all have the
2264 * same horizontal characteristics, so initialize them now. The
2265 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002267 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002268 ReadRegion.Left = 0;
2269 ReadRegion.Right = cb->Info.dwSize.X - 1;
2270 Y_incr = 12000 / cb->Info.dwSize.X;
2271 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002272 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002273 /*
2274 * Read into position (0, Y) in our buffer.
2275 */
2276 BufferCoord.Y = Y;
2277 /*
2278 * Read the region whose top left corner is (0, Y) and whose bottom
2279 * right corner is (width - 1, Y + Y_incr - 1). This should define
2280 * a region of size width by Y_incr. Don't worry if this region is
2281 * too large for the remaining buffer; it will be cropped.
2282 */
2283 ReadRegion.Top = Y;
2284 ReadRegion.Bottom = Y + Y_incr - 1;
2285 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2286 cb->Buffer, /* our buffer */
2287 cb->BufferSize, /* dimensions of our buffer */
2288 BufferCoord, /* offset in our buffer */
2289 &ReadRegion)) /* region to save */
2290 {
2291 vim_free(cb->Buffer);
2292 cb->Buffer = NULL;
2293 return FALSE;
2294 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002295 }
2296
2297 return TRUE;
2298}
2299
2300/*
2301 * RestoreConsoleBuffer()
2302 * Description:
2303 * Restores important information about the console buffer, including the
2304 * actual buffer contents, if desired. The information to restore is in
2305 * the same format used by SaveConsoleBuffer().
2306 * Returns:
2307 * TRUE on success
2308 */
2309 static BOOL
2310RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002311 ConsoleBuffer *cb,
2312 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002314 COORD BufferCoord;
2315 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316
2317 if (cb == NULL || !cb->IsValid)
2318 return FALSE;
2319
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002320 /*
2321 * Before restoring the buffer contents, clear the current buffer, and
2322 * restore the cursor position and window information. Doing this now
2323 * prevents old buffer contents from "flashing" onto the screen.
2324 */
2325 if (RestoreScreen)
2326 ClearConsoleBuffer(cb->Info.wAttributes);
2327
2328 FitConsoleWindow(cb->Info.dwSize, TRUE);
2329 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2330 return FALSE;
2331 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2332 return FALSE;
2333
2334 if (!RestoreScreen)
2335 {
2336 /*
2337 * No need to restore the screen buffer contents, so we're done.
2338 */
2339 return TRUE;
2340 }
2341
2342 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2343 return FALSE;
2344 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2345 return FALSE;
2346
2347 /*
2348 * Restore the screen buffer contents.
2349 */
2350 if (cb->Buffer != NULL)
2351 {
2352 BufferCoord.X = 0;
2353 BufferCoord.Y = 0;
2354 WriteRegion.Left = 0;
2355 WriteRegion.Top = 0;
2356 WriteRegion.Right = cb->Info.dwSize.X - 1;
2357 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2358 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2359 cb->Buffer, /* our buffer */
2360 cb->BufferSize, /* dimensions of our buffer */
2361 BufferCoord, /* offset in our buffer */
2362 &WriteRegion)) /* region to restore */
2363 {
2364 return FALSE;
2365 }
2366 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367
2368 return TRUE;
2369}
2370
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002371#define FEAT_RESTORE_ORIG_SCREEN
2372#ifdef FEAT_RESTORE_ORIG_SCREEN
2373static ConsoleBuffer g_cbOrig = { 0 };
2374#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375static ConsoleBuffer g_cbNonTermcap = { 0 };
2376static ConsoleBuffer g_cbTermcap = { 0 };
2377
2378#ifdef FEAT_TITLE
2379#ifdef __BORLANDC__
2380typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2381#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002382typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383#endif
2384char g_szOrigTitle[256] = { 0 };
2385HWND g_hWnd = NULL; /* also used in os_mswin.c */
2386static HICON g_hOrigIconSmall = NULL;
2387static HICON g_hOrigIcon = NULL;
2388static HICON g_hVimIcon = NULL;
2389static BOOL g_fCanChangeIcon = FALSE;
2390
2391/* ICON* are not defined in VC++ 4.0 */
2392#ifndef ICON_SMALL
2393#define ICON_SMALL 0
2394#endif
2395#ifndef ICON_BIG
2396#define ICON_BIG 1
2397#endif
2398/*
2399 * GetConsoleIcon()
2400 * Description:
2401 * Attempts to retrieve the small icon and/or the big icon currently in
2402 * use by a given window.
2403 * Returns:
2404 * TRUE on success
2405 */
2406 static BOOL
2407GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002408 HWND hWnd,
2409 HICON *phIconSmall,
2410 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411{
2412 if (hWnd == NULL)
2413 return FALSE;
2414
2415 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002416 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2417 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002419 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2420 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421 return TRUE;
2422}
2423
2424/*
2425 * SetConsoleIcon()
2426 * Description:
2427 * Attempts to change the small icon and/or the big icon currently in
2428 * use by a given window.
2429 * Returns:
2430 * TRUE on success
2431 */
2432 static BOOL
2433SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002434 HWND hWnd,
2435 HICON hIconSmall,
2436 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438 if (hWnd == NULL)
2439 return FALSE;
2440
2441 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002442 SendMessage(hWnd, WM_SETICON,
2443 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002445 SendMessage(hWnd, WM_SETICON,
2446 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447 return TRUE;
2448}
2449
2450/*
2451 * SaveConsoleTitleAndIcon()
2452 * Description:
2453 * Saves the current console window title in g_szOrigTitle, for later
2454 * restoration. Also, attempts to obtain a handle to the console window,
2455 * and use it to save the small and big icons currently in use by the
2456 * console window. This is not always possible on some versions of Windows;
2457 * nor is it possible when running Vim remotely using Telnet (since the
2458 * console window the user sees is owned by a remote process).
2459 */
2460 static void
2461SaveConsoleTitleAndIcon(void)
2462{
2463 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2464
2465 /* Save the original title. */
2466 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2467 return;
2468
2469 /*
2470 * Obtain a handle to the console window using GetConsoleWindow() from
2471 * KERNEL32.DLL; we need to handle in order to change the window icon.
2472 * This function only exists on NT-based Windows, starting with Windows
2473 * 2000. On older operating systems, we can't change the window icon
2474 * anyway.
2475 */
2476 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2477 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2478 "GetConsoleWindow")) != NULL)
2479 {
2480 g_hWnd = (*GetConsoleWindowProc)();
2481 }
2482 if (g_hWnd == NULL)
2483 return;
2484
2485 /* Save the original console window icon. */
2486 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2487 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2488 return;
2489
2490 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002491 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002492 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 if (g_hVimIcon != NULL)
2494 g_fCanChangeIcon = TRUE;
2495}
2496#endif
2497
2498static int g_fWindInitCalled = FALSE;
2499static int g_fTermcapMode = FALSE;
2500static CONSOLE_CURSOR_INFO g_cci;
2501static DWORD g_cmodein = 0;
2502static DWORD g_cmodeout = 0;
2503
2504/*
2505 * non-GUI version of mch_init().
2506 */
2507 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002508mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002510#ifndef FEAT_RESTORE_ORIG_SCREEN
2511 CONSOLE_SCREEN_BUFFER_INFO csbi;
2512#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513#ifndef __MINGW32__
2514 extern int _fmode;
2515#endif
2516
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002517 /* Silently handle invalid parameters to CRT functions */
2518 SET_INVALID_PARAM_HANDLER;
2519
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 /* Let critical errors result in a failure, not in a dialog box. Required
2521 * for the timestamp test to work on removed floppies. */
2522 SetErrorMode(SEM_FAILCRITICALERRORS);
2523
2524 _fmode = O_BINARY; /* we do our own CR-LF translation */
2525 out_flush();
2526
2527 /* Obtain handles for the standard Console I/O devices */
2528 if (read_cmd_fd == 0)
2529 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2530 else
2531 create_conin();
2532 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2533
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002534#ifdef FEAT_RESTORE_ORIG_SCREEN
2535 /* Save the initial console buffer for later restoration */
2536 SaveConsoleBuffer(&g_cbOrig);
2537 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2538#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002540 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2541 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2542#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 if (cterm_normal_fg_color == 0)
2544 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2545 if (cterm_normal_bg_color == 0)
2546 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2547
2548 /* set termcap codes to current text attributes */
2549 update_tcap(g_attrCurrent);
2550
2551 GetConsoleCursorInfo(g_hConOut, &g_cci);
2552 GetConsoleMode(g_hConIn, &g_cmodein);
2553 GetConsoleMode(g_hConOut, &g_cmodeout);
2554
2555#ifdef FEAT_TITLE
2556 SaveConsoleTitleAndIcon();
2557 /*
2558 * Set both the small and big icons of the console window to Vim's icon.
2559 * Note that Vim presently only has one size of icon (32x32), but it
2560 * automatically gets scaled down to 16x16 when setting the small icon.
2561 */
2562 if (g_fCanChangeIcon)
2563 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2564#endif
2565
2566 ui_get_shellsize();
2567
2568#ifdef MCH_WRITE_DUMP
2569 fdDump = fopen("dump", "wt");
2570
2571 if (fdDump)
2572 {
2573 time_t t;
2574
2575 time(&t);
2576 fputs(ctime(&t), fdDump);
2577 fflush(fdDump);
2578 }
2579#endif
2580
2581 g_fWindInitCalled = TRUE;
2582
2583#ifdef FEAT_MOUSE
2584 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2585#endif
2586
2587#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002588 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589#endif
2590
2591 /* This will be NULL on anything but NT 4.0 */
2592 s_pfnGetConsoleKeyboardLayoutName =
2593 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2594 "GetConsoleKeyboardLayoutNameA");
2595}
2596
2597/*
2598 * non-GUI version of mch_exit().
2599 * Shut down and exit with status `r'
2600 * Careful: mch_exit() may be called before mch_init()!
2601 */
2602 void
2603mch_exit(int r)
2604{
2605 stoptermcap();
2606
2607 if (g_fWindInitCalled)
2608 settmode(TMODE_COOK);
2609
2610 ml_close_all(TRUE); /* remove all memfiles */
2611
2612 if (g_fWindInitCalled)
2613 {
2614#ifdef FEAT_TITLE
2615 mch_restore_title(3);
2616 /*
2617 * Restore both the small and big icons of the console window to
2618 * what they were at startup. Don't do this when the window is
2619 * closed, Vim would hang here.
2620 */
2621 if (g_fCanChangeIcon && !g_fForceExit)
2622 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2623#endif
2624
2625#ifdef MCH_WRITE_DUMP
2626 if (fdDump)
2627 {
2628 time_t t;
2629
2630 time(&t);
2631 fputs(ctime(&t), fdDump);
2632 fclose(fdDump);
2633 }
2634 fdDump = NULL;
2635#endif
2636 }
2637
2638 SetConsoleCursorInfo(g_hConOut, &g_cci);
2639 SetConsoleMode(g_hConIn, g_cmodein);
2640 SetConsoleMode(g_hConOut, g_cmodeout);
2641
2642#ifdef DYNAMIC_GETTEXT
2643 dyn_libintl_end();
2644#endif
2645
2646 exit(r);
2647}
2648#endif /* !FEAT_GUI_W32 */
2649
Bram Moolenaar071d4272004-06-13 20:20:40 +00002650/*
2651 * Do we have an interactive window?
2652 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002653/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002654 int
2655mch_check_win(
2656 int argc,
2657 char **argv)
2658{
2659 get_exe_name();
2660
2661#ifdef FEAT_GUI_W32
2662 return OK; /* GUI always has a tty */
2663#else
2664 if (isatty(1))
2665 return OK;
2666 return FAIL;
2667#endif
2668}
2669
2670
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002671#ifdef FEAT_MBYTE
2672/*
2673 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2674 * if it already exists. When "len" is > 0, also expand short to long
2675 * filenames.
2676 * Return FAIL if wide functions are not available, OK otherwise.
2677 * NOTE: much of this is identical to fname_case(), keep in sync!
2678 */
2679 static int
2680fname_casew(
2681 WCHAR *name,
2682 int len)
2683{
2684 WCHAR szTrueName[_MAX_PATH + 2];
2685 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2686 WCHAR *ptrue, *ptruePrev;
2687 WCHAR *porig, *porigPrev;
2688 int flen;
2689 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002690 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002691 int c;
2692 int slen;
2693
2694 flen = (int)wcslen(name);
2695 if (flen > _MAX_PATH)
2696 return OK;
2697
2698 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2699
2700 /* Build the new name in szTrueName[] one component at a time. */
2701 porig = name;
2702 ptrue = szTrueName;
2703
2704 if (iswalpha(porig[0]) && porig[1] == L':')
2705 {
2706 /* copy leading drive letter */
2707 *ptrue++ = *porig++;
2708 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002709 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002710 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002711
2712 while (*porig != NUL)
2713 {
2714 /* copy \ characters */
2715 while (*porig == psepc)
2716 *ptrue++ = *porig++;
2717
2718 ptruePrev = ptrue;
2719 porigPrev = porig;
2720 while (*porig != NUL && *porig != psepc)
2721 {
2722 *ptrue++ = *porig++;
2723 }
2724 *ptrue = NUL;
2725
2726 /* To avoid a slow failure append "\*" when searching a directory,
2727 * server or network share. */
2728 wcscpy(szTrueNameTemp, szTrueName);
2729 slen = (int)wcslen(szTrueNameTemp);
2730 if (*porig == psepc && slen + 2 < _MAX_PATH)
2731 wcscpy(szTrueNameTemp + slen, L"\\*");
2732
2733 /* Skip "", "." and "..". */
2734 if (ptrue > ptruePrev
2735 && (ptruePrev[0] != L'.'
2736 || (ptruePrev[1] != NUL
2737 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2738 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2739 != INVALID_HANDLE_VALUE)
2740 {
2741 c = *porig;
2742 *porig = NUL;
2743
2744 /* Only use the match when it's the same name (ignoring case) or
2745 * expansion is allowed and there is a match with the short name
2746 * and there is enough room. */
2747 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2748 || (len > 0
2749 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2750 && (int)(ptruePrev - szTrueName)
2751 + (int)wcslen(fb.cFileName) < len)))
2752 {
2753 wcscpy(ptruePrev, fb.cFileName);
2754
2755 /* Look for exact match and prefer it if found. Must be a
2756 * long name, otherwise there would be only one match. */
2757 while (FindNextFileW(hFind, &fb))
2758 {
2759 if (*fb.cAlternateFileName != NUL
2760 && (wcscoll(porigPrev, fb.cFileName) == 0
2761 || (len > 0
2762 && (_wcsicoll(porigPrev,
2763 fb.cAlternateFileName) == 0
2764 && (int)(ptruePrev - szTrueName)
2765 + (int)wcslen(fb.cFileName) < len))))
2766 {
2767 wcscpy(ptruePrev, fb.cFileName);
2768 break;
2769 }
2770 }
2771 }
2772 FindClose(hFind);
2773 *porig = c;
2774 ptrue = ptruePrev + wcslen(ptruePrev);
2775 }
2776 else if (hFind == INVALID_HANDLE_VALUE
2777 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2778 return FAIL;
2779 }
2780
2781 wcscpy(name, szTrueName);
2782 return OK;
2783}
2784#endif
2785
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786/*
2787 * fname_case(): Set the case of the file name, if it already exists.
2788 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002789 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790 */
2791 void
2792fname_case(
2793 char_u *name,
2794 int len)
2795{
2796 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002797 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002798 char *ptrue, *ptruePrev;
2799 char *porig, *porigPrev;
2800 int flen;
2801 WIN32_FIND_DATA fb;
2802 HANDLE hFind;
2803 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002804 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002806 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002807 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002808 return;
2809
2810 slash_adjust(name);
2811
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002812#ifdef FEAT_MBYTE
2813 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2814 {
2815 WCHAR *p = enc_to_utf16(name, NULL);
2816
2817 if (p != NULL)
2818 {
2819 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002820 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002821
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002822 wcsncpy(buf, p, _MAX_PATH);
2823 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002824 vim_free(p);
2825
2826 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2827 {
2828 q = utf16_to_enc(buf, NULL);
2829 if (q != NULL)
2830 {
2831 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2832 vim_free(q);
2833 return;
2834 }
2835 }
2836 }
2837 /* Retry with non-wide function (for Windows 98). */
2838 }
2839#endif
2840
2841 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2842 * So we should check this after calling wide function. */
2843 if (flen > _MAX_PATH)
2844 return;
2845
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002847 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848 ptrue = szTrueName;
2849
2850 if (isalpha(porig[0]) && porig[1] == ':')
2851 {
2852 /* copy leading drive letter */
2853 *ptrue++ = *porig++;
2854 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002855 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002856 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857
2858 while (*porig != NUL)
2859 {
2860 /* copy \ characters */
2861 while (*porig == psepc)
2862 *ptrue++ = *porig++;
2863
2864 ptruePrev = ptrue;
2865 porigPrev = porig;
2866 while (*porig != NUL && *porig != psepc)
2867 {
2868#ifdef FEAT_MBYTE
2869 int l;
2870
2871 if (enc_dbcs)
2872 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002873 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874 while (--l >= 0)
2875 *ptrue++ = *porig++;
2876 }
2877 else
2878#endif
2879 *ptrue++ = *porig++;
2880 }
2881 *ptrue = NUL;
2882
Bram Moolenaar464c9252010-10-13 20:37:41 +02002883 /* To avoid a slow failure append "\*" when searching a directory,
2884 * server or network share. */
2885 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002886 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002887 if (*porig == psepc && slen + 2 < _MAX_PATH)
2888 STRCPY(szTrueNameTemp + slen, "\\*");
2889
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 /* Skip "", "." and "..". */
2891 if (ptrue > ptruePrev
2892 && (ptruePrev[0] != '.'
2893 || (ptruePrev[1] != NUL
2894 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002895 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 != INVALID_HANDLE_VALUE)
2897 {
2898 c = *porig;
2899 *porig = NUL;
2900
2901 /* Only use the match when it's the same name (ignoring case) or
2902 * expansion is allowed and there is a match with the short name
2903 * and there is enough room. */
2904 if (_stricoll(porigPrev, fb.cFileName) == 0
2905 || (len > 0
2906 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2907 && (int)(ptruePrev - szTrueName)
2908 + (int)strlen(fb.cFileName) < len)))
2909 {
2910 STRCPY(ptruePrev, fb.cFileName);
2911
2912 /* Look for exact match and prefer it if found. Must be a
2913 * long name, otherwise there would be only one match. */
2914 while (FindNextFile(hFind, &fb))
2915 {
2916 if (*fb.cAlternateFileName != NUL
2917 && (strcoll(porigPrev, fb.cFileName) == 0
2918 || (len > 0
2919 && (_stricoll(porigPrev,
2920 fb.cAlternateFileName) == 0
2921 && (int)(ptruePrev - szTrueName)
2922 + (int)strlen(fb.cFileName) < len))))
2923 {
2924 STRCPY(ptruePrev, fb.cFileName);
2925 break;
2926 }
2927 }
2928 }
2929 FindClose(hFind);
2930 *porig = c;
2931 ptrue = ptruePrev + strlen(ptruePrev);
2932 }
2933 }
2934
2935 STRCPY(name, szTrueName);
2936}
2937
2938
2939/*
2940 * Insert user name in s[len].
2941 */
2942 int
2943mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002944 char_u *s,
2945 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002947 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948 DWORD cch = sizeof szUserName;
2949
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002950#ifdef FEAT_MBYTE
2951 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2952 {
2953 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2954 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2955
2956 if (GetUserNameW(wszUserName, &wcch))
2957 {
2958 char_u *p = utf16_to_enc(wszUserName, NULL);
2959
2960 if (p != NULL)
2961 {
2962 vim_strncpy(s, p, len - 1);
2963 vim_free(p);
2964 return OK;
2965 }
2966 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002967 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2968 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002969 /* Retry with non-wide function (for Windows 98). */
2970 }
2971#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972 if (GetUserName(szUserName, &cch))
2973 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002974 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975 return OK;
2976 }
2977 s[0] = NUL;
2978 return FAIL;
2979}
2980
2981
2982/*
2983 * Insert host name in s[len].
2984 */
2985 void
2986mch_get_host_name(
2987 char_u *s,
2988 int len)
2989{
2990 DWORD cch = len;
2991
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002992#ifdef FEAT_MBYTE
2993 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2994 {
2995 WCHAR wszHostName[256 + 1];
2996 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2997
2998 if (GetComputerNameW(wszHostName, &wcch))
2999 {
3000 char_u *p = utf16_to_enc(wszHostName, NULL);
3001
3002 if (p != NULL)
3003 {
3004 vim_strncpy(s, p, len - 1);
3005 vim_free(p);
3006 return;
3007 }
3008 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003009 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3010 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003011 /* Retry with non-wide function (for Windows 98). */
3012 }
3013#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003014 if (!GetComputerName((LPSTR)s, &cch))
3015 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016}
3017
3018
3019/*
3020 * return process ID
3021 */
3022 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003023mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024{
3025 return (long)GetCurrentProcessId();
3026}
3027
3028
3029/*
3030 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3031 * Return OK for success, FAIL for failure.
3032 */
3033 int
3034mch_dirname(
3035 char_u *buf,
3036 int len)
3037{
3038 /*
3039 * Originally this was:
3040 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3041 * But the Win32s known bug list says that getcwd() doesn't work
3042 * so use the Win32 system call instead. <Negri>
3043 */
3044#ifdef FEAT_MBYTE
3045 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3046 {
3047 WCHAR wbuf[_MAX_PATH + 1];
3048
3049 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3050 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003051 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052
3053 if (p != NULL)
3054 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003055 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056 vim_free(p);
3057 return OK;
3058 }
3059 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003060 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3061 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062 /* Retry with non-wide function (for Windows 98). */
3063 }
3064#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003065 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066}
3067
3068/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003069 * Get file permissions for "name".
3070 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 */
3072 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003073mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003075 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003076 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003078 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003079 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080}
3081
3082
3083/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003084 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003085 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003086 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087 */
3088 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003089mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003091 long n = -1;
3092
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093#ifdef FEAT_MBYTE
3094 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3095 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003096 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097
3098 if (p != NULL)
3099 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003100 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003102 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003103 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104 /* Retry with non-wide function (for Windows 98). */
3105 }
3106 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003107 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003109 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003110 if (n == -1)
3111 return FAIL;
3112
3113 win32_set_archive(name);
3114
3115 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116}
3117
3118/*
3119 * Set hidden flag for "name".
3120 */
3121 void
3122mch_hide(char_u *name)
3123{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003124 int attrs = win32_getattrs(name);
3125 if (attrs == -1)
3126 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003128 attrs |= FILE_ATTRIBUTE_HIDDEN;
3129 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130}
3131
3132/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003133 * Return TRUE if file "name" exists and is hidden.
3134 */
3135 int
3136mch_ishidden(char_u *name)
3137{
3138 int f = win32_getattrs(name);
3139
3140 if (f == -1)
3141 return FALSE; /* file does not exist at all */
3142
3143 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3144}
3145
3146/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147 * return TRUE if "name" is a directory
3148 * return FALSE if "name" is not a directory or upon error
3149 */
3150 int
3151mch_isdir(char_u *name)
3152{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003153 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154
3155 if (f == -1)
3156 return FALSE; /* file does not exist at all */
3157
3158 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3159}
3160
3161/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003162 * return TRUE if "name" is a directory, NOT a symlink to a directory
3163 * return FALSE if "name" is not a directory
3164 * return FALSE for error
3165 */
3166 int
3167mch_isrealdir(char_u *name)
3168{
3169 return mch_isdir(name) && !mch_is_symbolic_link(name);
3170}
3171
3172/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003173 * Create directory "name".
3174 * Return 0 on success, -1 on error.
3175 */
3176 int
3177mch_mkdir(char_u *name)
3178{
3179#ifdef FEAT_MBYTE
3180 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3181 {
3182 WCHAR *p;
3183 int retval;
3184
3185 p = enc_to_utf16(name, NULL);
3186 if (p == NULL)
3187 return -1;
3188 retval = _wmkdir(p);
3189 vim_free(p);
3190 return retval;
3191 }
3192#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003193 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003194}
3195
3196/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003197 * Delete directory "name".
3198 * Return 0 on success, -1 on error.
3199 */
3200 int
3201mch_rmdir(char_u *name)
3202{
3203#ifdef FEAT_MBYTE
3204 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3205 {
3206 WCHAR *p;
3207 int retval;
3208
3209 p = enc_to_utf16(name, NULL);
3210 if (p == NULL)
3211 return -1;
3212 retval = _wrmdir(p);
3213 vim_free(p);
3214 return retval;
3215 }
3216#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003217 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003218}
3219
3220/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003221 * Return TRUE if file "fname" has more than one link.
3222 */
3223 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003224mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003225{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003226 BY_HANDLE_FILE_INFORMATION info;
3227
3228 return win32_fileinfo(fname, &info) == FILEINFO_OK
3229 && info.nNumberOfLinks > 1;
3230}
3231
3232/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003233 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003234 */
3235 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003236mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003237{
3238 HANDLE hFind;
3239 int res = FALSE;
3240 WIN32_FIND_DATAA findDataA;
3241 DWORD fileFlags = 0, reparseTag = 0;
3242#ifdef FEAT_MBYTE
3243 WCHAR *wn = NULL;
3244 WIN32_FIND_DATAW findDataW;
3245
3246 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003247 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003248 if (wn != NULL)
3249 {
3250 hFind = FindFirstFileW(wn, &findDataW);
3251 vim_free(wn);
3252 if (hFind == INVALID_HANDLE_VALUE
3253 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3254 {
3255 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003256 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003257 if (hFind != INVALID_HANDLE_VALUE)
3258 {
3259 fileFlags = findDataA.dwFileAttributes;
3260 reparseTag = findDataA.dwReserved0;
3261 }
3262 }
3263 else
3264 {
3265 fileFlags = findDataW.dwFileAttributes;
3266 reparseTag = findDataW.dwReserved0;
3267 }
3268 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003269 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003270#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003271 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003272 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003273 if (hFind != INVALID_HANDLE_VALUE)
3274 {
3275 fileFlags = findDataA.dwFileAttributes;
3276 reparseTag = findDataA.dwReserved0;
3277 }
3278 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003279
3280 if (hFind != INVALID_HANDLE_VALUE)
3281 FindClose(hFind);
3282
3283 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003284 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3285 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003286 res = TRUE;
3287
3288 return res;
3289}
3290
3291/*
3292 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3293 * link.
3294 */
3295 int
3296mch_is_linked(char_u *fname)
3297{
3298 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3299 return TRUE;
3300 return FALSE;
3301}
3302
3303/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003304 * Get the by-handle-file-information for "fname".
3305 * Returns FILEINFO_OK when OK.
3306 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3307 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3308 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3309 */
3310 int
3311win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3312{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003313 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003314 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003315#ifdef FEAT_MBYTE
3316 WCHAR *wn = NULL;
3317
3318 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003319 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003320 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003321 if (wn == NULL)
3322 res = FILEINFO_ENC_FAIL;
3323 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003324 if (wn != NULL)
3325 {
3326 hFile = CreateFileW(wn, /* file name */
3327 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003328 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003329 NULL, /* security descriptor */
3330 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003331 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003332 NULL); /* handle to template file */
3333 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003334 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003335 {
3336 /* Retry with non-wide function (for Windows 98). */
3337 vim_free(wn);
3338 wn = NULL;
3339 }
3340 }
3341 if (wn == NULL)
3342#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003343 hFile = CreateFile((LPCSTR)fname, /* file name */
3344 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003345 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003346 NULL, /* security descriptor */
3347 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003348 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003349 NULL); /* handle to template file */
3350
3351 if (hFile != INVALID_HANDLE_VALUE)
3352 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003353 if (GetFileInformationByHandle(hFile, info) != 0)
3354 res = FILEINFO_OK;
3355 else
3356 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003357 CloseHandle(hFile);
3358 }
3359
3360#ifdef FEAT_MBYTE
3361 vim_free(wn);
3362#endif
3363 return res;
3364}
3365
3366/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003367 * get file attributes for `name'
3368 * -1 : error
3369 * else FILE_ATTRIBUTE_* defined in winnt.h
3370 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003371 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003372win32_getattrs(char_u *name)
3373{
3374 int attr;
3375#ifdef FEAT_MBYTE
3376 WCHAR *p = NULL;
3377
3378 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3379 p = enc_to_utf16(name, NULL);
3380
3381 if (p != NULL)
3382 {
3383 attr = GetFileAttributesW(p);
3384 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3385 {
3386 /* Retry with non-wide function (for Windows 98). */
3387 vim_free(p);
3388 p = NULL;
3389 }
3390 }
3391 if (p == NULL)
3392#endif
3393 attr = GetFileAttributes((char *)name);
3394#ifdef FEAT_MBYTE
3395 vim_free(p);
3396#endif
3397 return attr;
3398}
3399
3400/*
3401 * set file attributes for `name' to `attrs'
3402 *
3403 * return -1 for failure, 0 otherwise
3404 */
3405 static
3406 int
3407win32_setattrs(char_u *name, int attrs)
3408{
3409 int res;
3410#ifdef FEAT_MBYTE
3411 WCHAR *p = NULL;
3412
3413 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3414 p = enc_to_utf16(name, NULL);
3415
3416 if (p != NULL)
3417 {
3418 res = SetFileAttributesW(p, attrs);
3419 if (res == FALSE
3420 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3421 {
3422 /* Retry with non-wide function (for Windows 98). */
3423 vim_free(p);
3424 p = NULL;
3425 }
3426 }
3427 if (p == NULL)
3428#endif
3429 res = SetFileAttributes((char *)name, attrs);
3430#ifdef FEAT_MBYTE
3431 vim_free(p);
3432#endif
3433 return res ? 0 : -1;
3434}
3435
3436/*
3437 * Set archive flag for "name".
3438 */
3439 static
3440 int
3441win32_set_archive(char_u *name)
3442{
3443 int attrs = win32_getattrs(name);
3444 if (attrs == -1)
3445 return -1;
3446
3447 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3448 return win32_setattrs(name, attrs);
3449}
3450
3451/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003452 * Return TRUE if file or directory "name" is writable (not readonly).
3453 * Strange semantics of Win32: a readonly directory is writable, but you can't
3454 * delete a file. Let's say this means it is writable.
3455 */
3456 int
3457mch_writable(char_u *name)
3458{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003459 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003461 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3462 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463}
3464
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465/*
3466 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003467 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003468 * Return -1 if unknown.
3469 */
3470 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003471mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003473 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003474 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003475 char_u *p;
3476
3477 if (len >= _MAX_PATH) /* safety check */
3478 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003479 if (!use_path)
3480 {
3481 /* TODO: check if file is really executable. */
3482 return mch_getperm(name) != -1 && !mch_isdir(name);
3483 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003484
3485 /* If there already is an extension try using the name directly. Also do
3486 * this with a Unix-shell like 'shell'. */
3487 if (vim_strchr(gettail(name), '.') != NULL
3488 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003489 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003490 return TRUE;
3491
3492 /*
3493 * Loop over all extensions in $PATHEXT.
3494 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003495 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003496 p = mch_getenv("PATHEXT");
3497 if (p == NULL)
3498 p = (char_u *)".com;.exe;.bat;.cmd";
3499 while (*p)
3500 {
3501 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3502 {
3503 /* A single "." means no extension is added. */
3504 buf[len] = NUL;
3505 ++p;
3506 if (*p)
3507 ++p;
3508 }
3509 else
3510 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003511 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003512 return TRUE;
3513 }
3514 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516
3517/*
3518 * Check what "name" is:
3519 * NODE_NORMAL: file or directory (or doesn't exist)
3520 * NODE_WRITABLE: writable device, socket, fifo, etc.
3521 * NODE_OTHER: non-writable things
3522 */
3523 int
3524mch_nodetype(char_u *name)
3525{
3526 HANDLE hFile;
3527 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003528#ifdef FEAT_MBYTE
3529 WCHAR *wn = NULL;
3530#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003531
Bram Moolenaar043545e2006-10-10 16:44:07 +00003532 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3533 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3534 * here. */
3535 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3536 return NODE_WRITABLE;
3537
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003538#ifdef FEAT_MBYTE
3539 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3540 {
3541 wn = enc_to_utf16(name, NULL);
3542 if (wn != NULL)
3543 {
3544 hFile = CreateFileW(wn, /* file name */
3545 GENERIC_WRITE, /* access mode */
3546 0, /* share mode */
3547 NULL, /* security descriptor */
3548 OPEN_EXISTING, /* creation disposition */
3549 0, /* file attributes */
3550 NULL); /* handle to template file */
3551 if (hFile == INVALID_HANDLE_VALUE
3552 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3553 {
3554 /* Retry with non-wide function (for Windows 98). */
3555 vim_free(wn);
3556 wn = NULL;
3557 }
3558 }
3559 }
3560 if (wn == NULL)
3561#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003562 hFile = CreateFile((LPCSTR)name, /* file name */
3563 GENERIC_WRITE, /* access mode */
3564 0, /* share mode */
3565 NULL, /* security descriptor */
3566 OPEN_EXISTING, /* creation disposition */
3567 0, /* file attributes */
3568 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003569
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003570#ifdef FEAT_MBYTE
3571 vim_free(wn);
3572#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003573 if (hFile == INVALID_HANDLE_VALUE)
3574 return NODE_NORMAL;
3575
3576 type = GetFileType(hFile);
3577 CloseHandle(hFile);
3578 if (type == FILE_TYPE_CHAR)
3579 return NODE_WRITABLE;
3580 if (type == FILE_TYPE_DISK)
3581 return NODE_NORMAL;
3582 return NODE_OTHER;
3583}
3584
3585#ifdef HAVE_ACL
3586struct my_acl
3587{
3588 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3589 PSID pSidOwner;
3590 PSID pSidGroup;
3591 PACL pDacl;
3592 PACL pSacl;
3593};
3594#endif
3595
3596/*
3597 * Return a pointer to the ACL of file "fname" in allocated memory.
3598 * Return NULL if the ACL is not available for whatever reason.
3599 */
3600 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003601mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602{
3603#ifndef HAVE_ACL
3604 return (vim_acl_T)NULL;
3605#else
3606 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003607 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608
3609 /* This only works on Windows NT and 2000. */
3610 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3611 {
3612 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3613 if (p != NULL)
3614 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003615# ifdef FEAT_MBYTE
3616 WCHAR *wn = NULL;
3617
3618 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3619 wn = enc_to_utf16(fname, NULL);
3620 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003622 /* Try to retrieve the entire security descriptor. */
3623 err = pGetNamedSecurityInfoW(
3624 wn, // Abstract filename
3625 SE_FILE_OBJECT, // File Object
3626 OWNER_SECURITY_INFORMATION |
3627 GROUP_SECURITY_INFORMATION |
3628 DACL_SECURITY_INFORMATION |
3629 SACL_SECURITY_INFORMATION,
3630 &p->pSidOwner, // Ownership information.
3631 &p->pSidGroup, // Group membership.
3632 &p->pDacl, // Discretionary information.
3633 &p->pSacl, // For auditing purposes.
3634 &p->pSecurityDescriptor);
3635 if (err == ERROR_ACCESS_DENIED ||
3636 err == ERROR_PRIVILEGE_NOT_HELD)
3637 {
3638 /* Retrieve only DACL. */
3639 (void)pGetNamedSecurityInfoW(
3640 wn,
3641 SE_FILE_OBJECT,
3642 DACL_SECURITY_INFORMATION,
3643 NULL,
3644 NULL,
3645 &p->pDacl,
3646 NULL,
3647 &p->pSecurityDescriptor);
3648 }
3649 if (p->pSecurityDescriptor == NULL)
3650 {
3651 mch_free_acl((vim_acl_T)p);
3652 p = NULL;
3653 }
3654 vim_free(wn);
3655 }
3656 else
3657# endif
3658 {
3659 /* Try to retrieve the entire security descriptor. */
3660 err = pGetNamedSecurityInfo(
3661 (LPSTR)fname, // Abstract filename
3662 SE_FILE_OBJECT, // File Object
3663 OWNER_SECURITY_INFORMATION |
3664 GROUP_SECURITY_INFORMATION |
3665 DACL_SECURITY_INFORMATION |
3666 SACL_SECURITY_INFORMATION,
3667 &p->pSidOwner, // Ownership information.
3668 &p->pSidGroup, // Group membership.
3669 &p->pDacl, // Discretionary information.
3670 &p->pSacl, // For auditing purposes.
3671 &p->pSecurityDescriptor);
3672 if (err == ERROR_ACCESS_DENIED ||
3673 err == ERROR_PRIVILEGE_NOT_HELD)
3674 {
3675 /* Retrieve only DACL. */
3676 (void)pGetNamedSecurityInfo(
3677 (LPSTR)fname,
3678 SE_FILE_OBJECT,
3679 DACL_SECURITY_INFORMATION,
3680 NULL,
3681 NULL,
3682 &p->pDacl,
3683 NULL,
3684 &p->pSecurityDescriptor);
3685 }
3686 if (p->pSecurityDescriptor == NULL)
3687 {
3688 mch_free_acl((vim_acl_T)p);
3689 p = NULL;
3690 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003691 }
3692 }
3693 }
3694
3695 return (vim_acl_T)p;
3696#endif
3697}
3698
Bram Moolenaar27515922013-06-29 15:36:26 +02003699#ifdef HAVE_ACL
3700/*
3701 * Check if "acl" contains inherited ACE.
3702 */
3703 static BOOL
3704is_acl_inherited(PACL acl)
3705{
3706 DWORD i;
3707 ACL_SIZE_INFORMATION acl_info;
3708 PACCESS_ALLOWED_ACE ace;
3709
3710 acl_info.AceCount = 0;
3711 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3712 for (i = 0; i < acl_info.AceCount; i++)
3713 {
3714 GetAce(acl, i, (LPVOID *)&ace);
3715 if (ace->Header.AceFlags & INHERITED_ACE)
3716 return TRUE;
3717 }
3718 return FALSE;
3719}
3720#endif
3721
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722/*
3723 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3724 * Errors are ignored.
3725 * This must only be called with "acl" equal to what mch_get_acl() returned.
3726 */
3727 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003728mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729{
3730#ifdef HAVE_ACL
3731 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003732 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003733
3734 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003735 {
3736# ifdef FEAT_MBYTE
3737 WCHAR *wn = NULL;
3738# endif
3739
3740 /* Set security flags */
3741 if (p->pSidOwner)
3742 sec_info |= OWNER_SECURITY_INFORMATION;
3743 if (p->pSidGroup)
3744 sec_info |= GROUP_SECURITY_INFORMATION;
3745 if (p->pDacl)
3746 {
3747 sec_info |= DACL_SECURITY_INFORMATION;
3748 /* Do not inherit its parent's DACL.
3749 * If the DACL is inherited, Cygwin permissions would be changed.
3750 */
3751 if (!is_acl_inherited(p->pDacl))
3752 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3753 }
3754 if (p->pSacl)
3755 sec_info |= SACL_SECURITY_INFORMATION;
3756
3757# ifdef FEAT_MBYTE
3758 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3759 wn = enc_to_utf16(fname, NULL);
3760 if (wn != NULL)
3761 {
3762 (void)pSetNamedSecurityInfoW(
3763 wn, // Abstract filename
3764 SE_FILE_OBJECT, // File Object
3765 sec_info,
3766 p->pSidOwner, // Ownership information.
3767 p->pSidGroup, // Group membership.
3768 p->pDacl, // Discretionary information.
3769 p->pSacl // For auditing purposes.
3770 );
3771 vim_free(wn);
3772 }
3773 else
3774# endif
3775 {
3776 (void)pSetNamedSecurityInfo(
3777 (LPSTR)fname, // Abstract filename
3778 SE_FILE_OBJECT, // File Object
3779 sec_info,
3780 p->pSidOwner, // Ownership information.
3781 p->pSidGroup, // Group membership.
3782 p->pDacl, // Discretionary information.
3783 p->pSacl // For auditing purposes.
3784 );
3785 }
3786 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787#endif
3788}
3789
3790 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003791mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792{
3793#ifdef HAVE_ACL
3794 struct my_acl *p = (struct my_acl *)acl;
3795
3796 if (p != NULL)
3797 {
3798 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3799 vim_free(p);
3800 }
3801#endif
3802}
3803
3804#ifndef FEAT_GUI_W32
3805
3806/*
3807 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3808 */
3809 static BOOL WINAPI
3810handler_routine(
3811 DWORD dwCtrlType)
3812{
3813 switch (dwCtrlType)
3814 {
3815 case CTRL_C_EVENT:
3816 if (ctrl_c_interrupts)
3817 g_fCtrlCPressed = TRUE;
3818 return TRUE;
3819
3820 case CTRL_BREAK_EVENT:
3821 g_fCBrkPressed = TRUE;
3822 return TRUE;
3823
3824 /* fatal events: shut down gracefully */
3825 case CTRL_CLOSE_EVENT:
3826 case CTRL_LOGOFF_EVENT:
3827 case CTRL_SHUTDOWN_EVENT:
3828 windgoto((int)Rows - 1, 0);
3829 g_fForceExit = TRUE;
3830
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003831 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 (dwCtrlType == CTRL_CLOSE_EVENT
3833 ? _("close")
3834 : dwCtrlType == CTRL_LOGOFF_EVENT
3835 ? _("logoff")
3836 : _("shutdown")));
3837#ifdef DEBUG
3838 OutputDebugString(IObuff);
3839#endif
3840
3841 preserve_exit(); /* output IObuff, preserve files and exit */
3842
3843 return TRUE; /* not reached */
3844
3845 default:
3846 return FALSE;
3847 }
3848}
3849
3850
3851/*
3852 * set the tty in (raw) ? "raw" : "cooked" mode
3853 */
3854 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003855mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003856{
3857 DWORD cmodein;
3858 DWORD cmodeout;
3859 BOOL bEnableHandler;
3860
3861 GetConsoleMode(g_hConIn, &cmodein);
3862 GetConsoleMode(g_hConOut, &cmodeout);
3863 if (tmode == TMODE_RAW)
3864 {
3865 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3866 ENABLE_ECHO_INPUT);
3867#ifdef FEAT_MOUSE
3868 if (g_fMouseActive)
3869 cmodein |= ENABLE_MOUSE_INPUT;
3870#endif
3871 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3872 bEnableHandler = TRUE;
3873 }
3874 else /* cooked */
3875 {
3876 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3877 ENABLE_ECHO_INPUT);
3878 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3879 bEnableHandler = FALSE;
3880 }
3881 SetConsoleMode(g_hConIn, cmodein);
3882 SetConsoleMode(g_hConOut, cmodeout);
3883 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3884
3885#ifdef MCH_WRITE_DUMP
3886 if (fdDump)
3887 {
3888 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3889 tmode == TMODE_RAW ? "raw" :
3890 tmode == TMODE_COOK ? "cooked" : "normal",
3891 cmodein, cmodeout);
3892 fflush(fdDump);
3893 }
3894#endif
3895}
3896
3897
3898/*
3899 * Get the size of the current window in `Rows' and `Columns'
3900 * Return OK when size could be determined, FAIL otherwise.
3901 */
3902 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003903mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003904{
3905 CONSOLE_SCREEN_BUFFER_INFO csbi;
3906
3907 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3908 {
3909 /*
3910 * For some reason, we are trying to get the screen dimensions
3911 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3912 * variables are really intended to mean the size of Vim screen
3913 * while in termcap mode.
3914 */
3915 Rows = g_cbTermcap.Info.dwSize.Y;
3916 Columns = g_cbTermcap.Info.dwSize.X;
3917 }
3918 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3919 {
3920 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3921 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3922 }
3923 else
3924 {
3925 Rows = 25;
3926 Columns = 80;
3927 }
3928 return OK;
3929}
3930
3931/*
3932 * Set a console window to `xSize' * `ySize'
3933 */
3934 static void
3935ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003936 HANDLE hConsole,
3937 int xSize,
3938 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939{
3940 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3941 SMALL_RECT srWindowRect; /* hold the new console size */
3942 COORD coordScreen;
3943
3944#ifdef MCH_WRITE_DUMP
3945 if (fdDump)
3946 {
3947 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3948 fflush(fdDump);
3949 }
3950#endif
3951
3952 /* get the largest size we can size the console window to */
3953 coordScreen = GetLargestConsoleWindowSize(hConsole);
3954
3955 /* define the new console window size and scroll position */
3956 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3957 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3958 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3959
3960 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3961 {
3962 int sx, sy;
3963
3964 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3965 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3966 if (sy < ySize || sx < xSize)
3967 {
3968 /*
3969 * Increasing number of lines/columns, do buffer first.
3970 * Use the maximal size in x and y direction.
3971 */
3972 if (sy < ySize)
3973 coordScreen.Y = ySize;
3974 else
3975 coordScreen.Y = sy;
3976 if (sx < xSize)
3977 coordScreen.X = xSize;
3978 else
3979 coordScreen.X = sx;
3980 SetConsoleScreenBufferSize(hConsole, coordScreen);
3981 }
3982 }
3983
3984 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3985 {
3986#ifdef MCH_WRITE_DUMP
3987 if (fdDump)
3988 {
3989 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3990 GetLastError());
3991 fflush(fdDump);
3992 }
3993#endif
3994 }
3995
3996 /* define the new console buffer size */
3997 coordScreen.X = xSize;
3998 coordScreen.Y = ySize;
3999
4000 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4001 {
4002#ifdef MCH_WRITE_DUMP
4003 if (fdDump)
4004 {
4005 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4006 GetLastError());
4007 fflush(fdDump);
4008 }
4009#endif
4010 }
4011}
4012
4013
4014/*
4015 * Set the console window to `Rows' * `Columns'
4016 */
4017 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004018mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004019{
4020 COORD coordScreen;
4021
4022 /* Don't change window size while still starting up */
4023 if (suppress_winsize != 0)
4024 {
4025 suppress_winsize = 2;
4026 return;
4027 }
4028
4029 if (term_console)
4030 {
4031 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4032
4033 /* Clamp Rows and Columns to reasonable values */
4034 if (Rows > coordScreen.Y)
4035 Rows = coordScreen.Y;
4036 if (Columns > coordScreen.X)
4037 Columns = coordScreen.X;
4038
4039 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4040 }
4041}
4042
4043/*
4044 * Rows and/or Columns has changed.
4045 */
4046 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004047mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048{
4049 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4050}
4051
4052
4053/*
4054 * Called when started up, to set the winsize that was delayed.
4055 */
4056 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004057mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058{
4059 if (suppress_winsize == 2)
4060 {
4061 suppress_winsize = 0;
4062 mch_set_shellsize();
4063 shell_resized();
4064 }
4065 suppress_winsize = 0;
4066}
4067#endif /* FEAT_GUI_W32 */
4068
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004069 static BOOL
4070vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004071 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004072 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004073 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004074 STARTUPINFO *si,
4075 PROCESS_INFORMATION *pi)
4076{
4077# ifdef FEAT_MBYTE
4078 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4079 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004080 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004081
4082 if (wcmd != NULL)
4083 {
4084 BOOL ret;
4085 ret = CreateProcessW(
4086 NULL, /* Executable name */
4087 wcmd, /* Command to execute */
4088 NULL, /* Process security attributes */
4089 NULL, /* Thread security attributes */
4090 inherit_handles, /* Inherit handles */
4091 flags, /* Creation flags */
4092 NULL, /* Environment */
4093 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004094 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004095 pi); /* Process information */
4096 vim_free(wcmd);
4097 return ret;
4098 }
4099 }
4100#endif
4101 return CreateProcess(
4102 NULL, /* Executable name */
4103 cmd, /* Command to execute */
4104 NULL, /* Process security attributes */
4105 NULL, /* Thread security attributes */
4106 inherit_handles, /* Inherit handles */
4107 flags, /* Creation flags */
4108 NULL, /* Environment */
4109 NULL, /* Current directory */
4110 si, /* Startup information */
4111 pi); /* Process information */
4112}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113
4114
4115#if defined(FEAT_GUI_W32) || defined(PROTO)
4116
4117/*
4118 * Specialised version of system() for Win32 GUI mode.
4119 * This version proceeds as follows:
4120 * 1. Create a console window for use by the subprocess
4121 * 2. Run the subprocess (it gets the allocated console by default)
4122 * 3. Wait for the subprocess to terminate and get its exit code
4123 * 4. Prompt the user to press a key to close the console window
4124 */
4125 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004126mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127{
4128 STARTUPINFO si;
4129 PROCESS_INFORMATION pi;
4130 DWORD ret = 0;
4131 HWND hwnd = GetFocus();
4132
4133 si.cb = sizeof(si);
4134 si.lpReserved = NULL;
4135 si.lpDesktop = NULL;
4136 si.lpTitle = NULL;
4137 si.dwFlags = STARTF_USESHOWWINDOW;
4138 /*
4139 * It's nicer to run a filter command in a minimized window, but in
4140 * Windows 95 this makes the command MUCH slower. We can't do it under
4141 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004142 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 */
Bram Moolenaar78c7e272016-08-25 23:19:29 +02004144 if ((options & SHELL_DOOUT) && !mch_windows95())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004145 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 else
4147 si.wShowWindow = SW_SHOWNORMAL;
4148 si.cbReserved2 = 0;
4149 si.lpReserved2 = NULL;
4150
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004151 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 * When the "c:\\" is left out it works OK...? */
4153 if (mch_windows95()
4154 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4155 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4156 cmd += 3;
4157
4158 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004159 vim_create_process(cmd, FALSE,
4160 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161
4162 /* Wait for the command to terminate before continuing */
4163 if (g_PlatformId != VER_PLATFORM_WIN32s)
4164 {
4165#ifdef FEAT_GUI
4166 int delay = 1;
4167
4168 /* Keep updating the window while waiting for the shell to finish. */
4169 for (;;)
4170 {
4171 MSG msg;
4172
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004173 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174 {
4175 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004176 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004177 delay = 1;
4178 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 }
4180 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4181 break;
4182
4183 /* We start waiting for a very short time and then increase it, so
4184 * that we respond quickly when the process is quick, and don't
4185 * consume too much overhead when it's slow. */
4186 if (delay < 50)
4187 delay += 10;
4188 }
4189#else
4190 WaitForSingleObject(pi.hProcess, INFINITE);
4191#endif
4192
4193 /* Get the command exit code */
4194 GetExitCodeProcess(pi.hProcess, &ret);
4195 }
4196 else
4197 {
4198 /*
4199 * This ugly code is the only quick way of performing
4200 * a synchronous spawn under Win32s. Yuk.
4201 */
4202 num_windows = 0;
4203 EnumWindows(win32ssynch_cb, 0);
4204 old_num_windows = num_windows;
4205 do
4206 {
4207 Sleep(1000);
4208 num_windows = 0;
4209 EnumWindows(win32ssynch_cb, 0);
4210 } while (num_windows == old_num_windows);
4211 ret = 0;
4212 }
4213
4214 /* Close the handles to the subprocess, so that it goes away */
4215 CloseHandle(pi.hThread);
4216 CloseHandle(pi.hProcess);
4217
4218 /* Try to get input focus back. Doesn't always work though. */
4219 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4220
4221 return ret;
4222}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004223
4224/*
4225 * Thread launched by the gui to send the current buffer data to the
4226 * process. This way avoid to hang up vim totally if the children
4227 * process take a long time to process the lines.
4228 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004229 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004230sub_process_writer(LPVOID param)
4231{
4232 HANDLE g_hChildStd_IN_Wr = param;
4233 linenr_T lnum = curbuf->b_op_start.lnum;
4234 DWORD len = 0;
4235 DWORD l;
4236 char_u *lp = ml_get(lnum);
4237 char_u *s;
4238 int written = 0;
4239
4240 for (;;)
4241 {
4242 l = (DWORD)STRLEN(lp + written);
4243 if (l == 0)
4244 len = 0;
4245 else if (lp[written] == NL)
4246 {
4247 /* NL -> NUL translation */
4248 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4249 }
4250 else
4251 {
4252 s = vim_strchr(lp + written, NL);
4253 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4254 s == NULL ? l : (DWORD)(s - (lp + written)),
4255 &len, NULL);
4256 }
4257 if (len == (int)l)
4258 {
4259 /* Finished a line, add a NL, unless this line should not have
4260 * one. */
4261 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004262 || (!curbuf->b_p_bin
4263 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004264 || (lnum != curbuf->b_no_eol_lnum
4265 && (lnum != curbuf->b_ml.ml_line_count
4266 || curbuf->b_p_eol)))
4267 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004268 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004269 }
4270
4271 ++lnum;
4272 if (lnum > curbuf->b_op_end.lnum)
4273 break;
4274
4275 lp = ml_get(lnum);
4276 written = 0;
4277 }
4278 else if (len > 0)
4279 written += len;
4280 }
4281
4282 /* finished all the lines, close pipe */
4283 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004284 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004285}
4286
4287
4288# define BUFLEN 100 /* length for buffer, stolen from unix version */
4289
4290/*
4291 * This function read from the children's stdout and write the
4292 * data on screen or in the buffer accordingly.
4293 */
4294 static void
4295dump_pipe(int options,
4296 HANDLE g_hChildStd_OUT_Rd,
4297 garray_T *ga,
4298 char_u buffer[],
4299 DWORD *buffer_off)
4300{
4301 DWORD availableBytes = 0;
4302 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004303 int ret;
4304 DWORD len;
4305 DWORD toRead;
4306 int repeatCount;
4307
4308 /* we query the pipe to see if there is any data to read
4309 * to avoid to perform a blocking read */
4310 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4311 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004312 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004313 NULL, /* number of read bytes */
4314 &availableBytes, /* available bytes total */
4315 NULL); /* byteLeft */
4316
4317 repeatCount = 0;
4318 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004319 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004320 {
4321 repeatCount++;
4322 toRead =
4323# ifdef FEAT_MBYTE
4324 (DWORD)(BUFLEN - *buffer_off);
4325# else
4326 (DWORD)BUFLEN;
4327# endif
4328 toRead = availableBytes < toRead ? availableBytes : toRead;
4329 ReadFile(g_hChildStd_OUT_Rd, buffer
4330# ifdef FEAT_MBYTE
4331 + *buffer_off, toRead
4332# else
4333 , toRead
4334# endif
4335 , &len, NULL);
4336
4337 /* If we haven't read anything, there is a problem */
4338 if (len == 0)
4339 break;
4340
4341 availableBytes -= len;
4342
4343 if (options & SHELL_READ)
4344 {
4345 /* Do NUL -> NL translation, append NL separated
4346 * lines to the current buffer. */
4347 for (i = 0; i < len; ++i)
4348 {
4349 if (buffer[i] == NL)
4350 append_ga_line(ga);
4351 else if (buffer[i] == NUL)
4352 ga_append(ga, NL);
4353 else
4354 ga_append(ga, buffer[i]);
4355 }
4356 }
4357# ifdef FEAT_MBYTE
4358 else if (has_mbyte)
4359 {
4360 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004361 int c;
4362 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004363
4364 len += *buffer_off;
4365 buffer[len] = NUL;
4366
4367 /* Check if the last character in buffer[] is
4368 * incomplete, keep these bytes for the next
4369 * round. */
4370 for (p = buffer; p < buffer + len; p += l)
4371 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004372 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004373 if (l == 0)
4374 l = 1; /* NUL byte? */
4375 else if (MB_BYTE2LEN(*p) != l)
4376 break;
4377 }
4378 if (p == buffer) /* no complete character */
4379 {
4380 /* avoid getting stuck at an illegal byte */
4381 if (len >= 12)
4382 ++p;
4383 else
4384 {
4385 *buffer_off = len;
4386 return;
4387 }
4388 }
4389 c = *p;
4390 *p = NUL;
4391 msg_puts(buffer);
4392 if (p < buffer + len)
4393 {
4394 *p = c;
4395 *buffer_off = (DWORD)((buffer + len) - p);
4396 mch_memmove(buffer, p, *buffer_off);
4397 return;
4398 }
4399 *buffer_off = 0;
4400 }
4401# endif /* FEAT_MBYTE */
4402 else
4403 {
4404 buffer[len] = NUL;
4405 msg_puts(buffer);
4406 }
4407
4408 windgoto(msg_row, msg_col);
4409 cursor_on();
4410 out_flush();
4411 }
4412}
4413
4414/*
4415 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4416 * for communication and doesn't open any new window.
4417 */
4418 static int
4419mch_system_piped(char *cmd, int options)
4420{
4421 STARTUPINFO si;
4422 PROCESS_INFORMATION pi;
4423 DWORD ret = 0;
4424
4425 HANDLE g_hChildStd_IN_Rd = NULL;
4426 HANDLE g_hChildStd_IN_Wr = NULL;
4427 HANDLE g_hChildStd_OUT_Rd = NULL;
4428 HANDLE g_hChildStd_OUT_Wr = NULL;
4429
4430 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4431 DWORD len;
4432
4433 /* buffer used to receive keys */
4434 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4435 int ta_len = 0; /* valid bytes in ta_buf[] */
4436
4437 DWORD i;
4438 int c;
4439 int noread_cnt = 0;
4440 garray_T ga;
4441 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004442 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004443 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004444
4445 SECURITY_ATTRIBUTES saAttr;
4446
4447 /* Set the bInheritHandle flag so pipe handles are inherited. */
4448 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4449 saAttr.bInheritHandle = TRUE;
4450 saAttr.lpSecurityDescriptor = NULL;
4451
4452 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4453 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4454 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4455 /* Create a pipe for the child process's STDIN. */
4456 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4457 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4458 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4459 {
4460 CloseHandle(g_hChildStd_IN_Rd);
4461 CloseHandle(g_hChildStd_IN_Wr);
4462 CloseHandle(g_hChildStd_OUT_Rd);
4463 CloseHandle(g_hChildStd_OUT_Wr);
4464 MSG_PUTS(_("\nCannot create pipes\n"));
4465 }
4466
4467 si.cb = sizeof(si);
4468 si.lpReserved = NULL;
4469 si.lpDesktop = NULL;
4470 si.lpTitle = NULL;
4471 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4472
4473 /* set-up our file redirection */
4474 si.hStdError = g_hChildStd_OUT_Wr;
4475 si.hStdOutput = g_hChildStd_OUT_Wr;
4476 si.hStdInput = g_hChildStd_IN_Rd;
4477 si.wShowWindow = SW_HIDE;
4478 si.cbReserved2 = 0;
4479 si.lpReserved2 = NULL;
4480
4481 if (options & SHELL_READ)
4482 ga_init2(&ga, 1, BUFLEN);
4483
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004484 if (cmd != NULL)
4485 {
4486 p = (char *)vim_strsave((char_u *)cmd);
4487 if (p != NULL)
4488 unescape_shellxquote((char_u *)p, p_sxe);
4489 else
4490 p = cmd;
4491 }
4492
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004493 /* Now, run the command.
4494 * About "Inherit handles" being TRUE: this command can be litigious,
4495 * handle inheritance was deactivated for pending temp file, but, if we
4496 * deactivate it, the pipes don't work for some reason. */
4497 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004498
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004499 if (p != cmd)
4500 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004501
4502 /* Close our unused side of the pipes */
4503 CloseHandle(g_hChildStd_IN_Rd);
4504 CloseHandle(g_hChildStd_OUT_Wr);
4505
4506 if (options & SHELL_WRITE)
4507 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004508 HANDLE thread = (HANDLE)
4509 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004510 0, /* default stack size */
4511 sub_process_writer, /* function to be executed */
4512 g_hChildStd_IN_Wr, /* parameter */
4513 0, /* creation flag, start immediately */
4514 NULL); /* we don't care about thread id */
4515 CloseHandle(thread);
4516 g_hChildStd_IN_Wr = NULL;
4517 }
4518
4519 /* Keep updating the window while waiting for the shell to finish. */
4520 for (;;)
4521 {
4522 MSG msg;
4523
Bram Moolenaar175d0702013-12-11 18:36:33 +01004524 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004525 {
4526 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004527 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004528 }
4529
4530 /* write pipe information in the window */
4531 if ((options & (SHELL_READ|SHELL_WRITE))
4532# ifdef FEAT_GUI
4533 || gui.in_use
4534# endif
4535 )
4536 {
4537 len = 0;
4538 if (!(options & SHELL_EXPAND)
4539 && ((options &
4540 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4541 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4542# ifdef FEAT_GUI
4543 || gui.in_use
4544# endif
4545 )
4546 && (ta_len > 0 || noread_cnt > 4))
4547 {
4548 if (ta_len == 0)
4549 {
4550 /* Get extra characters when we don't have any. Reset the
4551 * counter and timer. */
4552 noread_cnt = 0;
4553# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4554 gettimeofday(&start_tv, NULL);
4555# endif
4556 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4557 }
4558 if (ta_len > 0 || len > 0)
4559 {
4560 /*
4561 * For pipes: Check for CTRL-C: send interrupt signal to
4562 * child. Check for CTRL-D: EOF, close pipe to child.
4563 */
4564 if (len == 1 && cmd != NULL)
4565 {
4566 if (ta_buf[ta_len] == Ctrl_C)
4567 {
4568 /* Learn what exit code is expected, for
4569 * now put 9 as SIGKILL */
4570 TerminateProcess(pi.hProcess, 9);
4571 }
4572 if (ta_buf[ta_len] == Ctrl_D)
4573 {
4574 CloseHandle(g_hChildStd_IN_Wr);
4575 g_hChildStd_IN_Wr = NULL;
4576 }
4577 }
4578
4579 /* replace K_BS by <BS> and K_DEL by <DEL> */
4580 for (i = ta_len; i < ta_len + len; ++i)
4581 {
4582 if (ta_buf[i] == CSI && len - i > 2)
4583 {
4584 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4585 if (c == K_DEL || c == K_KDEL || c == K_BS)
4586 {
4587 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4588 (size_t)(len - i - 2));
4589 if (c == K_DEL || c == K_KDEL)
4590 ta_buf[i] = DEL;
4591 else
4592 ta_buf[i] = Ctrl_H;
4593 len -= 2;
4594 }
4595 }
4596 else if (ta_buf[i] == '\r')
4597 ta_buf[i] = '\n';
4598# ifdef FEAT_MBYTE
4599 if (has_mbyte)
4600 i += (*mb_ptr2len_len)(ta_buf + i,
4601 ta_len + len - i) - 1;
4602# endif
4603 }
4604
4605 /*
4606 * For pipes: echo the typed characters. For a pty this
4607 * does not seem to work.
4608 */
4609 for (i = ta_len; i < ta_len + len; ++i)
4610 {
4611 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4612 msg_putchar(ta_buf[i]);
4613# ifdef FEAT_MBYTE
4614 else if (has_mbyte)
4615 {
4616 int l = (*mb_ptr2len)(ta_buf + i);
4617
4618 msg_outtrans_len(ta_buf + i, l);
4619 i += l - 1;
4620 }
4621# endif
4622 else
4623 msg_outtrans_len(ta_buf + i, 1);
4624 }
4625 windgoto(msg_row, msg_col);
4626 out_flush();
4627
4628 ta_len += len;
4629
4630 /*
4631 * Write the characters to the child, unless EOF has been
4632 * typed for pipes. Write one character at a time, to
4633 * avoid losing too much typeahead. When writing buffer
4634 * lines, drop the typed characters (only check for
4635 * CTRL-C).
4636 */
4637 if (options & SHELL_WRITE)
4638 ta_len = 0;
4639 else if (g_hChildStd_IN_Wr != NULL)
4640 {
4641 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4642 1, &len, NULL);
4643 // if we are typing in, we want to keep things reactive
4644 delay = 1;
4645 if (len > 0)
4646 {
4647 ta_len -= len;
4648 mch_memmove(ta_buf, ta_buf + len, ta_len);
4649 }
4650 }
4651 }
4652 }
4653 }
4654
4655 if (ta_len)
4656 ui_inchar_undo(ta_buf, ta_len);
4657
4658 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4659 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004660 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004661 break;
4662 }
4663
4664 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004665 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004666
4667 /* We start waiting for a very short time and then increase it, so
4668 * that we respond quickly when the process is quick, and don't
4669 * consume too much overhead when it's slow. */
4670 if (delay < 50)
4671 delay += 10;
4672 }
4673
4674 /* Close the pipe */
4675 CloseHandle(g_hChildStd_OUT_Rd);
4676 if (g_hChildStd_IN_Wr != NULL)
4677 CloseHandle(g_hChildStd_IN_Wr);
4678
4679 WaitForSingleObject(pi.hProcess, INFINITE);
4680
4681 /* Get the command exit code */
4682 GetExitCodeProcess(pi.hProcess, &ret);
4683
4684 if (options & SHELL_READ)
4685 {
4686 if (ga.ga_len > 0)
4687 {
4688 append_ga_line(&ga);
4689 /* remember that the NL was missing */
4690 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4691 }
4692 else
4693 curbuf->b_no_eol_lnum = 0;
4694 ga_clear(&ga);
4695 }
4696
4697 /* Close the handles to the subprocess, so that it goes away */
4698 CloseHandle(pi.hThread);
4699 CloseHandle(pi.hProcess);
4700
4701 return ret;
4702}
4703
4704 static int
4705mch_system(char *cmd, int options)
4706{
4707 /* if we can pipe and the shelltemp option is off */
4708 if (allowPiping && !p_stmp)
4709 return mch_system_piped(cmd, options);
4710 else
4711 return mch_system_classic(cmd, options);
4712}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004713#else
4714
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004715# ifdef FEAT_MBYTE
4716 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004717mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004718{
4719 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4720 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004721 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004722 if (wcmd != NULL)
4723 {
4724 int ret = _wsystem(wcmd);
4725 vim_free(wcmd);
4726 return ret;
4727 }
4728 }
4729 return system(cmd);
4730}
4731# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004732# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004733# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004734
4735#endif
4736
4737/*
4738 * Either execute a command by calling the shell or start a new shell
4739 */
4740 int
4741mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004742 char_u *cmd,
4743 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744{
4745 int x = 0;
4746 int tmode = cur_tmode;
4747#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004748 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004749# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004750 int did_set_title = FALSE;
4751
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004752 /* Change the title to reflect that we are in a subshell. */
4753 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4754 {
4755 WCHAR szShellTitle[512];
4756
4757 if (GetConsoleTitleW(szShellTitle,
4758 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4759 {
4760 if (cmd == NULL)
4761 wcscat(szShellTitle, L" :sh");
4762 else
4763 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004764 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004765
4766 if (wn != NULL)
4767 {
4768 wcscat(szShellTitle, L" - !");
4769 if ((wcslen(szShellTitle) + wcslen(wn) <
4770 sizeof(szShellTitle)/sizeof(WCHAR)))
4771 wcscat(szShellTitle, wn);
4772 SetConsoleTitleW(szShellTitle);
4773 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004774 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004775 }
4776 }
4777 }
4778 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004779 if (!did_set_title)
4780# endif
4781 /* Change the title to reflect that we are in a subshell. */
4782 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004784 if (cmd == NULL)
4785 strcat(szShellTitle, " :sh");
4786 else
4787 {
4788 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004789 if ((strlen(szShellTitle) + strlen((char *)cmd)
4790 < sizeof(szShellTitle)))
4791 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004792 }
4793 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004794 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004795#endif
4796
4797 out_flush();
4798
4799#ifdef MCH_WRITE_DUMP
4800 if (fdDump)
4801 {
4802 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4803 fflush(fdDump);
4804 }
4805#endif
4806
4807 /*
4808 * Catch all deadly signals while running the external command, because a
4809 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4810 */
4811 signal(SIGINT, SIG_IGN);
4812#if defined(__GNUC__) && !defined(__MINGW32__)
4813 signal(SIGKILL, SIG_IGN);
4814#else
4815 signal(SIGBREAK, SIG_IGN);
4816#endif
4817 signal(SIGILL, SIG_IGN);
4818 signal(SIGFPE, SIG_IGN);
4819 signal(SIGSEGV, SIG_IGN);
4820 signal(SIGTERM, SIG_IGN);
4821 signal(SIGABRT, SIG_IGN);
4822
4823 if (options & SHELL_COOKED)
4824 settmode(TMODE_COOK); /* set to normal mode */
4825
4826 if (cmd == NULL)
4827 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004828 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004829 }
4830 else
4831 {
4832 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004833 char_u *newcmd = NULL;
4834 char_u *cmdbase = cmd;
4835 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004836
4837 /* Skip a leading ", ( and "(. */
4838 if (*cmdbase == '"' )
4839 ++cmdbase;
4840 if (*cmdbase == '(')
4841 ++cmdbase;
4842
4843 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4844 {
4845 STARTUPINFO si;
4846 PROCESS_INFORMATION pi;
4847 DWORD flags = CREATE_NEW_CONSOLE;
4848 char_u *p;
4849
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004850 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004851 si.cb = sizeof(si);
4852 si.lpReserved = NULL;
4853 si.lpDesktop = NULL;
4854 si.lpTitle = NULL;
4855 si.dwFlags = 0;
4856 si.cbReserved2 = 0;
4857 si.lpReserved2 = NULL;
4858
4859 cmdbase = skipwhite(cmdbase + 5);
4860 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4861 && vim_iswhite(cmdbase[4]))
4862 {
4863 cmdbase = skipwhite(cmdbase + 4);
4864 si.dwFlags = STARTF_USESHOWWINDOW;
4865 si.wShowWindow = SW_SHOWMINNOACTIVE;
4866 }
4867 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4868 && vim_iswhite(cmdbase[2]))
4869 {
4870 cmdbase = skipwhite(cmdbase + 2);
4871 flags = CREATE_NO_WINDOW;
4872 si.dwFlags = STARTF_USESTDHANDLES;
4873 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004874 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004875 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004876 NULL, // Security att.
4877 OPEN_EXISTING, // Open flags
4878 FILE_ATTRIBUTE_NORMAL, // File att.
4879 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004880 si.hStdOutput = si.hStdInput;
4881 si.hStdError = si.hStdInput;
4882 }
4883
4884 /* Remove a trailing ", ) and )" if they have a match
4885 * at the start of the command. */
4886 if (cmdbase > cmd)
4887 {
4888 p = cmdbase + STRLEN(cmdbase);
4889 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4890 *--p = NUL;
4891 if (p > cmdbase && p[-1] == ')'
4892 && (*cmd =='(' || cmd[1] == '('))
4893 *--p = NUL;
4894 }
4895
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004896 newcmd = cmdbase;
4897 unescape_shellxquote(cmdbase, p_sxe);
4898
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004899 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004900 * If creating new console, arguments are passed to the
4901 * 'cmd.exe' as-is. If it's not, arguments are not treated
4902 * correctly for current 'cmd.exe'. So unescape characters in
4903 * shellxescape except '|' for avoiding to be treated as
4904 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004905 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004906 if (flags != CREATE_NEW_CONSOLE)
4907 {
4908 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004909 char_u *cmd_shell = mch_getenv("COMSPEC");
4910
4911 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004912 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004913
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004914 subcmd = vim_strsave_escaped_ext(cmdbase,
4915 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004916 if (subcmd != NULL)
4917 {
4918 /* make "cmd.exe /c arguments" */
4919 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004920 newcmd = lalloc(cmdlen, TRUE);
4921 if (newcmd != NULL)
4922 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004923 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004924 else
4925 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004926 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004927 }
4928 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004929
4930 /*
4931 * Now, start the command as a process, so that it doesn't
4932 * inherit our handles which causes unpleasant dangling swap
4933 * files if we exit before the spawned process
4934 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004935 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004936 x = 0;
4937 else
4938 {
4939 x = -1;
4940#ifdef FEAT_GUI_W32
4941 EMSG(_("E371: Command not found"));
4942#endif
4943 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004944
4945 if (newcmd != cmdbase)
4946 vim_free(newcmd);
4947
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004948 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004949 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004950 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004951 CloseHandle(si.hStdInput);
4952 }
4953 /* Close the handles to the subprocess, so that it goes away */
4954 CloseHandle(pi.hThread);
4955 CloseHandle(pi.hProcess);
4956 }
4957 else
4958 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004959 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004960#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004961 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004963 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4964
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004965 newcmd = lalloc(cmdlen, TRUE);
4966 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967 {
4968#if defined(FEAT_GUI_W32)
4969 if (need_vimrun_warning)
4970 {
4971 MessageBox(NULL,
4972 _("VIMRUN.EXE not found in your $PATH.\n"
4973 "External commands will not pause after completion.\n"
4974 "See :help win32-vimrun for more information."),
4975 _("Vim Warning"),
4976 MB_ICONWARNING);
4977 need_vimrun_warning = FALSE;
4978 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004979 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004980 /* Use vimrun to execute the command. It opens a console
4981 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004982 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004983 vimrun_path,
4984 (msg_silent != 0 || (options & SHELL_DOOUT))
4985 ? "-s " : "",
4986 p_sh, p_shcf, cmd);
4987 else
4988#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004989 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004990 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004991 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004992 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004994 }
4995 }
4996
4997 if (tmode == TMODE_RAW)
4998 settmode(TMODE_RAW); /* set to raw mode */
4999
5000 /* Print the return value, unless "vimrun" was used. */
5001 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5002#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005003 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
5004 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005005#endif
5006 )
5007 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005008 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009 msg_putchar('\n');
5010 }
5011#ifdef FEAT_TITLE
5012 resettitle();
5013#endif
5014
5015 signal(SIGINT, SIG_DFL);
5016#if defined(__GNUC__) && !defined(__MINGW32__)
5017 signal(SIGKILL, SIG_DFL);
5018#else
5019 signal(SIGBREAK, SIG_DFL);
5020#endif
5021 signal(SIGILL, SIG_DFL);
5022 signal(SIGFPE, SIG_DFL);
5023 signal(SIGSEGV, SIG_DFL);
5024 signal(SIGTERM, SIG_DFL);
5025 signal(SIGABRT, SIG_DFL);
5026
5027 return x;
5028}
5029
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005030#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005031 static HANDLE
5032job_io_file_open(
5033 char_u *fname,
5034 DWORD dwDesiredAccess,
5035 DWORD dwShareMode,
5036 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5037 DWORD dwCreationDisposition,
5038 DWORD dwFlagsAndAttributes)
5039{
5040 HANDLE h;
5041# ifdef FEAT_MBYTE
5042 WCHAR *wn = NULL;
5043 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5044 {
5045 wn = enc_to_utf16(fname, NULL);
5046 if (wn != NULL)
5047 {
5048 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5049 lpSecurityAttributes, dwCreationDisposition,
5050 dwFlagsAndAttributes, NULL);
5051 vim_free(wn);
5052 if (h == INVALID_HANDLE_VALUE
5053 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5054 wn = NULL;
5055 }
5056 }
5057 if (wn == NULL)
5058# endif
5059
5060 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5061 lpSecurityAttributes, dwCreationDisposition,
5062 dwFlagsAndAttributes, NULL);
5063 return h;
5064}
5065
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005066 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005067mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005068{
5069 STARTUPINFO si;
5070 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005071 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005072 SECURITY_ATTRIBUTES saAttr;
5073 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005074 HANDLE ifd[2];
5075 HANDLE ofd[2];
5076 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005077
5078 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5079 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5080 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5081 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5082 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5083 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5084 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5085
5086 if (use_out_for_err && use_null_for_out)
5087 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005088
5089 ifd[0] = INVALID_HANDLE_VALUE;
5090 ifd[1] = INVALID_HANDLE_VALUE;
5091 ofd[0] = INVALID_HANDLE_VALUE;
5092 ofd[1] = INVALID_HANDLE_VALUE;
5093 efd[0] = INVALID_HANDLE_VALUE;
5094 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005095
Bram Moolenaar76467df2016-02-12 19:30:26 +01005096 jo = CreateJobObject(NULL, NULL);
5097 if (jo == NULL)
5098 {
5099 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005100 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005101 }
5102
5103 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005104 ZeroMemory(&si, sizeof(si));
5105 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005106 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005107 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005108
Bram Moolenaard8070362016-02-15 21:56:54 +01005109 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5110 saAttr.bInheritHandle = TRUE;
5111 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005112
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005113 if (use_file_for_in)
5114 {
5115 char_u *fname = options->jo_io_name[PART_IN];
5116
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005117 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5118 FILE_SHARE_READ | FILE_SHARE_WRITE,
5119 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5120 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005121 {
5122 EMSG2(_(e_notopen), fname);
5123 goto failed;
5124 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005125 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005126 else if (!use_null_for_in &&
5127 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5128 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005129 goto failed;
5130
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005131 if (use_file_for_out)
5132 {
5133 char_u *fname = options->jo_io_name[PART_OUT];
5134
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005135 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5136 FILE_SHARE_READ | FILE_SHARE_WRITE,
5137 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5138 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005139 {
5140 EMSG2(_(e_notopen), fname);
5141 goto failed;
5142 }
5143 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005144 else if (!use_null_for_out &&
5145 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5146 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005147 goto failed;
5148
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005149 if (use_file_for_err)
5150 {
5151 char_u *fname = options->jo_io_name[PART_ERR];
5152
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005153 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5154 FILE_SHARE_READ | FILE_SHARE_WRITE,
5155 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5156 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005157 {
5158 EMSG2(_(e_notopen), fname);
5159 goto failed;
5160 }
5161 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005162 else if (!use_out_for_err && !use_null_for_err &&
5163 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005164 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005165 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005166
Bram Moolenaard8070362016-02-15 21:56:54 +01005167 si.dwFlags |= STARTF_USESTDHANDLES;
5168 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005169 si.hStdOutput = ofd[1];
5170 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5171
5172 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5173 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005174 if (options->jo_set & JO_CHANNEL)
5175 {
5176 channel = options->jo_channel;
5177 if (channel != NULL)
5178 ++channel->ch_refcount;
5179 }
5180 else
5181 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005182 if (channel == NULL)
5183 goto failed;
5184 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005185
5186 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005187 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005188 CREATE_DEFAULT_ERROR_MODE |
5189 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005190 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005191 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005192 {
5193 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005194 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005195 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005196 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005197
5198 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005199 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005200 /* if failing, switch the way to terminate
5201 * process with TerminateProcess. */
5202 CloseHandle(jo);
5203 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005204 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005205 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005206 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005207 job->jv_proc_info = pi;
5208 job->jv_job_object = jo;
5209 job->jv_status = JOB_STARTED;
5210
Bram Moolenaar94d01912016-03-08 13:48:51 +01005211 if (!use_file_for_in)
5212 CloseHandle(ifd[0]);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005213 if (!use_file_for_out)
5214 CloseHandle(ofd[1]);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005215 if (!use_out_for_err && !use_file_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005216 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005217
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005218 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005219 if (channel != NULL)
5220 {
5221 channel_set_pipes(channel,
5222 use_file_for_in || use_null_for_in
5223 ? INVALID_FD : (sock_T)ifd[1],
5224 use_file_for_out || use_null_for_out
5225 ? INVALID_FD : (sock_T)ofd[0],
5226 use_out_for_err || use_file_for_err || use_null_for_err
5227 ? INVALID_FD : (sock_T)efd[0]);
5228 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005229 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005230 return;
5231
5232failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005233 CloseHandle(ifd[0]);
5234 CloseHandle(ofd[0]);
5235 CloseHandle(efd[0]);
5236 CloseHandle(ifd[1]);
5237 CloseHandle(ofd[1]);
5238 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005239 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005240}
5241
5242 char *
5243mch_job_status(job_T *job)
5244{
5245 DWORD dwExitCode = 0;
5246
Bram Moolenaar76467df2016-02-12 19:30:26 +01005247 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5248 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005249 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005250 job->jv_status = JOB_ENDED;
Bram Moolenaareab089d2016-02-21 19:32:02 +01005251 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005252 return "dead";
5253 }
5254 return "run";
5255}
5256
5257 int
5258mch_stop_job(job_T *job, char_u *how)
5259{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005260 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005261
Bram Moolenaar923d9262016-02-25 20:56:01 +01005262 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005263 {
5264 if (job->jv_job_object != NULL)
5265 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5266 else
5267 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5268 }
5269
5270 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5271 return FAIL;
5272 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005273 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5274 job->jv_proc_info.dwProcessId)
5275 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005276 FreeConsole();
5277 return ret;
5278}
5279
5280/*
5281 * Clear the data related to "job".
5282 */
5283 void
5284mch_clear_job(job_T *job)
5285{
5286 if (job->jv_status != JOB_FAILED)
5287 {
5288 if (job->jv_job_object != NULL)
5289 CloseHandle(job->jv_job_object);
5290 CloseHandle(job->jv_proc_info.hProcess);
5291 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005292}
5293#endif
5294
Bram Moolenaar071d4272004-06-13 20:20:40 +00005295
5296#ifndef FEAT_GUI_W32
5297
5298/*
5299 * Start termcap mode
5300 */
5301 static void
5302termcap_mode_start(void)
5303{
5304 DWORD cmodein;
5305
5306 if (g_fTermcapMode)
5307 return;
5308
5309 SaveConsoleBuffer(&g_cbNonTermcap);
5310
5311 if (g_cbTermcap.IsValid)
5312 {
5313 /*
5314 * We've been in termcap mode before. Restore certain screen
5315 * characteristics, including the buffer size and the window
5316 * size. Since we will be redrawing the screen, we don't need
5317 * to restore the actual contents of the buffer.
5318 */
5319 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5320 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5321 Rows = g_cbTermcap.Info.dwSize.Y;
5322 Columns = g_cbTermcap.Info.dwSize.X;
5323 }
5324 else
5325 {
5326 /*
5327 * This is our first time entering termcap mode. Clear the console
5328 * screen buffer, and resize the buffer to match the current window
5329 * size. We will use this as the size of our editing environment.
5330 */
5331 ClearConsoleBuffer(g_attrCurrent);
5332 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5333 }
5334
5335#ifdef FEAT_TITLE
5336 resettitle();
5337#endif
5338
5339 GetConsoleMode(g_hConIn, &cmodein);
5340#ifdef FEAT_MOUSE
5341 if (g_fMouseActive)
5342 cmodein |= ENABLE_MOUSE_INPUT;
5343 else
5344 cmodein &= ~ENABLE_MOUSE_INPUT;
5345#endif
5346 cmodein |= ENABLE_WINDOW_INPUT;
5347 SetConsoleMode(g_hConIn, cmodein);
5348
5349 redraw_later_clear();
5350 g_fTermcapMode = TRUE;
5351}
5352
5353
5354/*
5355 * End termcap mode
5356 */
5357 static void
5358termcap_mode_end(void)
5359{
5360 DWORD cmodein;
5361 ConsoleBuffer *cb;
5362 COORD coord;
5363 DWORD dwDummy;
5364
5365 if (!g_fTermcapMode)
5366 return;
5367
5368 SaveConsoleBuffer(&g_cbTermcap);
5369
5370 GetConsoleMode(g_hConIn, &cmodein);
5371 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5372 SetConsoleMode(g_hConIn, cmodein);
5373
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005374#ifdef FEAT_RESTORE_ORIG_SCREEN
5375 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5376#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005377 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005378#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005379 RestoreConsoleBuffer(cb, p_rs);
5380 SetConsoleCursorInfo(g_hConOut, &g_cci);
5381
5382 if (p_rs || exiting)
5383 {
5384 /*
5385 * Clear anything that happens to be on the current line.
5386 */
5387 coord.X = 0;
5388 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5389 FillConsoleOutputCharacter(g_hConOut, ' ',
5390 cb->Info.dwSize.X, coord, &dwDummy);
5391 /*
5392 * The following is just for aesthetics. If we are exiting without
5393 * restoring the screen, then we want to have a prompt string
5394 * appear at the bottom line. However, the command interpreter
5395 * seems to always advance the cursor one line before displaying
5396 * the prompt string, which causes the screen to scroll. To
5397 * counter this, move the cursor up one line before exiting.
5398 */
5399 if (exiting && !p_rs)
5400 coord.Y--;
5401 /*
5402 * Position the cursor at the leftmost column of the desired row.
5403 */
5404 SetConsoleCursorPosition(g_hConOut, coord);
5405 }
5406
5407 g_fTermcapMode = FALSE;
5408}
5409#endif /* FEAT_GUI_W32 */
5410
5411
5412#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005413/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414 void
5415mch_write(
5416 char_u *s,
5417 int len)
5418{
5419 /* never used */
5420}
5421
5422#else
5423
5424/*
5425 * clear `n' chars, starting from `coord'
5426 */
5427 static void
5428clear_chars(
5429 COORD coord,
5430 DWORD n)
5431{
5432 DWORD dwDummy;
5433
5434 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5435 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5436}
5437
5438
5439/*
5440 * Clear the screen
5441 */
5442 static void
5443clear_screen(void)
5444{
5445 g_coord.X = g_coord.Y = 0;
5446 clear_chars(g_coord, Rows * Columns);
5447}
5448
5449
5450/*
5451 * Clear to end of display
5452 */
5453 static void
5454clear_to_end_of_display(void)
5455{
5456 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5457 * Columns + (Columns - g_coord.X));
5458}
5459
5460
5461/*
5462 * Clear to end of line
5463 */
5464 static void
5465clear_to_end_of_line(void)
5466{
5467 clear_chars(g_coord, Columns - g_coord.X);
5468}
5469
5470
5471/*
5472 * Scroll the scroll region up by `cLines' lines
5473 */
5474 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005475scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476{
5477 COORD oldcoord = g_coord;
5478
5479 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5480 delete_lines(cLines);
5481
5482 g_coord = oldcoord;
5483}
5484
5485
5486/*
5487 * Set the scroll region
5488 */
5489 static void
5490set_scroll_region(
5491 unsigned left,
5492 unsigned top,
5493 unsigned right,
5494 unsigned bottom)
5495{
5496 if (left >= right
5497 || top >= bottom
5498 || right > (unsigned) Columns - 1
5499 || bottom > (unsigned) Rows - 1)
5500 return;
5501
5502 g_srScrollRegion.Left = left;
5503 g_srScrollRegion.Top = top;
5504 g_srScrollRegion.Right = right;
5505 g_srScrollRegion.Bottom = bottom;
5506}
5507
5508
5509/*
5510 * Insert `cLines' lines at the current cursor position
5511 */
5512 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005513insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005514{
5515 SMALL_RECT source;
5516 COORD dest;
5517 CHAR_INFO fill;
5518
5519 dest.X = 0;
5520 dest.Y = g_coord.Y + cLines;
5521
5522 source.Left = 0;
5523 source.Top = g_coord.Y;
5524 source.Right = g_srScrollRegion.Right;
5525 source.Bottom = g_srScrollRegion.Bottom - cLines;
5526
5527 fill.Char.AsciiChar = ' ';
5528 fill.Attributes = g_attrCurrent;
5529
5530 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5531
5532 /* Here we have to deal with a win32 console flake: If the scroll
5533 * region looks like abc and we scroll c to a and fill with d we get
5534 * cbd... if we scroll block c one line at a time to a, we get cdd...
5535 * vim expects cdd consistently... So we have to deal with that
5536 * here... (this also occurs scrolling the same way in the other
5537 * direction). */
5538
5539 if (source.Bottom < dest.Y)
5540 {
5541 COORD coord;
5542
5543 coord.X = 0;
5544 coord.Y = source.Bottom;
5545 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5546 }
5547}
5548
5549
5550/*
5551 * Delete `cLines' lines at the current cursor position
5552 */
5553 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005554delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005555{
5556 SMALL_RECT source;
5557 COORD dest;
5558 CHAR_INFO fill;
5559 int nb;
5560
5561 dest.X = 0;
5562 dest.Y = g_coord.Y;
5563
5564 source.Left = 0;
5565 source.Top = g_coord.Y + cLines;
5566 source.Right = g_srScrollRegion.Right;
5567 source.Bottom = g_srScrollRegion.Bottom;
5568
5569 fill.Char.AsciiChar = ' ';
5570 fill.Attributes = g_attrCurrent;
5571
5572 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5573
5574 /* Here we have to deal with a win32 console flake: If the scroll
5575 * region looks like abc and we scroll c to a and fill with d we get
5576 * cbd... if we scroll block c one line at a time to a, we get cdd...
5577 * vim expects cdd consistently... So we have to deal with that
5578 * here... (this also occurs scrolling the same way in the other
5579 * direction). */
5580
5581 nb = dest.Y + (source.Bottom - source.Top) + 1;
5582
5583 if (nb < source.Top)
5584 {
5585 COORD coord;
5586
5587 coord.X = 0;
5588 coord.Y = nb;
5589 clear_chars(coord, Columns * (source.Top - nb));
5590 }
5591}
5592
5593
5594/*
5595 * Set the cursor position
5596 */
5597 static void
5598gotoxy(
5599 unsigned x,
5600 unsigned y)
5601{
5602 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5603 return;
5604
5605 /* external cursor coords are 1-based; internal are 0-based */
5606 g_coord.X = x - 1;
5607 g_coord.Y = y - 1;
5608 SetConsoleCursorPosition(g_hConOut, g_coord);
5609}
5610
5611
5612/*
5613 * Set the current text attribute = (foreground | background)
5614 * See ../doc/os_win32.txt for the numbers.
5615 */
5616 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005617textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005619 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620
5621 SetConsoleTextAttribute(g_hConOut, wAttr);
5622}
5623
5624
5625 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005626textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005628 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005629
5630 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5631}
5632
5633
5634 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005635textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005637 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638
5639 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5640}
5641
5642
5643/*
5644 * restore the default text attribute (whatever we started with)
5645 */
5646 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005647normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648{
5649 textattr(g_attrDefault);
5650}
5651
5652
5653static WORD g_attrPreStandout = 0;
5654
5655/*
5656 * Make the text standout, by brightening it
5657 */
5658 static void
5659standout(void)
5660{
5661 g_attrPreStandout = g_attrCurrent;
5662 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5663}
5664
5665
5666/*
5667 * Turn off standout mode
5668 */
5669 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005670standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671{
5672 if (g_attrPreStandout)
5673 {
5674 textattr(g_attrPreStandout);
5675 g_attrPreStandout = 0;
5676 }
5677}
5678
5679
5680/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005681 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005682 */
5683 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005684mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685{
5686 char_u *p;
5687 int n;
5688
5689 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5690 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5691 if (T_ME[0] == ESC && T_ME[1] == '|')
5692 {
5693 p = T_ME + 2;
5694 n = getdigits(&p);
5695 if (*p == 'm' && n > 0)
5696 {
5697 cterm_normal_fg_color = (n & 0xf) + 1;
5698 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5699 }
5700 }
5701}
5702
5703
5704/*
5705 * visual bell: flash the screen
5706 */
5707 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005708visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005709{
5710 COORD coordOrigin = {0, 0};
5711 WORD attrFlash = ~g_attrCurrent & 0xff;
5712
5713 DWORD dwDummy;
5714 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5715
5716 if (oldattrs == NULL)
5717 return;
5718 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5719 coordOrigin, &dwDummy);
5720 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5721 coordOrigin, &dwDummy);
5722
5723 Sleep(15); /* wait for 15 msec */
5724 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5725 coordOrigin, &dwDummy);
5726 vim_free(oldattrs);
5727}
5728
5729
5730/*
5731 * Make the cursor visible or invisible
5732 */
5733 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005734cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735{
5736 s_cursor_visible = fVisible;
5737#ifdef MCH_CURSOR_SHAPE
5738 mch_update_cursor();
5739#endif
5740}
5741
5742
5743/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005744 * write `cbToWrite' bytes in `pchBuf' to the screen
5745 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005747 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005749 char_u *pchBuf,
5750 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005751{
5752 COORD coord = g_coord;
5753 DWORD written;
5754
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005755#ifdef FEAT_MBYTE
5756 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5757 {
5758 static WCHAR *unicodebuf = NULL;
5759 static int unibuflen = 0;
5760 int length;
5761 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005762
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005763 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5764 if (unicodebuf == NULL || length > unibuflen)
5765 {
5766 vim_free(unicodebuf);
5767 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5768 unibuflen = length;
5769 }
5770 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5771 unicodebuf, unibuflen);
5772
5773 cells = mb_string2cells(pchBuf, cbToWrite);
5774 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5775 coord, &written);
5776 /* When writing fails or didn't write a single character, pretend one
5777 * character was written, otherwise we get stuck. */
5778 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5779 coord, &cchwritten) == 0
5780 || cchwritten == 0)
5781 cchwritten = 1;
5782
5783 if (cchwritten == length)
5784 {
5785 written = cbToWrite;
5786 g_coord.X += (SHORT)cells;
5787 }
5788 else
5789 {
5790 char_u *p = pchBuf;
5791 for (n = 0; n < cchwritten; n++)
5792 mb_cptr_adv(p);
5793 written = p - pchBuf;
5794 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5795 }
5796 }
5797 else
5798#endif
5799 {
5800 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5801 coord, &written);
5802 /* When writing fails or didn't write a single character, pretend one
5803 * character was written, otherwise we get stuck. */
5804 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5805 coord, &written) == 0
5806 || written == 0)
5807 written = 1;
5808
5809 g_coord.X += (SHORT) written;
5810 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811
5812 while (g_coord.X > g_srScrollRegion.Right)
5813 {
5814 g_coord.X -= (SHORT) Columns;
5815 if (g_coord.Y < g_srScrollRegion.Bottom)
5816 g_coord.Y++;
5817 }
5818
5819 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5820
5821 return written;
5822}
5823
5824
5825/*
5826 * mch_write(): write the output buffer to the screen, translating ESC
5827 * sequences into calls to console output routines.
5828 */
5829 void
5830mch_write(
5831 char_u *s,
5832 int len)
5833{
5834 s[len] = NUL;
5835
5836 if (!term_console)
5837 {
5838 write(1, s, (unsigned)len);
5839 return;
5840 }
5841
5842 /* translate ESC | sequences into faked bios calls */
5843 while (len--)
5844 {
5845 /* optimization: use one single write_chars for runs of text,
5846 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005847 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848
5849 if (p_wd)
5850 {
5851 WaitForChar(p_wd);
5852 if (prefix != 0)
5853 prefix = 1;
5854 }
5855
5856 if (prefix != 0)
5857 {
5858 DWORD nWritten;
5859
5860 nWritten = write_chars(s, prefix);
5861#ifdef MCH_WRITE_DUMP
5862 if (fdDump)
5863 {
5864 fputc('>', fdDump);
5865 fwrite(s, sizeof(char_u), nWritten, fdDump);
5866 fputs("<\n", fdDump);
5867 }
5868#endif
5869 len -= (nWritten - 1);
5870 s += nWritten;
5871 }
5872 else if (s[0] == '\n')
5873 {
5874 /* \n, newline: go to the beginning of the next line or scroll */
5875 if (g_coord.Y == g_srScrollRegion.Bottom)
5876 {
5877 scroll(1);
5878 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5879 }
5880 else
5881 {
5882 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5883 }
5884#ifdef MCH_WRITE_DUMP
5885 if (fdDump)
5886 fputs("\\n\n", fdDump);
5887#endif
5888 s++;
5889 }
5890 else if (s[0] == '\r')
5891 {
5892 /* \r, carriage return: go to beginning of line */
5893 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5894#ifdef MCH_WRITE_DUMP
5895 if (fdDump)
5896 fputs("\\r\n", fdDump);
5897#endif
5898 s++;
5899 }
5900 else if (s[0] == '\b')
5901 {
5902 /* \b, backspace: move cursor one position left */
5903 if (g_coord.X > g_srScrollRegion.Left)
5904 g_coord.X--;
5905 else if (g_coord.Y > g_srScrollRegion.Top)
5906 {
5907 g_coord.X = g_srScrollRegion.Right;
5908 g_coord.Y--;
5909 }
5910 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5911#ifdef MCH_WRITE_DUMP
5912 if (fdDump)
5913 fputs("\\b\n", fdDump);
5914#endif
5915 s++;
5916 }
5917 else if (s[0] == '\a')
5918 {
5919 /* \a, bell */
5920 MessageBeep(0xFFFFFFFF);
5921#ifdef MCH_WRITE_DUMP
5922 if (fdDump)
5923 fputs("\\a\n", fdDump);
5924#endif
5925 s++;
5926 }
5927 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5928 {
5929#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005930 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005932 char_u *p;
5933 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934
5935 switch (s[2])
5936 {
5937 /* one or two numeric arguments, separated by ';' */
5938
5939 case '0': case '1': case '2': case '3': case '4':
5940 case '5': case '6': case '7': case '8': case '9':
5941 p = s + 2;
5942 arg1 = getdigits(&p); /* no check for length! */
5943 if (p > s + len)
5944 break;
5945
5946 if (*p == ';')
5947 {
5948 ++p;
5949 arg2 = getdigits(&p); /* no check for length! */
5950 if (p > s + len)
5951 break;
5952
5953 if (*p == 'H')
5954 gotoxy(arg2, arg1);
5955 else if (*p == 'r')
5956 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5957 }
5958 else if (*p == 'A')
5959 {
5960 /* move cursor up arg1 lines in same column */
5961 gotoxy(g_coord.X + 1,
5962 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5963 }
5964 else if (*p == 'C')
5965 {
5966 /* move cursor right arg1 columns in same line */
5967 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5968 g_coord.Y + 1);
5969 }
5970 else if (*p == 'H')
5971 {
5972 gotoxy(1, arg1);
5973 }
5974 else if (*p == 'L')
5975 {
5976 insert_lines(arg1);
5977 }
5978 else if (*p == 'm')
5979 {
5980 if (arg1 == 0)
5981 normvideo();
5982 else
5983 textattr((WORD) arg1);
5984 }
5985 else if (*p == 'f')
5986 {
5987 textcolor((WORD) arg1);
5988 }
5989 else if (*p == 'b')
5990 {
5991 textbackground((WORD) arg1);
5992 }
5993 else if (*p == 'M')
5994 {
5995 delete_lines(arg1);
5996 }
5997
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005998 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005999 s = p + 1;
6000 break;
6001
6002
6003 /* Three-character escape sequences */
6004
6005 case 'A':
6006 /* move cursor up one line in same column */
6007 gotoxy(g_coord.X + 1,
6008 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6009 goto got3;
6010
6011 case 'B':
6012 visual_bell();
6013 goto got3;
6014
6015 case 'C':
6016 /* move cursor right one column in same line */
6017 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6018 g_coord.Y + 1);
6019 goto got3;
6020
6021 case 'E':
6022 termcap_mode_end();
6023 goto got3;
6024
6025 case 'F':
6026 standout();
6027 goto got3;
6028
6029 case 'f':
6030 standend();
6031 goto got3;
6032
6033 case 'H':
6034 gotoxy(1, 1);
6035 goto got3;
6036
6037 case 'j':
6038 clear_to_end_of_display();
6039 goto got3;
6040
6041 case 'J':
6042 clear_screen();
6043 goto got3;
6044
6045 case 'K':
6046 clear_to_end_of_line();
6047 goto got3;
6048
6049 case 'L':
6050 insert_lines(1);
6051 goto got3;
6052
6053 case 'M':
6054 delete_lines(1);
6055 goto got3;
6056
6057 case 'S':
6058 termcap_mode_start();
6059 goto got3;
6060
6061 case 'V':
6062 cursor_visible(TRUE);
6063 goto got3;
6064
6065 case 'v':
6066 cursor_visible(FALSE);
6067 goto got3;
6068
6069 got3:
6070 s += 3;
6071 len -= 2;
6072 }
6073
6074#ifdef MCH_WRITE_DUMP
6075 if (fdDump)
6076 {
6077 fputs("ESC | ", fdDump);
6078 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6079 fputc('\n', fdDump);
6080 }
6081#endif
6082 }
6083 else
6084 {
6085 /* Write a single character */
6086 DWORD nWritten;
6087
6088 nWritten = write_chars(s, 1);
6089#ifdef MCH_WRITE_DUMP
6090 if (fdDump)
6091 {
6092 fputc('>', fdDump);
6093 fwrite(s, sizeof(char_u), nWritten, fdDump);
6094 fputs("<\n", fdDump);
6095 }
6096#endif
6097
6098 len -= (nWritten - 1);
6099 s += nWritten;
6100 }
6101 }
6102
6103#ifdef MCH_WRITE_DUMP
6104 if (fdDump)
6105 fflush(fdDump);
6106#endif
6107}
6108
6109#endif /* FEAT_GUI_W32 */
6110
6111
6112/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006113 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006115/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 void
6117mch_delay(
6118 long msec,
6119 int ignoreinput)
6120{
6121#ifdef FEAT_GUI_W32
6122 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006123#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006125# ifdef FEAT_MZSCHEME
6126 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6127 {
6128 int towait = p_mzq;
6129
6130 /* if msec is large enough, wait by portions in p_mzq */
6131 while (msec > 0)
6132 {
6133 mzvim_check_threads();
6134 if (msec < towait)
6135 towait = msec;
6136 Sleep(towait);
6137 msec -= towait;
6138 }
6139 }
6140 else
6141# endif
6142 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143 else
6144 WaitForChar(msec);
6145#endif
6146}
6147
6148
6149/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006150 * This version of remove is not scared by a readonly (backup) file.
6151 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152 * Return 0 for success, -1 for failure.
6153 */
6154 int
6155mch_remove(char_u *name)
6156{
6157#ifdef FEAT_MBYTE
6158 WCHAR *wn = NULL;
6159 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006160#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161
Bram Moolenaar203258c2016-01-17 22:15:16 +01006162 /*
6163 * On Windows, deleting a directory's symbolic link is done by
6164 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6165 */
6166 if (mch_isdir(name) && mch_is_symbolic_link(name))
6167 return mch_rmdir(name);
6168
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006169 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6170
6171#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6173 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006174 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 if (wn != NULL)
6176 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177 n = DeleteFileW(wn) ? 0 : -1;
6178 vim_free(wn);
6179 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6180 return n;
6181 /* Retry with non-wide function (for Windows 98). */
6182 }
6183 }
6184#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006185 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186}
6187
6188
6189/*
6190 * check for an "interrupt signal": CTRL-break or CTRL-C
6191 */
6192 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006193mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006194{
6195#ifndef FEAT_GUI_W32 /* never used */
6196 if (g_fCtrlCPressed || g_fCBrkPressed)
6197 {
6198 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6199 got_int = TRUE;
6200 }
6201#endif
6202}
6203
Bram Moolenaaree273972016-01-02 21:11:51 +01006204/* physical RAM to leave for the OS */
6205#define WINNT_RESERVE_BYTES (256*1024*1024)
6206#define WIN95_RESERVE_BYTES (8*1024*1024)
6207
6208/*
6209 * How much main memory in KiB that can be used by VIM.
6210 */
6211/*ARGSUSED*/
6212 long_u
6213mch_total_mem(int special)
6214{
6215 PlatformId();
6216#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6217 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6218 {
6219 MEMORYSTATUSEX ms;
6220
6221 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6222 * what fits in 32 bits. But it's not always available. */
6223 ms.dwLength = sizeof(MEMORYSTATUSEX);
6224 GlobalMemoryStatusEx(&ms);
6225 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6226 {
6227 /* Process address space fits in physical RAM, use all of it. */
6228 return (long_u)(ms.ullAvailVirtual / 1024);
6229 }
6230 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6231 {
6232 /* Catch old NT box or perverse hardware setup. */
6233 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6234 }
6235 /* Use physical RAM less reserve for OS + data. */
6236 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6237 }
6238 else
6239#endif
6240 {
6241 /* Pre-XP or 95 OS handling. */
6242 MEMORYSTATUS ms;
6243 long_u os_reserve_bytes;
6244
6245 ms.dwLength = sizeof(MEMORYSTATUS);
6246 GlobalMemoryStatus(&ms);
6247 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6248 {
6249 /* Process address space fits in physical RAM, use all of it. */
6250 return (long_u)(ms.dwAvailVirtual / 1024);
6251 }
6252 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6253 ? WINNT_RESERVE_BYTES
6254 : WIN95_RESERVE_BYTES;
6255 if (ms.dwTotalPhys <= os_reserve_bytes)
6256 {
6257 /* Catch old boxes or perverse hardware setup. */
6258 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6259 }
6260 /* Use physical RAM less reserve for OS + data. */
6261 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6262 }
6263}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265#ifdef FEAT_MBYTE
6266/*
6267 * Same code as below, but with wide functions and no comments.
6268 * Return 0 for success, non-zero for failure.
6269 */
6270 int
6271mch_wrename(WCHAR *wold, WCHAR *wnew)
6272{
6273 WCHAR *p;
6274 int i;
6275 WCHAR szTempFile[_MAX_PATH + 1];
6276 WCHAR szNewPath[_MAX_PATH + 1];
6277 HANDLE hf;
6278
6279 if (!mch_windows95())
6280 {
6281 p = wold;
6282 for (i = 0; wold[i] != NUL; ++i)
6283 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6284 && wold[i + 1] != 0)
6285 p = wold + i + 1;
6286 if ((int)(wold + i - p) < 8 || p[6] != '~')
6287 return (MoveFileW(wold, wnew) == 0);
6288 }
6289
6290 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6291 return -1;
6292 *p = NUL;
6293
6294 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6295 return -2;
6296
6297 if (!DeleteFileW(szTempFile))
6298 return -3;
6299
6300 if (!MoveFileW(wold, szTempFile))
6301 return -4;
6302
6303 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6304 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6305 return -5;
6306 if (!CloseHandle(hf))
6307 return -6;
6308
6309 if (!MoveFileW(szTempFile, wnew))
6310 {
6311 (void)MoveFileW(szTempFile, wold);
6312 return -7;
6313 }
6314
6315 DeleteFileW(szTempFile);
6316
6317 if (!DeleteFileW(wold))
6318 return -8;
6319
6320 return 0;
6321}
6322#endif
6323
6324
6325/*
6326 * mch_rename() works around a bug in rename (aka MoveFile) in
6327 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6328 * file whose short file name is "FOO.BAR" (its long file name will
6329 * be correct: "foo.bar~"). Because a file can be accessed by
6330 * either its SFN or its LFN, "foo.bar" has effectively been
6331 * renamed to "foo.bar", which is not at all what was wanted. This
6332 * seems to happen only when renaming files with three-character
6333 * extensions by appending a suffix that does not include ".".
6334 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6335 *
6336 * There is another problem, which isn't really a bug but isn't right either:
6337 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6338 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6339 * service pack 6. Doesn't seem to happen on Windows 98.
6340 *
6341 * Like rename(), returns 0 upon success, non-zero upon failure.
6342 * Should probably set errno appropriately when errors occur.
6343 */
6344 int
6345mch_rename(
6346 const char *pszOldFile,
6347 const char *pszNewFile)
6348{
6349 char szTempFile[_MAX_PATH+1];
6350 char szNewPath[_MAX_PATH+1];
6351 char *pszFilePart;
6352 HANDLE hf;
6353#ifdef FEAT_MBYTE
6354 WCHAR *wold = NULL;
6355 WCHAR *wnew = NULL;
6356 int retval = -1;
6357
6358 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6359 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006360 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6361 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362 if (wold != NULL && wnew != NULL)
6363 retval = mch_wrename(wold, wnew);
6364 vim_free(wold);
6365 vim_free(wnew);
6366 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6367 return retval;
6368 /* Retry with non-wide function (for Windows 98). */
6369 }
6370#endif
6371
6372 /*
6373 * No need to play tricks if not running Windows 95, unless the file name
6374 * contains a "~" as the seventh character.
6375 */
6376 if (!mch_windows95())
6377 {
6378 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6379 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6380 return rename(pszOldFile, pszNewFile);
6381 }
6382
6383 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6384 * a directory, no error is returned and pszFilePart will be NULL. */
6385 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6386 || pszFilePart == NULL)
6387 return -1;
6388 *pszFilePart = NUL;
6389
6390 /* Get (and create) a unique temporary file name in directory of new file */
6391 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6392 return -2;
6393
6394 /* blow the temp file away */
6395 if (!DeleteFile(szTempFile))
6396 return -3;
6397
6398 /* rename old file to the temp file */
6399 if (!MoveFile(pszOldFile, szTempFile))
6400 return -4;
6401
6402 /* now create an empty file called pszOldFile; this prevents the operating
6403 * system using pszOldFile as an alias (SFN) if we're renaming within the
6404 * same directory. For example, we're editing a file called
6405 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6406 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6407 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006408 * cause all sorts of problems later in buf_write(). So, we create an
6409 * empty file called filena~1.txt and the system will have to find some
6410 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 */
6412 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6413 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6414 return -5;
6415 if (!CloseHandle(hf))
6416 return -6;
6417
6418 /* rename the temp file to the new file */
6419 if (!MoveFile(szTempFile, pszNewFile))
6420 {
6421 /* Renaming failed. Rename the file back to its old name, so that it
6422 * looks like nothing happened. */
6423 (void)MoveFile(szTempFile, pszOldFile);
6424
6425 return -7;
6426 }
6427
6428 /* Seems to be left around on Novell filesystems */
6429 DeleteFile(szTempFile);
6430
6431 /* finally, remove the empty old file */
6432 if (!DeleteFile(pszOldFile))
6433 return -8;
6434
6435 return 0; /* success */
6436}
6437
6438/*
6439 * Get the default shell for the current hardware platform
6440 */
6441 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006442default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006443{
6444 char* psz = NULL;
6445
6446 PlatformId();
6447
6448 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6449 psz = "cmd.exe";
6450 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6451 psz = "command.com";
6452
6453 return psz;
6454}
6455
6456/*
6457 * mch_access() extends access() to do more detailed check on network drives.
6458 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6459 */
6460 int
6461mch_access(char *n, int p)
6462{
6463 HANDLE hFile;
6464 DWORD am;
6465 int retval = -1; /* default: fail */
6466#ifdef FEAT_MBYTE
6467 WCHAR *wn = NULL;
6468
6469 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006470 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471#endif
6472
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006473 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006474 {
6475 char TempName[_MAX_PATH + 16] = "";
6476#ifdef FEAT_MBYTE
6477 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6478#endif
6479
6480 if (p & R_OK)
6481 {
6482 /* Read check is performed by seeing if we can do a find file on
6483 * the directory for any file. */
6484#ifdef FEAT_MBYTE
6485 if (wn != NULL)
6486 {
6487 int i;
6488 WIN32_FIND_DATAW d;
6489
6490 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6491 TempNameW[i] = wn[i];
6492 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6493 TempNameW[i++] = '\\';
6494 TempNameW[i++] = '*';
6495 TempNameW[i++] = 0;
6496
6497 hFile = FindFirstFileW(TempNameW, &d);
6498 if (hFile == INVALID_HANDLE_VALUE)
6499 {
6500 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6501 goto getout;
6502
6503 /* Retry with non-wide function (for Windows 98). */
6504 vim_free(wn);
6505 wn = NULL;
6506 }
6507 else
6508 (void)FindClose(hFile);
6509 }
6510 if (wn == NULL)
6511#endif
6512 {
6513 char *pch;
6514 WIN32_FIND_DATA d;
6515
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006516 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 pch = TempName + STRLEN(TempName) - 1;
6518 if (*pch != '\\' && *pch != '/')
6519 *++pch = '\\';
6520 *++pch = '*';
6521 *++pch = NUL;
6522
6523 hFile = FindFirstFile(TempName, &d);
6524 if (hFile == INVALID_HANDLE_VALUE)
6525 goto getout;
6526 (void)FindClose(hFile);
6527 }
6528 }
6529
6530 if (p & W_OK)
6531 {
6532 /* Trying to create a temporary file in the directory should catch
6533 * directories on read-only network shares. However, in
6534 * directories whose ACL allows writes but denies deletes will end
6535 * up keeping the temporary file :-(. */
6536#ifdef FEAT_MBYTE
6537 if (wn != NULL)
6538 {
6539 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6540 {
6541 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6542 goto getout;
6543
6544 /* Retry with non-wide function (for Windows 98). */
6545 vim_free(wn);
6546 wn = NULL;
6547 }
6548 else
6549 DeleteFileW(TempNameW);
6550 }
6551 if (wn == NULL)
6552#endif
6553 {
6554 if (!GetTempFileName(n, "VIM", 0, TempName))
6555 goto getout;
6556 mch_remove((char_u *)TempName);
6557 }
6558 }
6559 }
6560 else
6561 {
6562 /* Trying to open the file for the required access does ACL, read-only
6563 * network share, and file attribute checks. */
6564 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6565 | ((p & R_OK) ? GENERIC_READ : 0);
6566#ifdef FEAT_MBYTE
6567 if (wn != NULL)
6568 {
6569 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6570 if (hFile == INVALID_HANDLE_VALUE
6571 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6572 {
6573 /* Retry with non-wide function (for Windows 98). */
6574 vim_free(wn);
6575 wn = NULL;
6576 }
6577 }
6578 if (wn == NULL)
6579#endif
6580 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6581 if (hFile == INVALID_HANDLE_VALUE)
6582 goto getout;
6583 CloseHandle(hFile);
6584 }
6585
6586 retval = 0; /* success */
6587getout:
6588#ifdef FEAT_MBYTE
6589 vim_free(wn);
6590#endif
6591 return retval;
6592}
6593
6594#if defined(FEAT_MBYTE) || defined(PROTO)
6595/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006596 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006597 */
6598 int
6599mch_open(char *name, int flags, int mode)
6600{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006601 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6602# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603 WCHAR *wn;
6604 int f;
6605
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006606 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006608 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006609 if (wn != NULL)
6610 {
6611 f = _wopen(wn, flags, mode);
6612 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006613 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614 return f;
6615 /* Retry with non-wide function (for Windows 98). Can't use
6616 * GetLastError() here and it's unclear what errno gets set to if
6617 * the _wopen() fails for missing wide functions. */
6618 }
6619 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006620# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006622 /* open() can open a file which name is longer than _MAX_PATH bytes
6623 * and shorter than _MAX_PATH characters successfully, but sometimes it
6624 * causes unexpected error in another part. We make it an error explicitly
6625 * here. */
6626 if (strlen(name) >= _MAX_PATH)
6627 return -1;
6628
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629 return open(name, flags, mode);
6630}
6631
6632/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006633 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634 */
6635 FILE *
6636mch_fopen(char *name, char *mode)
6637{
6638 WCHAR *wn, *wm;
6639 FILE *f = NULL;
6640
6641 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6642# ifdef __BORLANDC__
6643 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6644 && g_PlatformId == VER_PLATFORM_WIN32_NT
6645# endif
6646 )
6647 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006648# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006649 /* Work around an annoying assertion in the Microsoft debug CRT
6650 * when mode's text/binary setting doesn't match _get_fmode(). */
6651 char newMode = mode[strlen(mode) - 1];
6652 int oldMode = 0;
6653
6654 _get_fmode(&oldMode);
6655 if (newMode == 't')
6656 _set_fmode(_O_TEXT);
6657 else if (newMode == 'b')
6658 _set_fmode(_O_BINARY);
6659# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006660 wn = enc_to_utf16((char_u *)name, NULL);
6661 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 if (wn != NULL && wm != NULL)
6663 f = _wfopen(wn, wm);
6664 vim_free(wn);
6665 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006666
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006667# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006668 _set_fmode(oldMode);
6669# endif
6670
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006671 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 return f;
6673 /* Retry with non-wide function (for Windows 98). Can't use
6674 * GetLastError() here and it's unclear what errno gets set to if
6675 * the _wfopen() fails for missing wide functions. */
6676 }
6677
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006678 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6679 * and shorter than _MAX_PATH characters successfully, but sometimes it
6680 * causes unexpected error in another part. We make it an error explicitly
6681 * here. */
6682 if (strlen(name) >= _MAX_PATH)
6683 return NULL;
6684
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 return fopen(name, mode);
6686}
6687#endif
6688
6689#ifdef FEAT_MBYTE
6690/*
6691 * SUB STREAM (aka info stream) handling:
6692 *
6693 * NTFS can have sub streams for each file. Normal contents of file is
6694 * stored in the main stream, and extra contents (author information and
6695 * title and so on) can be stored in sub stream. After Windows 2000, user
6696 * can access and store those informations in sub streams via explorer's
6697 * property menuitem in right click menu. Those informations in sub streams
6698 * were lost when copying only the main stream. So we have to copy sub
6699 * streams.
6700 *
6701 * Incomplete explanation:
6702 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6703 * More useful info and an example:
6704 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6705 */
6706
6707/*
6708 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6709 * and write to stream "substream" of file "to".
6710 * Errors are ignored.
6711 */
6712 static void
6713copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6714{
6715 HANDLE hTo;
6716 WCHAR *to_name;
6717
6718 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6719 wcscpy(to_name, to);
6720 wcscat(to_name, substream);
6721
6722 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6723 FILE_ATTRIBUTE_NORMAL, NULL);
6724 if (hTo != INVALID_HANDLE_VALUE)
6725 {
6726 long done;
6727 DWORD todo;
6728 DWORD readcnt, written;
6729 char buf[4096];
6730
6731 /* Copy block of bytes at a time. Abort when something goes wrong. */
6732 for (done = 0; done < len; done += written)
6733 {
6734 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006735 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6736 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006737 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6738 FALSE, FALSE, context)
6739 || readcnt != todo
6740 || !WriteFile(hTo, buf, todo, &written, NULL)
6741 || written != todo)
6742 break;
6743 }
6744 CloseHandle(hTo);
6745 }
6746
6747 free(to_name);
6748}
6749
6750/*
6751 * Copy info streams from file "from" to file "to".
6752 */
6753 static void
6754copy_infostreams(char_u *from, char_u *to)
6755{
6756 WCHAR *fromw;
6757 WCHAR *tow;
6758 HANDLE sh;
6759 WIN32_STREAM_ID sid;
6760 int headersize;
6761 WCHAR streamname[_MAX_PATH];
6762 DWORD readcount;
6763 void *context = NULL;
6764 DWORD lo, hi;
6765 int len;
6766
6767 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006768 fromw = enc_to_utf16(from, NULL);
6769 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770 if (fromw != NULL && tow != NULL)
6771 {
6772 /* Open the file for reading. */
6773 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6774 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6775 if (sh != INVALID_HANDLE_VALUE)
6776 {
6777 /* Use BackupRead() to find the info streams. Repeat until we
6778 * have done them all.*/
6779 for (;;)
6780 {
6781 /* Get the header to find the length of the stream name. If
6782 * the "readcount" is zero we have done all info streams. */
6783 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006784 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6786 &readcount, FALSE, FALSE, &context)
6787 || readcount == 0)
6788 break;
6789
6790 /* We only deal with streams that have a name. The normal
6791 * file data appears to be without a name, even though docs
6792 * suggest it is called "::$DATA". */
6793 if (sid.dwStreamNameSize > 0)
6794 {
6795 /* Read the stream name. */
6796 if (!BackupRead(sh, (LPBYTE)streamname,
6797 sid.dwStreamNameSize,
6798 &readcount, FALSE, FALSE, &context))
6799 break;
6800
6801 /* Copy an info stream with a name ":anything:$DATA".
6802 * Skip "::$DATA", it has no stream name (examples suggest
6803 * it might be used for the normal file contents).
6804 * Note that BackupRead() counts bytes, but the name is in
6805 * wide characters. */
6806 len = readcount / sizeof(WCHAR);
6807 streamname[len] = 0;
6808 if (len > 7 && wcsicmp(streamname + len - 6,
6809 L":$DATA") == 0)
6810 {
6811 streamname[len - 6] = 0;
6812 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006813 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006814 }
6815 }
6816
6817 /* Advance to the next stream. We might try seeking too far,
6818 * but BackupSeek() doesn't skip over stream borders, thus
6819 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006820 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821 &lo, &hi, &context);
6822 }
6823
6824 /* Clear the context. */
6825 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6826
6827 CloseHandle(sh);
6828 }
6829 }
6830 vim_free(fromw);
6831 vim_free(tow);
6832}
6833#endif
6834
6835/*
6836 * Copy file attributes from file "from" to file "to".
6837 * For Windows NT and later we copy info streams.
6838 * Always returns zero, errors are ignored.
6839 */
6840 int
6841mch_copy_file_attribute(char_u *from, char_u *to)
6842{
6843#ifdef FEAT_MBYTE
6844 /* File streams only work on Windows NT and later. */
6845 PlatformId();
6846 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6847 copy_infostreams(from, to);
6848#endif
6849 return 0;
6850}
6851
6852#if defined(MYRESETSTKOFLW) || defined(PROTO)
6853/*
6854 * Recreate a destroyed stack guard page in win32.
6855 * Written by Benjamin Peterson.
6856 */
6857
6858/* These magic numbers are from the MS header files */
6859#define MIN_STACK_WIN9X 17
6860#define MIN_STACK_WINNT 2
6861
6862/*
6863 * This function does the same thing as _resetstkoflw(), which is only
6864 * available in DevStudio .net and later.
6865 * Returns 0 for failure, 1 for success.
6866 */
6867 int
6868myresetstkoflw(void)
6869{
6870 BYTE *pStackPtr;
6871 BYTE *pGuardPage;
6872 BYTE *pStackBase;
6873 BYTE *pLowestPossiblePage;
6874 MEMORY_BASIC_INFORMATION mbi;
6875 SYSTEM_INFO si;
6876 DWORD nPageSize;
6877 DWORD dummy;
6878
6879 /* This code will not work on win32s. */
6880 PlatformId();
6881 if (g_PlatformId == VER_PLATFORM_WIN32s)
6882 return 0;
6883
6884 /* We need to know the system page size. */
6885 GetSystemInfo(&si);
6886 nPageSize = si.dwPageSize;
6887
6888 /* ...and the current stack pointer */
6889 pStackPtr = (BYTE*)_alloca(1);
6890
6891 /* ...and the base of the stack. */
6892 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6893 return 0;
6894 pStackBase = (BYTE*)mbi.AllocationBase;
6895
6896 /* ...and the page thats min_stack_req pages away from stack base; this is
6897 * the lowest page we could use. */
6898 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6899 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6900
6901 /* On Win95, we want the next page down from the end of the stack. */
6902 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6903 {
6904 /* Find the page that's only 1 page down from the page that the stack
6905 * ptr is in. */
6906 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6907 / (DWORD)nPageSize) - 1));
6908 if (pGuardPage < pLowestPossiblePage)
6909 return 0;
6910
6911 /* Apply the noaccess attribute to the page -- there's no guard
6912 * attribute in win95-type OSes. */
6913 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6914 return 0;
6915 }
6916 else
6917 {
6918 /* On NT, however, we want the first committed page in the stack Start
6919 * at the stack base and move forward through memory until we find a
6920 * committed block. */
6921 BYTE *pBlock = pStackBase;
6922
Bram Moolenaara466c992005-07-09 21:03:22 +00006923 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924 {
6925 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6926 return 0;
6927
6928 pBlock += mbi.RegionSize;
6929
6930 if (mbi.State & MEM_COMMIT)
6931 break;
6932 }
6933
6934 /* mbi now describes the first committed block in the stack. */
6935 if (mbi.Protect & PAGE_GUARD)
6936 return 1;
6937
6938 /* decide where the guard page should start */
6939 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6940 pGuardPage = pLowestPossiblePage;
6941 else
6942 pGuardPage = (BYTE*)mbi.BaseAddress;
6943
6944 /* allocate the guard page */
6945 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6946 return 0;
6947
6948 /* apply the guard attribute to the page */
6949 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6950 &dummy))
6951 return 0;
6952 }
6953
6954 return 1;
6955}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006956#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006958
6959#if defined(FEAT_MBYTE) || defined(PROTO)
6960/*
6961 * The command line arguments in UCS2
6962 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006963static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006964static LPWSTR *ArglistW = NULL;
6965static int global_argc = 0;
6966static char **global_argv;
6967
6968static int used_file_argc = 0; /* last argument in global_argv[] used
6969 for the argument list. */
6970static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6971 command line arguments added to
6972 the argument list */
6973static int used_file_count = 0; /* nr of entries in used_file_indexes */
6974static int used_file_literal = FALSE; /* take file names literally */
6975static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006976static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006977static int used_alist_count = 0;
6978
6979
6980/*
6981 * Get the command line arguments. Unicode version.
6982 * Returns argc. Zero when something fails.
6983 */
6984 int
6985get_cmd_argsW(char ***argvp)
6986{
6987 char **argv = NULL;
6988 int argc = 0;
6989 int i;
6990
Bram Moolenaar14993322014-09-09 12:25:33 +02006991 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006992 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6993 if (ArglistW != NULL)
6994 {
6995 argv = malloc((nArgsW + 1) * sizeof(char *));
6996 if (argv != NULL)
6997 {
6998 argc = nArgsW;
6999 argv[argc] = NULL;
7000 for (i = 0; i < argc; ++i)
7001 {
7002 int len;
7003
7004 /* Convert each Unicode argument to the current codepage. */
7005 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007006 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007007 (LPSTR *)&argv[i], &len, 0, 0);
7008 if (argv[i] == NULL)
7009 {
7010 /* Out of memory, clear everything. */
7011 while (i > 0)
7012 free(argv[--i]);
7013 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007014 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007015 argc = 0;
7016 }
7017 }
7018 }
7019 }
7020
7021 global_argc = argc;
7022 global_argv = argv;
7023 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007024 {
7025 if (used_file_indexes != NULL)
7026 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007027 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007028 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007029
7030 if (argvp != NULL)
7031 *argvp = argv;
7032 return argc;
7033}
7034
7035 void
7036free_cmd_argsW(void)
7037{
7038 if (ArglistW != NULL)
7039 {
7040 GlobalFree(ArglistW);
7041 ArglistW = NULL;
7042 }
7043}
7044
7045/*
7046 * Remember "name" is an argument that was added to the argument list.
7047 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7048 * is called.
7049 */
7050 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007051used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007052{
7053 int i;
7054
7055 if (used_file_indexes == NULL)
7056 return;
7057 for (i = used_file_argc + 1; i < global_argc; ++i)
7058 if (STRCMP(global_argv[i], name) == 0)
7059 {
7060 used_file_argc = i;
7061 used_file_indexes[used_file_count++] = i;
7062 break;
7063 }
7064 used_file_literal = literal;
7065 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007066 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007067}
7068
7069/*
7070 * Remember the length of the argument list as it was. If it changes then we
7071 * leave it alone when 'encoding' is set.
7072 */
7073 void
7074set_alist_count(void)
7075{
7076 used_alist_count = GARGCOUNT;
7077}
7078
7079/*
7080 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7081 * has been changed while starting up. Use the UCS-2 command line arguments
7082 * and convert them to 'encoding'.
7083 */
7084 void
7085fix_arg_enc(void)
7086{
7087 int i;
7088 int idx;
7089 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007090 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007091
7092 /* Safety checks:
7093 * - if argument count differs between the wide and non-wide argument
7094 * list, something must be wrong.
7095 * - the file name arguments must have been located.
7096 * - the length of the argument list wasn't changed by the user.
7097 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007098 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007099 || ArglistW == NULL
7100 || used_file_indexes == NULL
7101 || used_file_count == 0
7102 || used_alist_count != GARGCOUNT)
7103 return;
7104
Bram Moolenaar86b68352004-12-27 21:59:20 +00007105 /* Remember the buffer numbers for the arguments. */
7106 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7107 if (fnum_list == NULL)
7108 return; /* out of memory */
7109 for (i = 0; i < GARGCOUNT; ++i)
7110 fnum_list[i] = GARGLIST[i].ae_fnum;
7111
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007112 /* Clear the argument list. Make room for the new arguments. */
7113 alist_clear(&global_alist);
7114 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007115 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007116
7117 for (i = 0; i < used_file_count; ++i)
7118 {
7119 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007120 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007121 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007122 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007123#ifdef FEAT_DIFF
7124 /* When using diff mode may need to concatenate file name to
7125 * directory name. Just like it's done in main(). */
7126 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7127 && !mch_isdir(alist_name(&GARGLIST[0])))
7128 {
7129 char_u *r;
7130
7131 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7132 if (r != NULL)
7133 {
7134 vim_free(str);
7135 str = r;
7136 }
7137 }
7138#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007139 /* Re-use the old buffer by renaming it. When not using literal
7140 * names it's done by alist_expand() below. */
7141 if (used_file_literal)
7142 buf_set_name(fnum_list[i], str);
7143
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007144 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007145 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007146 }
7147
7148 if (!used_file_literal)
7149 {
7150 /* Now expand wildcards in the arguments. */
7151 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7152 * filename characters but are excluded from 'isfname' to make
7153 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7154 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007155 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007156 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7157 }
7158
7159 /* If wildcard expansion failed, we are editing the first file of the
7160 * arglist and there is no file name: Edit the first argument now. */
7161 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7162 {
7163 do_cmdline_cmd((char_u *)":rewind");
7164 if (GARGCOUNT == 1 && used_file_full_path)
7165 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7166 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007167
7168 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007169}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170#endif