blob: 627d515dda5465ce5a5d719c6a16492b8d6e72a7 [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 *);
475static char *null_libintl_textdomain(const char *);
476static char *null_libintl_bindtextdomain(const char *, const char *);
477static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000480char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
481char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
482char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000483 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000484char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
485 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486
487 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100488dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000489{
490 int i;
491 static struct
492 {
493 char *name;
494 FARPROC *ptr;
495 } libintl_entry[] =
496 {
497 {"gettext", (FARPROC*)&dyn_libintl_gettext},
498 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
499 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
500 {NULL, NULL}
501 };
502
503 /* No need to initialize twice. */
504 if (hLibintlDLL)
505 return 1;
506 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100507 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100508#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100509 if (!hLibintlDLL)
510 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100511#endif
512 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000513 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200514 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200516 verbose_enter();
517 EMSG2(_(e_loadlib), GETTEXT_DLL);
518 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200520 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521 }
522 for (i = 0; libintl_entry[i].name != NULL
523 && libintl_entry[i].ptr != NULL; ++i)
524 {
525 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
526 libintl_entry[i].name)) == NULL)
527 {
528 dyn_libintl_end();
529 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000530 {
531 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000533 verbose_leave();
534 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535 return 0;
536 }
537 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000538
539 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000540 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000541 "bind_textdomain_codeset");
542 if (dyn_libintl_bind_textdomain_codeset == NULL)
543 dyn_libintl_bind_textdomain_codeset =
544 null_libintl_bind_textdomain_codeset;
545
Bram Moolenaar071d4272004-06-13 20:20:40 +0000546 return 1;
547}
548
549 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100550dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000551{
552 if (hLibintlDLL)
553 FreeLibrary(hLibintlDLL);
554 hLibintlDLL = NULL;
555 dyn_libintl_gettext = null_libintl_gettext;
556 dyn_libintl_textdomain = null_libintl_textdomain;
557 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000558 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559}
560
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000561/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000562 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000563null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000564{
565 return (char*)msgid;
566}
567
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000568/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000570null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000571{
572 return NULL;
573}
574
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000575/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000577null_libintl_bind_textdomain_codeset(const char *domainname,
578 const char *codeset)
579{
580 return NULL;
581}
582
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000583/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000584 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000585null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000586{
587 return NULL;
588}
589
590#endif /* DYNAMIC_GETTEXT */
591
592/* This symbol is not defined in older versions of the SDK or Visual C++ */
593
594#ifndef VER_PLATFORM_WIN32_WINDOWS
595# define VER_PLATFORM_WIN32_WINDOWS 1
596#endif
597
598DWORD g_PlatformId;
599
600#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100601# ifndef PROTO
602# include <aclapi.h>
603# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200604# ifndef PROTECTED_DACL_SECURITY_INFORMATION
605# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
606# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100607
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608/*
609 * These are needed to dynamically load the ADVAPI DLL, which is not
610 * implemented under Windows 95 (and causes VIM to crash)
611 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200612typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000613 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200614typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
616 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200617# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200618typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200619 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200620typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200621 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
622 PSECURITY_DESCRIPTOR *);
623# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624
625static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
626static PSNSECINFO pSetNamedSecurityInfo;
627static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200628# ifdef FEAT_MBYTE
629static PSNSECINFOW pSetNamedSecurityInfoW;
630static PGNSECINFOW pGetNamedSecurityInfoW;
631# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632#endif
633
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200634typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
635
636static BOOL allowPiping = FALSE;
637static PSETHANDLEINFORMATION pSetHandleInformation;
638
Bram Moolenaar27515922013-06-29 15:36:26 +0200639#ifdef HAVE_ACL
640/*
641 * Enables or disables the specified privilege.
642 */
643 static BOOL
644win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
645{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100646 BOOL bResult;
647 LUID luid;
648 HANDLE hToken;
649 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200650
651 if (!OpenProcessToken(GetCurrentProcess(),
652 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
653 return FALSE;
654
655 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
656 {
657 CloseHandle(hToken);
658 return FALSE;
659 }
660
Bram Moolenaar45500912014-07-09 20:51:07 +0200661 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200662 tokenPrivileges.Privileges[0].Luid = luid;
663 tokenPrivileges.Privileges[0].Attributes = bEnable ?
664 SE_PRIVILEGE_ENABLED : 0;
665
666 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
667 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
668
669 CloseHandle(hToken);
670
671 return bResult && GetLastError() == ERROR_SUCCESS;
672}
673#endif
674
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675/*
676 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
677 * VER_PLATFORM_WIN32_WINDOWS (Win95).
678 */
679 void
680PlatformId(void)
681{
682 static int done = FALSE;
683
684 if (!done)
685 {
686 OSVERSIONINFO ovi;
687
688 ovi.dwOSVersionInfoSize = sizeof(ovi);
689 GetVersionEx(&ovi);
690
691 g_PlatformId = ovi.dwPlatformId;
692
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100693 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
694 || ovi.dwMajorVersion > 6)
695 win8_or_later = TRUE;
696
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697#ifdef HAVE_ACL
698 /*
699 * Load the ADVAPI runtime if we are on anything
700 * other than Windows 95
701 */
702 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
703 {
704 /*
705 * do this load. Problems: Doesn't unload at end of run (this is
706 * theoretically okay, since Windows should unload it when VIM
707 * terminates). Should we be using the 'mch_libcall' routines?
708 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
709 * time we verify security...
710 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200711 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712 if (advapi_lib != NULL)
713 {
714 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
715 "SetNamedSecurityInfoA");
716 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
717 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200718# ifdef FEAT_MBYTE
719 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
720 "SetNamedSecurityInfoW");
721 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
722 "GetNamedSecurityInfoW");
723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200725 || pGetNamedSecurityInfo == NULL
726# ifdef FEAT_MBYTE
727 || pSetNamedSecurityInfoW == NULL
728 || pGetNamedSecurityInfoW == NULL
729# endif
730 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000731 {
732 /* If we can't get the function addresses, set advapi_lib
733 * to NULL so that we don't use them. */
734 FreeLibrary(advapi_lib);
735 advapi_lib = NULL;
736 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200737 /* Enable privilege for getting or setting SACLs. */
738 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 }
740 }
741#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200742 /*
743 * If we are on windows NT, try to load the pipe functions, only
744 * available from Win2K.
745 */
746 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
747 {
748 HANDLE kernel32 = GetModuleHandle("kernel32");
749 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
750 kernel32, "SetHandleInformation");
751
752 allowPiping = pSetHandleInformation != NULL;
753 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754 done = TRUE;
755 }
756}
757
758/*
759 * Return TRUE when running on Windows 95 (or 98 or ME).
760 * Only to be used after mch_init().
761 */
762 int
763mch_windows95(void)
764{
765 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
766}
767
768#ifdef FEAT_GUI_W32
769/*
770 * Used to work around the "can't do synchronous spawn"
771 * problem on Win32s, without resorting to Universal Thunk.
772 */
773static int old_num_windows;
774static int num_windows;
775
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000776/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777 static BOOL CALLBACK
778win32ssynch_cb(HWND hwnd, LPARAM lparam)
779{
780 num_windows++;
781 return TRUE;
782}
783#endif
784
785#ifndef FEAT_GUI_W32
786
787#define SHIFT (SHIFT_PRESSED)
788#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
789#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
790#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
791
792
793/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
794 * We map function keys to their ANSI terminal equivalents, as produced
795 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
796 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
797 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
798 * combinations of function/arrow/etc keys.
799 */
800
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000801static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000802{
803 WORD wVirtKey;
804 BOOL fAnsiKey;
805 int chAlone;
806 int chShift;
807 int chCtrl;
808 int chAlt;
809} VirtKeyMap[] =
810{
811
812/* Key ANSI alone shift ctrl alt */
813 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
814
815 { VK_F1, TRUE, ';', 'T', '^', 'h', },
816 { VK_F2, TRUE, '<', 'U', '_', 'i', },
817 { VK_F3, TRUE, '=', 'V', '`', 'j', },
818 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
819 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
820 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
821 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
822 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
823 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
824 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
825 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
826 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
827
828 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
829 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
830 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
831 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
832 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
833 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
834 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
835 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
836 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
837 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
838
839 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
840
841#if 0
842 /* Most people don't have F13-F20, but what the hell... */
843 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
844 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
845 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
846 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
847 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
848 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
849 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
850 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
851#endif
852 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
853 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
854 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
855 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
856
857 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
858 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
859 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
860 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
861 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
862 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
863 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
864 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
865 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
866 /* Sorry, out of number space! <negri>*/
867 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
868
869};
870
871
872#ifdef _MSC_VER
873// The ToAscii bug destroys several registers. Need to turn off optimization
874// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000875# pragma warning(push)
876# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877# pragma optimize("", off)
878#endif
879
880#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200881# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000882#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200883# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000884#endif
885
886/* The return code indicates key code size. */
887 static int
888#ifdef __BORLANDC__
889 __stdcall
890#endif
891win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000892 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893{
894 UINT uMods = pker->dwControlKeyState;
895 static int s_iIsDead = 0;
896 static WORD awAnsiCode[2];
897 static BYTE abKeystate[256];
898
899
900 if (s_iIsDead == 2)
901 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200902 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903 s_iIsDead = 0;
904 return 1;
905 }
906
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200907 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908 return 1;
909
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200910 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911
912 // Should only be non-NULL on NT 4.0
913 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
914 {
915 CHAR szKLID[KL_NAMELENGTH];
916
917 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
918 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
919 }
920
921 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200922 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923
924 if (uMods & SHIFT_PRESSED)
925 abKeystate[VK_SHIFT] = 0x80;
926 if (uMods & CAPSLOCK_ON)
927 abKeystate[VK_CAPITAL] = 1;
928
929 if ((uMods & ALT_GR) == ALT_GR)
930 {
931 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
932 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
933 }
934
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200935 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
936 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937
938 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200939 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940
941 return s_iIsDead;
942}
943
944#ifdef _MSC_VER
945/* MUST switch optimization on again here, otherwise a call to
946 * decode_key_event() may crash (e.g. when hitting caps-lock) */
947# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000948# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949
950# if (_MSC_VER < 1100)
951/* MUST turn off global optimisation for this next function, or
952 * pressing ctrl-minus in insert mode crashes Vim when built with
953 * VC4.1. -- negri. */
954# pragma optimize("g", off)
955# endif
956#endif
957
958static BOOL g_fJustGotFocus = FALSE;
959
960/*
961 * Decode a KEY_EVENT into one or two keystrokes
962 */
963 static BOOL
964decode_key_event(
965 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200966 WCHAR *pch,
967 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968 int *pmodifiers,
969 BOOL fDoPost)
970{
971 int i;
972 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
973
974 *pch = *pch2 = NUL;
975 g_fJustGotFocus = FALSE;
976
977 /* ignore key up events */
978 if (!pker->bKeyDown)
979 return FALSE;
980
981 /* ignore some keystrokes */
982 switch (pker->wVirtualKeyCode)
983 {
984 /* modifiers */
985 case VK_SHIFT:
986 case VK_CONTROL:
987 case VK_MENU: /* Alt key */
988 return FALSE;
989
990 default:
991 break;
992 }
993
994 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200995 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996 {
997 /* Ctrl-6 is Ctrl-^ */
998 if (pker->wVirtualKeyCode == '6')
999 {
1000 *pch = Ctrl_HAT;
1001 return TRUE;
1002 }
1003 /* Ctrl-2 is Ctrl-@ */
1004 else if (pker->wVirtualKeyCode == '2')
1005 {
1006 *pch = NUL;
1007 return TRUE;
1008 }
1009 /* Ctrl-- is Ctrl-_ */
1010 else if (pker->wVirtualKeyCode == 0xBD)
1011 {
1012 *pch = Ctrl__;
1013 return TRUE;
1014 }
1015 }
1016
1017 /* Shift-TAB */
1018 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1019 {
1020 *pch = K_NUL;
1021 *pch2 = '\017';
1022 return TRUE;
1023 }
1024
1025 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1026 {
1027 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1028 {
1029 if (nModifs == 0)
1030 *pch = VirtKeyMap[i].chAlone;
1031 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1032 *pch = VirtKeyMap[i].chShift;
1033 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1034 *pch = VirtKeyMap[i].chCtrl;
1035 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1036 *pch = VirtKeyMap[i].chAlt;
1037
1038 if (*pch != 0)
1039 {
1040 if (VirtKeyMap[i].fAnsiKey)
1041 {
1042 *pch2 = *pch;
1043 *pch = K_NUL;
1044 }
1045
1046 return TRUE;
1047 }
1048 }
1049 }
1050
1051 i = win32_kbd_patch_key(pker);
1052
1053 if (i < 0)
1054 *pch = NUL;
1055 else
1056 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001057 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058
1059 if (pmodifiers != NULL)
1060 {
1061 /* Pass on the ALT key as a modifier, but only when not combined
1062 * with CTRL (which is ALTGR). */
1063 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1064 *pmodifiers |= MOD_MASK_ALT;
1065
1066 /* Pass on SHIFT only for special keys, because we don't know when
1067 * it's already included with the character. */
1068 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1069 *pmodifiers |= MOD_MASK_SHIFT;
1070
1071 /* Pass on CTRL only for non-special keys, because we don't know
1072 * when it's already included with the character. And not when
1073 * combined with ALT (which is ALTGR). */
1074 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1075 && *pch >= 0x20 && *pch < 0x80)
1076 *pmodifiers |= MOD_MASK_CTRL;
1077 }
1078 }
1079
1080 return (*pch != NUL);
1081}
1082
1083#ifdef _MSC_VER
1084# pragma optimize("", on)
1085#endif
1086
1087#endif /* FEAT_GUI_W32 */
1088
1089
1090#ifdef FEAT_MOUSE
1091
1092/*
1093 * For the GUI the mouse handling is in gui_w32.c.
1094 */
1095# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001096/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001098mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099{
1100}
1101# else
1102static int g_fMouseAvail = FALSE; /* mouse present */
1103static int g_fMouseActive = FALSE; /* mouse enabled */
1104static int g_nMouseClick = -1; /* mouse status */
1105static int g_xMouse; /* mouse x coordinate */
1106static int g_yMouse; /* mouse y coordinate */
1107
1108/*
1109 * Enable or disable mouse input
1110 */
1111 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001112mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113{
1114 DWORD cmodein;
1115
1116 if (!g_fMouseAvail)
1117 return;
1118
1119 g_fMouseActive = on;
1120 GetConsoleMode(g_hConIn, &cmodein);
1121
1122 if (g_fMouseActive)
1123 cmodein |= ENABLE_MOUSE_INPUT;
1124 else
1125 cmodein &= ~ENABLE_MOUSE_INPUT;
1126
1127 SetConsoleMode(g_hConIn, cmodein);
1128}
1129
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130/*
1131 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1132 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1133 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1134 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1135 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1136 * and we return the mouse position in g_xMouse and g_yMouse.
1137 *
1138 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1139 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1140 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1141 *
1142 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1143 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1144 *
1145 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1146 * moves, even if it stays within the same character cell. We ignore
1147 * all MOUSE_MOVED messages if the position hasn't really changed, and
1148 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1149 * we're only interested in MOUSE_DRAG).
1150 *
1151 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1152 * 2-button mouses by pressing the left & right buttons simultaneously.
1153 * In practice, it's almost impossible to click both at the same time,
1154 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1155 * in such cases, if the user is clicking quickly.
1156 */
1157 static BOOL
1158decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001159 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160{
1161 static int s_nOldButton = -1;
1162 static int s_nOldMouseClick = -1;
1163 static int s_xOldMouse = -1;
1164 static int s_yOldMouse = -1;
1165 static linenr_T s_old_topline = 0;
1166#ifdef FEAT_DIFF
1167 static int s_old_topfill = 0;
1168#endif
1169 static int s_cClicks = 1;
1170 static BOOL s_fReleased = TRUE;
1171 static DWORD s_dwLastClickTime = 0;
1172 static BOOL s_fNextIsMiddle = FALSE;
1173
1174 static DWORD cButtons = 0; /* number of buttons supported */
1175
1176 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1177 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1178 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1179 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1180
1181 int nButton;
1182
1183 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1184 cButtons = 2;
1185
1186 if (!g_fMouseAvail || !g_fMouseActive)
1187 {
1188 g_nMouseClick = -1;
1189 return FALSE;
1190 }
1191
1192 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1193 if (g_fJustGotFocus)
1194 {
1195 g_fJustGotFocus = FALSE;
1196 return FALSE;
1197 }
1198
1199 /* unprocessed mouse click? */
1200 if (g_nMouseClick != -1)
1201 return TRUE;
1202
1203 nButton = -1;
1204 g_xMouse = pmer->dwMousePosition.X;
1205 g_yMouse = pmer->dwMousePosition.Y;
1206
1207 if (pmer->dwEventFlags == MOUSE_MOVED)
1208 {
1209 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1210 * events even when the mouse moves only within a char cell.) */
1211 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1212 return FALSE;
1213 }
1214
1215 /* If no buttons are pressed... */
1216 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1217 {
1218 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1219 if (s_fReleased)
1220 return FALSE;
1221
1222 nButton = MOUSE_RELEASE;
1223 s_fReleased = TRUE;
1224 }
1225 else /* one or more buttons pressed */
1226 {
1227 /* on a 2-button mouse, hold down left and right buttons
1228 * simultaneously to get MIDDLE. */
1229
1230 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1231 {
1232 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1233
1234 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001235 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236 if (dwLR == LEFT || dwLR == RIGHT)
1237 {
1238 for (;;)
1239 {
1240 /* wait a short time for next input event */
1241 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1242 != WAIT_OBJECT_0)
1243 break;
1244 else
1245 {
1246 DWORD cRecords = 0;
1247 INPUT_RECORD ir;
1248 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1249
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001250 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251
1252 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1253 || !(pmer2->dwButtonState & LEFT_RIGHT))
1254 break;
1255 else
1256 {
1257 if (pmer2->dwEventFlags != MOUSE_MOVED)
1258 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001259 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001260
1261 return decode_mouse_event(pmer2);
1262 }
1263 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1264 s_yOldMouse == pmer2->dwMousePosition.Y)
1265 {
1266 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001267 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001268
1269 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001270 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001271
1272 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1273 break;
1274 }
1275 else
1276 break;
1277 }
1278 }
1279 }
1280 }
1281 }
1282
1283 if (s_fNextIsMiddle)
1284 {
1285 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1286 ? MOUSE_DRAG : MOUSE_MIDDLE;
1287 s_fNextIsMiddle = FALSE;
1288 }
1289 else if (cButtons == 2 &&
1290 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1291 {
1292 nButton = MOUSE_MIDDLE;
1293
1294 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1295 {
1296 s_fNextIsMiddle = TRUE;
1297 nButton = MOUSE_RELEASE;
1298 }
1299 }
1300 else if ((pmer->dwButtonState & LEFT) == LEFT)
1301 nButton = MOUSE_LEFT;
1302 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1303 nButton = MOUSE_MIDDLE;
1304 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1305 nButton = MOUSE_RIGHT;
1306
1307 if (! s_fReleased && ! s_fNextIsMiddle
1308 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1309 return FALSE;
1310
1311 s_fReleased = s_fNextIsMiddle;
1312 }
1313
1314 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1315 {
1316 /* button pressed or released, without mouse moving */
1317 if (nButton != -1 && nButton != MOUSE_RELEASE)
1318 {
1319 DWORD dwCurrentTime = GetTickCount();
1320
1321 if (s_xOldMouse != g_xMouse
1322 || s_yOldMouse != g_yMouse
1323 || s_nOldButton != nButton
1324 || s_old_topline != curwin->w_topline
1325#ifdef FEAT_DIFF
1326 || s_old_topfill != curwin->w_topfill
1327#endif
1328 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1329 {
1330 s_cClicks = 1;
1331 }
1332 else if (++s_cClicks > 4)
1333 {
1334 s_cClicks = 1;
1335 }
1336
1337 s_dwLastClickTime = dwCurrentTime;
1338 }
1339 }
1340 else if (pmer->dwEventFlags == MOUSE_MOVED)
1341 {
1342 if (nButton != -1 && nButton != MOUSE_RELEASE)
1343 nButton = MOUSE_DRAG;
1344
1345 s_cClicks = 1;
1346 }
1347
1348 if (nButton == -1)
1349 return FALSE;
1350
1351 if (nButton != MOUSE_RELEASE)
1352 s_nOldButton = nButton;
1353
1354 g_nMouseClick = nButton;
1355
1356 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1357 g_nMouseClick |= MOUSE_SHIFT;
1358 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1359 g_nMouseClick |= MOUSE_CTRL;
1360 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1361 g_nMouseClick |= MOUSE_ALT;
1362
1363 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1364 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1365
1366 /* only pass on interesting (i.e., different) mouse events */
1367 if (s_xOldMouse == g_xMouse
1368 && s_yOldMouse == g_yMouse
1369 && s_nOldMouseClick == g_nMouseClick)
1370 {
1371 g_nMouseClick = -1;
1372 return FALSE;
1373 }
1374
1375 s_xOldMouse = g_xMouse;
1376 s_yOldMouse = g_yMouse;
1377 s_old_topline = curwin->w_topline;
1378#ifdef FEAT_DIFF
1379 s_old_topfill = curwin->w_topfill;
1380#endif
1381 s_nOldMouseClick = g_nMouseClick;
1382
1383 return TRUE;
1384}
1385
1386# endif /* FEAT_GUI_W32 */
1387#endif /* FEAT_MOUSE */
1388
1389
1390#ifdef MCH_CURSOR_SHAPE
1391/*
1392 * Set the shape of the cursor.
1393 * 'thickness' can be from 1 (thin) to 99 (block)
1394 */
1395 static void
1396mch_set_cursor_shape(int thickness)
1397{
1398 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1399 ConsoleCursorInfo.dwSize = thickness;
1400 ConsoleCursorInfo.bVisible = s_cursor_visible;
1401
1402 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1403 if (s_cursor_visible)
1404 SetConsoleCursorPosition(g_hConOut, g_coord);
1405}
1406
1407 void
1408mch_update_cursor(void)
1409{
1410 int idx;
1411 int thickness;
1412
1413 /*
1414 * How the cursor is drawn depends on the current mode.
1415 */
1416 idx = get_shape_idx(FALSE);
1417
1418 if (shape_table[idx].shape == SHAPE_BLOCK)
1419 thickness = 99; /* 100 doesn't work on W95 */
1420 else
1421 thickness = shape_table[idx].percentage;
1422 mch_set_cursor_shape(thickness);
1423}
1424#endif
1425
1426#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1427/*
1428 * Handle FOCUS_EVENT.
1429 */
1430 static void
1431handle_focus_event(INPUT_RECORD ir)
1432{
1433 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1434 ui_focus_change((int)g_fJustGotFocus);
1435}
1436
1437/*
1438 * Wait until console input from keyboard or mouse is available,
1439 * or the time is up.
1440 * Return TRUE if something is available FALSE if not.
1441 */
1442 static int
1443WaitForChar(long msec)
1444{
1445 DWORD dwNow = 0, dwEndTime = 0;
1446 INPUT_RECORD ir;
1447 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001448 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001449
1450 if (msec > 0)
1451 /* Wait until the specified time has elapsed. */
1452 dwEndTime = GetTickCount() + msec;
1453 else if (msec < 0)
1454 /* Wait forever. */
1455 dwEndTime = INFINITE;
1456
1457 /* We need to loop until the end of the time period, because
1458 * we might get multiple unusable mouse events in that time.
1459 */
1460 for (;;)
1461 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001462#ifdef MESSAGE_QUEUE
1463 parse_queued_messages();
1464#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001465#ifdef FEAT_MZSCHEME
1466 mzvim_check_threads();
1467#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468#ifdef FEAT_CLIENTSERVER
1469 serverProcessPendingMessages();
1470#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001471
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 if (0
1473#ifdef FEAT_MOUSE
1474 || g_nMouseClick != -1
1475#endif
1476#ifdef FEAT_CLIENTSERVER
1477 || input_available()
1478#endif
1479 )
1480 return TRUE;
1481
1482 if (msec > 0)
1483 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001484 /* If the specified wait time has passed, return. Beware that
1485 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001487 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488 break;
1489 }
1490 if (msec != 0)
1491 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001492 DWORD dwWaitTime = dwEndTime - dwNow;
1493
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001494#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar9186a272016-02-23 19:34:01 +01001495 /* Check channel while waiting input. */
1496 if (dwWaitTime > 100)
1497 dwWaitTime = 100;
1498#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001499#ifdef FEAT_MZSCHEME
1500 if (mzthreads_allowed() && p_mzq > 0
1501 && (msec < 0 || (long)dwWaitTime > p_mzq))
1502 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1503#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001504#ifdef FEAT_TIMERS
1505 {
1506 long due_time;
1507
1508 /* When waiting very briefly don't trigger timers. */
1509 if (dwWaitTime > 10)
1510 {
1511 /* Trigger timers and then get the time in msec until the
1512 * next one is due. Wait up to that time. */
1513 due_time = check_due_timer();
1514 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1515 dwWaitTime = due_time;
1516 }
1517 }
1518#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519#ifdef FEAT_CLIENTSERVER
1520 /* Wait for either an event on the console input or a message in
1521 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001522 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001523 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001524#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001525 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526#endif
1527 continue;
1528 }
1529
1530 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001531 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532
1533#ifdef FEAT_MBYTE_IME
1534 if (State & CMDLINE && msg_row == Rows - 1)
1535 {
1536 CONSOLE_SCREEN_BUFFER_INFO csbi;
1537
1538 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1539 {
1540 if (csbi.dwCursorPosition.Y != msg_row)
1541 {
1542 /* The screen is now messed up, must redraw the
1543 * command line and later all the windows. */
1544 redraw_all_later(CLEAR);
1545 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1546 redrawcmd();
1547 }
1548 }
1549 }
1550#endif
1551
1552 if (cRecords > 0)
1553 {
1554 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1555 {
1556#ifdef FEAT_MBYTE_IME
1557 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1558 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001559 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1561 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001562 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 continue;
1564 }
1565#endif
1566 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1567 NULL, FALSE))
1568 return TRUE;
1569 }
1570
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001571 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572
1573 if (ir.EventType == FOCUS_EVENT)
1574 handle_focus_event(ir);
1575 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1576 shell_resized();
1577#ifdef FEAT_MOUSE
1578 else if (ir.EventType == MOUSE_EVENT
1579 && decode_mouse_event(&ir.Event.MouseEvent))
1580 return TRUE;
1581#endif
1582 }
1583 else if (msec == 0)
1584 break;
1585 }
1586
1587#ifdef FEAT_CLIENTSERVER
1588 /* Something might have been received while we were waiting. */
1589 if (input_available())
1590 return TRUE;
1591#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001592
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593 return FALSE;
1594}
1595
1596#ifndef FEAT_GUI_MSWIN
1597/*
1598 * return non-zero if a character is available
1599 */
1600 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001601mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602{
1603 return WaitForChar(0L);
1604}
1605#endif
1606
1607/*
1608 * Create the console input. Used when reading stdin doesn't work.
1609 */
1610 static void
1611create_conin(void)
1612{
1613 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1614 FILE_SHARE_READ|FILE_SHARE_WRITE,
1615 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001616 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617 did_create_conin = TRUE;
1618}
1619
1620/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001621 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001623 static WCHAR
1624tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001626 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627
1628 for (;;)
1629 {
1630 INPUT_RECORD ir;
1631 DWORD cRecords = 0;
1632
1633#ifdef FEAT_CLIENTSERVER
1634 (void)WaitForChar(-1L);
1635 if (input_available())
1636 return 0;
1637# ifdef FEAT_MOUSE
1638 if (g_nMouseClick != -1)
1639 return 0;
1640# endif
1641#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001642 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643 {
1644 if (did_create_conin)
1645 read_error_exit();
1646 create_conin();
1647 continue;
1648 }
1649
1650 if (ir.EventType == KEY_EVENT)
1651 {
1652 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1653 pmodifiers, TRUE))
1654 return ch;
1655 }
1656 else if (ir.EventType == FOCUS_EVENT)
1657 handle_focus_event(ir);
1658 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1659 shell_resized();
1660#ifdef FEAT_MOUSE
1661 else if (ir.EventType == MOUSE_EVENT)
1662 {
1663 if (decode_mouse_event(&ir.Event.MouseEvent))
1664 return 0;
1665 }
1666#endif
1667 }
1668}
1669#endif /* !FEAT_GUI_W32 */
1670
1671
1672/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001673 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 * Get one or more characters from the keyboard or the mouse.
1675 * If time == 0, do not wait for characters.
1676 * If time == n, wait a short time for characters.
1677 * If time == -1, wait forever for characters.
1678 * Returns the number of characters read into buf.
1679 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001680/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681 int
1682mch_inchar(
1683 char_u *buf,
1684 int maxlen,
1685 long time,
1686 int tb_change_cnt)
1687{
1688#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1689
1690 int len;
1691 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692#define TYPEAHEADLEN 20
1693 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1694 static int typeaheadlen = 0;
1695
1696 /* First use any typeahead that was kept because "buf" was too small. */
1697 if (typeaheadlen > 0)
1698 goto theend;
1699
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700 if (time >= 0)
1701 {
1702 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001703 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704 }
1705 else /* time == -1, wait forever */
1706 {
1707 mch_set_winsize_now(); /* Allow winsize changes from now on */
1708
Bram Moolenaar3918c952005-03-15 22:34:55 +00001709 /*
1710 * If there is no character available within 2 seconds (default)
1711 * write the autoscript file to disk. Or cause the CursorHold event
1712 * to be triggered.
1713 */
1714 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715 {
1716#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001717 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001719 buf[0] = K_SPECIAL;
1720 buf[1] = KS_EXTRA;
1721 buf[2] = (int)KE_CURSORHOLD;
1722 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 }
1724#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001725 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 }
1727 }
1728
1729 /*
1730 * Try to read as many characters as there are, until the buffer is full.
1731 */
1732
1733 /* we will get at least one key. Get more if they are available. */
1734 g_fCBrkPressed = FALSE;
1735
1736#ifdef MCH_WRITE_DUMP
1737 if (fdDump)
1738 fputc('[', fdDump);
1739#endif
1740
1741 /* Keep looping until there is something in the typeahead buffer and more
1742 * to get and still room in the buffer (up to two bytes for a char and
1743 * three bytes for a modifier). */
1744 while ((typeaheadlen == 0 || WaitForChar(0L))
1745 && typeaheadlen + 5 <= TYPEAHEADLEN)
1746 {
1747 if (typebuf_changed(tb_change_cnt))
1748 {
1749 /* "buf" may be invalid now if a client put something in the
1750 * typeahead buffer and "buf" is in the typeahead buffer. */
1751 typeaheadlen = 0;
1752 break;
1753 }
1754#ifdef FEAT_MOUSE
1755 if (g_nMouseClick != -1)
1756 {
1757# ifdef MCH_WRITE_DUMP
1758 if (fdDump)
1759 fprintf(fdDump, "{%02x @ %d, %d}",
1760 g_nMouseClick, g_xMouse, g_yMouse);
1761# endif
1762 typeahead[typeaheadlen++] = ESC + 128;
1763 typeahead[typeaheadlen++] = 'M';
1764 typeahead[typeaheadlen++] = g_nMouseClick;
1765 typeahead[typeaheadlen++] = g_xMouse + '!';
1766 typeahead[typeaheadlen++] = g_yMouse + '!';
1767 g_nMouseClick = -1;
1768 }
1769 else
1770#endif
1771 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001772 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 int modifiers = 0;
1774
1775 c = tgetch(&modifiers, &ch2);
1776
1777 if (typebuf_changed(tb_change_cnt))
1778 {
1779 /* "buf" may be invalid now if a client put something in the
1780 * typeahead buffer and "buf" is in the typeahead buffer. */
1781 typeaheadlen = 0;
1782 break;
1783 }
1784
1785 if (c == Ctrl_C && ctrl_c_interrupts)
1786 {
1787#if defined(FEAT_CLIENTSERVER)
1788 trash_input_buf();
1789#endif
1790 got_int = TRUE;
1791 }
1792
1793#ifdef FEAT_MOUSE
1794 if (g_nMouseClick == -1)
1795#endif
1796 {
1797 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001798 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001800#ifdef FEAT_MBYTE
1801 if (ch2 == NUL)
1802 {
1803 int i;
1804 char_u *p;
1805 WCHAR ch[2];
1806
1807 ch[0] = c;
1808 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1809 {
1810 ch[1] = tgetch(&modifiers, &ch2);
1811 n++;
1812 }
1813 p = utf16_to_enc(ch, &n);
1814 if (p != NULL)
1815 {
1816 for (i = 0; i < n; i++)
1817 typeahead[typeaheadlen + i] = p[i];
1818 vim_free(p);
1819 }
1820 }
1821 else
1822#endif
1823 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001824 if (ch2 != NUL)
1825 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001826 typeahead[typeaheadlen + n] = 3;
1827 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001828 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001829 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830
Bram Moolenaar45500912014-07-09 20:51:07 +02001831 if (conv)
1832 {
1833 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001834
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001835 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001836 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001837 char_u *e = typeahead + TYPEAHEADLEN;
1838
1839 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001840 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001841 if (*p == K_NUL)
1842 {
1843 ++p;
1844 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1845 *p = 3;
1846 ++n;
1847 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001848 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001849 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001850 }
1851 }
1852
Bram Moolenaar071d4272004-06-13 20:20:40 +00001853 /* Use the ALT key to set the 8th bit of the character
1854 * when it's one byte, the 8th bit isn't set yet and not
1855 * using a double-byte encoding (would become a lead
1856 * byte). */
1857 if ((modifiers & MOD_MASK_ALT)
1858 && n == 1
1859 && (typeahead[typeaheadlen] & 0x80) == 0
1860#ifdef FEAT_MBYTE
1861 && !enc_dbcs
1862#endif
1863 )
1864 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001865#ifdef FEAT_MBYTE
1866 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1867 typeahead + typeaheadlen);
1868#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001869 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001870#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871 modifiers &= ~MOD_MASK_ALT;
1872 }
1873
1874 if (modifiers != 0)
1875 {
1876 /* Prepend modifiers to the character. */
1877 mch_memmove(typeahead + typeaheadlen + 3,
1878 typeahead + typeaheadlen, n);
1879 typeahead[typeaheadlen++] = K_SPECIAL;
1880 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1881 typeahead[typeaheadlen++] = modifiers;
1882 }
1883
1884 typeaheadlen += n;
1885
1886#ifdef MCH_WRITE_DUMP
1887 if (fdDump)
1888 fputc(c, fdDump);
1889#endif
1890 }
1891 }
1892 }
1893
1894#ifdef MCH_WRITE_DUMP
1895 if (fdDump)
1896 {
1897 fputs("]\n", fdDump);
1898 fflush(fdDump);
1899 }
1900#endif
1901
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902theend:
1903 /* Move typeahead to "buf", as much as fits. */
1904 len = 0;
1905 while (len < maxlen && typeaheadlen > 0)
1906 {
1907 buf[len++] = typeahead[0];
1908 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1909 }
1910 return len;
1911
1912#else /* FEAT_GUI_W32 */
1913 return 0;
1914#endif /* FEAT_GUI_W32 */
1915}
1916
Bram Moolenaar82881492012-11-20 16:53:39 +01001917#ifndef PROTO
1918# ifndef __MINGW32__
1919# include <shellapi.h> /* required for FindExecutable() */
1920# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921#endif
1922
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001923/*
1924 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001925 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001926 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001928executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001930 char *dum;
1931 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001932 char *curpath, *newpath;
1933 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001935#ifdef FEAT_MBYTE
1936 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001938 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001939 WCHAR fnamew[_MAX_PATH];
1940 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001941 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001942
1943 if (p != NULL)
1944 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001945 wcurpath = _wgetenv(L"PATH");
1946 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1947 * sizeof(WCHAR));
1948 if (wnewpath == NULL)
1949 return FALSE;
1950 wcscpy(wnewpath, L".;");
1951 wcscat(wnewpath, wcurpath);
1952 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1953 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001954 vim_free(p);
1955 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1956 {
1957 if (n == 0)
1958 return FALSE;
1959 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1960 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001961 if (path != NULL)
1962 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001963 return TRUE;
1964 }
1965 /* Retry with non-wide function (for Windows 98). */
1966 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001968#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001969
1970 curpath = getenv("PATH");
1971 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1972 if (newpath == NULL)
1973 return FALSE;
1974 STRCPY(newpath, ".;");
1975 STRCAT(newpath, curpath);
1976 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1977 vim_free(newpath);
1978 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001979 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001980 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001981 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001982 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001983 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001984 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985}
1986
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001987#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001988 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001989/*
1990 * Bad parameter handler.
1991 *
1992 * Certain MS CRT functions will intentionally crash when passed invalid
1993 * parameters to highlight possible security holes. Setting this function as
1994 * the bad parameter handler will prevent the crash.
1995 *
1996 * In debug builds the parameters contain CRT information that might help track
1997 * down the source of a problem, but in non-debug builds the arguments are all
1998 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1999 * worth allowing these to make debugging of issues easier.
2000 */
2001 static void
2002bad_param_handler(const wchar_t *expression,
2003 const wchar_t *function,
2004 const wchar_t *file,
2005 unsigned int line,
2006 uintptr_t pReserved)
2007{
2008}
2009
2010# define SET_INVALID_PARAM_HANDLER \
2011 ((void)_set_invalid_parameter_handler(bad_param_handler))
2012#else
2013# define SET_INVALID_PARAM_HANDLER
2014#endif
2015
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016#ifdef FEAT_GUI_W32
2017
2018/*
2019 * GUI version of mch_init().
2020 */
2021 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002022mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023{
2024#ifndef __MINGW32__
2025 extern int _fmode;
2026#endif
2027
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002028 /* Silently handle invalid parameters to CRT functions */
2029 SET_INVALID_PARAM_HANDLER;
2030
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 /* Let critical errors result in a failure, not in a dialog box. Required
2032 * for the timestamp test to work on removed floppies. */
2033 SetErrorMode(SEM_FAILCRITICALERRORS);
2034
2035 _fmode = O_BINARY; /* we do our own CR-LF translation */
2036
2037 /* Specify window size. Is there a place to get the default from? */
2038 Rows = 25;
2039 Columns = 80;
2040
2041 /* Look for 'vimrun' */
2042 if (!gui_is_win32s())
2043 {
2044 char_u vimrun_location[_MAX_PATH + 4];
2045
2046 /* First try in same directory as gvim.exe */
2047 STRCPY(vimrun_location, exe_name);
2048 STRCPY(gettail(vimrun_location), "vimrun.exe");
2049 if (mch_getperm(vimrun_location) >= 0)
2050 {
2051 if (*skiptowhite(vimrun_location) != NUL)
2052 {
2053 /* Enclose path with white space in double quotes. */
2054 mch_memmove(vimrun_location + 1, vimrun_location,
2055 STRLEN(vimrun_location) + 1);
2056 *vimrun_location = '"';
2057 STRCPY(gettail(vimrun_location), "vimrun\" ");
2058 }
2059 else
2060 STRCPY(gettail(vimrun_location), "vimrun ");
2061
2062 vimrun_path = (char *)vim_strsave(vimrun_location);
2063 s_dont_use_vimrun = FALSE;
2064 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002065 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 s_dont_use_vimrun = FALSE;
2067
2068 /* Don't give the warning for a missing vimrun.exe right now, but only
2069 * when vimrun was supposed to be used. Don't bother people that do
2070 * not need vimrun.exe. */
2071 if (s_dont_use_vimrun)
2072 need_vimrun_warning = TRUE;
2073 }
2074
2075 /*
2076 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2077 * Otherwise the default "findstr /n" is used.
2078 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002079 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2081
2082#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002083 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002084#endif
2085}
2086
2087
2088#else /* FEAT_GUI_W32 */
2089
2090#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2091#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2092
2093/*
2094 * ClearConsoleBuffer()
2095 * Description:
2096 * Clears the entire contents of the console screen buffer, using the
2097 * specified attribute.
2098 * Returns:
2099 * TRUE on success
2100 */
2101 static BOOL
2102ClearConsoleBuffer(WORD wAttribute)
2103{
2104 CONSOLE_SCREEN_BUFFER_INFO csbi;
2105 COORD coord;
2106 DWORD NumCells, dummy;
2107
2108 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2109 return FALSE;
2110
2111 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2112 coord.X = 0;
2113 coord.Y = 0;
2114 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2115 coord, &dummy))
2116 {
2117 return FALSE;
2118 }
2119 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2120 coord, &dummy))
2121 {
2122 return FALSE;
2123 }
2124
2125 return TRUE;
2126}
2127
2128/*
2129 * FitConsoleWindow()
2130 * Description:
2131 * Checks if the console window will fit within given buffer dimensions.
2132 * Also, if requested, will shrink the window to fit.
2133 * Returns:
2134 * TRUE on success
2135 */
2136 static BOOL
2137FitConsoleWindow(
2138 COORD dwBufferSize,
2139 BOOL WantAdjust)
2140{
2141 CONSOLE_SCREEN_BUFFER_INFO csbi;
2142 COORD dwWindowSize;
2143 BOOL NeedAdjust = FALSE;
2144
2145 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2146 {
2147 /*
2148 * A buffer resize will fail if the current console window does
2149 * not lie completely within that buffer. To avoid this, we might
2150 * have to move and possibly shrink the window.
2151 */
2152 if (csbi.srWindow.Right >= dwBufferSize.X)
2153 {
2154 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2155 if (dwWindowSize.X > dwBufferSize.X)
2156 dwWindowSize.X = dwBufferSize.X;
2157 csbi.srWindow.Right = dwBufferSize.X - 1;
2158 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2159 NeedAdjust = TRUE;
2160 }
2161 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2162 {
2163 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2164 if (dwWindowSize.Y > dwBufferSize.Y)
2165 dwWindowSize.Y = dwBufferSize.Y;
2166 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2167 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2168 NeedAdjust = TRUE;
2169 }
2170 if (NeedAdjust && WantAdjust)
2171 {
2172 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2173 return FALSE;
2174 }
2175 return TRUE;
2176 }
2177
2178 return FALSE;
2179}
2180
2181typedef struct ConsoleBufferStruct
2182{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002183 BOOL IsValid;
2184 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002185 PCHAR_INFO Buffer;
2186 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002187} ConsoleBuffer;
2188
2189/*
2190 * SaveConsoleBuffer()
2191 * Description:
2192 * Saves important information about the console buffer, including the
2193 * actual buffer contents. The saved information is suitable for later
2194 * restoration by RestoreConsoleBuffer().
2195 * Returns:
2196 * TRUE if all information was saved; FALSE otherwise
2197 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2198 */
2199 static BOOL
2200SaveConsoleBuffer(
2201 ConsoleBuffer *cb)
2202{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002203 DWORD NumCells;
2204 COORD BufferCoord;
2205 SMALL_RECT ReadRegion;
2206 WORD Y, Y_incr;
2207
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208 if (cb == NULL)
2209 return FALSE;
2210
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002211 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212 {
2213 cb->IsValid = FALSE;
2214 return FALSE;
2215 }
2216 cb->IsValid = TRUE;
2217
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002218 /*
2219 * Allocate a buffer large enough to hold the entire console screen
2220 * buffer. If this ConsoleBuffer structure has already been initialized
2221 * with a buffer of the correct size, then just use that one.
2222 */
2223 if (!cb->IsValid || cb->Buffer == NULL ||
2224 cb->BufferSize.X != cb->Info.dwSize.X ||
2225 cb->BufferSize.Y != cb->Info.dwSize.Y)
2226 {
2227 cb->BufferSize.X = cb->Info.dwSize.X;
2228 cb->BufferSize.Y = cb->Info.dwSize.Y;
2229 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2230 vim_free(cb->Buffer);
2231 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2232 if (cb->Buffer == NULL)
2233 return FALSE;
2234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235
2236 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002237 * We will now copy the console screen buffer into our buffer.
2238 * ReadConsoleOutput() seems to be limited as far as how much you
2239 * can read at a time. Empirically, this number seems to be about
2240 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2241 * in chunks until it is all copied. The chunks will all have the
2242 * same horizontal characteristics, so initialize them now. The
2243 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002245 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002246 ReadRegion.Left = 0;
2247 ReadRegion.Right = cb->Info.dwSize.X - 1;
2248 Y_incr = 12000 / cb->Info.dwSize.X;
2249 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002251 /*
2252 * Read into position (0, Y) in our buffer.
2253 */
2254 BufferCoord.Y = Y;
2255 /*
2256 * Read the region whose top left corner is (0, Y) and whose bottom
2257 * right corner is (width - 1, Y + Y_incr - 1). This should define
2258 * a region of size width by Y_incr. Don't worry if this region is
2259 * too large for the remaining buffer; it will be cropped.
2260 */
2261 ReadRegion.Top = Y;
2262 ReadRegion.Bottom = Y + Y_incr - 1;
2263 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2264 cb->Buffer, /* our buffer */
2265 cb->BufferSize, /* dimensions of our buffer */
2266 BufferCoord, /* offset in our buffer */
2267 &ReadRegion)) /* region to save */
2268 {
2269 vim_free(cb->Buffer);
2270 cb->Buffer = NULL;
2271 return FALSE;
2272 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 }
2274
2275 return TRUE;
2276}
2277
2278/*
2279 * RestoreConsoleBuffer()
2280 * Description:
2281 * Restores important information about the console buffer, including the
2282 * actual buffer contents, if desired. The information to restore is in
2283 * the same format used by SaveConsoleBuffer().
2284 * Returns:
2285 * TRUE on success
2286 */
2287 static BOOL
2288RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002289 ConsoleBuffer *cb,
2290 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002291{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002292 COORD BufferCoord;
2293 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002294
2295 if (cb == NULL || !cb->IsValid)
2296 return FALSE;
2297
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002298 /*
2299 * Before restoring the buffer contents, clear the current buffer, and
2300 * restore the cursor position and window information. Doing this now
2301 * prevents old buffer contents from "flashing" onto the screen.
2302 */
2303 if (RestoreScreen)
2304 ClearConsoleBuffer(cb->Info.wAttributes);
2305
2306 FitConsoleWindow(cb->Info.dwSize, TRUE);
2307 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2308 return FALSE;
2309 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2310 return FALSE;
2311
2312 if (!RestoreScreen)
2313 {
2314 /*
2315 * No need to restore the screen buffer contents, so we're done.
2316 */
2317 return TRUE;
2318 }
2319
2320 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2321 return FALSE;
2322 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2323 return FALSE;
2324
2325 /*
2326 * Restore the screen buffer contents.
2327 */
2328 if (cb->Buffer != NULL)
2329 {
2330 BufferCoord.X = 0;
2331 BufferCoord.Y = 0;
2332 WriteRegion.Left = 0;
2333 WriteRegion.Top = 0;
2334 WriteRegion.Right = cb->Info.dwSize.X - 1;
2335 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2336 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2337 cb->Buffer, /* our buffer */
2338 cb->BufferSize, /* dimensions of our buffer */
2339 BufferCoord, /* offset in our buffer */
2340 &WriteRegion)) /* region to restore */
2341 {
2342 return FALSE;
2343 }
2344 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345
2346 return TRUE;
2347}
2348
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002349#define FEAT_RESTORE_ORIG_SCREEN
2350#ifdef FEAT_RESTORE_ORIG_SCREEN
2351static ConsoleBuffer g_cbOrig = { 0 };
2352#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353static ConsoleBuffer g_cbNonTermcap = { 0 };
2354static ConsoleBuffer g_cbTermcap = { 0 };
2355
2356#ifdef FEAT_TITLE
2357#ifdef __BORLANDC__
2358typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2359#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002360typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002361#endif
2362char g_szOrigTitle[256] = { 0 };
2363HWND g_hWnd = NULL; /* also used in os_mswin.c */
2364static HICON g_hOrigIconSmall = NULL;
2365static HICON g_hOrigIcon = NULL;
2366static HICON g_hVimIcon = NULL;
2367static BOOL g_fCanChangeIcon = FALSE;
2368
2369/* ICON* are not defined in VC++ 4.0 */
2370#ifndef ICON_SMALL
2371#define ICON_SMALL 0
2372#endif
2373#ifndef ICON_BIG
2374#define ICON_BIG 1
2375#endif
2376/*
2377 * GetConsoleIcon()
2378 * Description:
2379 * Attempts to retrieve the small icon and/or the big icon currently in
2380 * use by a given window.
2381 * Returns:
2382 * TRUE on success
2383 */
2384 static BOOL
2385GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002386 HWND hWnd,
2387 HICON *phIconSmall,
2388 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389{
2390 if (hWnd == NULL)
2391 return FALSE;
2392
2393 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002394 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2395 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002397 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2398 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 return TRUE;
2400}
2401
2402/*
2403 * SetConsoleIcon()
2404 * Description:
2405 * Attempts to change the small icon and/or the big icon currently in
2406 * use by a given window.
2407 * Returns:
2408 * TRUE on success
2409 */
2410 static BOOL
2411SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002412 HWND hWnd,
2413 HICON hIconSmall,
2414 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416 if (hWnd == NULL)
2417 return FALSE;
2418
2419 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002420 SendMessage(hWnd, WM_SETICON,
2421 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002423 SendMessage(hWnd, WM_SETICON,
2424 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425 return TRUE;
2426}
2427
2428/*
2429 * SaveConsoleTitleAndIcon()
2430 * Description:
2431 * Saves the current console window title in g_szOrigTitle, for later
2432 * restoration. Also, attempts to obtain a handle to the console window,
2433 * and use it to save the small and big icons currently in use by the
2434 * console window. This is not always possible on some versions of Windows;
2435 * nor is it possible when running Vim remotely using Telnet (since the
2436 * console window the user sees is owned by a remote process).
2437 */
2438 static void
2439SaveConsoleTitleAndIcon(void)
2440{
2441 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2442
2443 /* Save the original title. */
2444 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2445 return;
2446
2447 /*
2448 * Obtain a handle to the console window using GetConsoleWindow() from
2449 * KERNEL32.DLL; we need to handle in order to change the window icon.
2450 * This function only exists on NT-based Windows, starting with Windows
2451 * 2000. On older operating systems, we can't change the window icon
2452 * anyway.
2453 */
2454 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2455 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2456 "GetConsoleWindow")) != NULL)
2457 {
2458 g_hWnd = (*GetConsoleWindowProc)();
2459 }
2460 if (g_hWnd == NULL)
2461 return;
2462
2463 /* Save the original console window icon. */
2464 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2465 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2466 return;
2467
2468 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002469 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002470 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471 if (g_hVimIcon != NULL)
2472 g_fCanChangeIcon = TRUE;
2473}
2474#endif
2475
2476static int g_fWindInitCalled = FALSE;
2477static int g_fTermcapMode = FALSE;
2478static CONSOLE_CURSOR_INFO g_cci;
2479static DWORD g_cmodein = 0;
2480static DWORD g_cmodeout = 0;
2481
2482/*
2483 * non-GUI version of mch_init().
2484 */
2485 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002486mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002488#ifndef FEAT_RESTORE_ORIG_SCREEN
2489 CONSOLE_SCREEN_BUFFER_INFO csbi;
2490#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491#ifndef __MINGW32__
2492 extern int _fmode;
2493#endif
2494
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002495 /* Silently handle invalid parameters to CRT functions */
2496 SET_INVALID_PARAM_HANDLER;
2497
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498 /* Let critical errors result in a failure, not in a dialog box. Required
2499 * for the timestamp test to work on removed floppies. */
2500 SetErrorMode(SEM_FAILCRITICALERRORS);
2501
2502 _fmode = O_BINARY; /* we do our own CR-LF translation */
2503 out_flush();
2504
2505 /* Obtain handles for the standard Console I/O devices */
2506 if (read_cmd_fd == 0)
2507 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2508 else
2509 create_conin();
2510 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2511
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002512#ifdef FEAT_RESTORE_ORIG_SCREEN
2513 /* Save the initial console buffer for later restoration */
2514 SaveConsoleBuffer(&g_cbOrig);
2515 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2516#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002518 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2519 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2520#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521 if (cterm_normal_fg_color == 0)
2522 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2523 if (cterm_normal_bg_color == 0)
2524 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2525
2526 /* set termcap codes to current text attributes */
2527 update_tcap(g_attrCurrent);
2528
2529 GetConsoleCursorInfo(g_hConOut, &g_cci);
2530 GetConsoleMode(g_hConIn, &g_cmodein);
2531 GetConsoleMode(g_hConOut, &g_cmodeout);
2532
2533#ifdef FEAT_TITLE
2534 SaveConsoleTitleAndIcon();
2535 /*
2536 * Set both the small and big icons of the console window to Vim's icon.
2537 * Note that Vim presently only has one size of icon (32x32), but it
2538 * automatically gets scaled down to 16x16 when setting the small icon.
2539 */
2540 if (g_fCanChangeIcon)
2541 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2542#endif
2543
2544 ui_get_shellsize();
2545
2546#ifdef MCH_WRITE_DUMP
2547 fdDump = fopen("dump", "wt");
2548
2549 if (fdDump)
2550 {
2551 time_t t;
2552
2553 time(&t);
2554 fputs(ctime(&t), fdDump);
2555 fflush(fdDump);
2556 }
2557#endif
2558
2559 g_fWindInitCalled = TRUE;
2560
2561#ifdef FEAT_MOUSE
2562 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2563#endif
2564
2565#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002566 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567#endif
2568
2569 /* This will be NULL on anything but NT 4.0 */
2570 s_pfnGetConsoleKeyboardLayoutName =
2571 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2572 "GetConsoleKeyboardLayoutNameA");
2573}
2574
2575/*
2576 * non-GUI version of mch_exit().
2577 * Shut down and exit with status `r'
2578 * Careful: mch_exit() may be called before mch_init()!
2579 */
2580 void
2581mch_exit(int r)
2582{
2583 stoptermcap();
2584
2585 if (g_fWindInitCalled)
2586 settmode(TMODE_COOK);
2587
2588 ml_close_all(TRUE); /* remove all memfiles */
2589
2590 if (g_fWindInitCalled)
2591 {
2592#ifdef FEAT_TITLE
2593 mch_restore_title(3);
2594 /*
2595 * Restore both the small and big icons of the console window to
2596 * what they were at startup. Don't do this when the window is
2597 * closed, Vim would hang here.
2598 */
2599 if (g_fCanChangeIcon && !g_fForceExit)
2600 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2601#endif
2602
2603#ifdef MCH_WRITE_DUMP
2604 if (fdDump)
2605 {
2606 time_t t;
2607
2608 time(&t);
2609 fputs(ctime(&t), fdDump);
2610 fclose(fdDump);
2611 }
2612 fdDump = NULL;
2613#endif
2614 }
2615
2616 SetConsoleCursorInfo(g_hConOut, &g_cci);
2617 SetConsoleMode(g_hConIn, g_cmodein);
2618 SetConsoleMode(g_hConOut, g_cmodeout);
2619
2620#ifdef DYNAMIC_GETTEXT
2621 dyn_libintl_end();
2622#endif
2623
2624 exit(r);
2625}
2626#endif /* !FEAT_GUI_W32 */
2627
Bram Moolenaar071d4272004-06-13 20:20:40 +00002628/*
2629 * Do we have an interactive window?
2630 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002631/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632 int
2633mch_check_win(
2634 int argc,
2635 char **argv)
2636{
2637 get_exe_name();
2638
2639#ifdef FEAT_GUI_W32
2640 return OK; /* GUI always has a tty */
2641#else
2642 if (isatty(1))
2643 return OK;
2644 return FAIL;
2645#endif
2646}
2647
2648
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002649#ifdef FEAT_MBYTE
2650/*
2651 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2652 * if it already exists. When "len" is > 0, also expand short to long
2653 * filenames.
2654 * Return FAIL if wide functions are not available, OK otherwise.
2655 * NOTE: much of this is identical to fname_case(), keep in sync!
2656 */
2657 static int
2658fname_casew(
2659 WCHAR *name,
2660 int len)
2661{
2662 WCHAR szTrueName[_MAX_PATH + 2];
2663 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2664 WCHAR *ptrue, *ptruePrev;
2665 WCHAR *porig, *porigPrev;
2666 int flen;
2667 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002668 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002669 int c;
2670 int slen;
2671
2672 flen = (int)wcslen(name);
2673 if (flen > _MAX_PATH)
2674 return OK;
2675
2676 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2677
2678 /* Build the new name in szTrueName[] one component at a time. */
2679 porig = name;
2680 ptrue = szTrueName;
2681
2682 if (iswalpha(porig[0]) && porig[1] == L':')
2683 {
2684 /* copy leading drive letter */
2685 *ptrue++ = *porig++;
2686 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002687 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002688 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002689
2690 while (*porig != NUL)
2691 {
2692 /* copy \ characters */
2693 while (*porig == psepc)
2694 *ptrue++ = *porig++;
2695
2696 ptruePrev = ptrue;
2697 porigPrev = porig;
2698 while (*porig != NUL && *porig != psepc)
2699 {
2700 *ptrue++ = *porig++;
2701 }
2702 *ptrue = NUL;
2703
2704 /* To avoid a slow failure append "\*" when searching a directory,
2705 * server or network share. */
2706 wcscpy(szTrueNameTemp, szTrueName);
2707 slen = (int)wcslen(szTrueNameTemp);
2708 if (*porig == psepc && slen + 2 < _MAX_PATH)
2709 wcscpy(szTrueNameTemp + slen, L"\\*");
2710
2711 /* Skip "", "." and "..". */
2712 if (ptrue > ptruePrev
2713 && (ptruePrev[0] != L'.'
2714 || (ptruePrev[1] != NUL
2715 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2716 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2717 != INVALID_HANDLE_VALUE)
2718 {
2719 c = *porig;
2720 *porig = NUL;
2721
2722 /* Only use the match when it's the same name (ignoring case) or
2723 * expansion is allowed and there is a match with the short name
2724 * and there is enough room. */
2725 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2726 || (len > 0
2727 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2728 && (int)(ptruePrev - szTrueName)
2729 + (int)wcslen(fb.cFileName) < len)))
2730 {
2731 wcscpy(ptruePrev, fb.cFileName);
2732
2733 /* Look for exact match and prefer it if found. Must be a
2734 * long name, otherwise there would be only one match. */
2735 while (FindNextFileW(hFind, &fb))
2736 {
2737 if (*fb.cAlternateFileName != NUL
2738 && (wcscoll(porigPrev, fb.cFileName) == 0
2739 || (len > 0
2740 && (_wcsicoll(porigPrev,
2741 fb.cAlternateFileName) == 0
2742 && (int)(ptruePrev - szTrueName)
2743 + (int)wcslen(fb.cFileName) < len))))
2744 {
2745 wcscpy(ptruePrev, fb.cFileName);
2746 break;
2747 }
2748 }
2749 }
2750 FindClose(hFind);
2751 *porig = c;
2752 ptrue = ptruePrev + wcslen(ptruePrev);
2753 }
2754 else if (hFind == INVALID_HANDLE_VALUE
2755 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2756 return FAIL;
2757 }
2758
2759 wcscpy(name, szTrueName);
2760 return OK;
2761}
2762#endif
2763
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764/*
2765 * fname_case(): Set the case of the file name, if it already exists.
2766 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002767 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768 */
2769 void
2770fname_case(
2771 char_u *name,
2772 int len)
2773{
2774 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002775 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776 char *ptrue, *ptruePrev;
2777 char *porig, *porigPrev;
2778 int flen;
2779 WIN32_FIND_DATA fb;
2780 HANDLE hFind;
2781 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002782 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002784 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002785 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786 return;
2787
2788 slash_adjust(name);
2789
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002790#ifdef FEAT_MBYTE
2791 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2792 {
2793 WCHAR *p = enc_to_utf16(name, NULL);
2794
2795 if (p != NULL)
2796 {
2797 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002798 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002799
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002800 wcsncpy(buf, p, _MAX_PATH);
2801 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002802 vim_free(p);
2803
2804 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2805 {
2806 q = utf16_to_enc(buf, NULL);
2807 if (q != NULL)
2808 {
2809 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2810 vim_free(q);
2811 return;
2812 }
2813 }
2814 }
2815 /* Retry with non-wide function (for Windows 98). */
2816 }
2817#endif
2818
2819 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2820 * So we should check this after calling wide function. */
2821 if (flen > _MAX_PATH)
2822 return;
2823
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002825 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002826 ptrue = szTrueName;
2827
2828 if (isalpha(porig[0]) && porig[1] == ':')
2829 {
2830 /* copy leading drive letter */
2831 *ptrue++ = *porig++;
2832 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002834 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835
2836 while (*porig != NUL)
2837 {
2838 /* copy \ characters */
2839 while (*porig == psepc)
2840 *ptrue++ = *porig++;
2841
2842 ptruePrev = ptrue;
2843 porigPrev = porig;
2844 while (*porig != NUL && *porig != psepc)
2845 {
2846#ifdef FEAT_MBYTE
2847 int l;
2848
2849 if (enc_dbcs)
2850 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002851 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002852 while (--l >= 0)
2853 *ptrue++ = *porig++;
2854 }
2855 else
2856#endif
2857 *ptrue++ = *porig++;
2858 }
2859 *ptrue = NUL;
2860
Bram Moolenaar464c9252010-10-13 20:37:41 +02002861 /* To avoid a slow failure append "\*" when searching a directory,
2862 * server or network share. */
2863 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002864 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002865 if (*porig == psepc && slen + 2 < _MAX_PATH)
2866 STRCPY(szTrueNameTemp + slen, "\\*");
2867
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868 /* Skip "", "." and "..". */
2869 if (ptrue > ptruePrev
2870 && (ptruePrev[0] != '.'
2871 || (ptruePrev[1] != NUL
2872 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002873 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874 != INVALID_HANDLE_VALUE)
2875 {
2876 c = *porig;
2877 *porig = NUL;
2878
2879 /* Only use the match when it's the same name (ignoring case) or
2880 * expansion is allowed and there is a match with the short name
2881 * and there is enough room. */
2882 if (_stricoll(porigPrev, fb.cFileName) == 0
2883 || (len > 0
2884 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2885 && (int)(ptruePrev - szTrueName)
2886 + (int)strlen(fb.cFileName) < len)))
2887 {
2888 STRCPY(ptruePrev, fb.cFileName);
2889
2890 /* Look for exact match and prefer it if found. Must be a
2891 * long name, otherwise there would be only one match. */
2892 while (FindNextFile(hFind, &fb))
2893 {
2894 if (*fb.cAlternateFileName != NUL
2895 && (strcoll(porigPrev, fb.cFileName) == 0
2896 || (len > 0
2897 && (_stricoll(porigPrev,
2898 fb.cAlternateFileName) == 0
2899 && (int)(ptruePrev - szTrueName)
2900 + (int)strlen(fb.cFileName) < len))))
2901 {
2902 STRCPY(ptruePrev, fb.cFileName);
2903 break;
2904 }
2905 }
2906 }
2907 FindClose(hFind);
2908 *porig = c;
2909 ptrue = ptruePrev + strlen(ptruePrev);
2910 }
2911 }
2912
2913 STRCPY(name, szTrueName);
2914}
2915
2916
2917/*
2918 * Insert user name in s[len].
2919 */
2920 int
2921mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002922 char_u *s,
2923 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002925 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 DWORD cch = sizeof szUserName;
2927
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002928#ifdef FEAT_MBYTE
2929 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2930 {
2931 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2932 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2933
2934 if (GetUserNameW(wszUserName, &wcch))
2935 {
2936 char_u *p = utf16_to_enc(wszUserName, NULL);
2937
2938 if (p != NULL)
2939 {
2940 vim_strncpy(s, p, len - 1);
2941 vim_free(p);
2942 return OK;
2943 }
2944 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002945 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2946 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002947 /* Retry with non-wide function (for Windows 98). */
2948 }
2949#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 if (GetUserName(szUserName, &cch))
2951 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002952 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953 return OK;
2954 }
2955 s[0] = NUL;
2956 return FAIL;
2957}
2958
2959
2960/*
2961 * Insert host name in s[len].
2962 */
2963 void
2964mch_get_host_name(
2965 char_u *s,
2966 int len)
2967{
2968 DWORD cch = len;
2969
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002970#ifdef FEAT_MBYTE
2971 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2972 {
2973 WCHAR wszHostName[256 + 1];
2974 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2975
2976 if (GetComputerNameW(wszHostName, &wcch))
2977 {
2978 char_u *p = utf16_to_enc(wszHostName, NULL);
2979
2980 if (p != NULL)
2981 {
2982 vim_strncpy(s, p, len - 1);
2983 vim_free(p);
2984 return;
2985 }
2986 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002987 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2988 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002989 /* Retry with non-wide function (for Windows 98). */
2990 }
2991#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002992 if (!GetComputerName((LPSTR)s, &cch))
2993 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994}
2995
2996
2997/*
2998 * return process ID
2999 */
3000 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003001mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002{
3003 return (long)GetCurrentProcessId();
3004}
3005
3006
3007/*
3008 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3009 * Return OK for success, FAIL for failure.
3010 */
3011 int
3012mch_dirname(
3013 char_u *buf,
3014 int len)
3015{
3016 /*
3017 * Originally this was:
3018 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3019 * But the Win32s known bug list says that getcwd() doesn't work
3020 * so use the Win32 system call instead. <Negri>
3021 */
3022#ifdef FEAT_MBYTE
3023 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3024 {
3025 WCHAR wbuf[_MAX_PATH + 1];
3026
3027 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3028 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003029 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030
3031 if (p != NULL)
3032 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003033 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034 vim_free(p);
3035 return OK;
3036 }
3037 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003038 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3039 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 /* Retry with non-wide function (for Windows 98). */
3041 }
3042#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003043 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044}
3045
3046/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003047 * Get file permissions for "name".
3048 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049 */
3050 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003051mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003053 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003054 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003056 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003057 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058}
3059
3060
3061/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003062 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003063 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003064 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 */
3066 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003067mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003069 long n = -1;
3070
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071#ifdef FEAT_MBYTE
3072 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3073 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003074 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075
3076 if (p != NULL)
3077 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003078 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003080 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003081 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082 /* Retry with non-wide function (for Windows 98). */
3083 }
3084 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003085 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003087 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003088 if (n == -1)
3089 return FAIL;
3090
3091 win32_set_archive(name);
3092
3093 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094}
3095
3096/*
3097 * Set hidden flag for "name".
3098 */
3099 void
3100mch_hide(char_u *name)
3101{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003102 int attrs = win32_getattrs(name);
3103 if (attrs == -1)
3104 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003106 attrs |= FILE_ATTRIBUTE_HIDDEN;
3107 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108}
3109
3110/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003111 * Return TRUE if file "name" exists and is hidden.
3112 */
3113 int
3114mch_ishidden(char_u *name)
3115{
3116 int f = win32_getattrs(name);
3117
3118 if (f == -1)
3119 return FALSE; /* file does not exist at all */
3120
3121 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3122}
3123
3124/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125 * return TRUE if "name" is a directory
3126 * return FALSE if "name" is not a directory or upon error
3127 */
3128 int
3129mch_isdir(char_u *name)
3130{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003131 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003132
3133 if (f == -1)
3134 return FALSE; /* file does not exist at all */
3135
3136 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3137}
3138
3139/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003140 * return TRUE if "name" is a directory, NOT a symlink to a directory
3141 * return FALSE if "name" is not a directory
3142 * return FALSE for error
3143 */
3144 int
3145mch_isrealdir(char_u *name)
3146{
3147 return mch_isdir(name) && !mch_is_symbolic_link(name);
3148}
3149
3150/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003151 * Create directory "name".
3152 * Return 0 on success, -1 on error.
3153 */
3154 int
3155mch_mkdir(char_u *name)
3156{
3157#ifdef FEAT_MBYTE
3158 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3159 {
3160 WCHAR *p;
3161 int retval;
3162
3163 p = enc_to_utf16(name, NULL);
3164 if (p == NULL)
3165 return -1;
3166 retval = _wmkdir(p);
3167 vim_free(p);
3168 return retval;
3169 }
3170#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003171 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003172}
3173
3174/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003175 * Delete directory "name".
3176 * Return 0 on success, -1 on error.
3177 */
3178 int
3179mch_rmdir(char_u *name)
3180{
3181#ifdef FEAT_MBYTE
3182 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3183 {
3184 WCHAR *p;
3185 int retval;
3186
3187 p = enc_to_utf16(name, NULL);
3188 if (p == NULL)
3189 return -1;
3190 retval = _wrmdir(p);
3191 vim_free(p);
3192 return retval;
3193 }
3194#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003195 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003196}
3197
3198/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003199 * Return TRUE if file "fname" has more than one link.
3200 */
3201 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003202mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003203{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003204 BY_HANDLE_FILE_INFORMATION info;
3205
3206 return win32_fileinfo(fname, &info) == FILEINFO_OK
3207 && info.nNumberOfLinks > 1;
3208}
3209
3210/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003211 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003212 */
3213 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003214mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003215{
3216 HANDLE hFind;
3217 int res = FALSE;
3218 WIN32_FIND_DATAA findDataA;
3219 DWORD fileFlags = 0, reparseTag = 0;
3220#ifdef FEAT_MBYTE
3221 WCHAR *wn = NULL;
3222 WIN32_FIND_DATAW findDataW;
3223
3224 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003225 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003226 if (wn != NULL)
3227 {
3228 hFind = FindFirstFileW(wn, &findDataW);
3229 vim_free(wn);
3230 if (hFind == INVALID_HANDLE_VALUE
3231 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3232 {
3233 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003234 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003235 if (hFind != INVALID_HANDLE_VALUE)
3236 {
3237 fileFlags = findDataA.dwFileAttributes;
3238 reparseTag = findDataA.dwReserved0;
3239 }
3240 }
3241 else
3242 {
3243 fileFlags = findDataW.dwFileAttributes;
3244 reparseTag = findDataW.dwReserved0;
3245 }
3246 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003247 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003248#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003249 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003250 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003251 if (hFind != INVALID_HANDLE_VALUE)
3252 {
3253 fileFlags = findDataA.dwFileAttributes;
3254 reparseTag = findDataA.dwReserved0;
3255 }
3256 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003257
3258 if (hFind != INVALID_HANDLE_VALUE)
3259 FindClose(hFind);
3260
3261 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003262 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3263 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003264 res = TRUE;
3265
3266 return res;
3267}
3268
3269/*
3270 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3271 * link.
3272 */
3273 int
3274mch_is_linked(char_u *fname)
3275{
3276 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3277 return TRUE;
3278 return FALSE;
3279}
3280
3281/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003282 * Get the by-handle-file-information for "fname".
3283 * Returns FILEINFO_OK when OK.
3284 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3285 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3286 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3287 */
3288 int
3289win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3290{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003291 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003292 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003293#ifdef FEAT_MBYTE
3294 WCHAR *wn = NULL;
3295
3296 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003297 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003298 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003299 if (wn == NULL)
3300 res = FILEINFO_ENC_FAIL;
3301 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003302 if (wn != NULL)
3303 {
3304 hFile = CreateFileW(wn, /* file name */
3305 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003306 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003307 NULL, /* security descriptor */
3308 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003309 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003310 NULL); /* handle to template file */
3311 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003312 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003313 {
3314 /* Retry with non-wide function (for Windows 98). */
3315 vim_free(wn);
3316 wn = NULL;
3317 }
3318 }
3319 if (wn == NULL)
3320#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003321 hFile = CreateFile((LPCSTR)fname, /* file name */
3322 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003323 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003324 NULL, /* security descriptor */
3325 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003326 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003327 NULL); /* handle to template file */
3328
3329 if (hFile != INVALID_HANDLE_VALUE)
3330 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003331 if (GetFileInformationByHandle(hFile, info) != 0)
3332 res = FILEINFO_OK;
3333 else
3334 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003335 CloseHandle(hFile);
3336 }
3337
3338#ifdef FEAT_MBYTE
3339 vim_free(wn);
3340#endif
3341 return res;
3342}
3343
3344/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003345 * get file attributes for `name'
3346 * -1 : error
3347 * else FILE_ATTRIBUTE_* defined in winnt.h
3348 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003349 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003350win32_getattrs(char_u *name)
3351{
3352 int attr;
3353#ifdef FEAT_MBYTE
3354 WCHAR *p = NULL;
3355
3356 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3357 p = enc_to_utf16(name, NULL);
3358
3359 if (p != NULL)
3360 {
3361 attr = GetFileAttributesW(p);
3362 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3363 {
3364 /* Retry with non-wide function (for Windows 98). */
3365 vim_free(p);
3366 p = NULL;
3367 }
3368 }
3369 if (p == NULL)
3370#endif
3371 attr = GetFileAttributes((char *)name);
3372#ifdef FEAT_MBYTE
3373 vim_free(p);
3374#endif
3375 return attr;
3376}
3377
3378/*
3379 * set file attributes for `name' to `attrs'
3380 *
3381 * return -1 for failure, 0 otherwise
3382 */
3383 static
3384 int
3385win32_setattrs(char_u *name, int attrs)
3386{
3387 int res;
3388#ifdef FEAT_MBYTE
3389 WCHAR *p = NULL;
3390
3391 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3392 p = enc_to_utf16(name, NULL);
3393
3394 if (p != NULL)
3395 {
3396 res = SetFileAttributesW(p, attrs);
3397 if (res == FALSE
3398 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3399 {
3400 /* Retry with non-wide function (for Windows 98). */
3401 vim_free(p);
3402 p = NULL;
3403 }
3404 }
3405 if (p == NULL)
3406#endif
3407 res = SetFileAttributes((char *)name, attrs);
3408#ifdef FEAT_MBYTE
3409 vim_free(p);
3410#endif
3411 return res ? 0 : -1;
3412}
3413
3414/*
3415 * Set archive flag for "name".
3416 */
3417 static
3418 int
3419win32_set_archive(char_u *name)
3420{
3421 int attrs = win32_getattrs(name);
3422 if (attrs == -1)
3423 return -1;
3424
3425 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3426 return win32_setattrs(name, attrs);
3427}
3428
3429/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003430 * Return TRUE if file or directory "name" is writable (not readonly).
3431 * Strange semantics of Win32: a readonly directory is writable, but you can't
3432 * delete a file. Let's say this means it is writable.
3433 */
3434 int
3435mch_writable(char_u *name)
3436{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003437 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003439 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3440 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441}
3442
Bram Moolenaar071d4272004-06-13 20:20:40 +00003443/*
3444 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003445 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003446 * Return -1 if unknown.
3447 */
3448 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003449mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003451 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003452 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003453 char_u *p;
3454
3455 if (len >= _MAX_PATH) /* safety check */
3456 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003457 if (!use_path)
3458 {
3459 /* TODO: check if file is really executable. */
3460 return mch_getperm(name) != -1 && !mch_isdir(name);
3461 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003462
3463 /* If there already is an extension try using the name directly. Also do
3464 * this with a Unix-shell like 'shell'. */
3465 if (vim_strchr(gettail(name), '.') != NULL
3466 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003467 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003468 return TRUE;
3469
3470 /*
3471 * Loop over all extensions in $PATHEXT.
3472 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003473 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003474 p = mch_getenv("PATHEXT");
3475 if (p == NULL)
3476 p = (char_u *)".com;.exe;.bat;.cmd";
3477 while (*p)
3478 {
3479 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3480 {
3481 /* A single "." means no extension is added. */
3482 buf[len] = NUL;
3483 ++p;
3484 if (*p)
3485 ++p;
3486 }
3487 else
3488 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003489 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003490 return TRUE;
3491 }
3492 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494
3495/*
3496 * Check what "name" is:
3497 * NODE_NORMAL: file or directory (or doesn't exist)
3498 * NODE_WRITABLE: writable device, socket, fifo, etc.
3499 * NODE_OTHER: non-writable things
3500 */
3501 int
3502mch_nodetype(char_u *name)
3503{
3504 HANDLE hFile;
3505 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003506#ifdef FEAT_MBYTE
3507 WCHAR *wn = NULL;
3508#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509
Bram Moolenaar043545e2006-10-10 16:44:07 +00003510 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3511 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3512 * here. */
3513 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3514 return NODE_WRITABLE;
3515
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003516#ifdef FEAT_MBYTE
3517 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3518 {
3519 wn = enc_to_utf16(name, NULL);
3520 if (wn != NULL)
3521 {
3522 hFile = CreateFileW(wn, /* file name */
3523 GENERIC_WRITE, /* access mode */
3524 0, /* share mode */
3525 NULL, /* security descriptor */
3526 OPEN_EXISTING, /* creation disposition */
3527 0, /* file attributes */
3528 NULL); /* handle to template file */
3529 if (hFile == INVALID_HANDLE_VALUE
3530 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3531 {
3532 /* Retry with non-wide function (for Windows 98). */
3533 vim_free(wn);
3534 wn = NULL;
3535 }
3536 }
3537 }
3538 if (wn == NULL)
3539#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003540 hFile = CreateFile((LPCSTR)name, /* file name */
3541 GENERIC_WRITE, /* access mode */
3542 0, /* share mode */
3543 NULL, /* security descriptor */
3544 OPEN_EXISTING, /* creation disposition */
3545 0, /* file attributes */
3546 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003548#ifdef FEAT_MBYTE
3549 vim_free(wn);
3550#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551 if (hFile == INVALID_HANDLE_VALUE)
3552 return NODE_NORMAL;
3553
3554 type = GetFileType(hFile);
3555 CloseHandle(hFile);
3556 if (type == FILE_TYPE_CHAR)
3557 return NODE_WRITABLE;
3558 if (type == FILE_TYPE_DISK)
3559 return NODE_NORMAL;
3560 return NODE_OTHER;
3561}
3562
3563#ifdef HAVE_ACL
3564struct my_acl
3565{
3566 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3567 PSID pSidOwner;
3568 PSID pSidGroup;
3569 PACL pDacl;
3570 PACL pSacl;
3571};
3572#endif
3573
3574/*
3575 * Return a pointer to the ACL of file "fname" in allocated memory.
3576 * Return NULL if the ACL is not available for whatever reason.
3577 */
3578 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003579mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580{
3581#ifndef HAVE_ACL
3582 return (vim_acl_T)NULL;
3583#else
3584 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003585 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003586
3587 /* This only works on Windows NT and 2000. */
3588 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3589 {
3590 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3591 if (p != NULL)
3592 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003593# ifdef FEAT_MBYTE
3594 WCHAR *wn = NULL;
3595
3596 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3597 wn = enc_to_utf16(fname, NULL);
3598 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003600 /* Try to retrieve the entire security descriptor. */
3601 err = pGetNamedSecurityInfoW(
3602 wn, // Abstract filename
3603 SE_FILE_OBJECT, // File Object
3604 OWNER_SECURITY_INFORMATION |
3605 GROUP_SECURITY_INFORMATION |
3606 DACL_SECURITY_INFORMATION |
3607 SACL_SECURITY_INFORMATION,
3608 &p->pSidOwner, // Ownership information.
3609 &p->pSidGroup, // Group membership.
3610 &p->pDacl, // Discretionary information.
3611 &p->pSacl, // For auditing purposes.
3612 &p->pSecurityDescriptor);
3613 if (err == ERROR_ACCESS_DENIED ||
3614 err == ERROR_PRIVILEGE_NOT_HELD)
3615 {
3616 /* Retrieve only DACL. */
3617 (void)pGetNamedSecurityInfoW(
3618 wn,
3619 SE_FILE_OBJECT,
3620 DACL_SECURITY_INFORMATION,
3621 NULL,
3622 NULL,
3623 &p->pDacl,
3624 NULL,
3625 &p->pSecurityDescriptor);
3626 }
3627 if (p->pSecurityDescriptor == NULL)
3628 {
3629 mch_free_acl((vim_acl_T)p);
3630 p = NULL;
3631 }
3632 vim_free(wn);
3633 }
3634 else
3635# endif
3636 {
3637 /* Try to retrieve the entire security descriptor. */
3638 err = pGetNamedSecurityInfo(
3639 (LPSTR)fname, // Abstract filename
3640 SE_FILE_OBJECT, // File Object
3641 OWNER_SECURITY_INFORMATION |
3642 GROUP_SECURITY_INFORMATION |
3643 DACL_SECURITY_INFORMATION |
3644 SACL_SECURITY_INFORMATION,
3645 &p->pSidOwner, // Ownership information.
3646 &p->pSidGroup, // Group membership.
3647 &p->pDacl, // Discretionary information.
3648 &p->pSacl, // For auditing purposes.
3649 &p->pSecurityDescriptor);
3650 if (err == ERROR_ACCESS_DENIED ||
3651 err == ERROR_PRIVILEGE_NOT_HELD)
3652 {
3653 /* Retrieve only DACL. */
3654 (void)pGetNamedSecurityInfo(
3655 (LPSTR)fname,
3656 SE_FILE_OBJECT,
3657 DACL_SECURITY_INFORMATION,
3658 NULL,
3659 NULL,
3660 &p->pDacl,
3661 NULL,
3662 &p->pSecurityDescriptor);
3663 }
3664 if (p->pSecurityDescriptor == NULL)
3665 {
3666 mch_free_acl((vim_acl_T)p);
3667 p = NULL;
3668 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003669 }
3670 }
3671 }
3672
3673 return (vim_acl_T)p;
3674#endif
3675}
3676
Bram Moolenaar27515922013-06-29 15:36:26 +02003677#ifdef HAVE_ACL
3678/*
3679 * Check if "acl" contains inherited ACE.
3680 */
3681 static BOOL
3682is_acl_inherited(PACL acl)
3683{
3684 DWORD i;
3685 ACL_SIZE_INFORMATION acl_info;
3686 PACCESS_ALLOWED_ACE ace;
3687
3688 acl_info.AceCount = 0;
3689 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3690 for (i = 0; i < acl_info.AceCount; i++)
3691 {
3692 GetAce(acl, i, (LPVOID *)&ace);
3693 if (ace->Header.AceFlags & INHERITED_ACE)
3694 return TRUE;
3695 }
3696 return FALSE;
3697}
3698#endif
3699
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700/*
3701 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3702 * Errors are ignored.
3703 * This must only be called with "acl" equal to what mch_get_acl() returned.
3704 */
3705 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003706mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707{
3708#ifdef HAVE_ACL
3709 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003710 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711
3712 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003713 {
3714# ifdef FEAT_MBYTE
3715 WCHAR *wn = NULL;
3716# endif
3717
3718 /* Set security flags */
3719 if (p->pSidOwner)
3720 sec_info |= OWNER_SECURITY_INFORMATION;
3721 if (p->pSidGroup)
3722 sec_info |= GROUP_SECURITY_INFORMATION;
3723 if (p->pDacl)
3724 {
3725 sec_info |= DACL_SECURITY_INFORMATION;
3726 /* Do not inherit its parent's DACL.
3727 * If the DACL is inherited, Cygwin permissions would be changed.
3728 */
3729 if (!is_acl_inherited(p->pDacl))
3730 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3731 }
3732 if (p->pSacl)
3733 sec_info |= SACL_SECURITY_INFORMATION;
3734
3735# ifdef FEAT_MBYTE
3736 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3737 wn = enc_to_utf16(fname, NULL);
3738 if (wn != NULL)
3739 {
3740 (void)pSetNamedSecurityInfoW(
3741 wn, // Abstract filename
3742 SE_FILE_OBJECT, // File Object
3743 sec_info,
3744 p->pSidOwner, // Ownership information.
3745 p->pSidGroup, // Group membership.
3746 p->pDacl, // Discretionary information.
3747 p->pSacl // For auditing purposes.
3748 );
3749 vim_free(wn);
3750 }
3751 else
3752# endif
3753 {
3754 (void)pSetNamedSecurityInfo(
3755 (LPSTR)fname, // Abstract filename
3756 SE_FILE_OBJECT, // File Object
3757 sec_info,
3758 p->pSidOwner, // Ownership information.
3759 p->pSidGroup, // Group membership.
3760 p->pDacl, // Discretionary information.
3761 p->pSacl // For auditing purposes.
3762 );
3763 }
3764 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765#endif
3766}
3767
3768 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003769mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770{
3771#ifdef HAVE_ACL
3772 struct my_acl *p = (struct my_acl *)acl;
3773
3774 if (p != NULL)
3775 {
3776 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3777 vim_free(p);
3778 }
3779#endif
3780}
3781
3782#ifndef FEAT_GUI_W32
3783
3784/*
3785 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3786 */
3787 static BOOL WINAPI
3788handler_routine(
3789 DWORD dwCtrlType)
3790{
3791 switch (dwCtrlType)
3792 {
3793 case CTRL_C_EVENT:
3794 if (ctrl_c_interrupts)
3795 g_fCtrlCPressed = TRUE;
3796 return TRUE;
3797
3798 case CTRL_BREAK_EVENT:
3799 g_fCBrkPressed = TRUE;
3800 return TRUE;
3801
3802 /* fatal events: shut down gracefully */
3803 case CTRL_CLOSE_EVENT:
3804 case CTRL_LOGOFF_EVENT:
3805 case CTRL_SHUTDOWN_EVENT:
3806 windgoto((int)Rows - 1, 0);
3807 g_fForceExit = TRUE;
3808
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003809 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 (dwCtrlType == CTRL_CLOSE_EVENT
3811 ? _("close")
3812 : dwCtrlType == CTRL_LOGOFF_EVENT
3813 ? _("logoff")
3814 : _("shutdown")));
3815#ifdef DEBUG
3816 OutputDebugString(IObuff);
3817#endif
3818
3819 preserve_exit(); /* output IObuff, preserve files and exit */
3820
3821 return TRUE; /* not reached */
3822
3823 default:
3824 return FALSE;
3825 }
3826}
3827
3828
3829/*
3830 * set the tty in (raw) ? "raw" : "cooked" mode
3831 */
3832 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003833mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834{
3835 DWORD cmodein;
3836 DWORD cmodeout;
3837 BOOL bEnableHandler;
3838
3839 GetConsoleMode(g_hConIn, &cmodein);
3840 GetConsoleMode(g_hConOut, &cmodeout);
3841 if (tmode == TMODE_RAW)
3842 {
3843 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3844 ENABLE_ECHO_INPUT);
3845#ifdef FEAT_MOUSE
3846 if (g_fMouseActive)
3847 cmodein |= ENABLE_MOUSE_INPUT;
3848#endif
3849 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3850 bEnableHandler = TRUE;
3851 }
3852 else /* cooked */
3853 {
3854 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3855 ENABLE_ECHO_INPUT);
3856 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3857 bEnableHandler = FALSE;
3858 }
3859 SetConsoleMode(g_hConIn, cmodein);
3860 SetConsoleMode(g_hConOut, cmodeout);
3861 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3862
3863#ifdef MCH_WRITE_DUMP
3864 if (fdDump)
3865 {
3866 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3867 tmode == TMODE_RAW ? "raw" :
3868 tmode == TMODE_COOK ? "cooked" : "normal",
3869 cmodein, cmodeout);
3870 fflush(fdDump);
3871 }
3872#endif
3873}
3874
3875
3876/*
3877 * Get the size of the current window in `Rows' and `Columns'
3878 * Return OK when size could be determined, FAIL otherwise.
3879 */
3880 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003881mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003882{
3883 CONSOLE_SCREEN_BUFFER_INFO csbi;
3884
3885 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3886 {
3887 /*
3888 * For some reason, we are trying to get the screen dimensions
3889 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3890 * variables are really intended to mean the size of Vim screen
3891 * while in termcap mode.
3892 */
3893 Rows = g_cbTermcap.Info.dwSize.Y;
3894 Columns = g_cbTermcap.Info.dwSize.X;
3895 }
3896 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3897 {
3898 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3899 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3900 }
3901 else
3902 {
3903 Rows = 25;
3904 Columns = 80;
3905 }
3906 return OK;
3907}
3908
3909/*
3910 * Set a console window to `xSize' * `ySize'
3911 */
3912 static void
3913ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003914 HANDLE hConsole,
3915 int xSize,
3916 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917{
3918 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3919 SMALL_RECT srWindowRect; /* hold the new console size */
3920 COORD coordScreen;
3921
3922#ifdef MCH_WRITE_DUMP
3923 if (fdDump)
3924 {
3925 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3926 fflush(fdDump);
3927 }
3928#endif
3929
3930 /* get the largest size we can size the console window to */
3931 coordScreen = GetLargestConsoleWindowSize(hConsole);
3932
3933 /* define the new console window size and scroll position */
3934 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3935 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3936 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3937
3938 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3939 {
3940 int sx, sy;
3941
3942 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3943 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3944 if (sy < ySize || sx < xSize)
3945 {
3946 /*
3947 * Increasing number of lines/columns, do buffer first.
3948 * Use the maximal size in x and y direction.
3949 */
3950 if (sy < ySize)
3951 coordScreen.Y = ySize;
3952 else
3953 coordScreen.Y = sy;
3954 if (sx < xSize)
3955 coordScreen.X = xSize;
3956 else
3957 coordScreen.X = sx;
3958 SetConsoleScreenBufferSize(hConsole, coordScreen);
3959 }
3960 }
3961
3962 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3963 {
3964#ifdef MCH_WRITE_DUMP
3965 if (fdDump)
3966 {
3967 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3968 GetLastError());
3969 fflush(fdDump);
3970 }
3971#endif
3972 }
3973
3974 /* define the new console buffer size */
3975 coordScreen.X = xSize;
3976 coordScreen.Y = ySize;
3977
3978 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3979 {
3980#ifdef MCH_WRITE_DUMP
3981 if (fdDump)
3982 {
3983 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3984 GetLastError());
3985 fflush(fdDump);
3986 }
3987#endif
3988 }
3989}
3990
3991
3992/*
3993 * Set the console window to `Rows' * `Columns'
3994 */
3995 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003996mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003997{
3998 COORD coordScreen;
3999
4000 /* Don't change window size while still starting up */
4001 if (suppress_winsize != 0)
4002 {
4003 suppress_winsize = 2;
4004 return;
4005 }
4006
4007 if (term_console)
4008 {
4009 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4010
4011 /* Clamp Rows and Columns to reasonable values */
4012 if (Rows > coordScreen.Y)
4013 Rows = coordScreen.Y;
4014 if (Columns > coordScreen.X)
4015 Columns = coordScreen.X;
4016
4017 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4018 }
4019}
4020
4021/*
4022 * Rows and/or Columns has changed.
4023 */
4024 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004025mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004026{
4027 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4028}
4029
4030
4031/*
4032 * Called when started up, to set the winsize that was delayed.
4033 */
4034 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004035mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004036{
4037 if (suppress_winsize == 2)
4038 {
4039 suppress_winsize = 0;
4040 mch_set_shellsize();
4041 shell_resized();
4042 }
4043 suppress_winsize = 0;
4044}
4045#endif /* FEAT_GUI_W32 */
4046
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004047 static BOOL
4048vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004049 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004050 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004051 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004052 STARTUPINFO *si,
4053 PROCESS_INFORMATION *pi)
4054{
4055# ifdef FEAT_MBYTE
4056 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4057 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004058 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004059
4060 if (wcmd != NULL)
4061 {
4062 BOOL ret;
4063 ret = CreateProcessW(
4064 NULL, /* Executable name */
4065 wcmd, /* Command to execute */
4066 NULL, /* Process security attributes */
4067 NULL, /* Thread security attributes */
4068 inherit_handles, /* Inherit handles */
4069 flags, /* Creation flags */
4070 NULL, /* Environment */
4071 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004072 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004073 pi); /* Process information */
4074 vim_free(wcmd);
4075 return ret;
4076 }
4077 }
4078#endif
4079 return CreateProcess(
4080 NULL, /* Executable name */
4081 cmd, /* Command to execute */
4082 NULL, /* Process security attributes */
4083 NULL, /* Thread security attributes */
4084 inherit_handles, /* Inherit handles */
4085 flags, /* Creation flags */
4086 NULL, /* Environment */
4087 NULL, /* Current directory */
4088 si, /* Startup information */
4089 pi); /* Process information */
4090}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091
4092
4093#if defined(FEAT_GUI_W32) || defined(PROTO)
4094
4095/*
4096 * Specialised version of system() for Win32 GUI mode.
4097 * This version proceeds as follows:
4098 * 1. Create a console window for use by the subprocess
4099 * 2. Run the subprocess (it gets the allocated console by default)
4100 * 3. Wait for the subprocess to terminate and get its exit code
4101 * 4. Prompt the user to press a key to close the console window
4102 */
4103 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004104mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105{
4106 STARTUPINFO si;
4107 PROCESS_INFORMATION pi;
4108 DWORD ret = 0;
4109 HWND hwnd = GetFocus();
4110
4111 si.cb = sizeof(si);
4112 si.lpReserved = NULL;
4113 si.lpDesktop = NULL;
4114 si.lpTitle = NULL;
4115 si.dwFlags = STARTF_USESHOWWINDOW;
4116 /*
4117 * It's nicer to run a filter command in a minimized window, but in
4118 * Windows 95 this makes the command MUCH slower. We can't do it under
4119 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004120 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 */
4122 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004123 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004124 else
4125 si.wShowWindow = SW_SHOWNORMAL;
4126 si.cbReserved2 = 0;
4127 si.lpReserved2 = NULL;
4128
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004129 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 * When the "c:\\" is left out it works OK...? */
4131 if (mch_windows95()
4132 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4133 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4134 cmd += 3;
4135
4136 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004137 vim_create_process(cmd, FALSE,
4138 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139
4140 /* Wait for the command to terminate before continuing */
4141 if (g_PlatformId != VER_PLATFORM_WIN32s)
4142 {
4143#ifdef FEAT_GUI
4144 int delay = 1;
4145
4146 /* Keep updating the window while waiting for the shell to finish. */
4147 for (;;)
4148 {
4149 MSG msg;
4150
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004151 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 {
4153 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004154 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004155 delay = 1;
4156 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157 }
4158 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4159 break;
4160
4161 /* We start waiting for a very short time and then increase it, so
4162 * that we respond quickly when the process is quick, and don't
4163 * consume too much overhead when it's slow. */
4164 if (delay < 50)
4165 delay += 10;
4166 }
4167#else
4168 WaitForSingleObject(pi.hProcess, INFINITE);
4169#endif
4170
4171 /* Get the command exit code */
4172 GetExitCodeProcess(pi.hProcess, &ret);
4173 }
4174 else
4175 {
4176 /*
4177 * This ugly code is the only quick way of performing
4178 * a synchronous spawn under Win32s. Yuk.
4179 */
4180 num_windows = 0;
4181 EnumWindows(win32ssynch_cb, 0);
4182 old_num_windows = num_windows;
4183 do
4184 {
4185 Sleep(1000);
4186 num_windows = 0;
4187 EnumWindows(win32ssynch_cb, 0);
4188 } while (num_windows == old_num_windows);
4189 ret = 0;
4190 }
4191
4192 /* Close the handles to the subprocess, so that it goes away */
4193 CloseHandle(pi.hThread);
4194 CloseHandle(pi.hProcess);
4195
4196 /* Try to get input focus back. Doesn't always work though. */
4197 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4198
4199 return ret;
4200}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004201
4202/*
4203 * Thread launched by the gui to send the current buffer data to the
4204 * process. This way avoid to hang up vim totally if the children
4205 * process take a long time to process the lines.
4206 */
4207 static DWORD WINAPI
4208sub_process_writer(LPVOID param)
4209{
4210 HANDLE g_hChildStd_IN_Wr = param;
4211 linenr_T lnum = curbuf->b_op_start.lnum;
4212 DWORD len = 0;
4213 DWORD l;
4214 char_u *lp = ml_get(lnum);
4215 char_u *s;
4216 int written = 0;
4217
4218 for (;;)
4219 {
4220 l = (DWORD)STRLEN(lp + written);
4221 if (l == 0)
4222 len = 0;
4223 else if (lp[written] == NL)
4224 {
4225 /* NL -> NUL translation */
4226 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4227 }
4228 else
4229 {
4230 s = vim_strchr(lp + written, NL);
4231 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4232 s == NULL ? l : (DWORD)(s - (lp + written)),
4233 &len, NULL);
4234 }
4235 if (len == (int)l)
4236 {
4237 /* Finished a line, add a NL, unless this line should not have
4238 * one. */
4239 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004240 || (!curbuf->b_p_bin
4241 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004242 || (lnum != curbuf->b_no_eol_lnum
4243 && (lnum != curbuf->b_ml.ml_line_count
4244 || curbuf->b_p_eol)))
4245 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004246 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004247 }
4248
4249 ++lnum;
4250 if (lnum > curbuf->b_op_end.lnum)
4251 break;
4252
4253 lp = ml_get(lnum);
4254 written = 0;
4255 }
4256 else if (len > 0)
4257 written += len;
4258 }
4259
4260 /* finished all the lines, close pipe */
4261 CloseHandle(g_hChildStd_IN_Wr);
4262 ExitThread(0);
4263}
4264
4265
4266# define BUFLEN 100 /* length for buffer, stolen from unix version */
4267
4268/*
4269 * This function read from the children's stdout and write the
4270 * data on screen or in the buffer accordingly.
4271 */
4272 static void
4273dump_pipe(int options,
4274 HANDLE g_hChildStd_OUT_Rd,
4275 garray_T *ga,
4276 char_u buffer[],
4277 DWORD *buffer_off)
4278{
4279 DWORD availableBytes = 0;
4280 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004281 int ret;
4282 DWORD len;
4283 DWORD toRead;
4284 int repeatCount;
4285
4286 /* we query the pipe to see if there is any data to read
4287 * to avoid to perform a blocking read */
4288 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4289 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004290 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004291 NULL, /* number of read bytes */
4292 &availableBytes, /* available bytes total */
4293 NULL); /* byteLeft */
4294
4295 repeatCount = 0;
4296 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004297 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298 {
4299 repeatCount++;
4300 toRead =
4301# ifdef FEAT_MBYTE
4302 (DWORD)(BUFLEN - *buffer_off);
4303# else
4304 (DWORD)BUFLEN;
4305# endif
4306 toRead = availableBytes < toRead ? availableBytes : toRead;
4307 ReadFile(g_hChildStd_OUT_Rd, buffer
4308# ifdef FEAT_MBYTE
4309 + *buffer_off, toRead
4310# else
4311 , toRead
4312# endif
4313 , &len, NULL);
4314
4315 /* If we haven't read anything, there is a problem */
4316 if (len == 0)
4317 break;
4318
4319 availableBytes -= len;
4320
4321 if (options & SHELL_READ)
4322 {
4323 /* Do NUL -> NL translation, append NL separated
4324 * lines to the current buffer. */
4325 for (i = 0; i < len; ++i)
4326 {
4327 if (buffer[i] == NL)
4328 append_ga_line(ga);
4329 else if (buffer[i] == NUL)
4330 ga_append(ga, NL);
4331 else
4332 ga_append(ga, buffer[i]);
4333 }
4334 }
4335# ifdef FEAT_MBYTE
4336 else if (has_mbyte)
4337 {
4338 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004339 int c;
4340 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004341
4342 len += *buffer_off;
4343 buffer[len] = NUL;
4344
4345 /* Check if the last character in buffer[] is
4346 * incomplete, keep these bytes for the next
4347 * round. */
4348 for (p = buffer; p < buffer + len; p += l)
4349 {
4350 l = mb_cptr2len(p);
4351 if (l == 0)
4352 l = 1; /* NUL byte? */
4353 else if (MB_BYTE2LEN(*p) != l)
4354 break;
4355 }
4356 if (p == buffer) /* no complete character */
4357 {
4358 /* avoid getting stuck at an illegal byte */
4359 if (len >= 12)
4360 ++p;
4361 else
4362 {
4363 *buffer_off = len;
4364 return;
4365 }
4366 }
4367 c = *p;
4368 *p = NUL;
4369 msg_puts(buffer);
4370 if (p < buffer + len)
4371 {
4372 *p = c;
4373 *buffer_off = (DWORD)((buffer + len) - p);
4374 mch_memmove(buffer, p, *buffer_off);
4375 return;
4376 }
4377 *buffer_off = 0;
4378 }
4379# endif /* FEAT_MBYTE */
4380 else
4381 {
4382 buffer[len] = NUL;
4383 msg_puts(buffer);
4384 }
4385
4386 windgoto(msg_row, msg_col);
4387 cursor_on();
4388 out_flush();
4389 }
4390}
4391
4392/*
4393 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4394 * for communication and doesn't open any new window.
4395 */
4396 static int
4397mch_system_piped(char *cmd, int options)
4398{
4399 STARTUPINFO si;
4400 PROCESS_INFORMATION pi;
4401 DWORD ret = 0;
4402
4403 HANDLE g_hChildStd_IN_Rd = NULL;
4404 HANDLE g_hChildStd_IN_Wr = NULL;
4405 HANDLE g_hChildStd_OUT_Rd = NULL;
4406 HANDLE g_hChildStd_OUT_Wr = NULL;
4407
4408 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4409 DWORD len;
4410
4411 /* buffer used to receive keys */
4412 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4413 int ta_len = 0; /* valid bytes in ta_buf[] */
4414
4415 DWORD i;
4416 int c;
4417 int noread_cnt = 0;
4418 garray_T ga;
4419 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004420 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004421 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422
4423 SECURITY_ATTRIBUTES saAttr;
4424
4425 /* Set the bInheritHandle flag so pipe handles are inherited. */
4426 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4427 saAttr.bInheritHandle = TRUE;
4428 saAttr.lpSecurityDescriptor = NULL;
4429
4430 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4431 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4432 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4433 /* Create a pipe for the child process's STDIN. */
4434 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4435 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4436 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4437 {
4438 CloseHandle(g_hChildStd_IN_Rd);
4439 CloseHandle(g_hChildStd_IN_Wr);
4440 CloseHandle(g_hChildStd_OUT_Rd);
4441 CloseHandle(g_hChildStd_OUT_Wr);
4442 MSG_PUTS(_("\nCannot create pipes\n"));
4443 }
4444
4445 si.cb = sizeof(si);
4446 si.lpReserved = NULL;
4447 si.lpDesktop = NULL;
4448 si.lpTitle = NULL;
4449 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4450
4451 /* set-up our file redirection */
4452 si.hStdError = g_hChildStd_OUT_Wr;
4453 si.hStdOutput = g_hChildStd_OUT_Wr;
4454 si.hStdInput = g_hChildStd_IN_Rd;
4455 si.wShowWindow = SW_HIDE;
4456 si.cbReserved2 = 0;
4457 si.lpReserved2 = NULL;
4458
4459 if (options & SHELL_READ)
4460 ga_init2(&ga, 1, BUFLEN);
4461
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004462 if (cmd != NULL)
4463 {
4464 p = (char *)vim_strsave((char_u *)cmd);
4465 if (p != NULL)
4466 unescape_shellxquote((char_u *)p, p_sxe);
4467 else
4468 p = cmd;
4469 }
4470
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004471 /* Now, run the command.
4472 * About "Inherit handles" being TRUE: this command can be litigious,
4473 * handle inheritance was deactivated for pending temp file, but, if we
4474 * deactivate it, the pipes don't work for some reason. */
4475 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004476
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004477 if (p != cmd)
4478 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004479
4480 /* Close our unused side of the pipes */
4481 CloseHandle(g_hChildStd_IN_Rd);
4482 CloseHandle(g_hChildStd_OUT_Wr);
4483
4484 if (options & SHELL_WRITE)
4485 {
4486 HANDLE thread =
4487 CreateThread(NULL, /* security attributes */
4488 0, /* default stack size */
4489 sub_process_writer, /* function to be executed */
4490 g_hChildStd_IN_Wr, /* parameter */
4491 0, /* creation flag, start immediately */
4492 NULL); /* we don't care about thread id */
4493 CloseHandle(thread);
4494 g_hChildStd_IN_Wr = NULL;
4495 }
4496
4497 /* Keep updating the window while waiting for the shell to finish. */
4498 for (;;)
4499 {
4500 MSG msg;
4501
Bram Moolenaar175d0702013-12-11 18:36:33 +01004502 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004503 {
4504 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004505 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004506 }
4507
4508 /* write pipe information in the window */
4509 if ((options & (SHELL_READ|SHELL_WRITE))
4510# ifdef FEAT_GUI
4511 || gui.in_use
4512# endif
4513 )
4514 {
4515 len = 0;
4516 if (!(options & SHELL_EXPAND)
4517 && ((options &
4518 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4519 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4520# ifdef FEAT_GUI
4521 || gui.in_use
4522# endif
4523 )
4524 && (ta_len > 0 || noread_cnt > 4))
4525 {
4526 if (ta_len == 0)
4527 {
4528 /* Get extra characters when we don't have any. Reset the
4529 * counter and timer. */
4530 noread_cnt = 0;
4531# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4532 gettimeofday(&start_tv, NULL);
4533# endif
4534 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4535 }
4536 if (ta_len > 0 || len > 0)
4537 {
4538 /*
4539 * For pipes: Check for CTRL-C: send interrupt signal to
4540 * child. Check for CTRL-D: EOF, close pipe to child.
4541 */
4542 if (len == 1 && cmd != NULL)
4543 {
4544 if (ta_buf[ta_len] == Ctrl_C)
4545 {
4546 /* Learn what exit code is expected, for
4547 * now put 9 as SIGKILL */
4548 TerminateProcess(pi.hProcess, 9);
4549 }
4550 if (ta_buf[ta_len] == Ctrl_D)
4551 {
4552 CloseHandle(g_hChildStd_IN_Wr);
4553 g_hChildStd_IN_Wr = NULL;
4554 }
4555 }
4556
4557 /* replace K_BS by <BS> and K_DEL by <DEL> */
4558 for (i = ta_len; i < ta_len + len; ++i)
4559 {
4560 if (ta_buf[i] == CSI && len - i > 2)
4561 {
4562 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4563 if (c == K_DEL || c == K_KDEL || c == K_BS)
4564 {
4565 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4566 (size_t)(len - i - 2));
4567 if (c == K_DEL || c == K_KDEL)
4568 ta_buf[i] = DEL;
4569 else
4570 ta_buf[i] = Ctrl_H;
4571 len -= 2;
4572 }
4573 }
4574 else if (ta_buf[i] == '\r')
4575 ta_buf[i] = '\n';
4576# ifdef FEAT_MBYTE
4577 if (has_mbyte)
4578 i += (*mb_ptr2len_len)(ta_buf + i,
4579 ta_len + len - i) - 1;
4580# endif
4581 }
4582
4583 /*
4584 * For pipes: echo the typed characters. For a pty this
4585 * does not seem to work.
4586 */
4587 for (i = ta_len; i < ta_len + len; ++i)
4588 {
4589 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4590 msg_putchar(ta_buf[i]);
4591# ifdef FEAT_MBYTE
4592 else if (has_mbyte)
4593 {
4594 int l = (*mb_ptr2len)(ta_buf + i);
4595
4596 msg_outtrans_len(ta_buf + i, l);
4597 i += l - 1;
4598 }
4599# endif
4600 else
4601 msg_outtrans_len(ta_buf + i, 1);
4602 }
4603 windgoto(msg_row, msg_col);
4604 out_flush();
4605
4606 ta_len += len;
4607
4608 /*
4609 * Write the characters to the child, unless EOF has been
4610 * typed for pipes. Write one character at a time, to
4611 * avoid losing too much typeahead. When writing buffer
4612 * lines, drop the typed characters (only check for
4613 * CTRL-C).
4614 */
4615 if (options & SHELL_WRITE)
4616 ta_len = 0;
4617 else if (g_hChildStd_IN_Wr != NULL)
4618 {
4619 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4620 1, &len, NULL);
4621 // if we are typing in, we want to keep things reactive
4622 delay = 1;
4623 if (len > 0)
4624 {
4625 ta_len -= len;
4626 mch_memmove(ta_buf, ta_buf + len, ta_len);
4627 }
4628 }
4629 }
4630 }
4631 }
4632
4633 if (ta_len)
4634 ui_inchar_undo(ta_buf, ta_len);
4635
4636 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4637 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004638 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004639 break;
4640 }
4641
4642 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004643 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004644
4645 /* We start waiting for a very short time and then increase it, so
4646 * that we respond quickly when the process is quick, and don't
4647 * consume too much overhead when it's slow. */
4648 if (delay < 50)
4649 delay += 10;
4650 }
4651
4652 /* Close the pipe */
4653 CloseHandle(g_hChildStd_OUT_Rd);
4654 if (g_hChildStd_IN_Wr != NULL)
4655 CloseHandle(g_hChildStd_IN_Wr);
4656
4657 WaitForSingleObject(pi.hProcess, INFINITE);
4658
4659 /* Get the command exit code */
4660 GetExitCodeProcess(pi.hProcess, &ret);
4661
4662 if (options & SHELL_READ)
4663 {
4664 if (ga.ga_len > 0)
4665 {
4666 append_ga_line(&ga);
4667 /* remember that the NL was missing */
4668 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4669 }
4670 else
4671 curbuf->b_no_eol_lnum = 0;
4672 ga_clear(&ga);
4673 }
4674
4675 /* Close the handles to the subprocess, so that it goes away */
4676 CloseHandle(pi.hThread);
4677 CloseHandle(pi.hProcess);
4678
4679 return ret;
4680}
4681
4682 static int
4683mch_system(char *cmd, int options)
4684{
4685 /* if we can pipe and the shelltemp option is off */
4686 if (allowPiping && !p_stmp)
4687 return mch_system_piped(cmd, options);
4688 else
4689 return mch_system_classic(cmd, options);
4690}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004691#else
4692
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004693# ifdef FEAT_MBYTE
4694 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004695mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004696{
4697 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4698 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004699 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004700 if (wcmd != NULL)
4701 {
4702 int ret = _wsystem(wcmd);
4703 vim_free(wcmd);
4704 return ret;
4705 }
4706 }
4707 return system(cmd);
4708}
4709# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004710# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004711# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004712
4713#endif
4714
4715/*
4716 * Either execute a command by calling the shell or start a new shell
4717 */
4718 int
4719mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004720 char_u *cmd,
4721 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722{
4723 int x = 0;
4724 int tmode = cur_tmode;
4725#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004726 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004727# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004728 int did_set_title = FALSE;
4729
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004730 /* Change the title to reflect that we are in a subshell. */
4731 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4732 {
4733 WCHAR szShellTitle[512];
4734
4735 if (GetConsoleTitleW(szShellTitle,
4736 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4737 {
4738 if (cmd == NULL)
4739 wcscat(szShellTitle, L" :sh");
4740 else
4741 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004742 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004743
4744 if (wn != NULL)
4745 {
4746 wcscat(szShellTitle, L" - !");
4747 if ((wcslen(szShellTitle) + wcslen(wn) <
4748 sizeof(szShellTitle)/sizeof(WCHAR)))
4749 wcscat(szShellTitle, wn);
4750 SetConsoleTitleW(szShellTitle);
4751 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004752 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004753 }
4754 }
4755 }
4756 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004757 if (!did_set_title)
4758# endif
4759 /* Change the title to reflect that we are in a subshell. */
4760 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004762 if (cmd == NULL)
4763 strcat(szShellTitle, " :sh");
4764 else
4765 {
4766 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004767 if ((strlen(szShellTitle) + strlen((char *)cmd)
4768 < sizeof(szShellTitle)))
4769 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004770 }
4771 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773#endif
4774
4775 out_flush();
4776
4777#ifdef MCH_WRITE_DUMP
4778 if (fdDump)
4779 {
4780 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4781 fflush(fdDump);
4782 }
4783#endif
4784
4785 /*
4786 * Catch all deadly signals while running the external command, because a
4787 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4788 */
4789 signal(SIGINT, SIG_IGN);
4790#if defined(__GNUC__) && !defined(__MINGW32__)
4791 signal(SIGKILL, SIG_IGN);
4792#else
4793 signal(SIGBREAK, SIG_IGN);
4794#endif
4795 signal(SIGILL, SIG_IGN);
4796 signal(SIGFPE, SIG_IGN);
4797 signal(SIGSEGV, SIG_IGN);
4798 signal(SIGTERM, SIG_IGN);
4799 signal(SIGABRT, SIG_IGN);
4800
4801 if (options & SHELL_COOKED)
4802 settmode(TMODE_COOK); /* set to normal mode */
4803
4804 if (cmd == NULL)
4805 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004806 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807 }
4808 else
4809 {
4810 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004811 char_u *newcmd = NULL;
4812 char_u *cmdbase = cmd;
4813 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004814
4815 /* Skip a leading ", ( and "(. */
4816 if (*cmdbase == '"' )
4817 ++cmdbase;
4818 if (*cmdbase == '(')
4819 ++cmdbase;
4820
4821 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4822 {
4823 STARTUPINFO si;
4824 PROCESS_INFORMATION pi;
4825 DWORD flags = CREATE_NEW_CONSOLE;
4826 char_u *p;
4827
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004828 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004829 si.cb = sizeof(si);
4830 si.lpReserved = NULL;
4831 si.lpDesktop = NULL;
4832 si.lpTitle = NULL;
4833 si.dwFlags = 0;
4834 si.cbReserved2 = 0;
4835 si.lpReserved2 = NULL;
4836
4837 cmdbase = skipwhite(cmdbase + 5);
4838 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4839 && vim_iswhite(cmdbase[4]))
4840 {
4841 cmdbase = skipwhite(cmdbase + 4);
4842 si.dwFlags = STARTF_USESHOWWINDOW;
4843 si.wShowWindow = SW_SHOWMINNOACTIVE;
4844 }
4845 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4846 && vim_iswhite(cmdbase[2]))
4847 {
4848 cmdbase = skipwhite(cmdbase + 2);
4849 flags = CREATE_NO_WINDOW;
4850 si.dwFlags = STARTF_USESTDHANDLES;
4851 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004852 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004853 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004854 NULL, // Security att.
4855 OPEN_EXISTING, // Open flags
4856 FILE_ATTRIBUTE_NORMAL, // File att.
4857 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004858 si.hStdOutput = si.hStdInput;
4859 si.hStdError = si.hStdInput;
4860 }
4861
4862 /* Remove a trailing ", ) and )" if they have a match
4863 * at the start of the command. */
4864 if (cmdbase > cmd)
4865 {
4866 p = cmdbase + STRLEN(cmdbase);
4867 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4868 *--p = NUL;
4869 if (p > cmdbase && p[-1] == ')'
4870 && (*cmd =='(' || cmd[1] == '('))
4871 *--p = NUL;
4872 }
4873
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004874 newcmd = cmdbase;
4875 unescape_shellxquote(cmdbase, p_sxe);
4876
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004877 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004878 * If creating new console, arguments are passed to the
4879 * 'cmd.exe' as-is. If it's not, arguments are not treated
4880 * correctly for current 'cmd.exe'. So unescape characters in
4881 * shellxescape except '|' for avoiding to be treated as
4882 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004883 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004884 if (flags != CREATE_NEW_CONSOLE)
4885 {
4886 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004887 char_u *cmd_shell = mch_getenv("COMSPEC");
4888
4889 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004890 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004891
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004892 subcmd = vim_strsave_escaped_ext(cmdbase,
4893 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004894 if (subcmd != NULL)
4895 {
4896 /* make "cmd.exe /c arguments" */
4897 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004898 newcmd = lalloc(cmdlen, TRUE);
4899 if (newcmd != NULL)
4900 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004901 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004902 else
4903 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004904 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004905 }
4906 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004907
4908 /*
4909 * Now, start the command as a process, so that it doesn't
4910 * inherit our handles which causes unpleasant dangling swap
4911 * files if we exit before the spawned process
4912 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004913 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004914 x = 0;
4915 else
4916 {
4917 x = -1;
4918#ifdef FEAT_GUI_W32
4919 EMSG(_("E371: Command not found"));
4920#endif
4921 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004922
4923 if (newcmd != cmdbase)
4924 vim_free(newcmd);
4925
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004926 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004927 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004928 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004929 CloseHandle(si.hStdInput);
4930 }
4931 /* Close the handles to the subprocess, so that it goes away */
4932 CloseHandle(pi.hThread);
4933 CloseHandle(pi.hProcess);
4934 }
4935 else
4936 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004937 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004939 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004941 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4942
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004943 newcmd = lalloc(cmdlen, TRUE);
4944 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004945 {
4946#if defined(FEAT_GUI_W32)
4947 if (need_vimrun_warning)
4948 {
4949 MessageBox(NULL,
4950 _("VIMRUN.EXE not found in your $PATH.\n"
4951 "External commands will not pause after completion.\n"
4952 "See :help win32-vimrun for more information."),
4953 _("Vim Warning"),
4954 MB_ICONWARNING);
4955 need_vimrun_warning = FALSE;
4956 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004957 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004958 /* Use vimrun to execute the command. It opens a console
4959 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004960 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004961 vimrun_path,
4962 (msg_silent != 0 || (options & SHELL_DOOUT))
4963 ? "-s " : "",
4964 p_sh, p_shcf, cmd);
4965 else
4966#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004967 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004968 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004969 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004970 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004972 }
4973 }
4974
4975 if (tmode == TMODE_RAW)
4976 settmode(TMODE_RAW); /* set to raw mode */
4977
4978 /* Print the return value, unless "vimrun" was used. */
4979 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4980#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004981 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4982 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004983#endif
4984 )
4985 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004986 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004987 msg_putchar('\n');
4988 }
4989#ifdef FEAT_TITLE
4990 resettitle();
4991#endif
4992
4993 signal(SIGINT, SIG_DFL);
4994#if defined(__GNUC__) && !defined(__MINGW32__)
4995 signal(SIGKILL, SIG_DFL);
4996#else
4997 signal(SIGBREAK, SIG_DFL);
4998#endif
4999 signal(SIGILL, SIG_DFL);
5000 signal(SIGFPE, SIG_DFL);
5001 signal(SIGSEGV, SIG_DFL);
5002 signal(SIGTERM, SIG_DFL);
5003 signal(SIGABRT, SIG_DFL);
5004
5005 return x;
5006}
5007
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005008#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005009 static HANDLE
5010job_io_file_open(
5011 char_u *fname,
5012 DWORD dwDesiredAccess,
5013 DWORD dwShareMode,
5014 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5015 DWORD dwCreationDisposition,
5016 DWORD dwFlagsAndAttributes)
5017{
5018 HANDLE h;
5019# ifdef FEAT_MBYTE
5020 WCHAR *wn = NULL;
5021 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5022 {
5023 wn = enc_to_utf16(fname, NULL);
5024 if (wn != NULL)
5025 {
5026 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5027 lpSecurityAttributes, dwCreationDisposition,
5028 dwFlagsAndAttributes, NULL);
5029 vim_free(wn);
5030 if (h == INVALID_HANDLE_VALUE
5031 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5032 wn = NULL;
5033 }
5034 }
5035 if (wn == NULL)
5036# endif
5037
5038 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5039 lpSecurityAttributes, dwCreationDisposition,
5040 dwFlagsAndAttributes, NULL);
5041 return h;
5042}
5043
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005044 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005045mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005046{
5047 STARTUPINFO si;
5048 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005049 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005050 SECURITY_ATTRIBUTES saAttr;
5051 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005052 HANDLE ifd[2];
5053 HANDLE ofd[2];
5054 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005055
5056 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5057 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5058 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5059 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5060 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5061 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5062 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5063
5064 if (use_out_for_err && use_null_for_out)
5065 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005066
5067 ifd[0] = INVALID_HANDLE_VALUE;
5068 ifd[1] = INVALID_HANDLE_VALUE;
5069 ofd[0] = INVALID_HANDLE_VALUE;
5070 ofd[1] = INVALID_HANDLE_VALUE;
5071 efd[0] = INVALID_HANDLE_VALUE;
5072 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005073
Bram Moolenaar76467df2016-02-12 19:30:26 +01005074 jo = CreateJobObject(NULL, NULL);
5075 if (jo == NULL)
5076 {
5077 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005078 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005079 }
5080
5081 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005082 ZeroMemory(&si, sizeof(si));
5083 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005084 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005085 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005086
Bram Moolenaard8070362016-02-15 21:56:54 +01005087 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5088 saAttr.bInheritHandle = TRUE;
5089 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005090
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005091 if (use_file_for_in)
5092 {
5093 char_u *fname = options->jo_io_name[PART_IN];
5094
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005095 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5096 FILE_SHARE_READ | FILE_SHARE_WRITE,
5097 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5098 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005099 {
5100 EMSG2(_(e_notopen), fname);
5101 goto failed;
5102 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005103 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005104 else if (!use_null_for_in &&
5105 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5106 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005107 goto failed;
5108
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005109 if (use_file_for_out)
5110 {
5111 char_u *fname = options->jo_io_name[PART_OUT];
5112
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005113 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5114 FILE_SHARE_READ | FILE_SHARE_WRITE,
5115 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5116 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005117 {
5118 EMSG2(_(e_notopen), fname);
5119 goto failed;
5120 }
5121 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005122 else if (!use_null_for_out &&
5123 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5124 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005125 goto failed;
5126
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005127 if (use_file_for_err)
5128 {
5129 char_u *fname = options->jo_io_name[PART_ERR];
5130
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005131 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5132 FILE_SHARE_READ | FILE_SHARE_WRITE,
5133 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5134 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005135 {
5136 EMSG2(_(e_notopen), fname);
5137 goto failed;
5138 }
5139 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005140 else if (!use_out_for_err && !use_null_for_err &&
5141 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005142 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005143 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005144
Bram Moolenaard8070362016-02-15 21:56:54 +01005145 si.dwFlags |= STARTF_USESTDHANDLES;
5146 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005147 si.hStdOutput = ofd[1];
5148 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5149
5150 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5151 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005152 if (options->jo_set & JO_CHANNEL)
5153 {
5154 channel = options->jo_channel;
5155 if (channel != NULL)
5156 ++channel->ch_refcount;
5157 }
5158 else
5159 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005160 if (channel == NULL)
5161 goto failed;
5162 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005163
5164 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005165 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005166 CREATE_DEFAULT_ERROR_MODE |
5167 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005168 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005169 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005170 {
5171 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005172 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005173 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005174 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005175
5176 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005177 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005178 /* if failing, switch the way to terminate
5179 * process with TerminateProcess. */
5180 CloseHandle(jo);
5181 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005182 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005183 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005184 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005185 job->jv_proc_info = pi;
5186 job->jv_job_object = jo;
5187 job->jv_status = JOB_STARTED;
5188
Bram Moolenaar94d01912016-03-08 13:48:51 +01005189 if (!use_file_for_in)
5190 CloseHandle(ifd[0]);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005191 if (!use_file_for_out)
5192 CloseHandle(ofd[1]);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005193 if (!use_out_for_err && !use_file_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005194 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005195
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005196 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005197 if (channel != NULL)
5198 {
5199 channel_set_pipes(channel,
5200 use_file_for_in || use_null_for_in
5201 ? INVALID_FD : (sock_T)ifd[1],
5202 use_file_for_out || use_null_for_out
5203 ? INVALID_FD : (sock_T)ofd[0],
5204 use_out_for_err || use_file_for_err || use_null_for_err
5205 ? INVALID_FD : (sock_T)efd[0]);
5206 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005207 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005208 return;
5209
5210failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005211 CloseHandle(ifd[0]);
5212 CloseHandle(ofd[0]);
5213 CloseHandle(efd[0]);
5214 CloseHandle(ifd[1]);
5215 CloseHandle(ofd[1]);
5216 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005217 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005218}
5219
5220 char *
5221mch_job_status(job_T *job)
5222{
5223 DWORD dwExitCode = 0;
5224
Bram Moolenaar76467df2016-02-12 19:30:26 +01005225 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5226 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005227 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005228 job->jv_status = JOB_ENDED;
Bram Moolenaareab089d2016-02-21 19:32:02 +01005229 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005230 return "dead";
5231 }
5232 return "run";
5233}
5234
5235 int
5236mch_stop_job(job_T *job, char_u *how)
5237{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005238 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005239
Bram Moolenaar923d9262016-02-25 20:56:01 +01005240 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005241 {
5242 if (job->jv_job_object != NULL)
5243 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5244 else
5245 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5246 }
5247
5248 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5249 return FAIL;
5250 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005251 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5252 job->jv_proc_info.dwProcessId)
5253 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005254 FreeConsole();
5255 return ret;
5256}
5257
5258/*
5259 * Clear the data related to "job".
5260 */
5261 void
5262mch_clear_job(job_T *job)
5263{
5264 if (job->jv_status != JOB_FAILED)
5265 {
5266 if (job->jv_job_object != NULL)
5267 CloseHandle(job->jv_job_object);
5268 CloseHandle(job->jv_proc_info.hProcess);
5269 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005270}
5271#endif
5272
Bram Moolenaar071d4272004-06-13 20:20:40 +00005273
5274#ifndef FEAT_GUI_W32
5275
5276/*
5277 * Start termcap mode
5278 */
5279 static void
5280termcap_mode_start(void)
5281{
5282 DWORD cmodein;
5283
5284 if (g_fTermcapMode)
5285 return;
5286
5287 SaveConsoleBuffer(&g_cbNonTermcap);
5288
5289 if (g_cbTermcap.IsValid)
5290 {
5291 /*
5292 * We've been in termcap mode before. Restore certain screen
5293 * characteristics, including the buffer size and the window
5294 * size. Since we will be redrawing the screen, we don't need
5295 * to restore the actual contents of the buffer.
5296 */
5297 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5298 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5299 Rows = g_cbTermcap.Info.dwSize.Y;
5300 Columns = g_cbTermcap.Info.dwSize.X;
5301 }
5302 else
5303 {
5304 /*
5305 * This is our first time entering termcap mode. Clear the console
5306 * screen buffer, and resize the buffer to match the current window
5307 * size. We will use this as the size of our editing environment.
5308 */
5309 ClearConsoleBuffer(g_attrCurrent);
5310 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5311 }
5312
5313#ifdef FEAT_TITLE
5314 resettitle();
5315#endif
5316
5317 GetConsoleMode(g_hConIn, &cmodein);
5318#ifdef FEAT_MOUSE
5319 if (g_fMouseActive)
5320 cmodein |= ENABLE_MOUSE_INPUT;
5321 else
5322 cmodein &= ~ENABLE_MOUSE_INPUT;
5323#endif
5324 cmodein |= ENABLE_WINDOW_INPUT;
5325 SetConsoleMode(g_hConIn, cmodein);
5326
5327 redraw_later_clear();
5328 g_fTermcapMode = TRUE;
5329}
5330
5331
5332/*
5333 * End termcap mode
5334 */
5335 static void
5336termcap_mode_end(void)
5337{
5338 DWORD cmodein;
5339 ConsoleBuffer *cb;
5340 COORD coord;
5341 DWORD dwDummy;
5342
5343 if (!g_fTermcapMode)
5344 return;
5345
5346 SaveConsoleBuffer(&g_cbTermcap);
5347
5348 GetConsoleMode(g_hConIn, &cmodein);
5349 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5350 SetConsoleMode(g_hConIn, cmodein);
5351
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005352#ifdef FEAT_RESTORE_ORIG_SCREEN
5353 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5354#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005355 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005356#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005357 RestoreConsoleBuffer(cb, p_rs);
5358 SetConsoleCursorInfo(g_hConOut, &g_cci);
5359
5360 if (p_rs || exiting)
5361 {
5362 /*
5363 * Clear anything that happens to be on the current line.
5364 */
5365 coord.X = 0;
5366 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5367 FillConsoleOutputCharacter(g_hConOut, ' ',
5368 cb->Info.dwSize.X, coord, &dwDummy);
5369 /*
5370 * The following is just for aesthetics. If we are exiting without
5371 * restoring the screen, then we want to have a prompt string
5372 * appear at the bottom line. However, the command interpreter
5373 * seems to always advance the cursor one line before displaying
5374 * the prompt string, which causes the screen to scroll. To
5375 * counter this, move the cursor up one line before exiting.
5376 */
5377 if (exiting && !p_rs)
5378 coord.Y--;
5379 /*
5380 * Position the cursor at the leftmost column of the desired row.
5381 */
5382 SetConsoleCursorPosition(g_hConOut, coord);
5383 }
5384
5385 g_fTermcapMode = FALSE;
5386}
5387#endif /* FEAT_GUI_W32 */
5388
5389
5390#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005391/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005392 void
5393mch_write(
5394 char_u *s,
5395 int len)
5396{
5397 /* never used */
5398}
5399
5400#else
5401
5402/*
5403 * clear `n' chars, starting from `coord'
5404 */
5405 static void
5406clear_chars(
5407 COORD coord,
5408 DWORD n)
5409{
5410 DWORD dwDummy;
5411
5412 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5413 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5414}
5415
5416
5417/*
5418 * Clear the screen
5419 */
5420 static void
5421clear_screen(void)
5422{
5423 g_coord.X = g_coord.Y = 0;
5424 clear_chars(g_coord, Rows * Columns);
5425}
5426
5427
5428/*
5429 * Clear to end of display
5430 */
5431 static void
5432clear_to_end_of_display(void)
5433{
5434 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5435 * Columns + (Columns - g_coord.X));
5436}
5437
5438
5439/*
5440 * Clear to end of line
5441 */
5442 static void
5443clear_to_end_of_line(void)
5444{
5445 clear_chars(g_coord, Columns - g_coord.X);
5446}
5447
5448
5449/*
5450 * Scroll the scroll region up by `cLines' lines
5451 */
5452 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005453scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454{
5455 COORD oldcoord = g_coord;
5456
5457 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5458 delete_lines(cLines);
5459
5460 g_coord = oldcoord;
5461}
5462
5463
5464/*
5465 * Set the scroll region
5466 */
5467 static void
5468set_scroll_region(
5469 unsigned left,
5470 unsigned top,
5471 unsigned right,
5472 unsigned bottom)
5473{
5474 if (left >= right
5475 || top >= bottom
5476 || right > (unsigned) Columns - 1
5477 || bottom > (unsigned) Rows - 1)
5478 return;
5479
5480 g_srScrollRegion.Left = left;
5481 g_srScrollRegion.Top = top;
5482 g_srScrollRegion.Right = right;
5483 g_srScrollRegion.Bottom = bottom;
5484}
5485
5486
5487/*
5488 * Insert `cLines' lines at the current cursor position
5489 */
5490 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005491insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005492{
5493 SMALL_RECT source;
5494 COORD dest;
5495 CHAR_INFO fill;
5496
5497 dest.X = 0;
5498 dest.Y = g_coord.Y + cLines;
5499
5500 source.Left = 0;
5501 source.Top = g_coord.Y;
5502 source.Right = g_srScrollRegion.Right;
5503 source.Bottom = g_srScrollRegion.Bottom - cLines;
5504
5505 fill.Char.AsciiChar = ' ';
5506 fill.Attributes = g_attrCurrent;
5507
5508 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5509
5510 /* Here we have to deal with a win32 console flake: If the scroll
5511 * region looks like abc and we scroll c to a and fill with d we get
5512 * cbd... if we scroll block c one line at a time to a, we get cdd...
5513 * vim expects cdd consistently... So we have to deal with that
5514 * here... (this also occurs scrolling the same way in the other
5515 * direction). */
5516
5517 if (source.Bottom < dest.Y)
5518 {
5519 COORD coord;
5520
5521 coord.X = 0;
5522 coord.Y = source.Bottom;
5523 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5524 }
5525}
5526
5527
5528/*
5529 * Delete `cLines' lines at the current cursor position
5530 */
5531 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005532delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005533{
5534 SMALL_RECT source;
5535 COORD dest;
5536 CHAR_INFO fill;
5537 int nb;
5538
5539 dest.X = 0;
5540 dest.Y = g_coord.Y;
5541
5542 source.Left = 0;
5543 source.Top = g_coord.Y + cLines;
5544 source.Right = g_srScrollRegion.Right;
5545 source.Bottom = g_srScrollRegion.Bottom;
5546
5547 fill.Char.AsciiChar = ' ';
5548 fill.Attributes = g_attrCurrent;
5549
5550 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5551
5552 /* Here we have to deal with a win32 console flake: If the scroll
5553 * region looks like abc and we scroll c to a and fill with d we get
5554 * cbd... if we scroll block c one line at a time to a, we get cdd...
5555 * vim expects cdd consistently... So we have to deal with that
5556 * here... (this also occurs scrolling the same way in the other
5557 * direction). */
5558
5559 nb = dest.Y + (source.Bottom - source.Top) + 1;
5560
5561 if (nb < source.Top)
5562 {
5563 COORD coord;
5564
5565 coord.X = 0;
5566 coord.Y = nb;
5567 clear_chars(coord, Columns * (source.Top - nb));
5568 }
5569}
5570
5571
5572/*
5573 * Set the cursor position
5574 */
5575 static void
5576gotoxy(
5577 unsigned x,
5578 unsigned y)
5579{
5580 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5581 return;
5582
5583 /* external cursor coords are 1-based; internal are 0-based */
5584 g_coord.X = x - 1;
5585 g_coord.Y = y - 1;
5586 SetConsoleCursorPosition(g_hConOut, g_coord);
5587}
5588
5589
5590/*
5591 * Set the current text attribute = (foreground | background)
5592 * See ../doc/os_win32.txt for the numbers.
5593 */
5594 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005595textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005596{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005597 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598
5599 SetConsoleTextAttribute(g_hConOut, wAttr);
5600}
5601
5602
5603 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005604textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005606 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607
5608 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5609}
5610
5611
5612 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005613textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005615 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616
5617 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5618}
5619
5620
5621/*
5622 * restore the default text attribute (whatever we started with)
5623 */
5624 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005625normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626{
5627 textattr(g_attrDefault);
5628}
5629
5630
5631static WORD g_attrPreStandout = 0;
5632
5633/*
5634 * Make the text standout, by brightening it
5635 */
5636 static void
5637standout(void)
5638{
5639 g_attrPreStandout = g_attrCurrent;
5640 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5641}
5642
5643
5644/*
5645 * Turn off standout mode
5646 */
5647 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005648standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649{
5650 if (g_attrPreStandout)
5651 {
5652 textattr(g_attrPreStandout);
5653 g_attrPreStandout = 0;
5654 }
5655}
5656
5657
5658/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005659 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 */
5661 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005662mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663{
5664 char_u *p;
5665 int n;
5666
5667 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5668 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5669 if (T_ME[0] == ESC && T_ME[1] == '|')
5670 {
5671 p = T_ME + 2;
5672 n = getdigits(&p);
5673 if (*p == 'm' && n > 0)
5674 {
5675 cterm_normal_fg_color = (n & 0xf) + 1;
5676 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5677 }
5678 }
5679}
5680
5681
5682/*
5683 * visual bell: flash the screen
5684 */
5685 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005686visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005687{
5688 COORD coordOrigin = {0, 0};
5689 WORD attrFlash = ~g_attrCurrent & 0xff;
5690
5691 DWORD dwDummy;
5692 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5693
5694 if (oldattrs == NULL)
5695 return;
5696 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5697 coordOrigin, &dwDummy);
5698 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5699 coordOrigin, &dwDummy);
5700
5701 Sleep(15); /* wait for 15 msec */
5702 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5703 coordOrigin, &dwDummy);
5704 vim_free(oldattrs);
5705}
5706
5707
5708/*
5709 * Make the cursor visible or invisible
5710 */
5711 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005712cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005713{
5714 s_cursor_visible = fVisible;
5715#ifdef MCH_CURSOR_SHAPE
5716 mch_update_cursor();
5717#endif
5718}
5719
5720
5721/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005722 * write `cbToWrite' bytes in `pchBuf' to the screen
5723 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005725 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005726write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005727 char_u *pchBuf,
5728 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729{
5730 COORD coord = g_coord;
5731 DWORD written;
5732
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005733#ifdef FEAT_MBYTE
5734 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5735 {
5736 static WCHAR *unicodebuf = NULL;
5737 static int unibuflen = 0;
5738 int length;
5739 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005740
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005741 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5742 if (unicodebuf == NULL || length > unibuflen)
5743 {
5744 vim_free(unicodebuf);
5745 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5746 unibuflen = length;
5747 }
5748 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5749 unicodebuf, unibuflen);
5750
5751 cells = mb_string2cells(pchBuf, cbToWrite);
5752 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5753 coord, &written);
5754 /* When writing fails or didn't write a single character, pretend one
5755 * character was written, otherwise we get stuck. */
5756 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5757 coord, &cchwritten) == 0
5758 || cchwritten == 0)
5759 cchwritten = 1;
5760
5761 if (cchwritten == length)
5762 {
5763 written = cbToWrite;
5764 g_coord.X += (SHORT)cells;
5765 }
5766 else
5767 {
5768 char_u *p = pchBuf;
5769 for (n = 0; n < cchwritten; n++)
5770 mb_cptr_adv(p);
5771 written = p - pchBuf;
5772 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5773 }
5774 }
5775 else
5776#endif
5777 {
5778 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5779 coord, &written);
5780 /* When writing fails or didn't write a single character, pretend one
5781 * character was written, otherwise we get stuck. */
5782 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5783 coord, &written) == 0
5784 || written == 0)
5785 written = 1;
5786
5787 g_coord.X += (SHORT) written;
5788 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789
5790 while (g_coord.X > g_srScrollRegion.Right)
5791 {
5792 g_coord.X -= (SHORT) Columns;
5793 if (g_coord.Y < g_srScrollRegion.Bottom)
5794 g_coord.Y++;
5795 }
5796
5797 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5798
5799 return written;
5800}
5801
5802
5803/*
5804 * mch_write(): write the output buffer to the screen, translating ESC
5805 * sequences into calls to console output routines.
5806 */
5807 void
5808mch_write(
5809 char_u *s,
5810 int len)
5811{
5812 s[len] = NUL;
5813
5814 if (!term_console)
5815 {
5816 write(1, s, (unsigned)len);
5817 return;
5818 }
5819
5820 /* translate ESC | sequences into faked bios calls */
5821 while (len--)
5822 {
5823 /* optimization: use one single write_chars for runs of text,
5824 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005825 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005826
5827 if (p_wd)
5828 {
5829 WaitForChar(p_wd);
5830 if (prefix != 0)
5831 prefix = 1;
5832 }
5833
5834 if (prefix != 0)
5835 {
5836 DWORD nWritten;
5837
5838 nWritten = write_chars(s, prefix);
5839#ifdef MCH_WRITE_DUMP
5840 if (fdDump)
5841 {
5842 fputc('>', fdDump);
5843 fwrite(s, sizeof(char_u), nWritten, fdDump);
5844 fputs("<\n", fdDump);
5845 }
5846#endif
5847 len -= (nWritten - 1);
5848 s += nWritten;
5849 }
5850 else if (s[0] == '\n')
5851 {
5852 /* \n, newline: go to the beginning of the next line or scroll */
5853 if (g_coord.Y == g_srScrollRegion.Bottom)
5854 {
5855 scroll(1);
5856 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5857 }
5858 else
5859 {
5860 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5861 }
5862#ifdef MCH_WRITE_DUMP
5863 if (fdDump)
5864 fputs("\\n\n", fdDump);
5865#endif
5866 s++;
5867 }
5868 else if (s[0] == '\r')
5869 {
5870 /* \r, carriage return: go to beginning of line */
5871 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5872#ifdef MCH_WRITE_DUMP
5873 if (fdDump)
5874 fputs("\\r\n", fdDump);
5875#endif
5876 s++;
5877 }
5878 else if (s[0] == '\b')
5879 {
5880 /* \b, backspace: move cursor one position left */
5881 if (g_coord.X > g_srScrollRegion.Left)
5882 g_coord.X--;
5883 else if (g_coord.Y > g_srScrollRegion.Top)
5884 {
5885 g_coord.X = g_srScrollRegion.Right;
5886 g_coord.Y--;
5887 }
5888 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5889#ifdef MCH_WRITE_DUMP
5890 if (fdDump)
5891 fputs("\\b\n", fdDump);
5892#endif
5893 s++;
5894 }
5895 else if (s[0] == '\a')
5896 {
5897 /* \a, bell */
5898 MessageBeep(0xFFFFFFFF);
5899#ifdef MCH_WRITE_DUMP
5900 if (fdDump)
5901 fputs("\\a\n", fdDump);
5902#endif
5903 s++;
5904 }
5905 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5906 {
5907#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005908 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005910 char_u *p;
5911 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912
5913 switch (s[2])
5914 {
5915 /* one or two numeric arguments, separated by ';' */
5916
5917 case '0': case '1': case '2': case '3': case '4':
5918 case '5': case '6': case '7': case '8': case '9':
5919 p = s + 2;
5920 arg1 = getdigits(&p); /* no check for length! */
5921 if (p > s + len)
5922 break;
5923
5924 if (*p == ';')
5925 {
5926 ++p;
5927 arg2 = getdigits(&p); /* no check for length! */
5928 if (p > s + len)
5929 break;
5930
5931 if (*p == 'H')
5932 gotoxy(arg2, arg1);
5933 else if (*p == 'r')
5934 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5935 }
5936 else if (*p == 'A')
5937 {
5938 /* move cursor up arg1 lines in same column */
5939 gotoxy(g_coord.X + 1,
5940 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5941 }
5942 else if (*p == 'C')
5943 {
5944 /* move cursor right arg1 columns in same line */
5945 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5946 g_coord.Y + 1);
5947 }
5948 else if (*p == 'H')
5949 {
5950 gotoxy(1, arg1);
5951 }
5952 else if (*p == 'L')
5953 {
5954 insert_lines(arg1);
5955 }
5956 else if (*p == 'm')
5957 {
5958 if (arg1 == 0)
5959 normvideo();
5960 else
5961 textattr((WORD) arg1);
5962 }
5963 else if (*p == 'f')
5964 {
5965 textcolor((WORD) arg1);
5966 }
5967 else if (*p == 'b')
5968 {
5969 textbackground((WORD) arg1);
5970 }
5971 else if (*p == 'M')
5972 {
5973 delete_lines(arg1);
5974 }
5975
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005976 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005977 s = p + 1;
5978 break;
5979
5980
5981 /* Three-character escape sequences */
5982
5983 case 'A':
5984 /* move cursor up one line in same column */
5985 gotoxy(g_coord.X + 1,
5986 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5987 goto got3;
5988
5989 case 'B':
5990 visual_bell();
5991 goto got3;
5992
5993 case 'C':
5994 /* move cursor right one column in same line */
5995 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5996 g_coord.Y + 1);
5997 goto got3;
5998
5999 case 'E':
6000 termcap_mode_end();
6001 goto got3;
6002
6003 case 'F':
6004 standout();
6005 goto got3;
6006
6007 case 'f':
6008 standend();
6009 goto got3;
6010
6011 case 'H':
6012 gotoxy(1, 1);
6013 goto got3;
6014
6015 case 'j':
6016 clear_to_end_of_display();
6017 goto got3;
6018
6019 case 'J':
6020 clear_screen();
6021 goto got3;
6022
6023 case 'K':
6024 clear_to_end_of_line();
6025 goto got3;
6026
6027 case 'L':
6028 insert_lines(1);
6029 goto got3;
6030
6031 case 'M':
6032 delete_lines(1);
6033 goto got3;
6034
6035 case 'S':
6036 termcap_mode_start();
6037 goto got3;
6038
6039 case 'V':
6040 cursor_visible(TRUE);
6041 goto got3;
6042
6043 case 'v':
6044 cursor_visible(FALSE);
6045 goto got3;
6046
6047 got3:
6048 s += 3;
6049 len -= 2;
6050 }
6051
6052#ifdef MCH_WRITE_DUMP
6053 if (fdDump)
6054 {
6055 fputs("ESC | ", fdDump);
6056 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6057 fputc('\n', fdDump);
6058 }
6059#endif
6060 }
6061 else
6062 {
6063 /* Write a single character */
6064 DWORD nWritten;
6065
6066 nWritten = write_chars(s, 1);
6067#ifdef MCH_WRITE_DUMP
6068 if (fdDump)
6069 {
6070 fputc('>', fdDump);
6071 fwrite(s, sizeof(char_u), nWritten, fdDump);
6072 fputs("<\n", fdDump);
6073 }
6074#endif
6075
6076 len -= (nWritten - 1);
6077 s += nWritten;
6078 }
6079 }
6080
6081#ifdef MCH_WRITE_DUMP
6082 if (fdDump)
6083 fflush(fdDump);
6084#endif
6085}
6086
6087#endif /* FEAT_GUI_W32 */
6088
6089
6090/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006091 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006093/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094 void
6095mch_delay(
6096 long msec,
6097 int ignoreinput)
6098{
6099#ifdef FEAT_GUI_W32
6100 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006101#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006103# ifdef FEAT_MZSCHEME
6104 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6105 {
6106 int towait = p_mzq;
6107
6108 /* if msec is large enough, wait by portions in p_mzq */
6109 while (msec > 0)
6110 {
6111 mzvim_check_threads();
6112 if (msec < towait)
6113 towait = msec;
6114 Sleep(towait);
6115 msec -= towait;
6116 }
6117 }
6118 else
6119# endif
6120 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121 else
6122 WaitForChar(msec);
6123#endif
6124}
6125
6126
6127/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006128 * This version of remove is not scared by a readonly (backup) file.
6129 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130 * Return 0 for success, -1 for failure.
6131 */
6132 int
6133mch_remove(char_u *name)
6134{
6135#ifdef FEAT_MBYTE
6136 WCHAR *wn = NULL;
6137 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006138#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139
Bram Moolenaar203258c2016-01-17 22:15:16 +01006140 /*
6141 * On Windows, deleting a directory's symbolic link is done by
6142 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6143 */
6144 if (mch_isdir(name) && mch_is_symbolic_link(name))
6145 return mch_rmdir(name);
6146
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006147 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6148
6149#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6151 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006152 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006153 if (wn != NULL)
6154 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155 n = DeleteFileW(wn) ? 0 : -1;
6156 vim_free(wn);
6157 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6158 return n;
6159 /* Retry with non-wide function (for Windows 98). */
6160 }
6161 }
6162#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006163 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164}
6165
6166
6167/*
6168 * check for an "interrupt signal": CTRL-break or CTRL-C
6169 */
6170 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006171mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172{
6173#ifndef FEAT_GUI_W32 /* never used */
6174 if (g_fCtrlCPressed || g_fCBrkPressed)
6175 {
6176 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6177 got_int = TRUE;
6178 }
6179#endif
6180}
6181
Bram Moolenaaree273972016-01-02 21:11:51 +01006182/* physical RAM to leave for the OS */
6183#define WINNT_RESERVE_BYTES (256*1024*1024)
6184#define WIN95_RESERVE_BYTES (8*1024*1024)
6185
6186/*
6187 * How much main memory in KiB that can be used by VIM.
6188 */
6189/*ARGSUSED*/
6190 long_u
6191mch_total_mem(int special)
6192{
6193 PlatformId();
6194#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6195 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6196 {
6197 MEMORYSTATUSEX ms;
6198
6199 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6200 * what fits in 32 bits. But it's not always available. */
6201 ms.dwLength = sizeof(MEMORYSTATUSEX);
6202 GlobalMemoryStatusEx(&ms);
6203 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6204 {
6205 /* Process address space fits in physical RAM, use all of it. */
6206 return (long_u)(ms.ullAvailVirtual / 1024);
6207 }
6208 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6209 {
6210 /* Catch old NT box or perverse hardware setup. */
6211 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6212 }
6213 /* Use physical RAM less reserve for OS + data. */
6214 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6215 }
6216 else
6217#endif
6218 {
6219 /* Pre-XP or 95 OS handling. */
6220 MEMORYSTATUS ms;
6221 long_u os_reserve_bytes;
6222
6223 ms.dwLength = sizeof(MEMORYSTATUS);
6224 GlobalMemoryStatus(&ms);
6225 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6226 {
6227 /* Process address space fits in physical RAM, use all of it. */
6228 return (long_u)(ms.dwAvailVirtual / 1024);
6229 }
6230 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6231 ? WINNT_RESERVE_BYTES
6232 : WIN95_RESERVE_BYTES;
6233 if (ms.dwTotalPhys <= os_reserve_bytes)
6234 {
6235 /* Catch old boxes or perverse hardware setup. */
6236 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6237 }
6238 /* Use physical RAM less reserve for OS + data. */
6239 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6240 }
6241}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243#ifdef FEAT_MBYTE
6244/*
6245 * Same code as below, but with wide functions and no comments.
6246 * Return 0 for success, non-zero for failure.
6247 */
6248 int
6249mch_wrename(WCHAR *wold, WCHAR *wnew)
6250{
6251 WCHAR *p;
6252 int i;
6253 WCHAR szTempFile[_MAX_PATH + 1];
6254 WCHAR szNewPath[_MAX_PATH + 1];
6255 HANDLE hf;
6256
6257 if (!mch_windows95())
6258 {
6259 p = wold;
6260 for (i = 0; wold[i] != NUL; ++i)
6261 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6262 && wold[i + 1] != 0)
6263 p = wold + i + 1;
6264 if ((int)(wold + i - p) < 8 || p[6] != '~')
6265 return (MoveFileW(wold, wnew) == 0);
6266 }
6267
6268 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6269 return -1;
6270 *p = NUL;
6271
6272 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6273 return -2;
6274
6275 if (!DeleteFileW(szTempFile))
6276 return -3;
6277
6278 if (!MoveFileW(wold, szTempFile))
6279 return -4;
6280
6281 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6282 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6283 return -5;
6284 if (!CloseHandle(hf))
6285 return -6;
6286
6287 if (!MoveFileW(szTempFile, wnew))
6288 {
6289 (void)MoveFileW(szTempFile, wold);
6290 return -7;
6291 }
6292
6293 DeleteFileW(szTempFile);
6294
6295 if (!DeleteFileW(wold))
6296 return -8;
6297
6298 return 0;
6299}
6300#endif
6301
6302
6303/*
6304 * mch_rename() works around a bug in rename (aka MoveFile) in
6305 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6306 * file whose short file name is "FOO.BAR" (its long file name will
6307 * be correct: "foo.bar~"). Because a file can be accessed by
6308 * either its SFN or its LFN, "foo.bar" has effectively been
6309 * renamed to "foo.bar", which is not at all what was wanted. This
6310 * seems to happen only when renaming files with three-character
6311 * extensions by appending a suffix that does not include ".".
6312 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6313 *
6314 * There is another problem, which isn't really a bug but isn't right either:
6315 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6316 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6317 * service pack 6. Doesn't seem to happen on Windows 98.
6318 *
6319 * Like rename(), returns 0 upon success, non-zero upon failure.
6320 * Should probably set errno appropriately when errors occur.
6321 */
6322 int
6323mch_rename(
6324 const char *pszOldFile,
6325 const char *pszNewFile)
6326{
6327 char szTempFile[_MAX_PATH+1];
6328 char szNewPath[_MAX_PATH+1];
6329 char *pszFilePart;
6330 HANDLE hf;
6331#ifdef FEAT_MBYTE
6332 WCHAR *wold = NULL;
6333 WCHAR *wnew = NULL;
6334 int retval = -1;
6335
6336 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6337 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006338 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6339 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340 if (wold != NULL && wnew != NULL)
6341 retval = mch_wrename(wold, wnew);
6342 vim_free(wold);
6343 vim_free(wnew);
6344 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6345 return retval;
6346 /* Retry with non-wide function (for Windows 98). */
6347 }
6348#endif
6349
6350 /*
6351 * No need to play tricks if not running Windows 95, unless the file name
6352 * contains a "~" as the seventh character.
6353 */
6354 if (!mch_windows95())
6355 {
6356 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6357 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6358 return rename(pszOldFile, pszNewFile);
6359 }
6360
6361 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6362 * a directory, no error is returned and pszFilePart will be NULL. */
6363 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6364 || pszFilePart == NULL)
6365 return -1;
6366 *pszFilePart = NUL;
6367
6368 /* Get (and create) a unique temporary file name in directory of new file */
6369 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6370 return -2;
6371
6372 /* blow the temp file away */
6373 if (!DeleteFile(szTempFile))
6374 return -3;
6375
6376 /* rename old file to the temp file */
6377 if (!MoveFile(pszOldFile, szTempFile))
6378 return -4;
6379
6380 /* now create an empty file called pszOldFile; this prevents the operating
6381 * system using pszOldFile as an alias (SFN) if we're renaming within the
6382 * same directory. For example, we're editing a file called
6383 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6384 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6385 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006386 * cause all sorts of problems later in buf_write(). So, we create an
6387 * empty file called filena~1.txt and the system will have to find some
6388 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389 */
6390 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6391 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6392 return -5;
6393 if (!CloseHandle(hf))
6394 return -6;
6395
6396 /* rename the temp file to the new file */
6397 if (!MoveFile(szTempFile, pszNewFile))
6398 {
6399 /* Renaming failed. Rename the file back to its old name, so that it
6400 * looks like nothing happened. */
6401 (void)MoveFile(szTempFile, pszOldFile);
6402
6403 return -7;
6404 }
6405
6406 /* Seems to be left around on Novell filesystems */
6407 DeleteFile(szTempFile);
6408
6409 /* finally, remove the empty old file */
6410 if (!DeleteFile(pszOldFile))
6411 return -8;
6412
6413 return 0; /* success */
6414}
6415
6416/*
6417 * Get the default shell for the current hardware platform
6418 */
6419 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006420default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421{
6422 char* psz = NULL;
6423
6424 PlatformId();
6425
6426 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6427 psz = "cmd.exe";
6428 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6429 psz = "command.com";
6430
6431 return psz;
6432}
6433
6434/*
6435 * mch_access() extends access() to do more detailed check on network drives.
6436 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6437 */
6438 int
6439mch_access(char *n, int p)
6440{
6441 HANDLE hFile;
6442 DWORD am;
6443 int retval = -1; /* default: fail */
6444#ifdef FEAT_MBYTE
6445 WCHAR *wn = NULL;
6446
6447 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006448 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006449#endif
6450
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006451 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006452 {
6453 char TempName[_MAX_PATH + 16] = "";
6454#ifdef FEAT_MBYTE
6455 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6456#endif
6457
6458 if (p & R_OK)
6459 {
6460 /* Read check is performed by seeing if we can do a find file on
6461 * the directory for any file. */
6462#ifdef FEAT_MBYTE
6463 if (wn != NULL)
6464 {
6465 int i;
6466 WIN32_FIND_DATAW d;
6467
6468 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6469 TempNameW[i] = wn[i];
6470 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6471 TempNameW[i++] = '\\';
6472 TempNameW[i++] = '*';
6473 TempNameW[i++] = 0;
6474
6475 hFile = FindFirstFileW(TempNameW, &d);
6476 if (hFile == INVALID_HANDLE_VALUE)
6477 {
6478 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6479 goto getout;
6480
6481 /* Retry with non-wide function (for Windows 98). */
6482 vim_free(wn);
6483 wn = NULL;
6484 }
6485 else
6486 (void)FindClose(hFile);
6487 }
6488 if (wn == NULL)
6489#endif
6490 {
6491 char *pch;
6492 WIN32_FIND_DATA d;
6493
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006494 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006495 pch = TempName + STRLEN(TempName) - 1;
6496 if (*pch != '\\' && *pch != '/')
6497 *++pch = '\\';
6498 *++pch = '*';
6499 *++pch = NUL;
6500
6501 hFile = FindFirstFile(TempName, &d);
6502 if (hFile == INVALID_HANDLE_VALUE)
6503 goto getout;
6504 (void)FindClose(hFile);
6505 }
6506 }
6507
6508 if (p & W_OK)
6509 {
6510 /* Trying to create a temporary file in the directory should catch
6511 * directories on read-only network shares. However, in
6512 * directories whose ACL allows writes but denies deletes will end
6513 * up keeping the temporary file :-(. */
6514#ifdef FEAT_MBYTE
6515 if (wn != NULL)
6516 {
6517 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6518 {
6519 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6520 goto getout;
6521
6522 /* Retry with non-wide function (for Windows 98). */
6523 vim_free(wn);
6524 wn = NULL;
6525 }
6526 else
6527 DeleteFileW(TempNameW);
6528 }
6529 if (wn == NULL)
6530#endif
6531 {
6532 if (!GetTempFileName(n, "VIM", 0, TempName))
6533 goto getout;
6534 mch_remove((char_u *)TempName);
6535 }
6536 }
6537 }
6538 else
6539 {
6540 /* Trying to open the file for the required access does ACL, read-only
6541 * network share, and file attribute checks. */
6542 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6543 | ((p & R_OK) ? GENERIC_READ : 0);
6544#ifdef FEAT_MBYTE
6545 if (wn != NULL)
6546 {
6547 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6548 if (hFile == INVALID_HANDLE_VALUE
6549 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6550 {
6551 /* Retry with non-wide function (for Windows 98). */
6552 vim_free(wn);
6553 wn = NULL;
6554 }
6555 }
6556 if (wn == NULL)
6557#endif
6558 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6559 if (hFile == INVALID_HANDLE_VALUE)
6560 goto getout;
6561 CloseHandle(hFile);
6562 }
6563
6564 retval = 0; /* success */
6565getout:
6566#ifdef FEAT_MBYTE
6567 vim_free(wn);
6568#endif
6569 return retval;
6570}
6571
6572#if defined(FEAT_MBYTE) || defined(PROTO)
6573/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006574 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575 */
6576 int
6577mch_open(char *name, int flags, int mode)
6578{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006579 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6580# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581 WCHAR *wn;
6582 int f;
6583
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006584 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006586 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587 if (wn != NULL)
6588 {
6589 f = _wopen(wn, flags, mode);
6590 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006591 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592 return f;
6593 /* Retry with non-wide function (for Windows 98). Can't use
6594 * GetLastError() here and it's unclear what errno gets set to if
6595 * the _wopen() fails for missing wide functions. */
6596 }
6597 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006598# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006600 /* open() can open a file which name is longer than _MAX_PATH bytes
6601 * and shorter than _MAX_PATH characters successfully, but sometimes it
6602 * causes unexpected error in another part. We make it an error explicitly
6603 * here. */
6604 if (strlen(name) >= _MAX_PATH)
6605 return -1;
6606
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607 return open(name, flags, mode);
6608}
6609
6610/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006611 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612 */
6613 FILE *
6614mch_fopen(char *name, char *mode)
6615{
6616 WCHAR *wn, *wm;
6617 FILE *f = NULL;
6618
6619 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6620# ifdef __BORLANDC__
6621 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6622 && g_PlatformId == VER_PLATFORM_WIN32_NT
6623# endif
6624 )
6625 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006626# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006627 /* Work around an annoying assertion in the Microsoft debug CRT
6628 * when mode's text/binary setting doesn't match _get_fmode(). */
6629 char newMode = mode[strlen(mode) - 1];
6630 int oldMode = 0;
6631
6632 _get_fmode(&oldMode);
6633 if (newMode == 't')
6634 _set_fmode(_O_TEXT);
6635 else if (newMode == 'b')
6636 _set_fmode(_O_BINARY);
6637# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006638 wn = enc_to_utf16((char_u *)name, NULL);
6639 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006640 if (wn != NULL && wm != NULL)
6641 f = _wfopen(wn, wm);
6642 vim_free(wn);
6643 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006644
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006645# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006646 _set_fmode(oldMode);
6647# endif
6648
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006649 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650 return f;
6651 /* Retry with non-wide function (for Windows 98). Can't use
6652 * GetLastError() here and it's unclear what errno gets set to if
6653 * the _wfopen() fails for missing wide functions. */
6654 }
6655
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006656 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6657 * and shorter than _MAX_PATH characters successfully, but sometimes it
6658 * causes unexpected error in another part. We make it an error explicitly
6659 * here. */
6660 if (strlen(name) >= _MAX_PATH)
6661 return NULL;
6662
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 return fopen(name, mode);
6664}
6665#endif
6666
6667#ifdef FEAT_MBYTE
6668/*
6669 * SUB STREAM (aka info stream) handling:
6670 *
6671 * NTFS can have sub streams for each file. Normal contents of file is
6672 * stored in the main stream, and extra contents (author information and
6673 * title and so on) can be stored in sub stream. After Windows 2000, user
6674 * can access and store those informations in sub streams via explorer's
6675 * property menuitem in right click menu. Those informations in sub streams
6676 * were lost when copying only the main stream. So we have to copy sub
6677 * streams.
6678 *
6679 * Incomplete explanation:
6680 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6681 * More useful info and an example:
6682 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6683 */
6684
6685/*
6686 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6687 * and write to stream "substream" of file "to".
6688 * Errors are ignored.
6689 */
6690 static void
6691copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6692{
6693 HANDLE hTo;
6694 WCHAR *to_name;
6695
6696 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6697 wcscpy(to_name, to);
6698 wcscat(to_name, substream);
6699
6700 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6701 FILE_ATTRIBUTE_NORMAL, NULL);
6702 if (hTo != INVALID_HANDLE_VALUE)
6703 {
6704 long done;
6705 DWORD todo;
6706 DWORD readcnt, written;
6707 char buf[4096];
6708
6709 /* Copy block of bytes at a time. Abort when something goes wrong. */
6710 for (done = 0; done < len; done += written)
6711 {
6712 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006713 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6714 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6716 FALSE, FALSE, context)
6717 || readcnt != todo
6718 || !WriteFile(hTo, buf, todo, &written, NULL)
6719 || written != todo)
6720 break;
6721 }
6722 CloseHandle(hTo);
6723 }
6724
6725 free(to_name);
6726}
6727
6728/*
6729 * Copy info streams from file "from" to file "to".
6730 */
6731 static void
6732copy_infostreams(char_u *from, char_u *to)
6733{
6734 WCHAR *fromw;
6735 WCHAR *tow;
6736 HANDLE sh;
6737 WIN32_STREAM_ID sid;
6738 int headersize;
6739 WCHAR streamname[_MAX_PATH];
6740 DWORD readcount;
6741 void *context = NULL;
6742 DWORD lo, hi;
6743 int len;
6744
6745 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006746 fromw = enc_to_utf16(from, NULL);
6747 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748 if (fromw != NULL && tow != NULL)
6749 {
6750 /* Open the file for reading. */
6751 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6752 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6753 if (sh != INVALID_HANDLE_VALUE)
6754 {
6755 /* Use BackupRead() to find the info streams. Repeat until we
6756 * have done them all.*/
6757 for (;;)
6758 {
6759 /* Get the header to find the length of the stream name. If
6760 * the "readcount" is zero we have done all info streams. */
6761 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006762 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006763 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6764 &readcount, FALSE, FALSE, &context)
6765 || readcount == 0)
6766 break;
6767
6768 /* We only deal with streams that have a name. The normal
6769 * file data appears to be without a name, even though docs
6770 * suggest it is called "::$DATA". */
6771 if (sid.dwStreamNameSize > 0)
6772 {
6773 /* Read the stream name. */
6774 if (!BackupRead(sh, (LPBYTE)streamname,
6775 sid.dwStreamNameSize,
6776 &readcount, FALSE, FALSE, &context))
6777 break;
6778
6779 /* Copy an info stream with a name ":anything:$DATA".
6780 * Skip "::$DATA", it has no stream name (examples suggest
6781 * it might be used for the normal file contents).
6782 * Note that BackupRead() counts bytes, but the name is in
6783 * wide characters. */
6784 len = readcount / sizeof(WCHAR);
6785 streamname[len] = 0;
6786 if (len > 7 && wcsicmp(streamname + len - 6,
6787 L":$DATA") == 0)
6788 {
6789 streamname[len - 6] = 0;
6790 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006791 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792 }
6793 }
6794
6795 /* Advance to the next stream. We might try seeking too far,
6796 * but BackupSeek() doesn't skip over stream borders, thus
6797 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006798 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799 &lo, &hi, &context);
6800 }
6801
6802 /* Clear the context. */
6803 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6804
6805 CloseHandle(sh);
6806 }
6807 }
6808 vim_free(fromw);
6809 vim_free(tow);
6810}
6811#endif
6812
6813/*
6814 * Copy file attributes from file "from" to file "to".
6815 * For Windows NT and later we copy info streams.
6816 * Always returns zero, errors are ignored.
6817 */
6818 int
6819mch_copy_file_attribute(char_u *from, char_u *to)
6820{
6821#ifdef FEAT_MBYTE
6822 /* File streams only work on Windows NT and later. */
6823 PlatformId();
6824 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6825 copy_infostreams(from, to);
6826#endif
6827 return 0;
6828}
6829
6830#if defined(MYRESETSTKOFLW) || defined(PROTO)
6831/*
6832 * Recreate a destroyed stack guard page in win32.
6833 * Written by Benjamin Peterson.
6834 */
6835
6836/* These magic numbers are from the MS header files */
6837#define MIN_STACK_WIN9X 17
6838#define MIN_STACK_WINNT 2
6839
6840/*
6841 * This function does the same thing as _resetstkoflw(), which is only
6842 * available in DevStudio .net and later.
6843 * Returns 0 for failure, 1 for success.
6844 */
6845 int
6846myresetstkoflw(void)
6847{
6848 BYTE *pStackPtr;
6849 BYTE *pGuardPage;
6850 BYTE *pStackBase;
6851 BYTE *pLowestPossiblePage;
6852 MEMORY_BASIC_INFORMATION mbi;
6853 SYSTEM_INFO si;
6854 DWORD nPageSize;
6855 DWORD dummy;
6856
6857 /* This code will not work on win32s. */
6858 PlatformId();
6859 if (g_PlatformId == VER_PLATFORM_WIN32s)
6860 return 0;
6861
6862 /* We need to know the system page size. */
6863 GetSystemInfo(&si);
6864 nPageSize = si.dwPageSize;
6865
6866 /* ...and the current stack pointer */
6867 pStackPtr = (BYTE*)_alloca(1);
6868
6869 /* ...and the base of the stack. */
6870 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6871 return 0;
6872 pStackBase = (BYTE*)mbi.AllocationBase;
6873
6874 /* ...and the page thats min_stack_req pages away from stack base; this is
6875 * the lowest page we could use. */
6876 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6877 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6878
6879 /* On Win95, we want the next page down from the end of the stack. */
6880 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6881 {
6882 /* Find the page that's only 1 page down from the page that the stack
6883 * ptr is in. */
6884 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6885 / (DWORD)nPageSize) - 1));
6886 if (pGuardPage < pLowestPossiblePage)
6887 return 0;
6888
6889 /* Apply the noaccess attribute to the page -- there's no guard
6890 * attribute in win95-type OSes. */
6891 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6892 return 0;
6893 }
6894 else
6895 {
6896 /* On NT, however, we want the first committed page in the stack Start
6897 * at the stack base and move forward through memory until we find a
6898 * committed block. */
6899 BYTE *pBlock = pStackBase;
6900
Bram Moolenaara466c992005-07-09 21:03:22 +00006901 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902 {
6903 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6904 return 0;
6905
6906 pBlock += mbi.RegionSize;
6907
6908 if (mbi.State & MEM_COMMIT)
6909 break;
6910 }
6911
6912 /* mbi now describes the first committed block in the stack. */
6913 if (mbi.Protect & PAGE_GUARD)
6914 return 1;
6915
6916 /* decide where the guard page should start */
6917 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6918 pGuardPage = pLowestPossiblePage;
6919 else
6920 pGuardPage = (BYTE*)mbi.BaseAddress;
6921
6922 /* allocate the guard page */
6923 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6924 return 0;
6925
6926 /* apply the guard attribute to the page */
6927 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6928 &dummy))
6929 return 0;
6930 }
6931
6932 return 1;
6933}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006934#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006936
6937#if defined(FEAT_MBYTE) || defined(PROTO)
6938/*
6939 * The command line arguments in UCS2
6940 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006941static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006942static LPWSTR *ArglistW = NULL;
6943static int global_argc = 0;
6944static char **global_argv;
6945
6946static int used_file_argc = 0; /* last argument in global_argv[] used
6947 for the argument list. */
6948static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6949 command line arguments added to
6950 the argument list */
6951static int used_file_count = 0; /* nr of entries in used_file_indexes */
6952static int used_file_literal = FALSE; /* take file names literally */
6953static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006954static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006955static int used_alist_count = 0;
6956
6957
6958/*
6959 * Get the command line arguments. Unicode version.
6960 * Returns argc. Zero when something fails.
6961 */
6962 int
6963get_cmd_argsW(char ***argvp)
6964{
6965 char **argv = NULL;
6966 int argc = 0;
6967 int i;
6968
Bram Moolenaar14993322014-09-09 12:25:33 +02006969 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006970 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6971 if (ArglistW != NULL)
6972 {
6973 argv = malloc((nArgsW + 1) * sizeof(char *));
6974 if (argv != NULL)
6975 {
6976 argc = nArgsW;
6977 argv[argc] = NULL;
6978 for (i = 0; i < argc; ++i)
6979 {
6980 int len;
6981
6982 /* Convert each Unicode argument to the current codepage. */
6983 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006984 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006985 (LPSTR *)&argv[i], &len, 0, 0);
6986 if (argv[i] == NULL)
6987 {
6988 /* Out of memory, clear everything. */
6989 while (i > 0)
6990 free(argv[--i]);
6991 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006992 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006993 argc = 0;
6994 }
6995 }
6996 }
6997 }
6998
6999 global_argc = argc;
7000 global_argv = argv;
7001 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007002 {
7003 if (used_file_indexes != NULL)
7004 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007005 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007006 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007007
7008 if (argvp != NULL)
7009 *argvp = argv;
7010 return argc;
7011}
7012
7013 void
7014free_cmd_argsW(void)
7015{
7016 if (ArglistW != NULL)
7017 {
7018 GlobalFree(ArglistW);
7019 ArglistW = NULL;
7020 }
7021}
7022
7023/*
7024 * Remember "name" is an argument that was added to the argument list.
7025 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7026 * is called.
7027 */
7028 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007029used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007030{
7031 int i;
7032
7033 if (used_file_indexes == NULL)
7034 return;
7035 for (i = used_file_argc + 1; i < global_argc; ++i)
7036 if (STRCMP(global_argv[i], name) == 0)
7037 {
7038 used_file_argc = i;
7039 used_file_indexes[used_file_count++] = i;
7040 break;
7041 }
7042 used_file_literal = literal;
7043 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007044 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007045}
7046
7047/*
7048 * Remember the length of the argument list as it was. If it changes then we
7049 * leave it alone when 'encoding' is set.
7050 */
7051 void
7052set_alist_count(void)
7053{
7054 used_alist_count = GARGCOUNT;
7055}
7056
7057/*
7058 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7059 * has been changed while starting up. Use the UCS-2 command line arguments
7060 * and convert them to 'encoding'.
7061 */
7062 void
7063fix_arg_enc(void)
7064{
7065 int i;
7066 int idx;
7067 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007068 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007069
7070 /* Safety checks:
7071 * - if argument count differs between the wide and non-wide argument
7072 * list, something must be wrong.
7073 * - the file name arguments must have been located.
7074 * - the length of the argument list wasn't changed by the user.
7075 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007076 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007077 || ArglistW == NULL
7078 || used_file_indexes == NULL
7079 || used_file_count == 0
7080 || used_alist_count != GARGCOUNT)
7081 return;
7082
Bram Moolenaar86b68352004-12-27 21:59:20 +00007083 /* Remember the buffer numbers for the arguments. */
7084 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7085 if (fnum_list == NULL)
7086 return; /* out of memory */
7087 for (i = 0; i < GARGCOUNT; ++i)
7088 fnum_list[i] = GARGLIST[i].ae_fnum;
7089
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007090 /* Clear the argument list. Make room for the new arguments. */
7091 alist_clear(&global_alist);
7092 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007093 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007094
7095 for (i = 0; i < used_file_count; ++i)
7096 {
7097 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007098 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007099 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007100 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007101#ifdef FEAT_DIFF
7102 /* When using diff mode may need to concatenate file name to
7103 * directory name. Just like it's done in main(). */
7104 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7105 && !mch_isdir(alist_name(&GARGLIST[0])))
7106 {
7107 char_u *r;
7108
7109 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7110 if (r != NULL)
7111 {
7112 vim_free(str);
7113 str = r;
7114 }
7115 }
7116#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007117 /* Re-use the old buffer by renaming it. When not using literal
7118 * names it's done by alist_expand() below. */
7119 if (used_file_literal)
7120 buf_set_name(fnum_list[i], str);
7121
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007122 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007123 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007124 }
7125
7126 if (!used_file_literal)
7127 {
7128 /* Now expand wildcards in the arguments. */
7129 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7130 * filename characters but are excluded from 'isfname' to make
7131 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7132 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007133 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007134 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7135 }
7136
7137 /* If wildcard expansion failed, we are editing the first file of the
7138 * arglist and there is no file name: Edit the first argument now. */
7139 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7140 {
7141 do_cmdline_cmd((char_u *)":rewind");
7142 if (GARGCOUNT == 1 && used_file_full_path)
7143 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7144 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007145
7146 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007147}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007148#endif