blob: 159905d0b0d0564f4fc2d9fc9f3f5503d100b098 [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 Moolenaar40b1b542016-04-20 20:18:23 +02001449 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450
1451 if (msec > 0)
1452 /* Wait until the specified time has elapsed. */
1453 dwEndTime = GetTickCount() + msec;
1454 else if (msec < 0)
1455 /* Wait forever. */
1456 dwEndTime = INFINITE;
1457
1458 /* We need to loop until the end of the time period, because
1459 * we might get multiple unusable mouse events in that time.
1460 */
1461 for (;;)
1462 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001463#ifdef MESSAGE_QUEUE
1464 parse_queued_messages();
1465#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001466#ifdef FEAT_MZSCHEME
1467 mzvim_check_threads();
1468#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469#ifdef FEAT_CLIENTSERVER
1470 serverProcessPendingMessages();
1471#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001472
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473 if (0
1474#ifdef FEAT_MOUSE
1475 || g_nMouseClick != -1
1476#endif
1477#ifdef FEAT_CLIENTSERVER
1478 || input_available()
1479#endif
1480 )
1481 return TRUE;
1482
1483 if (msec > 0)
1484 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001485 /* If the specified wait time has passed, return. Beware that
1486 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001487 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001488 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 break;
1490 }
1491 if (msec != 0)
1492 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001493 DWORD dwWaitTime = dwEndTime - dwNow;
1494
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001495#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar9186a272016-02-23 19:34:01 +01001496 /* Check channel while waiting input. */
1497 if (dwWaitTime > 100)
1498 dwWaitTime = 100;
1499#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001500#ifdef FEAT_MZSCHEME
1501 if (mzthreads_allowed() && p_mzq > 0
1502 && (msec < 0 || (long)dwWaitTime > p_mzq))
1503 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1504#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001505#ifdef FEAT_TIMERS
1506 {
1507 long due_time;
1508
1509 /* When waiting very briefly don't trigger timers. */
1510 if (dwWaitTime > 10)
1511 {
1512 /* Trigger timers and then get the time in msec until the
1513 * next one is due. Wait up to that time. */
1514 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001515 if (typebuf.tb_change_cnt != tb_change_cnt)
1516 {
1517 /* timer may have used feedkeys() */
1518 return FALSE;
1519 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001520 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1521 dwWaitTime = due_time;
1522 }
1523 }
1524#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525#ifdef FEAT_CLIENTSERVER
1526 /* Wait for either an event on the console input or a message in
1527 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001528 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001529 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001531 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532#endif
1533 continue;
1534 }
1535
1536 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001537 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538
1539#ifdef FEAT_MBYTE_IME
1540 if (State & CMDLINE && msg_row == Rows - 1)
1541 {
1542 CONSOLE_SCREEN_BUFFER_INFO csbi;
1543
1544 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1545 {
1546 if (csbi.dwCursorPosition.Y != msg_row)
1547 {
1548 /* The screen is now messed up, must redraw the
1549 * command line and later all the windows. */
1550 redraw_all_later(CLEAR);
1551 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1552 redrawcmd();
1553 }
1554 }
1555 }
1556#endif
1557
1558 if (cRecords > 0)
1559 {
1560 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1561 {
1562#ifdef FEAT_MBYTE_IME
1563 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1564 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001565 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001566 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1567 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001568 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569 continue;
1570 }
1571#endif
1572 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1573 NULL, FALSE))
1574 return TRUE;
1575 }
1576
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001577 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578
1579 if (ir.EventType == FOCUS_EVENT)
1580 handle_focus_event(ir);
1581 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1582 shell_resized();
1583#ifdef FEAT_MOUSE
1584 else if (ir.EventType == MOUSE_EVENT
1585 && decode_mouse_event(&ir.Event.MouseEvent))
1586 return TRUE;
1587#endif
1588 }
1589 else if (msec == 0)
1590 break;
1591 }
1592
1593#ifdef FEAT_CLIENTSERVER
1594 /* Something might have been received while we were waiting. */
1595 if (input_available())
1596 return TRUE;
1597#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001598
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 return FALSE;
1600}
1601
1602#ifndef FEAT_GUI_MSWIN
1603/*
1604 * return non-zero if a character is available
1605 */
1606 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001607mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608{
1609 return WaitForChar(0L);
1610}
1611#endif
1612
1613/*
1614 * Create the console input. Used when reading stdin doesn't work.
1615 */
1616 static void
1617create_conin(void)
1618{
1619 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1620 FILE_SHARE_READ|FILE_SHARE_WRITE,
1621 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001622 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623 did_create_conin = TRUE;
1624}
1625
1626/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001627 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001629 static WCHAR
1630tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001631{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001632 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633
1634 for (;;)
1635 {
1636 INPUT_RECORD ir;
1637 DWORD cRecords = 0;
1638
1639#ifdef FEAT_CLIENTSERVER
1640 (void)WaitForChar(-1L);
1641 if (input_available())
1642 return 0;
1643# ifdef FEAT_MOUSE
1644 if (g_nMouseClick != -1)
1645 return 0;
1646# endif
1647#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001648 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 {
1650 if (did_create_conin)
1651 read_error_exit();
1652 create_conin();
1653 continue;
1654 }
1655
1656 if (ir.EventType == KEY_EVENT)
1657 {
1658 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1659 pmodifiers, TRUE))
1660 return ch;
1661 }
1662 else if (ir.EventType == FOCUS_EVENT)
1663 handle_focus_event(ir);
1664 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1665 shell_resized();
1666#ifdef FEAT_MOUSE
1667 else if (ir.EventType == MOUSE_EVENT)
1668 {
1669 if (decode_mouse_event(&ir.Event.MouseEvent))
1670 return 0;
1671 }
1672#endif
1673 }
1674}
1675#endif /* !FEAT_GUI_W32 */
1676
1677
1678/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001679 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680 * Get one or more characters from the keyboard or the mouse.
1681 * If time == 0, do not wait for characters.
1682 * If time == n, wait a short time for characters.
1683 * If time == -1, wait forever for characters.
1684 * Returns the number of characters read into buf.
1685 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001686/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687 int
1688mch_inchar(
1689 char_u *buf,
1690 int maxlen,
1691 long time,
1692 int tb_change_cnt)
1693{
1694#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1695
1696 int len;
1697 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698#define TYPEAHEADLEN 20
1699 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1700 static int typeaheadlen = 0;
1701
1702 /* First use any typeahead that was kept because "buf" was too small. */
1703 if (typeaheadlen > 0)
1704 goto theend;
1705
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 if (time >= 0)
1707 {
1708 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 }
1711 else /* time == -1, wait forever */
1712 {
1713 mch_set_winsize_now(); /* Allow winsize changes from now on */
1714
Bram Moolenaar3918c952005-03-15 22:34:55 +00001715 /*
1716 * If there is no character available within 2 seconds (default)
1717 * write the autoscript file to disk. Or cause the CursorHold event
1718 * to be triggered.
1719 */
1720 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 {
1722#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001723 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001725 buf[0] = K_SPECIAL;
1726 buf[1] = KS_EXTRA;
1727 buf[2] = (int)KE_CURSORHOLD;
1728 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 }
1730#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001731 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732 }
1733 }
1734
1735 /*
1736 * Try to read as many characters as there are, until the buffer is full.
1737 */
1738
1739 /* we will get at least one key. Get more if they are available. */
1740 g_fCBrkPressed = FALSE;
1741
1742#ifdef MCH_WRITE_DUMP
1743 if (fdDump)
1744 fputc('[', fdDump);
1745#endif
1746
1747 /* Keep looping until there is something in the typeahead buffer and more
1748 * to get and still room in the buffer (up to two bytes for a char and
1749 * three bytes for a modifier). */
1750 while ((typeaheadlen == 0 || WaitForChar(0L))
1751 && typeaheadlen + 5 <= TYPEAHEADLEN)
1752 {
1753 if (typebuf_changed(tb_change_cnt))
1754 {
1755 /* "buf" may be invalid now if a client put something in the
1756 * typeahead buffer and "buf" is in the typeahead buffer. */
1757 typeaheadlen = 0;
1758 break;
1759 }
1760#ifdef FEAT_MOUSE
1761 if (g_nMouseClick != -1)
1762 {
1763# ifdef MCH_WRITE_DUMP
1764 if (fdDump)
1765 fprintf(fdDump, "{%02x @ %d, %d}",
1766 g_nMouseClick, g_xMouse, g_yMouse);
1767# endif
1768 typeahead[typeaheadlen++] = ESC + 128;
1769 typeahead[typeaheadlen++] = 'M';
1770 typeahead[typeaheadlen++] = g_nMouseClick;
1771 typeahead[typeaheadlen++] = g_xMouse + '!';
1772 typeahead[typeaheadlen++] = g_yMouse + '!';
1773 g_nMouseClick = -1;
1774 }
1775 else
1776#endif
1777 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001778 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779 int modifiers = 0;
1780
1781 c = tgetch(&modifiers, &ch2);
1782
1783 if (typebuf_changed(tb_change_cnt))
1784 {
1785 /* "buf" may be invalid now if a client put something in the
1786 * typeahead buffer and "buf" is in the typeahead buffer. */
1787 typeaheadlen = 0;
1788 break;
1789 }
1790
1791 if (c == Ctrl_C && ctrl_c_interrupts)
1792 {
1793#if defined(FEAT_CLIENTSERVER)
1794 trash_input_buf();
1795#endif
1796 got_int = TRUE;
1797 }
1798
1799#ifdef FEAT_MOUSE
1800 if (g_nMouseClick == -1)
1801#endif
1802 {
1803 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001804 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001806#ifdef FEAT_MBYTE
1807 if (ch2 == NUL)
1808 {
1809 int i;
1810 char_u *p;
1811 WCHAR ch[2];
1812
1813 ch[0] = c;
1814 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1815 {
1816 ch[1] = tgetch(&modifiers, &ch2);
1817 n++;
1818 }
1819 p = utf16_to_enc(ch, &n);
1820 if (p != NULL)
1821 {
1822 for (i = 0; i < n; i++)
1823 typeahead[typeaheadlen + i] = p[i];
1824 vim_free(p);
1825 }
1826 }
1827 else
1828#endif
1829 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830 if (ch2 != NUL)
1831 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001832 typeahead[typeaheadlen + n] = 3;
1833 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001834 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836
Bram Moolenaar45500912014-07-09 20:51:07 +02001837 if (conv)
1838 {
1839 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001840
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001841 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001842 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001843 char_u *e = typeahead + TYPEAHEADLEN;
1844
1845 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001846 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001847 if (*p == K_NUL)
1848 {
1849 ++p;
1850 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1851 *p = 3;
1852 ++n;
1853 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001854 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001855 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001856 }
1857 }
1858
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859 /* Use the ALT key to set the 8th bit of the character
1860 * when it's one byte, the 8th bit isn't set yet and not
1861 * using a double-byte encoding (would become a lead
1862 * byte). */
1863 if ((modifiers & MOD_MASK_ALT)
1864 && n == 1
1865 && (typeahead[typeaheadlen] & 0x80) == 0
1866#ifdef FEAT_MBYTE
1867 && !enc_dbcs
1868#endif
1869 )
1870 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001871#ifdef FEAT_MBYTE
1872 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1873 typeahead + typeaheadlen);
1874#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001876#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877 modifiers &= ~MOD_MASK_ALT;
1878 }
1879
1880 if (modifiers != 0)
1881 {
1882 /* Prepend modifiers to the character. */
1883 mch_memmove(typeahead + typeaheadlen + 3,
1884 typeahead + typeaheadlen, n);
1885 typeahead[typeaheadlen++] = K_SPECIAL;
1886 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1887 typeahead[typeaheadlen++] = modifiers;
1888 }
1889
1890 typeaheadlen += n;
1891
1892#ifdef MCH_WRITE_DUMP
1893 if (fdDump)
1894 fputc(c, fdDump);
1895#endif
1896 }
1897 }
1898 }
1899
1900#ifdef MCH_WRITE_DUMP
1901 if (fdDump)
1902 {
1903 fputs("]\n", fdDump);
1904 fflush(fdDump);
1905 }
1906#endif
1907
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908theend:
1909 /* Move typeahead to "buf", as much as fits. */
1910 len = 0;
1911 while (len < maxlen && typeaheadlen > 0)
1912 {
1913 buf[len++] = typeahead[0];
1914 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1915 }
1916 return len;
1917
1918#else /* FEAT_GUI_W32 */
1919 return 0;
1920#endif /* FEAT_GUI_W32 */
1921}
1922
Bram Moolenaar82881492012-11-20 16:53:39 +01001923#ifndef PROTO
1924# ifndef __MINGW32__
1925# include <shellapi.h> /* required for FindExecutable() */
1926# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927#endif
1928
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001929/*
1930 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001931 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001932 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001934executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001936 char *dum;
1937 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001938 char *curpath, *newpath;
1939 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001941#ifdef FEAT_MBYTE
1942 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001943 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001944 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001945 WCHAR fnamew[_MAX_PATH];
1946 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001947 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001948
1949 if (p != NULL)
1950 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001951 wcurpath = _wgetenv(L"PATH");
1952 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1953 * sizeof(WCHAR));
1954 if (wnewpath == NULL)
1955 return FALSE;
1956 wcscpy(wnewpath, L".;");
1957 wcscat(wnewpath, wcurpath);
1958 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1959 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001960 vim_free(p);
1961 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1962 {
1963 if (n == 0)
1964 return FALSE;
1965 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1966 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001967 if (path != NULL)
1968 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001969 return TRUE;
1970 }
1971 /* Retry with non-wide function (for Windows 98). */
1972 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001974#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001975
1976 curpath = getenv("PATH");
1977 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1978 if (newpath == NULL)
1979 return FALSE;
1980 STRCPY(newpath, ".;");
1981 STRCAT(newpath, curpath);
1982 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1983 vim_free(newpath);
1984 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001985 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001986 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001987 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001988 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001989 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001990 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001991}
1992
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001993#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001994 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001995/*
1996 * Bad parameter handler.
1997 *
1998 * Certain MS CRT functions will intentionally crash when passed invalid
1999 * parameters to highlight possible security holes. Setting this function as
2000 * the bad parameter handler will prevent the crash.
2001 *
2002 * In debug builds the parameters contain CRT information that might help track
2003 * down the source of a problem, but in non-debug builds the arguments are all
2004 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2005 * worth allowing these to make debugging of issues easier.
2006 */
2007 static void
2008bad_param_handler(const wchar_t *expression,
2009 const wchar_t *function,
2010 const wchar_t *file,
2011 unsigned int line,
2012 uintptr_t pReserved)
2013{
2014}
2015
2016# define SET_INVALID_PARAM_HANDLER \
2017 ((void)_set_invalid_parameter_handler(bad_param_handler))
2018#else
2019# define SET_INVALID_PARAM_HANDLER
2020#endif
2021
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022#ifdef FEAT_GUI_W32
2023
2024/*
2025 * GUI version of mch_init().
2026 */
2027 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002028mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029{
2030#ifndef __MINGW32__
2031 extern int _fmode;
2032#endif
2033
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002034 /* Silently handle invalid parameters to CRT functions */
2035 SET_INVALID_PARAM_HANDLER;
2036
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 /* Let critical errors result in a failure, not in a dialog box. Required
2038 * for the timestamp test to work on removed floppies. */
2039 SetErrorMode(SEM_FAILCRITICALERRORS);
2040
2041 _fmode = O_BINARY; /* we do our own CR-LF translation */
2042
2043 /* Specify window size. Is there a place to get the default from? */
2044 Rows = 25;
2045 Columns = 80;
2046
2047 /* Look for 'vimrun' */
2048 if (!gui_is_win32s())
2049 {
2050 char_u vimrun_location[_MAX_PATH + 4];
2051
2052 /* First try in same directory as gvim.exe */
2053 STRCPY(vimrun_location, exe_name);
2054 STRCPY(gettail(vimrun_location), "vimrun.exe");
2055 if (mch_getperm(vimrun_location) >= 0)
2056 {
2057 if (*skiptowhite(vimrun_location) != NUL)
2058 {
2059 /* Enclose path with white space in double quotes. */
2060 mch_memmove(vimrun_location + 1, vimrun_location,
2061 STRLEN(vimrun_location) + 1);
2062 *vimrun_location = '"';
2063 STRCPY(gettail(vimrun_location), "vimrun\" ");
2064 }
2065 else
2066 STRCPY(gettail(vimrun_location), "vimrun ");
2067
2068 vimrun_path = (char *)vim_strsave(vimrun_location);
2069 s_dont_use_vimrun = FALSE;
2070 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002071 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 s_dont_use_vimrun = FALSE;
2073
2074 /* Don't give the warning for a missing vimrun.exe right now, but only
2075 * when vimrun was supposed to be used. Don't bother people that do
2076 * not need vimrun.exe. */
2077 if (s_dont_use_vimrun)
2078 need_vimrun_warning = TRUE;
2079 }
2080
2081 /*
2082 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2083 * Otherwise the default "findstr /n" is used.
2084 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002085 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2087
2088#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002089 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090#endif
2091}
2092
2093
2094#else /* FEAT_GUI_W32 */
2095
2096#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2097#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2098
2099/*
2100 * ClearConsoleBuffer()
2101 * Description:
2102 * Clears the entire contents of the console screen buffer, using the
2103 * specified attribute.
2104 * Returns:
2105 * TRUE on success
2106 */
2107 static BOOL
2108ClearConsoleBuffer(WORD wAttribute)
2109{
2110 CONSOLE_SCREEN_BUFFER_INFO csbi;
2111 COORD coord;
2112 DWORD NumCells, dummy;
2113
2114 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2115 return FALSE;
2116
2117 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2118 coord.X = 0;
2119 coord.Y = 0;
2120 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2121 coord, &dummy))
2122 {
2123 return FALSE;
2124 }
2125 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2126 coord, &dummy))
2127 {
2128 return FALSE;
2129 }
2130
2131 return TRUE;
2132}
2133
2134/*
2135 * FitConsoleWindow()
2136 * Description:
2137 * Checks if the console window will fit within given buffer dimensions.
2138 * Also, if requested, will shrink the window to fit.
2139 * Returns:
2140 * TRUE on success
2141 */
2142 static BOOL
2143FitConsoleWindow(
2144 COORD dwBufferSize,
2145 BOOL WantAdjust)
2146{
2147 CONSOLE_SCREEN_BUFFER_INFO csbi;
2148 COORD dwWindowSize;
2149 BOOL NeedAdjust = FALSE;
2150
2151 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2152 {
2153 /*
2154 * A buffer resize will fail if the current console window does
2155 * not lie completely within that buffer. To avoid this, we might
2156 * have to move and possibly shrink the window.
2157 */
2158 if (csbi.srWindow.Right >= dwBufferSize.X)
2159 {
2160 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2161 if (dwWindowSize.X > dwBufferSize.X)
2162 dwWindowSize.X = dwBufferSize.X;
2163 csbi.srWindow.Right = dwBufferSize.X - 1;
2164 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2165 NeedAdjust = TRUE;
2166 }
2167 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2168 {
2169 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2170 if (dwWindowSize.Y > dwBufferSize.Y)
2171 dwWindowSize.Y = dwBufferSize.Y;
2172 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2173 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2174 NeedAdjust = TRUE;
2175 }
2176 if (NeedAdjust && WantAdjust)
2177 {
2178 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2179 return FALSE;
2180 }
2181 return TRUE;
2182 }
2183
2184 return FALSE;
2185}
2186
2187typedef struct ConsoleBufferStruct
2188{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002189 BOOL IsValid;
2190 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002191 PCHAR_INFO Buffer;
2192 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193} ConsoleBuffer;
2194
2195/*
2196 * SaveConsoleBuffer()
2197 * Description:
2198 * Saves important information about the console buffer, including the
2199 * actual buffer contents. The saved information is suitable for later
2200 * restoration by RestoreConsoleBuffer().
2201 * Returns:
2202 * TRUE if all information was saved; FALSE otherwise
2203 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2204 */
2205 static BOOL
2206SaveConsoleBuffer(
2207 ConsoleBuffer *cb)
2208{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002209 DWORD NumCells;
2210 COORD BufferCoord;
2211 SMALL_RECT ReadRegion;
2212 WORD Y, Y_incr;
2213
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214 if (cb == NULL)
2215 return FALSE;
2216
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002217 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002218 {
2219 cb->IsValid = FALSE;
2220 return FALSE;
2221 }
2222 cb->IsValid = TRUE;
2223
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002224 /*
2225 * Allocate a buffer large enough to hold the entire console screen
2226 * buffer. If this ConsoleBuffer structure has already been initialized
2227 * with a buffer of the correct size, then just use that one.
2228 */
2229 if (!cb->IsValid || cb->Buffer == NULL ||
2230 cb->BufferSize.X != cb->Info.dwSize.X ||
2231 cb->BufferSize.Y != cb->Info.dwSize.Y)
2232 {
2233 cb->BufferSize.X = cb->Info.dwSize.X;
2234 cb->BufferSize.Y = cb->Info.dwSize.Y;
2235 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2236 vim_free(cb->Buffer);
2237 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2238 if (cb->Buffer == NULL)
2239 return FALSE;
2240 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002241
2242 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002243 * We will now copy the console screen buffer into our buffer.
2244 * ReadConsoleOutput() seems to be limited as far as how much you
2245 * can read at a time. Empirically, this number seems to be about
2246 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2247 * in chunks until it is all copied. The chunks will all have the
2248 * same horizontal characteristics, so initialize them now. The
2249 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002251 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002252 ReadRegion.Left = 0;
2253 ReadRegion.Right = cb->Info.dwSize.X - 1;
2254 Y_incr = 12000 / cb->Info.dwSize.X;
2255 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002257 /*
2258 * Read into position (0, Y) in our buffer.
2259 */
2260 BufferCoord.Y = Y;
2261 /*
2262 * Read the region whose top left corner is (0, Y) and whose bottom
2263 * right corner is (width - 1, Y + Y_incr - 1). This should define
2264 * a region of size width by Y_incr. Don't worry if this region is
2265 * too large for the remaining buffer; it will be cropped.
2266 */
2267 ReadRegion.Top = Y;
2268 ReadRegion.Bottom = Y + Y_incr - 1;
2269 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2270 cb->Buffer, /* our buffer */
2271 cb->BufferSize, /* dimensions of our buffer */
2272 BufferCoord, /* offset in our buffer */
2273 &ReadRegion)) /* region to save */
2274 {
2275 vim_free(cb->Buffer);
2276 cb->Buffer = NULL;
2277 return FALSE;
2278 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279 }
2280
2281 return TRUE;
2282}
2283
2284/*
2285 * RestoreConsoleBuffer()
2286 * Description:
2287 * Restores important information about the console buffer, including the
2288 * actual buffer contents, if desired. The information to restore is in
2289 * the same format used by SaveConsoleBuffer().
2290 * Returns:
2291 * TRUE on success
2292 */
2293 static BOOL
2294RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002295 ConsoleBuffer *cb,
2296 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002298 COORD BufferCoord;
2299 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300
2301 if (cb == NULL || !cb->IsValid)
2302 return FALSE;
2303
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002304 /*
2305 * Before restoring the buffer contents, clear the current buffer, and
2306 * restore the cursor position and window information. Doing this now
2307 * prevents old buffer contents from "flashing" onto the screen.
2308 */
2309 if (RestoreScreen)
2310 ClearConsoleBuffer(cb->Info.wAttributes);
2311
2312 FitConsoleWindow(cb->Info.dwSize, TRUE);
2313 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2314 return FALSE;
2315 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2316 return FALSE;
2317
2318 if (!RestoreScreen)
2319 {
2320 /*
2321 * No need to restore the screen buffer contents, so we're done.
2322 */
2323 return TRUE;
2324 }
2325
2326 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2327 return FALSE;
2328 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2329 return FALSE;
2330
2331 /*
2332 * Restore the screen buffer contents.
2333 */
2334 if (cb->Buffer != NULL)
2335 {
2336 BufferCoord.X = 0;
2337 BufferCoord.Y = 0;
2338 WriteRegion.Left = 0;
2339 WriteRegion.Top = 0;
2340 WriteRegion.Right = cb->Info.dwSize.X - 1;
2341 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2342 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2343 cb->Buffer, /* our buffer */
2344 cb->BufferSize, /* dimensions of our buffer */
2345 BufferCoord, /* offset in our buffer */
2346 &WriteRegion)) /* region to restore */
2347 {
2348 return FALSE;
2349 }
2350 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351
2352 return TRUE;
2353}
2354
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002355#define FEAT_RESTORE_ORIG_SCREEN
2356#ifdef FEAT_RESTORE_ORIG_SCREEN
2357static ConsoleBuffer g_cbOrig = { 0 };
2358#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359static ConsoleBuffer g_cbNonTermcap = { 0 };
2360static ConsoleBuffer g_cbTermcap = { 0 };
2361
2362#ifdef FEAT_TITLE
2363#ifdef __BORLANDC__
2364typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2365#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002366typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367#endif
2368char g_szOrigTitle[256] = { 0 };
2369HWND g_hWnd = NULL; /* also used in os_mswin.c */
2370static HICON g_hOrigIconSmall = NULL;
2371static HICON g_hOrigIcon = NULL;
2372static HICON g_hVimIcon = NULL;
2373static BOOL g_fCanChangeIcon = FALSE;
2374
2375/* ICON* are not defined in VC++ 4.0 */
2376#ifndef ICON_SMALL
2377#define ICON_SMALL 0
2378#endif
2379#ifndef ICON_BIG
2380#define ICON_BIG 1
2381#endif
2382/*
2383 * GetConsoleIcon()
2384 * Description:
2385 * Attempts to retrieve the small icon and/or the big icon currently in
2386 * use by a given window.
2387 * Returns:
2388 * TRUE on success
2389 */
2390 static BOOL
2391GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002392 HWND hWnd,
2393 HICON *phIconSmall,
2394 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395{
2396 if (hWnd == NULL)
2397 return FALSE;
2398
2399 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002400 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2401 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002403 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2404 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 return TRUE;
2406}
2407
2408/*
2409 * SetConsoleIcon()
2410 * Description:
2411 * Attempts to change the small icon and/or the big icon currently in
2412 * use by a given window.
2413 * Returns:
2414 * TRUE on success
2415 */
2416 static BOOL
2417SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002418 HWND hWnd,
2419 HICON hIconSmall,
2420 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 if (hWnd == NULL)
2423 return FALSE;
2424
2425 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002426 SendMessage(hWnd, WM_SETICON,
2427 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002429 SendMessage(hWnd, WM_SETICON,
2430 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 return TRUE;
2432}
2433
2434/*
2435 * SaveConsoleTitleAndIcon()
2436 * Description:
2437 * Saves the current console window title in g_szOrigTitle, for later
2438 * restoration. Also, attempts to obtain a handle to the console window,
2439 * and use it to save the small and big icons currently in use by the
2440 * console window. This is not always possible on some versions of Windows;
2441 * nor is it possible when running Vim remotely using Telnet (since the
2442 * console window the user sees is owned by a remote process).
2443 */
2444 static void
2445SaveConsoleTitleAndIcon(void)
2446{
2447 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2448
2449 /* Save the original title. */
2450 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2451 return;
2452
2453 /*
2454 * Obtain a handle to the console window using GetConsoleWindow() from
2455 * KERNEL32.DLL; we need to handle in order to change the window icon.
2456 * This function only exists on NT-based Windows, starting with Windows
2457 * 2000. On older operating systems, we can't change the window icon
2458 * anyway.
2459 */
2460 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2461 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2462 "GetConsoleWindow")) != NULL)
2463 {
2464 g_hWnd = (*GetConsoleWindowProc)();
2465 }
2466 if (g_hWnd == NULL)
2467 return;
2468
2469 /* Save the original console window icon. */
2470 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2471 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2472 return;
2473
2474 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002475 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002476 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477 if (g_hVimIcon != NULL)
2478 g_fCanChangeIcon = TRUE;
2479}
2480#endif
2481
2482static int g_fWindInitCalled = FALSE;
2483static int g_fTermcapMode = FALSE;
2484static CONSOLE_CURSOR_INFO g_cci;
2485static DWORD g_cmodein = 0;
2486static DWORD g_cmodeout = 0;
2487
2488/*
2489 * non-GUI version of mch_init().
2490 */
2491 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002492mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002494#ifndef FEAT_RESTORE_ORIG_SCREEN
2495 CONSOLE_SCREEN_BUFFER_INFO csbi;
2496#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497#ifndef __MINGW32__
2498 extern int _fmode;
2499#endif
2500
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002501 /* Silently handle invalid parameters to CRT functions */
2502 SET_INVALID_PARAM_HANDLER;
2503
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 /* Let critical errors result in a failure, not in a dialog box. Required
2505 * for the timestamp test to work on removed floppies. */
2506 SetErrorMode(SEM_FAILCRITICALERRORS);
2507
2508 _fmode = O_BINARY; /* we do our own CR-LF translation */
2509 out_flush();
2510
2511 /* Obtain handles for the standard Console I/O devices */
2512 if (read_cmd_fd == 0)
2513 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2514 else
2515 create_conin();
2516 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2517
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002518#ifdef FEAT_RESTORE_ORIG_SCREEN
2519 /* Save the initial console buffer for later restoration */
2520 SaveConsoleBuffer(&g_cbOrig);
2521 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2522#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002524 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2525 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2526#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 if (cterm_normal_fg_color == 0)
2528 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2529 if (cterm_normal_bg_color == 0)
2530 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2531
2532 /* set termcap codes to current text attributes */
2533 update_tcap(g_attrCurrent);
2534
2535 GetConsoleCursorInfo(g_hConOut, &g_cci);
2536 GetConsoleMode(g_hConIn, &g_cmodein);
2537 GetConsoleMode(g_hConOut, &g_cmodeout);
2538
2539#ifdef FEAT_TITLE
2540 SaveConsoleTitleAndIcon();
2541 /*
2542 * Set both the small and big icons of the console window to Vim's icon.
2543 * Note that Vim presently only has one size of icon (32x32), but it
2544 * automatically gets scaled down to 16x16 when setting the small icon.
2545 */
2546 if (g_fCanChangeIcon)
2547 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2548#endif
2549
2550 ui_get_shellsize();
2551
2552#ifdef MCH_WRITE_DUMP
2553 fdDump = fopen("dump", "wt");
2554
2555 if (fdDump)
2556 {
2557 time_t t;
2558
2559 time(&t);
2560 fputs(ctime(&t), fdDump);
2561 fflush(fdDump);
2562 }
2563#endif
2564
2565 g_fWindInitCalled = TRUE;
2566
2567#ifdef FEAT_MOUSE
2568 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2569#endif
2570
2571#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002572 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573#endif
2574
2575 /* This will be NULL on anything but NT 4.0 */
2576 s_pfnGetConsoleKeyboardLayoutName =
2577 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2578 "GetConsoleKeyboardLayoutNameA");
2579}
2580
2581/*
2582 * non-GUI version of mch_exit().
2583 * Shut down and exit with status `r'
2584 * Careful: mch_exit() may be called before mch_init()!
2585 */
2586 void
2587mch_exit(int r)
2588{
2589 stoptermcap();
2590
2591 if (g_fWindInitCalled)
2592 settmode(TMODE_COOK);
2593
2594 ml_close_all(TRUE); /* remove all memfiles */
2595
2596 if (g_fWindInitCalled)
2597 {
2598#ifdef FEAT_TITLE
2599 mch_restore_title(3);
2600 /*
2601 * Restore both the small and big icons of the console window to
2602 * what they were at startup. Don't do this when the window is
2603 * closed, Vim would hang here.
2604 */
2605 if (g_fCanChangeIcon && !g_fForceExit)
2606 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2607#endif
2608
2609#ifdef MCH_WRITE_DUMP
2610 if (fdDump)
2611 {
2612 time_t t;
2613
2614 time(&t);
2615 fputs(ctime(&t), fdDump);
2616 fclose(fdDump);
2617 }
2618 fdDump = NULL;
2619#endif
2620 }
2621
2622 SetConsoleCursorInfo(g_hConOut, &g_cci);
2623 SetConsoleMode(g_hConIn, g_cmodein);
2624 SetConsoleMode(g_hConOut, g_cmodeout);
2625
2626#ifdef DYNAMIC_GETTEXT
2627 dyn_libintl_end();
2628#endif
2629
2630 exit(r);
2631}
2632#endif /* !FEAT_GUI_W32 */
2633
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634/*
2635 * Do we have an interactive window?
2636 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002637/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638 int
2639mch_check_win(
2640 int argc,
2641 char **argv)
2642{
2643 get_exe_name();
2644
2645#ifdef FEAT_GUI_W32
2646 return OK; /* GUI always has a tty */
2647#else
2648 if (isatty(1))
2649 return OK;
2650 return FAIL;
2651#endif
2652}
2653
2654
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002655#ifdef FEAT_MBYTE
2656/*
2657 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2658 * if it already exists. When "len" is > 0, also expand short to long
2659 * filenames.
2660 * Return FAIL if wide functions are not available, OK otherwise.
2661 * NOTE: much of this is identical to fname_case(), keep in sync!
2662 */
2663 static int
2664fname_casew(
2665 WCHAR *name,
2666 int len)
2667{
2668 WCHAR szTrueName[_MAX_PATH + 2];
2669 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2670 WCHAR *ptrue, *ptruePrev;
2671 WCHAR *porig, *porigPrev;
2672 int flen;
2673 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002674 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002675 int c;
2676 int slen;
2677
2678 flen = (int)wcslen(name);
2679 if (flen > _MAX_PATH)
2680 return OK;
2681
2682 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2683
2684 /* Build the new name in szTrueName[] one component at a time. */
2685 porig = name;
2686 ptrue = szTrueName;
2687
2688 if (iswalpha(porig[0]) && porig[1] == L':')
2689 {
2690 /* copy leading drive letter */
2691 *ptrue++ = *porig++;
2692 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002693 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002694 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002695
2696 while (*porig != NUL)
2697 {
2698 /* copy \ characters */
2699 while (*porig == psepc)
2700 *ptrue++ = *porig++;
2701
2702 ptruePrev = ptrue;
2703 porigPrev = porig;
2704 while (*porig != NUL && *porig != psepc)
2705 {
2706 *ptrue++ = *porig++;
2707 }
2708 *ptrue = NUL;
2709
2710 /* To avoid a slow failure append "\*" when searching a directory,
2711 * server or network share. */
2712 wcscpy(szTrueNameTemp, szTrueName);
2713 slen = (int)wcslen(szTrueNameTemp);
2714 if (*porig == psepc && slen + 2 < _MAX_PATH)
2715 wcscpy(szTrueNameTemp + slen, L"\\*");
2716
2717 /* Skip "", "." and "..". */
2718 if (ptrue > ptruePrev
2719 && (ptruePrev[0] != L'.'
2720 || (ptruePrev[1] != NUL
2721 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2722 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2723 != INVALID_HANDLE_VALUE)
2724 {
2725 c = *porig;
2726 *porig = NUL;
2727
2728 /* Only use the match when it's the same name (ignoring case) or
2729 * expansion is allowed and there is a match with the short name
2730 * and there is enough room. */
2731 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2732 || (len > 0
2733 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2734 && (int)(ptruePrev - szTrueName)
2735 + (int)wcslen(fb.cFileName) < len)))
2736 {
2737 wcscpy(ptruePrev, fb.cFileName);
2738
2739 /* Look for exact match and prefer it if found. Must be a
2740 * long name, otherwise there would be only one match. */
2741 while (FindNextFileW(hFind, &fb))
2742 {
2743 if (*fb.cAlternateFileName != NUL
2744 && (wcscoll(porigPrev, fb.cFileName) == 0
2745 || (len > 0
2746 && (_wcsicoll(porigPrev,
2747 fb.cAlternateFileName) == 0
2748 && (int)(ptruePrev - szTrueName)
2749 + (int)wcslen(fb.cFileName) < len))))
2750 {
2751 wcscpy(ptruePrev, fb.cFileName);
2752 break;
2753 }
2754 }
2755 }
2756 FindClose(hFind);
2757 *porig = c;
2758 ptrue = ptruePrev + wcslen(ptruePrev);
2759 }
2760 else if (hFind == INVALID_HANDLE_VALUE
2761 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2762 return FAIL;
2763 }
2764
2765 wcscpy(name, szTrueName);
2766 return OK;
2767}
2768#endif
2769
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770/*
2771 * fname_case(): Set the case of the file name, if it already exists.
2772 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002773 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 */
2775 void
2776fname_case(
2777 char_u *name,
2778 int len)
2779{
2780 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002781 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782 char *ptrue, *ptruePrev;
2783 char *porig, *porigPrev;
2784 int flen;
2785 WIN32_FIND_DATA fb;
2786 HANDLE hFind;
2787 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002788 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002790 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002791 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792 return;
2793
2794 slash_adjust(name);
2795
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002796#ifdef FEAT_MBYTE
2797 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2798 {
2799 WCHAR *p = enc_to_utf16(name, NULL);
2800
2801 if (p != NULL)
2802 {
2803 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002804 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002805
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002806 wcsncpy(buf, p, _MAX_PATH);
2807 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002808 vim_free(p);
2809
2810 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2811 {
2812 q = utf16_to_enc(buf, NULL);
2813 if (q != NULL)
2814 {
2815 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2816 vim_free(q);
2817 return;
2818 }
2819 }
2820 }
2821 /* Retry with non-wide function (for Windows 98). */
2822 }
2823#endif
2824
2825 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2826 * So we should check this after calling wide function. */
2827 if (flen > _MAX_PATH)
2828 return;
2829
Bram Moolenaar071d4272004-06-13 20:20:40 +00002830 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002831 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832 ptrue = szTrueName;
2833
2834 if (isalpha(porig[0]) && porig[1] == ':')
2835 {
2836 /* copy leading drive letter */
2837 *ptrue++ = *porig++;
2838 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002840 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002841
2842 while (*porig != NUL)
2843 {
2844 /* copy \ characters */
2845 while (*porig == psepc)
2846 *ptrue++ = *porig++;
2847
2848 ptruePrev = ptrue;
2849 porigPrev = porig;
2850 while (*porig != NUL && *porig != psepc)
2851 {
2852#ifdef FEAT_MBYTE
2853 int l;
2854
2855 if (enc_dbcs)
2856 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002857 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858 while (--l >= 0)
2859 *ptrue++ = *porig++;
2860 }
2861 else
2862#endif
2863 *ptrue++ = *porig++;
2864 }
2865 *ptrue = NUL;
2866
Bram Moolenaar464c9252010-10-13 20:37:41 +02002867 /* To avoid a slow failure append "\*" when searching a directory,
2868 * server or network share. */
2869 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002870 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002871 if (*porig == psepc && slen + 2 < _MAX_PATH)
2872 STRCPY(szTrueNameTemp + slen, "\\*");
2873
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874 /* Skip "", "." and "..". */
2875 if (ptrue > ptruePrev
2876 && (ptruePrev[0] != '.'
2877 || (ptruePrev[1] != NUL
2878 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002879 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880 != INVALID_HANDLE_VALUE)
2881 {
2882 c = *porig;
2883 *porig = NUL;
2884
2885 /* Only use the match when it's the same name (ignoring case) or
2886 * expansion is allowed and there is a match with the short name
2887 * and there is enough room. */
2888 if (_stricoll(porigPrev, fb.cFileName) == 0
2889 || (len > 0
2890 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2891 && (int)(ptruePrev - szTrueName)
2892 + (int)strlen(fb.cFileName) < len)))
2893 {
2894 STRCPY(ptruePrev, fb.cFileName);
2895
2896 /* Look for exact match and prefer it if found. Must be a
2897 * long name, otherwise there would be only one match. */
2898 while (FindNextFile(hFind, &fb))
2899 {
2900 if (*fb.cAlternateFileName != NUL
2901 && (strcoll(porigPrev, fb.cFileName) == 0
2902 || (len > 0
2903 && (_stricoll(porigPrev,
2904 fb.cAlternateFileName) == 0
2905 && (int)(ptruePrev - szTrueName)
2906 + (int)strlen(fb.cFileName) < len))))
2907 {
2908 STRCPY(ptruePrev, fb.cFileName);
2909 break;
2910 }
2911 }
2912 }
2913 FindClose(hFind);
2914 *porig = c;
2915 ptrue = ptruePrev + strlen(ptruePrev);
2916 }
2917 }
2918
2919 STRCPY(name, szTrueName);
2920}
2921
2922
2923/*
2924 * Insert user name in s[len].
2925 */
2926 int
2927mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002928 char_u *s,
2929 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002931 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 DWORD cch = sizeof szUserName;
2933
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002934#ifdef FEAT_MBYTE
2935 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2936 {
2937 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2938 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2939
2940 if (GetUserNameW(wszUserName, &wcch))
2941 {
2942 char_u *p = utf16_to_enc(wszUserName, NULL);
2943
2944 if (p != NULL)
2945 {
2946 vim_strncpy(s, p, len - 1);
2947 vim_free(p);
2948 return OK;
2949 }
2950 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002951 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2952 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002953 /* Retry with non-wide function (for Windows 98). */
2954 }
2955#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 if (GetUserName(szUserName, &cch))
2957 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002958 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959 return OK;
2960 }
2961 s[0] = NUL;
2962 return FAIL;
2963}
2964
2965
2966/*
2967 * Insert host name in s[len].
2968 */
2969 void
2970mch_get_host_name(
2971 char_u *s,
2972 int len)
2973{
2974 DWORD cch = len;
2975
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002976#ifdef FEAT_MBYTE
2977 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2978 {
2979 WCHAR wszHostName[256 + 1];
2980 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2981
2982 if (GetComputerNameW(wszHostName, &wcch))
2983 {
2984 char_u *p = utf16_to_enc(wszHostName, NULL);
2985
2986 if (p != NULL)
2987 {
2988 vim_strncpy(s, p, len - 1);
2989 vim_free(p);
2990 return;
2991 }
2992 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002993 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2994 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002995 /* Retry with non-wide function (for Windows 98). */
2996 }
2997#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002998 if (!GetComputerName((LPSTR)s, &cch))
2999 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003000}
3001
3002
3003/*
3004 * return process ID
3005 */
3006 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003007mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008{
3009 return (long)GetCurrentProcessId();
3010}
3011
3012
3013/*
3014 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3015 * Return OK for success, FAIL for failure.
3016 */
3017 int
3018mch_dirname(
3019 char_u *buf,
3020 int len)
3021{
3022 /*
3023 * Originally this was:
3024 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3025 * But the Win32s known bug list says that getcwd() doesn't work
3026 * so use the Win32 system call instead. <Negri>
3027 */
3028#ifdef FEAT_MBYTE
3029 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3030 {
3031 WCHAR wbuf[_MAX_PATH + 1];
3032
3033 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3034 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003035 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036
3037 if (p != NULL)
3038 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003039 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 vim_free(p);
3041 return OK;
3042 }
3043 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003044 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3045 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046 /* Retry with non-wide function (for Windows 98). */
3047 }
3048#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003049 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050}
3051
3052/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003053 * Get file permissions for "name".
3054 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 */
3056 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003057mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003059 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003060 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003062 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003063 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064}
3065
3066
3067/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003068 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003069 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003070 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 */
3072 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003073mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003075 long n = -1;
3076
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077#ifdef FEAT_MBYTE
3078 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3079 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003080 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081
3082 if (p != NULL)
3083 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003084 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003086 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003087 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088 /* Retry with non-wide function (for Windows 98). */
3089 }
3090 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003091 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003093 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003094 if (n == -1)
3095 return FAIL;
3096
3097 win32_set_archive(name);
3098
3099 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100}
3101
3102/*
3103 * Set hidden flag for "name".
3104 */
3105 void
3106mch_hide(char_u *name)
3107{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003108 int attrs = win32_getattrs(name);
3109 if (attrs == -1)
3110 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003112 attrs |= FILE_ATTRIBUTE_HIDDEN;
3113 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003114}
3115
3116/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003117 * Return TRUE if file "name" exists and is hidden.
3118 */
3119 int
3120mch_ishidden(char_u *name)
3121{
3122 int f = win32_getattrs(name);
3123
3124 if (f == -1)
3125 return FALSE; /* file does not exist at all */
3126
3127 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3128}
3129
3130/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131 * return TRUE if "name" is a directory
3132 * return FALSE if "name" is not a directory or upon error
3133 */
3134 int
3135mch_isdir(char_u *name)
3136{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003137 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138
3139 if (f == -1)
3140 return FALSE; /* file does not exist at all */
3141
3142 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3143}
3144
3145/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003146 * return TRUE if "name" is a directory, NOT a symlink to a directory
3147 * return FALSE if "name" is not a directory
3148 * return FALSE for error
3149 */
3150 int
3151mch_isrealdir(char_u *name)
3152{
3153 return mch_isdir(name) && !mch_is_symbolic_link(name);
3154}
3155
3156/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003157 * Create directory "name".
3158 * Return 0 on success, -1 on error.
3159 */
3160 int
3161mch_mkdir(char_u *name)
3162{
3163#ifdef FEAT_MBYTE
3164 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3165 {
3166 WCHAR *p;
3167 int retval;
3168
3169 p = enc_to_utf16(name, NULL);
3170 if (p == NULL)
3171 return -1;
3172 retval = _wmkdir(p);
3173 vim_free(p);
3174 return retval;
3175 }
3176#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003177 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003178}
3179
3180/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003181 * Delete directory "name".
3182 * Return 0 on success, -1 on error.
3183 */
3184 int
3185mch_rmdir(char_u *name)
3186{
3187#ifdef FEAT_MBYTE
3188 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3189 {
3190 WCHAR *p;
3191 int retval;
3192
3193 p = enc_to_utf16(name, NULL);
3194 if (p == NULL)
3195 return -1;
3196 retval = _wrmdir(p);
3197 vim_free(p);
3198 return retval;
3199 }
3200#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003201 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003202}
3203
3204/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003205 * Return TRUE if file "fname" has more than one link.
3206 */
3207 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003208mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003209{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003210 BY_HANDLE_FILE_INFORMATION info;
3211
3212 return win32_fileinfo(fname, &info) == FILEINFO_OK
3213 && info.nNumberOfLinks > 1;
3214}
3215
3216/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003217 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003218 */
3219 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003220mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003221{
3222 HANDLE hFind;
3223 int res = FALSE;
3224 WIN32_FIND_DATAA findDataA;
3225 DWORD fileFlags = 0, reparseTag = 0;
3226#ifdef FEAT_MBYTE
3227 WCHAR *wn = NULL;
3228 WIN32_FIND_DATAW findDataW;
3229
3230 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003231 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003232 if (wn != NULL)
3233 {
3234 hFind = FindFirstFileW(wn, &findDataW);
3235 vim_free(wn);
3236 if (hFind == INVALID_HANDLE_VALUE
3237 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3238 {
3239 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003240 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241 if (hFind != INVALID_HANDLE_VALUE)
3242 {
3243 fileFlags = findDataA.dwFileAttributes;
3244 reparseTag = findDataA.dwReserved0;
3245 }
3246 }
3247 else
3248 {
3249 fileFlags = findDataW.dwFileAttributes;
3250 reparseTag = findDataW.dwReserved0;
3251 }
3252 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003253 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003254#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003255 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003256 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003257 if (hFind != INVALID_HANDLE_VALUE)
3258 {
3259 fileFlags = findDataA.dwFileAttributes;
3260 reparseTag = findDataA.dwReserved0;
3261 }
3262 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003263
3264 if (hFind != INVALID_HANDLE_VALUE)
3265 FindClose(hFind);
3266
3267 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003268 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3269 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003270 res = TRUE;
3271
3272 return res;
3273}
3274
3275/*
3276 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3277 * link.
3278 */
3279 int
3280mch_is_linked(char_u *fname)
3281{
3282 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3283 return TRUE;
3284 return FALSE;
3285}
3286
3287/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003288 * Get the by-handle-file-information for "fname".
3289 * Returns FILEINFO_OK when OK.
3290 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3291 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3292 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3293 */
3294 int
3295win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3296{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003297 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003298 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003299#ifdef FEAT_MBYTE
3300 WCHAR *wn = NULL;
3301
3302 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003303 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003304 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003305 if (wn == NULL)
3306 res = FILEINFO_ENC_FAIL;
3307 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003308 if (wn != NULL)
3309 {
3310 hFile = CreateFileW(wn, /* file name */
3311 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003312 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003313 NULL, /* security descriptor */
3314 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003315 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003316 NULL); /* handle to template file */
3317 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003318 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003319 {
3320 /* Retry with non-wide function (for Windows 98). */
3321 vim_free(wn);
3322 wn = NULL;
3323 }
3324 }
3325 if (wn == NULL)
3326#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003327 hFile = CreateFile((LPCSTR)fname, /* file name */
3328 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003329 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003330 NULL, /* security descriptor */
3331 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003332 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003333 NULL); /* handle to template file */
3334
3335 if (hFile != INVALID_HANDLE_VALUE)
3336 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003337 if (GetFileInformationByHandle(hFile, info) != 0)
3338 res = FILEINFO_OK;
3339 else
3340 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003341 CloseHandle(hFile);
3342 }
3343
3344#ifdef FEAT_MBYTE
3345 vim_free(wn);
3346#endif
3347 return res;
3348}
3349
3350/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003351 * get file attributes for `name'
3352 * -1 : error
3353 * else FILE_ATTRIBUTE_* defined in winnt.h
3354 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003355 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003356win32_getattrs(char_u *name)
3357{
3358 int attr;
3359#ifdef FEAT_MBYTE
3360 WCHAR *p = NULL;
3361
3362 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3363 p = enc_to_utf16(name, NULL);
3364
3365 if (p != NULL)
3366 {
3367 attr = GetFileAttributesW(p);
3368 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3369 {
3370 /* Retry with non-wide function (for Windows 98). */
3371 vim_free(p);
3372 p = NULL;
3373 }
3374 }
3375 if (p == NULL)
3376#endif
3377 attr = GetFileAttributes((char *)name);
3378#ifdef FEAT_MBYTE
3379 vim_free(p);
3380#endif
3381 return attr;
3382}
3383
3384/*
3385 * set file attributes for `name' to `attrs'
3386 *
3387 * return -1 for failure, 0 otherwise
3388 */
3389 static
3390 int
3391win32_setattrs(char_u *name, int attrs)
3392{
3393 int res;
3394#ifdef FEAT_MBYTE
3395 WCHAR *p = NULL;
3396
3397 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3398 p = enc_to_utf16(name, NULL);
3399
3400 if (p != NULL)
3401 {
3402 res = SetFileAttributesW(p, attrs);
3403 if (res == FALSE
3404 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3405 {
3406 /* Retry with non-wide function (for Windows 98). */
3407 vim_free(p);
3408 p = NULL;
3409 }
3410 }
3411 if (p == NULL)
3412#endif
3413 res = SetFileAttributes((char *)name, attrs);
3414#ifdef FEAT_MBYTE
3415 vim_free(p);
3416#endif
3417 return res ? 0 : -1;
3418}
3419
3420/*
3421 * Set archive flag for "name".
3422 */
3423 static
3424 int
3425win32_set_archive(char_u *name)
3426{
3427 int attrs = win32_getattrs(name);
3428 if (attrs == -1)
3429 return -1;
3430
3431 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3432 return win32_setattrs(name, attrs);
3433}
3434
3435/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436 * Return TRUE if file or directory "name" is writable (not readonly).
3437 * Strange semantics of Win32: a readonly directory is writable, but you can't
3438 * delete a file. Let's say this means it is writable.
3439 */
3440 int
3441mch_writable(char_u *name)
3442{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003443 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003445 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3446 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447}
3448
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449/*
3450 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003451 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003452 * Return -1 if unknown.
3453 */
3454 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003455mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003456{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003457 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003458 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003459 char_u *p;
3460
3461 if (len >= _MAX_PATH) /* safety check */
3462 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003463 if (!use_path)
3464 {
3465 /* TODO: check if file is really executable. */
3466 return mch_getperm(name) != -1 && !mch_isdir(name);
3467 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003468
3469 /* If there already is an extension try using the name directly. Also do
3470 * this with a Unix-shell like 'shell'. */
3471 if (vim_strchr(gettail(name), '.') != NULL
3472 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003473 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003474 return TRUE;
3475
3476 /*
3477 * Loop over all extensions in $PATHEXT.
3478 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003479 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003480 p = mch_getenv("PATHEXT");
3481 if (p == NULL)
3482 p = (char_u *)".com;.exe;.bat;.cmd";
3483 while (*p)
3484 {
3485 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3486 {
3487 /* A single "." means no extension is added. */
3488 buf[len] = NUL;
3489 ++p;
3490 if (*p)
3491 ++p;
3492 }
3493 else
3494 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003495 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003496 return TRUE;
3497 }
3498 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500
3501/*
3502 * Check what "name" is:
3503 * NODE_NORMAL: file or directory (or doesn't exist)
3504 * NODE_WRITABLE: writable device, socket, fifo, etc.
3505 * NODE_OTHER: non-writable things
3506 */
3507 int
3508mch_nodetype(char_u *name)
3509{
3510 HANDLE hFile;
3511 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003512#ifdef FEAT_MBYTE
3513 WCHAR *wn = NULL;
3514#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515
Bram Moolenaar043545e2006-10-10 16:44:07 +00003516 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3517 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3518 * here. */
3519 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3520 return NODE_WRITABLE;
3521
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003522#ifdef FEAT_MBYTE
3523 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3524 {
3525 wn = enc_to_utf16(name, NULL);
3526 if (wn != NULL)
3527 {
3528 hFile = CreateFileW(wn, /* file name */
3529 GENERIC_WRITE, /* access mode */
3530 0, /* share mode */
3531 NULL, /* security descriptor */
3532 OPEN_EXISTING, /* creation disposition */
3533 0, /* file attributes */
3534 NULL); /* handle to template file */
3535 if (hFile == INVALID_HANDLE_VALUE
3536 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3537 {
3538 /* Retry with non-wide function (for Windows 98). */
3539 vim_free(wn);
3540 wn = NULL;
3541 }
3542 }
3543 }
3544 if (wn == NULL)
3545#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003546 hFile = CreateFile((LPCSTR)name, /* file name */
3547 GENERIC_WRITE, /* access mode */
3548 0, /* share mode */
3549 NULL, /* security descriptor */
3550 OPEN_EXISTING, /* creation disposition */
3551 0, /* file attributes */
3552 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003553
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003554#ifdef FEAT_MBYTE
3555 vim_free(wn);
3556#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557 if (hFile == INVALID_HANDLE_VALUE)
3558 return NODE_NORMAL;
3559
3560 type = GetFileType(hFile);
3561 CloseHandle(hFile);
3562 if (type == FILE_TYPE_CHAR)
3563 return NODE_WRITABLE;
3564 if (type == FILE_TYPE_DISK)
3565 return NODE_NORMAL;
3566 return NODE_OTHER;
3567}
3568
3569#ifdef HAVE_ACL
3570struct my_acl
3571{
3572 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3573 PSID pSidOwner;
3574 PSID pSidGroup;
3575 PACL pDacl;
3576 PACL pSacl;
3577};
3578#endif
3579
3580/*
3581 * Return a pointer to the ACL of file "fname" in allocated memory.
3582 * Return NULL if the ACL is not available for whatever reason.
3583 */
3584 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003585mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003586{
3587#ifndef HAVE_ACL
3588 return (vim_acl_T)NULL;
3589#else
3590 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003591 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003592
3593 /* This only works on Windows NT and 2000. */
3594 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3595 {
3596 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3597 if (p != NULL)
3598 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003599# ifdef FEAT_MBYTE
3600 WCHAR *wn = NULL;
3601
3602 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3603 wn = enc_to_utf16(fname, NULL);
3604 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003606 /* Try to retrieve the entire security descriptor. */
3607 err = pGetNamedSecurityInfoW(
3608 wn, // Abstract filename
3609 SE_FILE_OBJECT, // File Object
3610 OWNER_SECURITY_INFORMATION |
3611 GROUP_SECURITY_INFORMATION |
3612 DACL_SECURITY_INFORMATION |
3613 SACL_SECURITY_INFORMATION,
3614 &p->pSidOwner, // Ownership information.
3615 &p->pSidGroup, // Group membership.
3616 &p->pDacl, // Discretionary information.
3617 &p->pSacl, // For auditing purposes.
3618 &p->pSecurityDescriptor);
3619 if (err == ERROR_ACCESS_DENIED ||
3620 err == ERROR_PRIVILEGE_NOT_HELD)
3621 {
3622 /* Retrieve only DACL. */
3623 (void)pGetNamedSecurityInfoW(
3624 wn,
3625 SE_FILE_OBJECT,
3626 DACL_SECURITY_INFORMATION,
3627 NULL,
3628 NULL,
3629 &p->pDacl,
3630 NULL,
3631 &p->pSecurityDescriptor);
3632 }
3633 if (p->pSecurityDescriptor == NULL)
3634 {
3635 mch_free_acl((vim_acl_T)p);
3636 p = NULL;
3637 }
3638 vim_free(wn);
3639 }
3640 else
3641# endif
3642 {
3643 /* Try to retrieve the entire security descriptor. */
3644 err = pGetNamedSecurityInfo(
3645 (LPSTR)fname, // Abstract filename
3646 SE_FILE_OBJECT, // File Object
3647 OWNER_SECURITY_INFORMATION |
3648 GROUP_SECURITY_INFORMATION |
3649 DACL_SECURITY_INFORMATION |
3650 SACL_SECURITY_INFORMATION,
3651 &p->pSidOwner, // Ownership information.
3652 &p->pSidGroup, // Group membership.
3653 &p->pDacl, // Discretionary information.
3654 &p->pSacl, // For auditing purposes.
3655 &p->pSecurityDescriptor);
3656 if (err == ERROR_ACCESS_DENIED ||
3657 err == ERROR_PRIVILEGE_NOT_HELD)
3658 {
3659 /* Retrieve only DACL. */
3660 (void)pGetNamedSecurityInfo(
3661 (LPSTR)fname,
3662 SE_FILE_OBJECT,
3663 DACL_SECURITY_INFORMATION,
3664 NULL,
3665 NULL,
3666 &p->pDacl,
3667 NULL,
3668 &p->pSecurityDescriptor);
3669 }
3670 if (p->pSecurityDescriptor == NULL)
3671 {
3672 mch_free_acl((vim_acl_T)p);
3673 p = NULL;
3674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675 }
3676 }
3677 }
3678
3679 return (vim_acl_T)p;
3680#endif
3681}
3682
Bram Moolenaar27515922013-06-29 15:36:26 +02003683#ifdef HAVE_ACL
3684/*
3685 * Check if "acl" contains inherited ACE.
3686 */
3687 static BOOL
3688is_acl_inherited(PACL acl)
3689{
3690 DWORD i;
3691 ACL_SIZE_INFORMATION acl_info;
3692 PACCESS_ALLOWED_ACE ace;
3693
3694 acl_info.AceCount = 0;
3695 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3696 for (i = 0; i < acl_info.AceCount; i++)
3697 {
3698 GetAce(acl, i, (LPVOID *)&ace);
3699 if (ace->Header.AceFlags & INHERITED_ACE)
3700 return TRUE;
3701 }
3702 return FALSE;
3703}
3704#endif
3705
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706/*
3707 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3708 * Errors are ignored.
3709 * This must only be called with "acl" equal to what mch_get_acl() returned.
3710 */
3711 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003712mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713{
3714#ifdef HAVE_ACL
3715 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003716 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717
3718 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003719 {
3720# ifdef FEAT_MBYTE
3721 WCHAR *wn = NULL;
3722# endif
3723
3724 /* Set security flags */
3725 if (p->pSidOwner)
3726 sec_info |= OWNER_SECURITY_INFORMATION;
3727 if (p->pSidGroup)
3728 sec_info |= GROUP_SECURITY_INFORMATION;
3729 if (p->pDacl)
3730 {
3731 sec_info |= DACL_SECURITY_INFORMATION;
3732 /* Do not inherit its parent's DACL.
3733 * If the DACL is inherited, Cygwin permissions would be changed.
3734 */
3735 if (!is_acl_inherited(p->pDacl))
3736 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3737 }
3738 if (p->pSacl)
3739 sec_info |= SACL_SECURITY_INFORMATION;
3740
3741# ifdef FEAT_MBYTE
3742 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3743 wn = enc_to_utf16(fname, NULL);
3744 if (wn != NULL)
3745 {
3746 (void)pSetNamedSecurityInfoW(
3747 wn, // Abstract filename
3748 SE_FILE_OBJECT, // File Object
3749 sec_info,
3750 p->pSidOwner, // Ownership information.
3751 p->pSidGroup, // Group membership.
3752 p->pDacl, // Discretionary information.
3753 p->pSacl // For auditing purposes.
3754 );
3755 vim_free(wn);
3756 }
3757 else
3758# endif
3759 {
3760 (void)pSetNamedSecurityInfo(
3761 (LPSTR)fname, // Abstract filename
3762 SE_FILE_OBJECT, // File Object
3763 sec_info,
3764 p->pSidOwner, // Ownership information.
3765 p->pSidGroup, // Group membership.
3766 p->pDacl, // Discretionary information.
3767 p->pSacl // For auditing purposes.
3768 );
3769 }
3770 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771#endif
3772}
3773
3774 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003775mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776{
3777#ifdef HAVE_ACL
3778 struct my_acl *p = (struct my_acl *)acl;
3779
3780 if (p != NULL)
3781 {
3782 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3783 vim_free(p);
3784 }
3785#endif
3786}
3787
3788#ifndef FEAT_GUI_W32
3789
3790/*
3791 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3792 */
3793 static BOOL WINAPI
3794handler_routine(
3795 DWORD dwCtrlType)
3796{
3797 switch (dwCtrlType)
3798 {
3799 case CTRL_C_EVENT:
3800 if (ctrl_c_interrupts)
3801 g_fCtrlCPressed = TRUE;
3802 return TRUE;
3803
3804 case CTRL_BREAK_EVENT:
3805 g_fCBrkPressed = TRUE;
3806 return TRUE;
3807
3808 /* fatal events: shut down gracefully */
3809 case CTRL_CLOSE_EVENT:
3810 case CTRL_LOGOFF_EVENT:
3811 case CTRL_SHUTDOWN_EVENT:
3812 windgoto((int)Rows - 1, 0);
3813 g_fForceExit = TRUE;
3814
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003815 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816 (dwCtrlType == CTRL_CLOSE_EVENT
3817 ? _("close")
3818 : dwCtrlType == CTRL_LOGOFF_EVENT
3819 ? _("logoff")
3820 : _("shutdown")));
3821#ifdef DEBUG
3822 OutputDebugString(IObuff);
3823#endif
3824
3825 preserve_exit(); /* output IObuff, preserve files and exit */
3826
3827 return TRUE; /* not reached */
3828
3829 default:
3830 return FALSE;
3831 }
3832}
3833
3834
3835/*
3836 * set the tty in (raw) ? "raw" : "cooked" mode
3837 */
3838 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003839mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840{
3841 DWORD cmodein;
3842 DWORD cmodeout;
3843 BOOL bEnableHandler;
3844
3845 GetConsoleMode(g_hConIn, &cmodein);
3846 GetConsoleMode(g_hConOut, &cmodeout);
3847 if (tmode == TMODE_RAW)
3848 {
3849 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3850 ENABLE_ECHO_INPUT);
3851#ifdef FEAT_MOUSE
3852 if (g_fMouseActive)
3853 cmodein |= ENABLE_MOUSE_INPUT;
3854#endif
3855 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3856 bEnableHandler = TRUE;
3857 }
3858 else /* cooked */
3859 {
3860 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3861 ENABLE_ECHO_INPUT);
3862 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3863 bEnableHandler = FALSE;
3864 }
3865 SetConsoleMode(g_hConIn, cmodein);
3866 SetConsoleMode(g_hConOut, cmodeout);
3867 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3868
3869#ifdef MCH_WRITE_DUMP
3870 if (fdDump)
3871 {
3872 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3873 tmode == TMODE_RAW ? "raw" :
3874 tmode == TMODE_COOK ? "cooked" : "normal",
3875 cmodein, cmodeout);
3876 fflush(fdDump);
3877 }
3878#endif
3879}
3880
3881
3882/*
3883 * Get the size of the current window in `Rows' and `Columns'
3884 * Return OK when size could be determined, FAIL otherwise.
3885 */
3886 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003887mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003888{
3889 CONSOLE_SCREEN_BUFFER_INFO csbi;
3890
3891 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3892 {
3893 /*
3894 * For some reason, we are trying to get the screen dimensions
3895 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3896 * variables are really intended to mean the size of Vim screen
3897 * while in termcap mode.
3898 */
3899 Rows = g_cbTermcap.Info.dwSize.Y;
3900 Columns = g_cbTermcap.Info.dwSize.X;
3901 }
3902 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3903 {
3904 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3905 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3906 }
3907 else
3908 {
3909 Rows = 25;
3910 Columns = 80;
3911 }
3912 return OK;
3913}
3914
3915/*
3916 * Set a console window to `xSize' * `ySize'
3917 */
3918 static void
3919ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003920 HANDLE hConsole,
3921 int xSize,
3922 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923{
3924 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3925 SMALL_RECT srWindowRect; /* hold the new console size */
3926 COORD coordScreen;
3927
3928#ifdef MCH_WRITE_DUMP
3929 if (fdDump)
3930 {
3931 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3932 fflush(fdDump);
3933 }
3934#endif
3935
3936 /* get the largest size we can size the console window to */
3937 coordScreen = GetLargestConsoleWindowSize(hConsole);
3938
3939 /* define the new console window size and scroll position */
3940 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3941 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3942 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3943
3944 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3945 {
3946 int sx, sy;
3947
3948 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3949 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3950 if (sy < ySize || sx < xSize)
3951 {
3952 /*
3953 * Increasing number of lines/columns, do buffer first.
3954 * Use the maximal size in x and y direction.
3955 */
3956 if (sy < ySize)
3957 coordScreen.Y = ySize;
3958 else
3959 coordScreen.Y = sy;
3960 if (sx < xSize)
3961 coordScreen.X = xSize;
3962 else
3963 coordScreen.X = sx;
3964 SetConsoleScreenBufferSize(hConsole, coordScreen);
3965 }
3966 }
3967
3968 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3969 {
3970#ifdef MCH_WRITE_DUMP
3971 if (fdDump)
3972 {
3973 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3974 GetLastError());
3975 fflush(fdDump);
3976 }
3977#endif
3978 }
3979
3980 /* define the new console buffer size */
3981 coordScreen.X = xSize;
3982 coordScreen.Y = ySize;
3983
3984 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3985 {
3986#ifdef MCH_WRITE_DUMP
3987 if (fdDump)
3988 {
3989 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3990 GetLastError());
3991 fflush(fdDump);
3992 }
3993#endif
3994 }
3995}
3996
3997
3998/*
3999 * Set the console window to `Rows' * `Columns'
4000 */
4001 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004002mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004003{
4004 COORD coordScreen;
4005
4006 /* Don't change window size while still starting up */
4007 if (suppress_winsize != 0)
4008 {
4009 suppress_winsize = 2;
4010 return;
4011 }
4012
4013 if (term_console)
4014 {
4015 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4016
4017 /* Clamp Rows and Columns to reasonable values */
4018 if (Rows > coordScreen.Y)
4019 Rows = coordScreen.Y;
4020 if (Columns > coordScreen.X)
4021 Columns = coordScreen.X;
4022
4023 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4024 }
4025}
4026
4027/*
4028 * Rows and/or Columns has changed.
4029 */
4030 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004031mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032{
4033 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4034}
4035
4036
4037/*
4038 * Called when started up, to set the winsize that was delayed.
4039 */
4040 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004041mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004042{
4043 if (suppress_winsize == 2)
4044 {
4045 suppress_winsize = 0;
4046 mch_set_shellsize();
4047 shell_resized();
4048 }
4049 suppress_winsize = 0;
4050}
4051#endif /* FEAT_GUI_W32 */
4052
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004053 static BOOL
4054vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004055 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004056 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004057 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004058 STARTUPINFO *si,
4059 PROCESS_INFORMATION *pi)
4060{
4061# ifdef FEAT_MBYTE
4062 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4063 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004064 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004065
4066 if (wcmd != NULL)
4067 {
4068 BOOL ret;
4069 ret = CreateProcessW(
4070 NULL, /* Executable name */
4071 wcmd, /* Command to execute */
4072 NULL, /* Process security attributes */
4073 NULL, /* Thread security attributes */
4074 inherit_handles, /* Inherit handles */
4075 flags, /* Creation flags */
4076 NULL, /* Environment */
4077 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004078 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004079 pi); /* Process information */
4080 vim_free(wcmd);
4081 return ret;
4082 }
4083 }
4084#endif
4085 return CreateProcess(
4086 NULL, /* Executable name */
4087 cmd, /* Command to execute */
4088 NULL, /* Process security attributes */
4089 NULL, /* Thread security attributes */
4090 inherit_handles, /* Inherit handles */
4091 flags, /* Creation flags */
4092 NULL, /* Environment */
4093 NULL, /* Current directory */
4094 si, /* Startup information */
4095 pi); /* Process information */
4096}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097
4098
4099#if defined(FEAT_GUI_W32) || defined(PROTO)
4100
4101/*
4102 * Specialised version of system() for Win32 GUI mode.
4103 * This version proceeds as follows:
4104 * 1. Create a console window for use by the subprocess
4105 * 2. Run the subprocess (it gets the allocated console by default)
4106 * 3. Wait for the subprocess to terminate and get its exit code
4107 * 4. Prompt the user to press a key to close the console window
4108 */
4109 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004110mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111{
4112 STARTUPINFO si;
4113 PROCESS_INFORMATION pi;
4114 DWORD ret = 0;
4115 HWND hwnd = GetFocus();
4116
4117 si.cb = sizeof(si);
4118 si.lpReserved = NULL;
4119 si.lpDesktop = NULL;
4120 si.lpTitle = NULL;
4121 si.dwFlags = STARTF_USESHOWWINDOW;
4122 /*
4123 * It's nicer to run a filter command in a minimized window, but in
4124 * Windows 95 this makes the command MUCH slower. We can't do it under
4125 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004126 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 */
4128 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004129 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 else
4131 si.wShowWindow = SW_SHOWNORMAL;
4132 si.cbReserved2 = 0;
4133 si.lpReserved2 = NULL;
4134
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004135 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 * When the "c:\\" is left out it works OK...? */
4137 if (mch_windows95()
4138 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4139 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4140 cmd += 3;
4141
4142 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004143 vim_create_process(cmd, FALSE,
4144 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145
4146 /* Wait for the command to terminate before continuing */
4147 if (g_PlatformId != VER_PLATFORM_WIN32s)
4148 {
4149#ifdef FEAT_GUI
4150 int delay = 1;
4151
4152 /* Keep updating the window while waiting for the shell to finish. */
4153 for (;;)
4154 {
4155 MSG msg;
4156
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004157 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 {
4159 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004160 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004161 delay = 1;
4162 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 }
4164 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4165 break;
4166
4167 /* We start waiting for a very short time and then increase it, so
4168 * that we respond quickly when the process is quick, and don't
4169 * consume too much overhead when it's slow. */
4170 if (delay < 50)
4171 delay += 10;
4172 }
4173#else
4174 WaitForSingleObject(pi.hProcess, INFINITE);
4175#endif
4176
4177 /* Get the command exit code */
4178 GetExitCodeProcess(pi.hProcess, &ret);
4179 }
4180 else
4181 {
4182 /*
4183 * This ugly code is the only quick way of performing
4184 * a synchronous spawn under Win32s. Yuk.
4185 */
4186 num_windows = 0;
4187 EnumWindows(win32ssynch_cb, 0);
4188 old_num_windows = num_windows;
4189 do
4190 {
4191 Sleep(1000);
4192 num_windows = 0;
4193 EnumWindows(win32ssynch_cb, 0);
4194 } while (num_windows == old_num_windows);
4195 ret = 0;
4196 }
4197
4198 /* Close the handles to the subprocess, so that it goes away */
4199 CloseHandle(pi.hThread);
4200 CloseHandle(pi.hProcess);
4201
4202 /* Try to get input focus back. Doesn't always work though. */
4203 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4204
4205 return ret;
4206}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004207
4208/*
4209 * Thread launched by the gui to send the current buffer data to the
4210 * process. This way avoid to hang up vim totally if the children
4211 * process take a long time to process the lines.
4212 */
4213 static DWORD WINAPI
4214sub_process_writer(LPVOID param)
4215{
4216 HANDLE g_hChildStd_IN_Wr = param;
4217 linenr_T lnum = curbuf->b_op_start.lnum;
4218 DWORD len = 0;
4219 DWORD l;
4220 char_u *lp = ml_get(lnum);
4221 char_u *s;
4222 int written = 0;
4223
4224 for (;;)
4225 {
4226 l = (DWORD)STRLEN(lp + written);
4227 if (l == 0)
4228 len = 0;
4229 else if (lp[written] == NL)
4230 {
4231 /* NL -> NUL translation */
4232 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4233 }
4234 else
4235 {
4236 s = vim_strchr(lp + written, NL);
4237 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4238 s == NULL ? l : (DWORD)(s - (lp + written)),
4239 &len, NULL);
4240 }
4241 if (len == (int)l)
4242 {
4243 /* Finished a line, add a NL, unless this line should not have
4244 * one. */
4245 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004246 || (!curbuf->b_p_bin
4247 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004248 || (lnum != curbuf->b_no_eol_lnum
4249 && (lnum != curbuf->b_ml.ml_line_count
4250 || curbuf->b_p_eol)))
4251 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004252 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004253 }
4254
4255 ++lnum;
4256 if (lnum > curbuf->b_op_end.lnum)
4257 break;
4258
4259 lp = ml_get(lnum);
4260 written = 0;
4261 }
4262 else if (len > 0)
4263 written += len;
4264 }
4265
4266 /* finished all the lines, close pipe */
4267 CloseHandle(g_hChildStd_IN_Wr);
4268 ExitThread(0);
4269}
4270
4271
4272# define BUFLEN 100 /* length for buffer, stolen from unix version */
4273
4274/*
4275 * This function read from the children's stdout and write the
4276 * data on screen or in the buffer accordingly.
4277 */
4278 static void
4279dump_pipe(int options,
4280 HANDLE g_hChildStd_OUT_Rd,
4281 garray_T *ga,
4282 char_u buffer[],
4283 DWORD *buffer_off)
4284{
4285 DWORD availableBytes = 0;
4286 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287 int ret;
4288 DWORD len;
4289 DWORD toRead;
4290 int repeatCount;
4291
4292 /* we query the pipe to see if there is any data to read
4293 * to avoid to perform a blocking read */
4294 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4295 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004296 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004297 NULL, /* number of read bytes */
4298 &availableBytes, /* available bytes total */
4299 NULL); /* byteLeft */
4300
4301 repeatCount = 0;
4302 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004303 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004304 {
4305 repeatCount++;
4306 toRead =
4307# ifdef FEAT_MBYTE
4308 (DWORD)(BUFLEN - *buffer_off);
4309# else
4310 (DWORD)BUFLEN;
4311# endif
4312 toRead = availableBytes < toRead ? availableBytes : toRead;
4313 ReadFile(g_hChildStd_OUT_Rd, buffer
4314# ifdef FEAT_MBYTE
4315 + *buffer_off, toRead
4316# else
4317 , toRead
4318# endif
4319 , &len, NULL);
4320
4321 /* If we haven't read anything, there is a problem */
4322 if (len == 0)
4323 break;
4324
4325 availableBytes -= len;
4326
4327 if (options & SHELL_READ)
4328 {
4329 /* Do NUL -> NL translation, append NL separated
4330 * lines to the current buffer. */
4331 for (i = 0; i < len; ++i)
4332 {
4333 if (buffer[i] == NL)
4334 append_ga_line(ga);
4335 else if (buffer[i] == NUL)
4336 ga_append(ga, NL);
4337 else
4338 ga_append(ga, buffer[i]);
4339 }
4340 }
4341# ifdef FEAT_MBYTE
4342 else if (has_mbyte)
4343 {
4344 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004345 int c;
4346 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004347
4348 len += *buffer_off;
4349 buffer[len] = NUL;
4350
4351 /* Check if the last character in buffer[] is
4352 * incomplete, keep these bytes for the next
4353 * round. */
4354 for (p = buffer; p < buffer + len; p += l)
4355 {
4356 l = mb_cptr2len(p);
4357 if (l == 0)
4358 l = 1; /* NUL byte? */
4359 else if (MB_BYTE2LEN(*p) != l)
4360 break;
4361 }
4362 if (p == buffer) /* no complete character */
4363 {
4364 /* avoid getting stuck at an illegal byte */
4365 if (len >= 12)
4366 ++p;
4367 else
4368 {
4369 *buffer_off = len;
4370 return;
4371 }
4372 }
4373 c = *p;
4374 *p = NUL;
4375 msg_puts(buffer);
4376 if (p < buffer + len)
4377 {
4378 *p = c;
4379 *buffer_off = (DWORD)((buffer + len) - p);
4380 mch_memmove(buffer, p, *buffer_off);
4381 return;
4382 }
4383 *buffer_off = 0;
4384 }
4385# endif /* FEAT_MBYTE */
4386 else
4387 {
4388 buffer[len] = NUL;
4389 msg_puts(buffer);
4390 }
4391
4392 windgoto(msg_row, msg_col);
4393 cursor_on();
4394 out_flush();
4395 }
4396}
4397
4398/*
4399 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4400 * for communication and doesn't open any new window.
4401 */
4402 static int
4403mch_system_piped(char *cmd, int options)
4404{
4405 STARTUPINFO si;
4406 PROCESS_INFORMATION pi;
4407 DWORD ret = 0;
4408
4409 HANDLE g_hChildStd_IN_Rd = NULL;
4410 HANDLE g_hChildStd_IN_Wr = NULL;
4411 HANDLE g_hChildStd_OUT_Rd = NULL;
4412 HANDLE g_hChildStd_OUT_Wr = NULL;
4413
4414 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4415 DWORD len;
4416
4417 /* buffer used to receive keys */
4418 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4419 int ta_len = 0; /* valid bytes in ta_buf[] */
4420
4421 DWORD i;
4422 int c;
4423 int noread_cnt = 0;
4424 garray_T ga;
4425 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004426 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004427 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004428
4429 SECURITY_ATTRIBUTES saAttr;
4430
4431 /* Set the bInheritHandle flag so pipe handles are inherited. */
4432 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4433 saAttr.bInheritHandle = TRUE;
4434 saAttr.lpSecurityDescriptor = NULL;
4435
4436 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4437 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4438 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4439 /* Create a pipe for the child process's STDIN. */
4440 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4441 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4442 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4443 {
4444 CloseHandle(g_hChildStd_IN_Rd);
4445 CloseHandle(g_hChildStd_IN_Wr);
4446 CloseHandle(g_hChildStd_OUT_Rd);
4447 CloseHandle(g_hChildStd_OUT_Wr);
4448 MSG_PUTS(_("\nCannot create pipes\n"));
4449 }
4450
4451 si.cb = sizeof(si);
4452 si.lpReserved = NULL;
4453 si.lpDesktop = NULL;
4454 si.lpTitle = NULL;
4455 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4456
4457 /* set-up our file redirection */
4458 si.hStdError = g_hChildStd_OUT_Wr;
4459 si.hStdOutput = g_hChildStd_OUT_Wr;
4460 si.hStdInput = g_hChildStd_IN_Rd;
4461 si.wShowWindow = SW_HIDE;
4462 si.cbReserved2 = 0;
4463 si.lpReserved2 = NULL;
4464
4465 if (options & SHELL_READ)
4466 ga_init2(&ga, 1, BUFLEN);
4467
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004468 if (cmd != NULL)
4469 {
4470 p = (char *)vim_strsave((char_u *)cmd);
4471 if (p != NULL)
4472 unescape_shellxquote((char_u *)p, p_sxe);
4473 else
4474 p = cmd;
4475 }
4476
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004477 /* Now, run the command.
4478 * About "Inherit handles" being TRUE: this command can be litigious,
4479 * handle inheritance was deactivated for pending temp file, but, if we
4480 * deactivate it, the pipes don't work for some reason. */
4481 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004482
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004483 if (p != cmd)
4484 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004485
4486 /* Close our unused side of the pipes */
4487 CloseHandle(g_hChildStd_IN_Rd);
4488 CloseHandle(g_hChildStd_OUT_Wr);
4489
4490 if (options & SHELL_WRITE)
4491 {
4492 HANDLE thread =
4493 CreateThread(NULL, /* security attributes */
4494 0, /* default stack size */
4495 sub_process_writer, /* function to be executed */
4496 g_hChildStd_IN_Wr, /* parameter */
4497 0, /* creation flag, start immediately */
4498 NULL); /* we don't care about thread id */
4499 CloseHandle(thread);
4500 g_hChildStd_IN_Wr = NULL;
4501 }
4502
4503 /* Keep updating the window while waiting for the shell to finish. */
4504 for (;;)
4505 {
4506 MSG msg;
4507
Bram Moolenaar175d0702013-12-11 18:36:33 +01004508 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004509 {
4510 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004511 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004512 }
4513
4514 /* write pipe information in the window */
4515 if ((options & (SHELL_READ|SHELL_WRITE))
4516# ifdef FEAT_GUI
4517 || gui.in_use
4518# endif
4519 )
4520 {
4521 len = 0;
4522 if (!(options & SHELL_EXPAND)
4523 && ((options &
4524 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4525 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4526# ifdef FEAT_GUI
4527 || gui.in_use
4528# endif
4529 )
4530 && (ta_len > 0 || noread_cnt > 4))
4531 {
4532 if (ta_len == 0)
4533 {
4534 /* Get extra characters when we don't have any. Reset the
4535 * counter and timer. */
4536 noread_cnt = 0;
4537# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4538 gettimeofday(&start_tv, NULL);
4539# endif
4540 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4541 }
4542 if (ta_len > 0 || len > 0)
4543 {
4544 /*
4545 * For pipes: Check for CTRL-C: send interrupt signal to
4546 * child. Check for CTRL-D: EOF, close pipe to child.
4547 */
4548 if (len == 1 && cmd != NULL)
4549 {
4550 if (ta_buf[ta_len] == Ctrl_C)
4551 {
4552 /* Learn what exit code is expected, for
4553 * now put 9 as SIGKILL */
4554 TerminateProcess(pi.hProcess, 9);
4555 }
4556 if (ta_buf[ta_len] == Ctrl_D)
4557 {
4558 CloseHandle(g_hChildStd_IN_Wr);
4559 g_hChildStd_IN_Wr = NULL;
4560 }
4561 }
4562
4563 /* replace K_BS by <BS> and K_DEL by <DEL> */
4564 for (i = ta_len; i < ta_len + len; ++i)
4565 {
4566 if (ta_buf[i] == CSI && len - i > 2)
4567 {
4568 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4569 if (c == K_DEL || c == K_KDEL || c == K_BS)
4570 {
4571 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4572 (size_t)(len - i - 2));
4573 if (c == K_DEL || c == K_KDEL)
4574 ta_buf[i] = DEL;
4575 else
4576 ta_buf[i] = Ctrl_H;
4577 len -= 2;
4578 }
4579 }
4580 else if (ta_buf[i] == '\r')
4581 ta_buf[i] = '\n';
4582# ifdef FEAT_MBYTE
4583 if (has_mbyte)
4584 i += (*mb_ptr2len_len)(ta_buf + i,
4585 ta_len + len - i) - 1;
4586# endif
4587 }
4588
4589 /*
4590 * For pipes: echo the typed characters. For a pty this
4591 * does not seem to work.
4592 */
4593 for (i = ta_len; i < ta_len + len; ++i)
4594 {
4595 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4596 msg_putchar(ta_buf[i]);
4597# ifdef FEAT_MBYTE
4598 else if (has_mbyte)
4599 {
4600 int l = (*mb_ptr2len)(ta_buf + i);
4601
4602 msg_outtrans_len(ta_buf + i, l);
4603 i += l - 1;
4604 }
4605# endif
4606 else
4607 msg_outtrans_len(ta_buf + i, 1);
4608 }
4609 windgoto(msg_row, msg_col);
4610 out_flush();
4611
4612 ta_len += len;
4613
4614 /*
4615 * Write the characters to the child, unless EOF has been
4616 * typed for pipes. Write one character at a time, to
4617 * avoid losing too much typeahead. When writing buffer
4618 * lines, drop the typed characters (only check for
4619 * CTRL-C).
4620 */
4621 if (options & SHELL_WRITE)
4622 ta_len = 0;
4623 else if (g_hChildStd_IN_Wr != NULL)
4624 {
4625 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4626 1, &len, NULL);
4627 // if we are typing in, we want to keep things reactive
4628 delay = 1;
4629 if (len > 0)
4630 {
4631 ta_len -= len;
4632 mch_memmove(ta_buf, ta_buf + len, ta_len);
4633 }
4634 }
4635 }
4636 }
4637 }
4638
4639 if (ta_len)
4640 ui_inchar_undo(ta_buf, ta_len);
4641
4642 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4643 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004644 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004645 break;
4646 }
4647
4648 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004649 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004650
4651 /* We start waiting for a very short time and then increase it, so
4652 * that we respond quickly when the process is quick, and don't
4653 * consume too much overhead when it's slow. */
4654 if (delay < 50)
4655 delay += 10;
4656 }
4657
4658 /* Close the pipe */
4659 CloseHandle(g_hChildStd_OUT_Rd);
4660 if (g_hChildStd_IN_Wr != NULL)
4661 CloseHandle(g_hChildStd_IN_Wr);
4662
4663 WaitForSingleObject(pi.hProcess, INFINITE);
4664
4665 /* Get the command exit code */
4666 GetExitCodeProcess(pi.hProcess, &ret);
4667
4668 if (options & SHELL_READ)
4669 {
4670 if (ga.ga_len > 0)
4671 {
4672 append_ga_line(&ga);
4673 /* remember that the NL was missing */
4674 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4675 }
4676 else
4677 curbuf->b_no_eol_lnum = 0;
4678 ga_clear(&ga);
4679 }
4680
4681 /* Close the handles to the subprocess, so that it goes away */
4682 CloseHandle(pi.hThread);
4683 CloseHandle(pi.hProcess);
4684
4685 return ret;
4686}
4687
4688 static int
4689mch_system(char *cmd, int options)
4690{
4691 /* if we can pipe and the shelltemp option is off */
4692 if (allowPiping && !p_stmp)
4693 return mch_system_piped(cmd, options);
4694 else
4695 return mch_system_classic(cmd, options);
4696}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697#else
4698
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004699# ifdef FEAT_MBYTE
4700 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004701mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004702{
4703 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4704 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004705 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004706 if (wcmd != NULL)
4707 {
4708 int ret = _wsystem(wcmd);
4709 vim_free(wcmd);
4710 return ret;
4711 }
4712 }
4713 return system(cmd);
4714}
4715# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004716# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004718
4719#endif
4720
4721/*
4722 * Either execute a command by calling the shell or start a new shell
4723 */
4724 int
4725mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004726 char_u *cmd,
4727 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004728{
4729 int x = 0;
4730 int tmode = cur_tmode;
4731#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004732 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004733# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004734 int did_set_title = FALSE;
4735
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004736 /* Change the title to reflect that we are in a subshell. */
4737 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4738 {
4739 WCHAR szShellTitle[512];
4740
4741 if (GetConsoleTitleW(szShellTitle,
4742 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4743 {
4744 if (cmd == NULL)
4745 wcscat(szShellTitle, L" :sh");
4746 else
4747 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004748 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004749
4750 if (wn != NULL)
4751 {
4752 wcscat(szShellTitle, L" - !");
4753 if ((wcslen(szShellTitle) + wcslen(wn) <
4754 sizeof(szShellTitle)/sizeof(WCHAR)))
4755 wcscat(szShellTitle, wn);
4756 SetConsoleTitleW(szShellTitle);
4757 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004758 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004759 }
4760 }
4761 }
4762 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004763 if (!did_set_title)
4764# endif
4765 /* Change the title to reflect that we are in a subshell. */
4766 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004767 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004768 if (cmd == NULL)
4769 strcat(szShellTitle, " :sh");
4770 else
4771 {
4772 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004773 if ((strlen(szShellTitle) + strlen((char *)cmd)
4774 < sizeof(szShellTitle)))
4775 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004776 }
4777 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004779#endif
4780
4781 out_flush();
4782
4783#ifdef MCH_WRITE_DUMP
4784 if (fdDump)
4785 {
4786 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4787 fflush(fdDump);
4788 }
4789#endif
4790
4791 /*
4792 * Catch all deadly signals while running the external command, because a
4793 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4794 */
4795 signal(SIGINT, SIG_IGN);
4796#if defined(__GNUC__) && !defined(__MINGW32__)
4797 signal(SIGKILL, SIG_IGN);
4798#else
4799 signal(SIGBREAK, SIG_IGN);
4800#endif
4801 signal(SIGILL, SIG_IGN);
4802 signal(SIGFPE, SIG_IGN);
4803 signal(SIGSEGV, SIG_IGN);
4804 signal(SIGTERM, SIG_IGN);
4805 signal(SIGABRT, SIG_IGN);
4806
4807 if (options & SHELL_COOKED)
4808 settmode(TMODE_COOK); /* set to normal mode */
4809
4810 if (cmd == NULL)
4811 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004812 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813 }
4814 else
4815 {
4816 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004817 char_u *newcmd = NULL;
4818 char_u *cmdbase = cmd;
4819 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004820
4821 /* Skip a leading ", ( and "(. */
4822 if (*cmdbase == '"' )
4823 ++cmdbase;
4824 if (*cmdbase == '(')
4825 ++cmdbase;
4826
4827 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4828 {
4829 STARTUPINFO si;
4830 PROCESS_INFORMATION pi;
4831 DWORD flags = CREATE_NEW_CONSOLE;
4832 char_u *p;
4833
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004834 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004835 si.cb = sizeof(si);
4836 si.lpReserved = NULL;
4837 si.lpDesktop = NULL;
4838 si.lpTitle = NULL;
4839 si.dwFlags = 0;
4840 si.cbReserved2 = 0;
4841 si.lpReserved2 = NULL;
4842
4843 cmdbase = skipwhite(cmdbase + 5);
4844 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4845 && vim_iswhite(cmdbase[4]))
4846 {
4847 cmdbase = skipwhite(cmdbase + 4);
4848 si.dwFlags = STARTF_USESHOWWINDOW;
4849 si.wShowWindow = SW_SHOWMINNOACTIVE;
4850 }
4851 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4852 && vim_iswhite(cmdbase[2]))
4853 {
4854 cmdbase = skipwhite(cmdbase + 2);
4855 flags = CREATE_NO_WINDOW;
4856 si.dwFlags = STARTF_USESTDHANDLES;
4857 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004858 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004859 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004860 NULL, // Security att.
4861 OPEN_EXISTING, // Open flags
4862 FILE_ATTRIBUTE_NORMAL, // File att.
4863 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004864 si.hStdOutput = si.hStdInput;
4865 si.hStdError = si.hStdInput;
4866 }
4867
4868 /* Remove a trailing ", ) and )" if they have a match
4869 * at the start of the command. */
4870 if (cmdbase > cmd)
4871 {
4872 p = cmdbase + STRLEN(cmdbase);
4873 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4874 *--p = NUL;
4875 if (p > cmdbase && p[-1] == ')'
4876 && (*cmd =='(' || cmd[1] == '('))
4877 *--p = NUL;
4878 }
4879
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004880 newcmd = cmdbase;
4881 unescape_shellxquote(cmdbase, p_sxe);
4882
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004883 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004884 * If creating new console, arguments are passed to the
4885 * 'cmd.exe' as-is. If it's not, arguments are not treated
4886 * correctly for current 'cmd.exe'. So unescape characters in
4887 * shellxescape except '|' for avoiding to be treated as
4888 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004889 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004890 if (flags != CREATE_NEW_CONSOLE)
4891 {
4892 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004893 char_u *cmd_shell = mch_getenv("COMSPEC");
4894
4895 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004896 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004897
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004898 subcmd = vim_strsave_escaped_ext(cmdbase,
4899 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004900 if (subcmd != NULL)
4901 {
4902 /* make "cmd.exe /c arguments" */
4903 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004904 newcmd = lalloc(cmdlen, TRUE);
4905 if (newcmd != NULL)
4906 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004907 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004908 else
4909 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004910 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004911 }
4912 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004913
4914 /*
4915 * Now, start the command as a process, so that it doesn't
4916 * inherit our handles which causes unpleasant dangling swap
4917 * files if we exit before the spawned process
4918 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004919 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004920 x = 0;
4921 else
4922 {
4923 x = -1;
4924#ifdef FEAT_GUI_W32
4925 EMSG(_("E371: Command not found"));
4926#endif
4927 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004928
4929 if (newcmd != cmdbase)
4930 vim_free(newcmd);
4931
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004932 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004933 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004934 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004935 CloseHandle(si.hStdInput);
4936 }
4937 /* Close the handles to the subprocess, so that it goes away */
4938 CloseHandle(pi.hThread);
4939 CloseHandle(pi.hProcess);
4940 }
4941 else
4942 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004943 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004945 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004946#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004947 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4948
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004949 newcmd = lalloc(cmdlen, TRUE);
4950 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004951 {
4952#if defined(FEAT_GUI_W32)
4953 if (need_vimrun_warning)
4954 {
4955 MessageBox(NULL,
4956 _("VIMRUN.EXE not found in your $PATH.\n"
4957 "External commands will not pause after completion.\n"
4958 "See :help win32-vimrun for more information."),
4959 _("Vim Warning"),
4960 MB_ICONWARNING);
4961 need_vimrun_warning = FALSE;
4962 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004963 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964 /* Use vimrun to execute the command. It opens a console
4965 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004966 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967 vimrun_path,
4968 (msg_silent != 0 || (options & SHELL_DOOUT))
4969 ? "-s " : "",
4970 p_sh, p_shcf, cmd);
4971 else
4972#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004973 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004974 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004975 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004976 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978 }
4979 }
4980
4981 if (tmode == TMODE_RAW)
4982 settmode(TMODE_RAW); /* set to raw mode */
4983
4984 /* Print the return value, unless "vimrun" was used. */
4985 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4986#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004987 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4988 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989#endif
4990 )
4991 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004992 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 msg_putchar('\n');
4994 }
4995#ifdef FEAT_TITLE
4996 resettitle();
4997#endif
4998
4999 signal(SIGINT, SIG_DFL);
5000#if defined(__GNUC__) && !defined(__MINGW32__)
5001 signal(SIGKILL, SIG_DFL);
5002#else
5003 signal(SIGBREAK, SIG_DFL);
5004#endif
5005 signal(SIGILL, SIG_DFL);
5006 signal(SIGFPE, SIG_DFL);
5007 signal(SIGSEGV, SIG_DFL);
5008 signal(SIGTERM, SIG_DFL);
5009 signal(SIGABRT, SIG_DFL);
5010
5011 return x;
5012}
5013
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005014#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005015 static HANDLE
5016job_io_file_open(
5017 char_u *fname,
5018 DWORD dwDesiredAccess,
5019 DWORD dwShareMode,
5020 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5021 DWORD dwCreationDisposition,
5022 DWORD dwFlagsAndAttributes)
5023{
5024 HANDLE h;
5025# ifdef FEAT_MBYTE
5026 WCHAR *wn = NULL;
5027 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5028 {
5029 wn = enc_to_utf16(fname, NULL);
5030 if (wn != NULL)
5031 {
5032 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5033 lpSecurityAttributes, dwCreationDisposition,
5034 dwFlagsAndAttributes, NULL);
5035 vim_free(wn);
5036 if (h == INVALID_HANDLE_VALUE
5037 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5038 wn = NULL;
5039 }
5040 }
5041 if (wn == NULL)
5042# endif
5043
5044 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5045 lpSecurityAttributes, dwCreationDisposition,
5046 dwFlagsAndAttributes, NULL);
5047 return h;
5048}
5049
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005050 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005051mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005052{
5053 STARTUPINFO si;
5054 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005055 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005056 SECURITY_ATTRIBUTES saAttr;
5057 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005058 HANDLE ifd[2];
5059 HANDLE ofd[2];
5060 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005061
5062 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5063 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5064 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5065 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5066 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5067 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5068 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5069
5070 if (use_out_for_err && use_null_for_out)
5071 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005072
5073 ifd[0] = INVALID_HANDLE_VALUE;
5074 ifd[1] = INVALID_HANDLE_VALUE;
5075 ofd[0] = INVALID_HANDLE_VALUE;
5076 ofd[1] = INVALID_HANDLE_VALUE;
5077 efd[0] = INVALID_HANDLE_VALUE;
5078 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005079
Bram Moolenaar76467df2016-02-12 19:30:26 +01005080 jo = CreateJobObject(NULL, NULL);
5081 if (jo == NULL)
5082 {
5083 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005084 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005085 }
5086
5087 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005088 ZeroMemory(&si, sizeof(si));
5089 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005090 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005091 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005092
Bram Moolenaard8070362016-02-15 21:56:54 +01005093 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5094 saAttr.bInheritHandle = TRUE;
5095 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005096
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005097 if (use_file_for_in)
5098 {
5099 char_u *fname = options->jo_io_name[PART_IN];
5100
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005101 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5102 FILE_SHARE_READ | FILE_SHARE_WRITE,
5103 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5104 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005105 {
5106 EMSG2(_(e_notopen), fname);
5107 goto failed;
5108 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005109 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005110 else if (!use_null_for_in &&
5111 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5112 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005113 goto failed;
5114
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005115 if (use_file_for_out)
5116 {
5117 char_u *fname = options->jo_io_name[PART_OUT];
5118
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005119 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5120 FILE_SHARE_READ | FILE_SHARE_WRITE,
5121 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5122 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005123 {
5124 EMSG2(_(e_notopen), fname);
5125 goto failed;
5126 }
5127 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005128 else if (!use_null_for_out &&
5129 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5130 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005131 goto failed;
5132
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005133 if (use_file_for_err)
5134 {
5135 char_u *fname = options->jo_io_name[PART_ERR];
5136
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005137 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5138 FILE_SHARE_READ | FILE_SHARE_WRITE,
5139 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5140 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005141 {
5142 EMSG2(_(e_notopen), fname);
5143 goto failed;
5144 }
5145 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005146 else if (!use_out_for_err && !use_null_for_err &&
5147 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005148 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005149 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005150
Bram Moolenaard8070362016-02-15 21:56:54 +01005151 si.dwFlags |= STARTF_USESTDHANDLES;
5152 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005153 si.hStdOutput = ofd[1];
5154 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5155
5156 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5157 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005158 if (options->jo_set & JO_CHANNEL)
5159 {
5160 channel = options->jo_channel;
5161 if (channel != NULL)
5162 ++channel->ch_refcount;
5163 }
5164 else
5165 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005166 if (channel == NULL)
5167 goto failed;
5168 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005169
5170 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005171 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005172 CREATE_DEFAULT_ERROR_MODE |
5173 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005174 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005175 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005176 {
5177 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005178 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005179 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005180 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005181
5182 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005183 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005184 /* if failing, switch the way to terminate
5185 * process with TerminateProcess. */
5186 CloseHandle(jo);
5187 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005188 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005189 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005190 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005191 job->jv_proc_info = pi;
5192 job->jv_job_object = jo;
5193 job->jv_status = JOB_STARTED;
5194
Bram Moolenaar94d01912016-03-08 13:48:51 +01005195 if (!use_file_for_in)
5196 CloseHandle(ifd[0]);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005197 if (!use_file_for_out)
5198 CloseHandle(ofd[1]);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005199 if (!use_out_for_err && !use_file_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005200 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005201
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005202 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005203 if (channel != NULL)
5204 {
5205 channel_set_pipes(channel,
5206 use_file_for_in || use_null_for_in
5207 ? INVALID_FD : (sock_T)ifd[1],
5208 use_file_for_out || use_null_for_out
5209 ? INVALID_FD : (sock_T)ofd[0],
5210 use_out_for_err || use_file_for_err || use_null_for_err
5211 ? INVALID_FD : (sock_T)efd[0]);
5212 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005213 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005214 return;
5215
5216failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005217 CloseHandle(ifd[0]);
5218 CloseHandle(ofd[0]);
5219 CloseHandle(efd[0]);
5220 CloseHandle(ifd[1]);
5221 CloseHandle(ofd[1]);
5222 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005223 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005224}
5225
5226 char *
5227mch_job_status(job_T *job)
5228{
5229 DWORD dwExitCode = 0;
5230
Bram Moolenaar76467df2016-02-12 19:30:26 +01005231 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5232 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005233 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005234 job->jv_status = JOB_ENDED;
Bram Moolenaareab089d2016-02-21 19:32:02 +01005235 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005236 return "dead";
5237 }
5238 return "run";
5239}
5240
5241 int
5242mch_stop_job(job_T *job, char_u *how)
5243{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005244 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005245
Bram Moolenaar923d9262016-02-25 20:56:01 +01005246 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005247 {
5248 if (job->jv_job_object != NULL)
5249 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5250 else
5251 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5252 }
5253
5254 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5255 return FAIL;
5256 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005257 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5258 job->jv_proc_info.dwProcessId)
5259 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005260 FreeConsole();
5261 return ret;
5262}
5263
5264/*
5265 * Clear the data related to "job".
5266 */
5267 void
5268mch_clear_job(job_T *job)
5269{
5270 if (job->jv_status != JOB_FAILED)
5271 {
5272 if (job->jv_job_object != NULL)
5273 CloseHandle(job->jv_job_object);
5274 CloseHandle(job->jv_proc_info.hProcess);
5275 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005276}
5277#endif
5278
Bram Moolenaar071d4272004-06-13 20:20:40 +00005279
5280#ifndef FEAT_GUI_W32
5281
5282/*
5283 * Start termcap mode
5284 */
5285 static void
5286termcap_mode_start(void)
5287{
5288 DWORD cmodein;
5289
5290 if (g_fTermcapMode)
5291 return;
5292
5293 SaveConsoleBuffer(&g_cbNonTermcap);
5294
5295 if (g_cbTermcap.IsValid)
5296 {
5297 /*
5298 * We've been in termcap mode before. Restore certain screen
5299 * characteristics, including the buffer size and the window
5300 * size. Since we will be redrawing the screen, we don't need
5301 * to restore the actual contents of the buffer.
5302 */
5303 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5304 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5305 Rows = g_cbTermcap.Info.dwSize.Y;
5306 Columns = g_cbTermcap.Info.dwSize.X;
5307 }
5308 else
5309 {
5310 /*
5311 * This is our first time entering termcap mode. Clear the console
5312 * screen buffer, and resize the buffer to match the current window
5313 * size. We will use this as the size of our editing environment.
5314 */
5315 ClearConsoleBuffer(g_attrCurrent);
5316 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5317 }
5318
5319#ifdef FEAT_TITLE
5320 resettitle();
5321#endif
5322
5323 GetConsoleMode(g_hConIn, &cmodein);
5324#ifdef FEAT_MOUSE
5325 if (g_fMouseActive)
5326 cmodein |= ENABLE_MOUSE_INPUT;
5327 else
5328 cmodein &= ~ENABLE_MOUSE_INPUT;
5329#endif
5330 cmodein |= ENABLE_WINDOW_INPUT;
5331 SetConsoleMode(g_hConIn, cmodein);
5332
5333 redraw_later_clear();
5334 g_fTermcapMode = TRUE;
5335}
5336
5337
5338/*
5339 * End termcap mode
5340 */
5341 static void
5342termcap_mode_end(void)
5343{
5344 DWORD cmodein;
5345 ConsoleBuffer *cb;
5346 COORD coord;
5347 DWORD dwDummy;
5348
5349 if (!g_fTermcapMode)
5350 return;
5351
5352 SaveConsoleBuffer(&g_cbTermcap);
5353
5354 GetConsoleMode(g_hConIn, &cmodein);
5355 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5356 SetConsoleMode(g_hConIn, cmodein);
5357
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005358#ifdef FEAT_RESTORE_ORIG_SCREEN
5359 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5360#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005361 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005362#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005363 RestoreConsoleBuffer(cb, p_rs);
5364 SetConsoleCursorInfo(g_hConOut, &g_cci);
5365
5366 if (p_rs || exiting)
5367 {
5368 /*
5369 * Clear anything that happens to be on the current line.
5370 */
5371 coord.X = 0;
5372 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5373 FillConsoleOutputCharacter(g_hConOut, ' ',
5374 cb->Info.dwSize.X, coord, &dwDummy);
5375 /*
5376 * The following is just for aesthetics. If we are exiting without
5377 * restoring the screen, then we want to have a prompt string
5378 * appear at the bottom line. However, the command interpreter
5379 * seems to always advance the cursor one line before displaying
5380 * the prompt string, which causes the screen to scroll. To
5381 * counter this, move the cursor up one line before exiting.
5382 */
5383 if (exiting && !p_rs)
5384 coord.Y--;
5385 /*
5386 * Position the cursor at the leftmost column of the desired row.
5387 */
5388 SetConsoleCursorPosition(g_hConOut, coord);
5389 }
5390
5391 g_fTermcapMode = FALSE;
5392}
5393#endif /* FEAT_GUI_W32 */
5394
5395
5396#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005397/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005398 void
5399mch_write(
5400 char_u *s,
5401 int len)
5402{
5403 /* never used */
5404}
5405
5406#else
5407
5408/*
5409 * clear `n' chars, starting from `coord'
5410 */
5411 static void
5412clear_chars(
5413 COORD coord,
5414 DWORD n)
5415{
5416 DWORD dwDummy;
5417
5418 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5419 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5420}
5421
5422
5423/*
5424 * Clear the screen
5425 */
5426 static void
5427clear_screen(void)
5428{
5429 g_coord.X = g_coord.Y = 0;
5430 clear_chars(g_coord, Rows * Columns);
5431}
5432
5433
5434/*
5435 * Clear to end of display
5436 */
5437 static void
5438clear_to_end_of_display(void)
5439{
5440 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5441 * Columns + (Columns - g_coord.X));
5442}
5443
5444
5445/*
5446 * Clear to end of line
5447 */
5448 static void
5449clear_to_end_of_line(void)
5450{
5451 clear_chars(g_coord, Columns - g_coord.X);
5452}
5453
5454
5455/*
5456 * Scroll the scroll region up by `cLines' lines
5457 */
5458 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005459scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005460{
5461 COORD oldcoord = g_coord;
5462
5463 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5464 delete_lines(cLines);
5465
5466 g_coord = oldcoord;
5467}
5468
5469
5470/*
5471 * Set the scroll region
5472 */
5473 static void
5474set_scroll_region(
5475 unsigned left,
5476 unsigned top,
5477 unsigned right,
5478 unsigned bottom)
5479{
5480 if (left >= right
5481 || top >= bottom
5482 || right > (unsigned) Columns - 1
5483 || bottom > (unsigned) Rows - 1)
5484 return;
5485
5486 g_srScrollRegion.Left = left;
5487 g_srScrollRegion.Top = top;
5488 g_srScrollRegion.Right = right;
5489 g_srScrollRegion.Bottom = bottom;
5490}
5491
5492
5493/*
5494 * Insert `cLines' lines at the current cursor position
5495 */
5496 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005497insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498{
5499 SMALL_RECT source;
5500 COORD dest;
5501 CHAR_INFO fill;
5502
5503 dest.X = 0;
5504 dest.Y = g_coord.Y + cLines;
5505
5506 source.Left = 0;
5507 source.Top = g_coord.Y;
5508 source.Right = g_srScrollRegion.Right;
5509 source.Bottom = g_srScrollRegion.Bottom - cLines;
5510
5511 fill.Char.AsciiChar = ' ';
5512 fill.Attributes = g_attrCurrent;
5513
5514 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5515
5516 /* Here we have to deal with a win32 console flake: If the scroll
5517 * region looks like abc and we scroll c to a and fill with d we get
5518 * cbd... if we scroll block c one line at a time to a, we get cdd...
5519 * vim expects cdd consistently... So we have to deal with that
5520 * here... (this also occurs scrolling the same way in the other
5521 * direction). */
5522
5523 if (source.Bottom < dest.Y)
5524 {
5525 COORD coord;
5526
5527 coord.X = 0;
5528 coord.Y = source.Bottom;
5529 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5530 }
5531}
5532
5533
5534/*
5535 * Delete `cLines' lines at the current cursor position
5536 */
5537 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005538delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005539{
5540 SMALL_RECT source;
5541 COORD dest;
5542 CHAR_INFO fill;
5543 int nb;
5544
5545 dest.X = 0;
5546 dest.Y = g_coord.Y;
5547
5548 source.Left = 0;
5549 source.Top = g_coord.Y + cLines;
5550 source.Right = g_srScrollRegion.Right;
5551 source.Bottom = g_srScrollRegion.Bottom;
5552
5553 fill.Char.AsciiChar = ' ';
5554 fill.Attributes = g_attrCurrent;
5555
5556 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5557
5558 /* Here we have to deal with a win32 console flake: If the scroll
5559 * region looks like abc and we scroll c to a and fill with d we get
5560 * cbd... if we scroll block c one line at a time to a, we get cdd...
5561 * vim expects cdd consistently... So we have to deal with that
5562 * here... (this also occurs scrolling the same way in the other
5563 * direction). */
5564
5565 nb = dest.Y + (source.Bottom - source.Top) + 1;
5566
5567 if (nb < source.Top)
5568 {
5569 COORD coord;
5570
5571 coord.X = 0;
5572 coord.Y = nb;
5573 clear_chars(coord, Columns * (source.Top - nb));
5574 }
5575}
5576
5577
5578/*
5579 * Set the cursor position
5580 */
5581 static void
5582gotoxy(
5583 unsigned x,
5584 unsigned y)
5585{
5586 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5587 return;
5588
5589 /* external cursor coords are 1-based; internal are 0-based */
5590 g_coord.X = x - 1;
5591 g_coord.Y = y - 1;
5592 SetConsoleCursorPosition(g_hConOut, g_coord);
5593}
5594
5595
5596/*
5597 * Set the current text attribute = (foreground | background)
5598 * See ../doc/os_win32.txt for the numbers.
5599 */
5600 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005601textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005603 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005604
5605 SetConsoleTextAttribute(g_hConOut, wAttr);
5606}
5607
5608
5609 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005610textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005611{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005612 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005613
5614 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5615}
5616
5617
5618 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005619textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005621 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005622
5623 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5624}
5625
5626
5627/*
5628 * restore the default text attribute (whatever we started with)
5629 */
5630 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005631normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632{
5633 textattr(g_attrDefault);
5634}
5635
5636
5637static WORD g_attrPreStandout = 0;
5638
5639/*
5640 * Make the text standout, by brightening it
5641 */
5642 static void
5643standout(void)
5644{
5645 g_attrPreStandout = g_attrCurrent;
5646 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5647}
5648
5649
5650/*
5651 * Turn off standout mode
5652 */
5653 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005654standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005655{
5656 if (g_attrPreStandout)
5657 {
5658 textattr(g_attrPreStandout);
5659 g_attrPreStandout = 0;
5660 }
5661}
5662
5663
5664/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005665 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666 */
5667 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005668mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669{
5670 char_u *p;
5671 int n;
5672
5673 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5674 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5675 if (T_ME[0] == ESC && T_ME[1] == '|')
5676 {
5677 p = T_ME + 2;
5678 n = getdigits(&p);
5679 if (*p == 'm' && n > 0)
5680 {
5681 cterm_normal_fg_color = (n & 0xf) + 1;
5682 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5683 }
5684 }
5685}
5686
5687
5688/*
5689 * visual bell: flash the screen
5690 */
5691 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005692visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693{
5694 COORD coordOrigin = {0, 0};
5695 WORD attrFlash = ~g_attrCurrent & 0xff;
5696
5697 DWORD dwDummy;
5698 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5699
5700 if (oldattrs == NULL)
5701 return;
5702 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5703 coordOrigin, &dwDummy);
5704 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5705 coordOrigin, &dwDummy);
5706
5707 Sleep(15); /* wait for 15 msec */
5708 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5709 coordOrigin, &dwDummy);
5710 vim_free(oldattrs);
5711}
5712
5713
5714/*
5715 * Make the cursor visible or invisible
5716 */
5717 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005718cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719{
5720 s_cursor_visible = fVisible;
5721#ifdef MCH_CURSOR_SHAPE
5722 mch_update_cursor();
5723#endif
5724}
5725
5726
5727/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005728 * write `cbToWrite' bytes in `pchBuf' to the screen
5729 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005731 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005732write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005733 char_u *pchBuf,
5734 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735{
5736 COORD coord = g_coord;
5737 DWORD written;
5738
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005739#ifdef FEAT_MBYTE
5740 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5741 {
5742 static WCHAR *unicodebuf = NULL;
5743 static int unibuflen = 0;
5744 int length;
5745 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005747 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5748 if (unicodebuf == NULL || length > unibuflen)
5749 {
5750 vim_free(unicodebuf);
5751 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5752 unibuflen = length;
5753 }
5754 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5755 unicodebuf, unibuflen);
5756
5757 cells = mb_string2cells(pchBuf, cbToWrite);
5758 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5759 coord, &written);
5760 /* When writing fails or didn't write a single character, pretend one
5761 * character was written, otherwise we get stuck. */
5762 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5763 coord, &cchwritten) == 0
5764 || cchwritten == 0)
5765 cchwritten = 1;
5766
5767 if (cchwritten == length)
5768 {
5769 written = cbToWrite;
5770 g_coord.X += (SHORT)cells;
5771 }
5772 else
5773 {
5774 char_u *p = pchBuf;
5775 for (n = 0; n < cchwritten; n++)
5776 mb_cptr_adv(p);
5777 written = p - pchBuf;
5778 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5779 }
5780 }
5781 else
5782#endif
5783 {
5784 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5785 coord, &written);
5786 /* When writing fails or didn't write a single character, pretend one
5787 * character was written, otherwise we get stuck. */
5788 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5789 coord, &written) == 0
5790 || written == 0)
5791 written = 1;
5792
5793 g_coord.X += (SHORT) written;
5794 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795
5796 while (g_coord.X > g_srScrollRegion.Right)
5797 {
5798 g_coord.X -= (SHORT) Columns;
5799 if (g_coord.Y < g_srScrollRegion.Bottom)
5800 g_coord.Y++;
5801 }
5802
5803 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5804
5805 return written;
5806}
5807
5808
5809/*
5810 * mch_write(): write the output buffer to the screen, translating ESC
5811 * sequences into calls to console output routines.
5812 */
5813 void
5814mch_write(
5815 char_u *s,
5816 int len)
5817{
5818 s[len] = NUL;
5819
5820 if (!term_console)
5821 {
5822 write(1, s, (unsigned)len);
5823 return;
5824 }
5825
5826 /* translate ESC | sequences into faked bios calls */
5827 while (len--)
5828 {
5829 /* optimization: use one single write_chars for runs of text,
5830 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005831 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832
5833 if (p_wd)
5834 {
5835 WaitForChar(p_wd);
5836 if (prefix != 0)
5837 prefix = 1;
5838 }
5839
5840 if (prefix != 0)
5841 {
5842 DWORD nWritten;
5843
5844 nWritten = write_chars(s, prefix);
5845#ifdef MCH_WRITE_DUMP
5846 if (fdDump)
5847 {
5848 fputc('>', fdDump);
5849 fwrite(s, sizeof(char_u), nWritten, fdDump);
5850 fputs("<\n", fdDump);
5851 }
5852#endif
5853 len -= (nWritten - 1);
5854 s += nWritten;
5855 }
5856 else if (s[0] == '\n')
5857 {
5858 /* \n, newline: go to the beginning of the next line or scroll */
5859 if (g_coord.Y == g_srScrollRegion.Bottom)
5860 {
5861 scroll(1);
5862 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5863 }
5864 else
5865 {
5866 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5867 }
5868#ifdef MCH_WRITE_DUMP
5869 if (fdDump)
5870 fputs("\\n\n", fdDump);
5871#endif
5872 s++;
5873 }
5874 else if (s[0] == '\r')
5875 {
5876 /* \r, carriage return: go to beginning of line */
5877 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5878#ifdef MCH_WRITE_DUMP
5879 if (fdDump)
5880 fputs("\\r\n", fdDump);
5881#endif
5882 s++;
5883 }
5884 else if (s[0] == '\b')
5885 {
5886 /* \b, backspace: move cursor one position left */
5887 if (g_coord.X > g_srScrollRegion.Left)
5888 g_coord.X--;
5889 else if (g_coord.Y > g_srScrollRegion.Top)
5890 {
5891 g_coord.X = g_srScrollRegion.Right;
5892 g_coord.Y--;
5893 }
5894 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5895#ifdef MCH_WRITE_DUMP
5896 if (fdDump)
5897 fputs("\\b\n", fdDump);
5898#endif
5899 s++;
5900 }
5901 else if (s[0] == '\a')
5902 {
5903 /* \a, bell */
5904 MessageBeep(0xFFFFFFFF);
5905#ifdef MCH_WRITE_DUMP
5906 if (fdDump)
5907 fputs("\\a\n", fdDump);
5908#endif
5909 s++;
5910 }
5911 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5912 {
5913#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005914 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005916 char_u *p;
5917 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005918
5919 switch (s[2])
5920 {
5921 /* one or two numeric arguments, separated by ';' */
5922
5923 case '0': case '1': case '2': case '3': case '4':
5924 case '5': case '6': case '7': case '8': case '9':
5925 p = s + 2;
5926 arg1 = getdigits(&p); /* no check for length! */
5927 if (p > s + len)
5928 break;
5929
5930 if (*p == ';')
5931 {
5932 ++p;
5933 arg2 = getdigits(&p); /* no check for length! */
5934 if (p > s + len)
5935 break;
5936
5937 if (*p == 'H')
5938 gotoxy(arg2, arg1);
5939 else if (*p == 'r')
5940 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5941 }
5942 else if (*p == 'A')
5943 {
5944 /* move cursor up arg1 lines in same column */
5945 gotoxy(g_coord.X + 1,
5946 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5947 }
5948 else if (*p == 'C')
5949 {
5950 /* move cursor right arg1 columns in same line */
5951 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5952 g_coord.Y + 1);
5953 }
5954 else if (*p == 'H')
5955 {
5956 gotoxy(1, arg1);
5957 }
5958 else if (*p == 'L')
5959 {
5960 insert_lines(arg1);
5961 }
5962 else if (*p == 'm')
5963 {
5964 if (arg1 == 0)
5965 normvideo();
5966 else
5967 textattr((WORD) arg1);
5968 }
5969 else if (*p == 'f')
5970 {
5971 textcolor((WORD) arg1);
5972 }
5973 else if (*p == 'b')
5974 {
5975 textbackground((WORD) arg1);
5976 }
5977 else if (*p == 'M')
5978 {
5979 delete_lines(arg1);
5980 }
5981
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005982 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005983 s = p + 1;
5984 break;
5985
5986
5987 /* Three-character escape sequences */
5988
5989 case 'A':
5990 /* move cursor up one line in same column */
5991 gotoxy(g_coord.X + 1,
5992 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5993 goto got3;
5994
5995 case 'B':
5996 visual_bell();
5997 goto got3;
5998
5999 case 'C':
6000 /* move cursor right one column in same line */
6001 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6002 g_coord.Y + 1);
6003 goto got3;
6004
6005 case 'E':
6006 termcap_mode_end();
6007 goto got3;
6008
6009 case 'F':
6010 standout();
6011 goto got3;
6012
6013 case 'f':
6014 standend();
6015 goto got3;
6016
6017 case 'H':
6018 gotoxy(1, 1);
6019 goto got3;
6020
6021 case 'j':
6022 clear_to_end_of_display();
6023 goto got3;
6024
6025 case 'J':
6026 clear_screen();
6027 goto got3;
6028
6029 case 'K':
6030 clear_to_end_of_line();
6031 goto got3;
6032
6033 case 'L':
6034 insert_lines(1);
6035 goto got3;
6036
6037 case 'M':
6038 delete_lines(1);
6039 goto got3;
6040
6041 case 'S':
6042 termcap_mode_start();
6043 goto got3;
6044
6045 case 'V':
6046 cursor_visible(TRUE);
6047 goto got3;
6048
6049 case 'v':
6050 cursor_visible(FALSE);
6051 goto got3;
6052
6053 got3:
6054 s += 3;
6055 len -= 2;
6056 }
6057
6058#ifdef MCH_WRITE_DUMP
6059 if (fdDump)
6060 {
6061 fputs("ESC | ", fdDump);
6062 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6063 fputc('\n', fdDump);
6064 }
6065#endif
6066 }
6067 else
6068 {
6069 /* Write a single character */
6070 DWORD nWritten;
6071
6072 nWritten = write_chars(s, 1);
6073#ifdef MCH_WRITE_DUMP
6074 if (fdDump)
6075 {
6076 fputc('>', fdDump);
6077 fwrite(s, sizeof(char_u), nWritten, fdDump);
6078 fputs("<\n", fdDump);
6079 }
6080#endif
6081
6082 len -= (nWritten - 1);
6083 s += nWritten;
6084 }
6085 }
6086
6087#ifdef MCH_WRITE_DUMP
6088 if (fdDump)
6089 fflush(fdDump);
6090#endif
6091}
6092
6093#endif /* FEAT_GUI_W32 */
6094
6095
6096/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006097 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006099/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100 void
6101mch_delay(
6102 long msec,
6103 int ignoreinput)
6104{
6105#ifdef FEAT_GUI_W32
6106 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006107#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006109# ifdef FEAT_MZSCHEME
6110 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6111 {
6112 int towait = p_mzq;
6113
6114 /* if msec is large enough, wait by portions in p_mzq */
6115 while (msec > 0)
6116 {
6117 mzvim_check_threads();
6118 if (msec < towait)
6119 towait = msec;
6120 Sleep(towait);
6121 msec -= towait;
6122 }
6123 }
6124 else
6125# endif
6126 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127 else
6128 WaitForChar(msec);
6129#endif
6130}
6131
6132
6133/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006134 * This version of remove is not scared by a readonly (backup) file.
6135 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136 * Return 0 for success, -1 for failure.
6137 */
6138 int
6139mch_remove(char_u *name)
6140{
6141#ifdef FEAT_MBYTE
6142 WCHAR *wn = NULL;
6143 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006144#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006145
Bram Moolenaar203258c2016-01-17 22:15:16 +01006146 /*
6147 * On Windows, deleting a directory's symbolic link is done by
6148 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6149 */
6150 if (mch_isdir(name) && mch_is_symbolic_link(name))
6151 return mch_rmdir(name);
6152
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006153 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6154
6155#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6157 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006158 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159 if (wn != NULL)
6160 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 n = DeleteFileW(wn) ? 0 : -1;
6162 vim_free(wn);
6163 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6164 return n;
6165 /* Retry with non-wide function (for Windows 98). */
6166 }
6167 }
6168#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006169 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170}
6171
6172
6173/*
6174 * check for an "interrupt signal": CTRL-break or CTRL-C
6175 */
6176 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006177mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178{
6179#ifndef FEAT_GUI_W32 /* never used */
6180 if (g_fCtrlCPressed || g_fCBrkPressed)
6181 {
6182 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6183 got_int = TRUE;
6184 }
6185#endif
6186}
6187
Bram Moolenaaree273972016-01-02 21:11:51 +01006188/* physical RAM to leave for the OS */
6189#define WINNT_RESERVE_BYTES (256*1024*1024)
6190#define WIN95_RESERVE_BYTES (8*1024*1024)
6191
6192/*
6193 * How much main memory in KiB that can be used by VIM.
6194 */
6195/*ARGSUSED*/
6196 long_u
6197mch_total_mem(int special)
6198{
6199 PlatformId();
6200#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6201 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6202 {
6203 MEMORYSTATUSEX ms;
6204
6205 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6206 * what fits in 32 bits. But it's not always available. */
6207 ms.dwLength = sizeof(MEMORYSTATUSEX);
6208 GlobalMemoryStatusEx(&ms);
6209 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6210 {
6211 /* Process address space fits in physical RAM, use all of it. */
6212 return (long_u)(ms.ullAvailVirtual / 1024);
6213 }
6214 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6215 {
6216 /* Catch old NT box or perverse hardware setup. */
6217 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6218 }
6219 /* Use physical RAM less reserve for OS + data. */
6220 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6221 }
6222 else
6223#endif
6224 {
6225 /* Pre-XP or 95 OS handling. */
6226 MEMORYSTATUS ms;
6227 long_u os_reserve_bytes;
6228
6229 ms.dwLength = sizeof(MEMORYSTATUS);
6230 GlobalMemoryStatus(&ms);
6231 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6232 {
6233 /* Process address space fits in physical RAM, use all of it. */
6234 return (long_u)(ms.dwAvailVirtual / 1024);
6235 }
6236 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6237 ? WINNT_RESERVE_BYTES
6238 : WIN95_RESERVE_BYTES;
6239 if (ms.dwTotalPhys <= os_reserve_bytes)
6240 {
6241 /* Catch old boxes or perverse hardware setup. */
6242 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6243 }
6244 /* Use physical RAM less reserve for OS + data. */
6245 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6246 }
6247}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249#ifdef FEAT_MBYTE
6250/*
6251 * Same code as below, but with wide functions and no comments.
6252 * Return 0 for success, non-zero for failure.
6253 */
6254 int
6255mch_wrename(WCHAR *wold, WCHAR *wnew)
6256{
6257 WCHAR *p;
6258 int i;
6259 WCHAR szTempFile[_MAX_PATH + 1];
6260 WCHAR szNewPath[_MAX_PATH + 1];
6261 HANDLE hf;
6262
6263 if (!mch_windows95())
6264 {
6265 p = wold;
6266 for (i = 0; wold[i] != NUL; ++i)
6267 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6268 && wold[i + 1] != 0)
6269 p = wold + i + 1;
6270 if ((int)(wold + i - p) < 8 || p[6] != '~')
6271 return (MoveFileW(wold, wnew) == 0);
6272 }
6273
6274 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6275 return -1;
6276 *p = NUL;
6277
6278 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6279 return -2;
6280
6281 if (!DeleteFileW(szTempFile))
6282 return -3;
6283
6284 if (!MoveFileW(wold, szTempFile))
6285 return -4;
6286
6287 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6288 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6289 return -5;
6290 if (!CloseHandle(hf))
6291 return -6;
6292
6293 if (!MoveFileW(szTempFile, wnew))
6294 {
6295 (void)MoveFileW(szTempFile, wold);
6296 return -7;
6297 }
6298
6299 DeleteFileW(szTempFile);
6300
6301 if (!DeleteFileW(wold))
6302 return -8;
6303
6304 return 0;
6305}
6306#endif
6307
6308
6309/*
6310 * mch_rename() works around a bug in rename (aka MoveFile) in
6311 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6312 * file whose short file name is "FOO.BAR" (its long file name will
6313 * be correct: "foo.bar~"). Because a file can be accessed by
6314 * either its SFN or its LFN, "foo.bar" has effectively been
6315 * renamed to "foo.bar", which is not at all what was wanted. This
6316 * seems to happen only when renaming files with three-character
6317 * extensions by appending a suffix that does not include ".".
6318 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6319 *
6320 * There is another problem, which isn't really a bug but isn't right either:
6321 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6322 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6323 * service pack 6. Doesn't seem to happen on Windows 98.
6324 *
6325 * Like rename(), returns 0 upon success, non-zero upon failure.
6326 * Should probably set errno appropriately when errors occur.
6327 */
6328 int
6329mch_rename(
6330 const char *pszOldFile,
6331 const char *pszNewFile)
6332{
6333 char szTempFile[_MAX_PATH+1];
6334 char szNewPath[_MAX_PATH+1];
6335 char *pszFilePart;
6336 HANDLE hf;
6337#ifdef FEAT_MBYTE
6338 WCHAR *wold = NULL;
6339 WCHAR *wnew = NULL;
6340 int retval = -1;
6341
6342 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6343 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006344 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6345 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 if (wold != NULL && wnew != NULL)
6347 retval = mch_wrename(wold, wnew);
6348 vim_free(wold);
6349 vim_free(wnew);
6350 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6351 return retval;
6352 /* Retry with non-wide function (for Windows 98). */
6353 }
6354#endif
6355
6356 /*
6357 * No need to play tricks if not running Windows 95, unless the file name
6358 * contains a "~" as the seventh character.
6359 */
6360 if (!mch_windows95())
6361 {
6362 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6363 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6364 return rename(pszOldFile, pszNewFile);
6365 }
6366
6367 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6368 * a directory, no error is returned and pszFilePart will be NULL. */
6369 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6370 || pszFilePart == NULL)
6371 return -1;
6372 *pszFilePart = NUL;
6373
6374 /* Get (and create) a unique temporary file name in directory of new file */
6375 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6376 return -2;
6377
6378 /* blow the temp file away */
6379 if (!DeleteFile(szTempFile))
6380 return -3;
6381
6382 /* rename old file to the temp file */
6383 if (!MoveFile(pszOldFile, szTempFile))
6384 return -4;
6385
6386 /* now create an empty file called pszOldFile; this prevents the operating
6387 * system using pszOldFile as an alias (SFN) if we're renaming within the
6388 * same directory. For example, we're editing a file called
6389 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6390 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6391 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006392 * cause all sorts of problems later in buf_write(). So, we create an
6393 * empty file called filena~1.txt and the system will have to find some
6394 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 */
6396 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6397 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6398 return -5;
6399 if (!CloseHandle(hf))
6400 return -6;
6401
6402 /* rename the temp file to the new file */
6403 if (!MoveFile(szTempFile, pszNewFile))
6404 {
6405 /* Renaming failed. Rename the file back to its old name, so that it
6406 * looks like nothing happened. */
6407 (void)MoveFile(szTempFile, pszOldFile);
6408
6409 return -7;
6410 }
6411
6412 /* Seems to be left around on Novell filesystems */
6413 DeleteFile(szTempFile);
6414
6415 /* finally, remove the empty old file */
6416 if (!DeleteFile(pszOldFile))
6417 return -8;
6418
6419 return 0; /* success */
6420}
6421
6422/*
6423 * Get the default shell for the current hardware platform
6424 */
6425 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006426default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006427{
6428 char* psz = NULL;
6429
6430 PlatformId();
6431
6432 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6433 psz = "cmd.exe";
6434 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6435 psz = "command.com";
6436
6437 return psz;
6438}
6439
6440/*
6441 * mch_access() extends access() to do more detailed check on network drives.
6442 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6443 */
6444 int
6445mch_access(char *n, int p)
6446{
6447 HANDLE hFile;
6448 DWORD am;
6449 int retval = -1; /* default: fail */
6450#ifdef FEAT_MBYTE
6451 WCHAR *wn = NULL;
6452
6453 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006454 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455#endif
6456
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006457 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458 {
6459 char TempName[_MAX_PATH + 16] = "";
6460#ifdef FEAT_MBYTE
6461 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6462#endif
6463
6464 if (p & R_OK)
6465 {
6466 /* Read check is performed by seeing if we can do a find file on
6467 * the directory for any file. */
6468#ifdef FEAT_MBYTE
6469 if (wn != NULL)
6470 {
6471 int i;
6472 WIN32_FIND_DATAW d;
6473
6474 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6475 TempNameW[i] = wn[i];
6476 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6477 TempNameW[i++] = '\\';
6478 TempNameW[i++] = '*';
6479 TempNameW[i++] = 0;
6480
6481 hFile = FindFirstFileW(TempNameW, &d);
6482 if (hFile == INVALID_HANDLE_VALUE)
6483 {
6484 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6485 goto getout;
6486
6487 /* Retry with non-wide function (for Windows 98). */
6488 vim_free(wn);
6489 wn = NULL;
6490 }
6491 else
6492 (void)FindClose(hFile);
6493 }
6494 if (wn == NULL)
6495#endif
6496 {
6497 char *pch;
6498 WIN32_FIND_DATA d;
6499
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006500 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501 pch = TempName + STRLEN(TempName) - 1;
6502 if (*pch != '\\' && *pch != '/')
6503 *++pch = '\\';
6504 *++pch = '*';
6505 *++pch = NUL;
6506
6507 hFile = FindFirstFile(TempName, &d);
6508 if (hFile == INVALID_HANDLE_VALUE)
6509 goto getout;
6510 (void)FindClose(hFile);
6511 }
6512 }
6513
6514 if (p & W_OK)
6515 {
6516 /* Trying to create a temporary file in the directory should catch
6517 * directories on read-only network shares. However, in
6518 * directories whose ACL allows writes but denies deletes will end
6519 * up keeping the temporary file :-(. */
6520#ifdef FEAT_MBYTE
6521 if (wn != NULL)
6522 {
6523 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6524 {
6525 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6526 goto getout;
6527
6528 /* Retry with non-wide function (for Windows 98). */
6529 vim_free(wn);
6530 wn = NULL;
6531 }
6532 else
6533 DeleteFileW(TempNameW);
6534 }
6535 if (wn == NULL)
6536#endif
6537 {
6538 if (!GetTempFileName(n, "VIM", 0, TempName))
6539 goto getout;
6540 mch_remove((char_u *)TempName);
6541 }
6542 }
6543 }
6544 else
6545 {
6546 /* Trying to open the file for the required access does ACL, read-only
6547 * network share, and file attribute checks. */
6548 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6549 | ((p & R_OK) ? GENERIC_READ : 0);
6550#ifdef FEAT_MBYTE
6551 if (wn != NULL)
6552 {
6553 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6554 if (hFile == INVALID_HANDLE_VALUE
6555 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6556 {
6557 /* Retry with non-wide function (for Windows 98). */
6558 vim_free(wn);
6559 wn = NULL;
6560 }
6561 }
6562 if (wn == NULL)
6563#endif
6564 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6565 if (hFile == INVALID_HANDLE_VALUE)
6566 goto getout;
6567 CloseHandle(hFile);
6568 }
6569
6570 retval = 0; /* success */
6571getout:
6572#ifdef FEAT_MBYTE
6573 vim_free(wn);
6574#endif
6575 return retval;
6576}
6577
6578#if defined(FEAT_MBYTE) || defined(PROTO)
6579/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006580 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581 */
6582 int
6583mch_open(char *name, int flags, int mode)
6584{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006585 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6586# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587 WCHAR *wn;
6588 int f;
6589
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006590 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006592 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 if (wn != NULL)
6594 {
6595 f = _wopen(wn, flags, mode);
6596 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006597 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598 return f;
6599 /* Retry with non-wide function (for Windows 98). Can't use
6600 * GetLastError() here and it's unclear what errno gets set to if
6601 * the _wopen() fails for missing wide functions. */
6602 }
6603 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006604# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006606 /* open() can open a file which name is longer than _MAX_PATH bytes
6607 * and shorter than _MAX_PATH characters successfully, but sometimes it
6608 * causes unexpected error in another part. We make it an error explicitly
6609 * here. */
6610 if (strlen(name) >= _MAX_PATH)
6611 return -1;
6612
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613 return open(name, flags, mode);
6614}
6615
6616/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006617 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006618 */
6619 FILE *
6620mch_fopen(char *name, char *mode)
6621{
6622 WCHAR *wn, *wm;
6623 FILE *f = NULL;
6624
6625 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6626# ifdef __BORLANDC__
6627 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6628 && g_PlatformId == VER_PLATFORM_WIN32_NT
6629# endif
6630 )
6631 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006632# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006633 /* Work around an annoying assertion in the Microsoft debug CRT
6634 * when mode's text/binary setting doesn't match _get_fmode(). */
6635 char newMode = mode[strlen(mode) - 1];
6636 int oldMode = 0;
6637
6638 _get_fmode(&oldMode);
6639 if (newMode == 't')
6640 _set_fmode(_O_TEXT);
6641 else if (newMode == 'b')
6642 _set_fmode(_O_BINARY);
6643# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006644 wn = enc_to_utf16((char_u *)name, NULL);
6645 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 if (wn != NULL && wm != NULL)
6647 f = _wfopen(wn, wm);
6648 vim_free(wn);
6649 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006650
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006651# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006652 _set_fmode(oldMode);
6653# endif
6654
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006655 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 return f;
6657 /* Retry with non-wide function (for Windows 98). Can't use
6658 * GetLastError() here and it's unclear what errno gets set to if
6659 * the _wfopen() fails for missing wide functions. */
6660 }
6661
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006662 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6663 * and shorter than _MAX_PATH characters successfully, but sometimes it
6664 * causes unexpected error in another part. We make it an error explicitly
6665 * here. */
6666 if (strlen(name) >= _MAX_PATH)
6667 return NULL;
6668
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 return fopen(name, mode);
6670}
6671#endif
6672
6673#ifdef FEAT_MBYTE
6674/*
6675 * SUB STREAM (aka info stream) handling:
6676 *
6677 * NTFS can have sub streams for each file. Normal contents of file is
6678 * stored in the main stream, and extra contents (author information and
6679 * title and so on) can be stored in sub stream. After Windows 2000, user
6680 * can access and store those informations in sub streams via explorer's
6681 * property menuitem in right click menu. Those informations in sub streams
6682 * were lost when copying only the main stream. So we have to copy sub
6683 * streams.
6684 *
6685 * Incomplete explanation:
6686 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6687 * More useful info and an example:
6688 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6689 */
6690
6691/*
6692 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6693 * and write to stream "substream" of file "to".
6694 * Errors are ignored.
6695 */
6696 static void
6697copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6698{
6699 HANDLE hTo;
6700 WCHAR *to_name;
6701
6702 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6703 wcscpy(to_name, to);
6704 wcscat(to_name, substream);
6705
6706 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6707 FILE_ATTRIBUTE_NORMAL, NULL);
6708 if (hTo != INVALID_HANDLE_VALUE)
6709 {
6710 long done;
6711 DWORD todo;
6712 DWORD readcnt, written;
6713 char buf[4096];
6714
6715 /* Copy block of bytes at a time. Abort when something goes wrong. */
6716 for (done = 0; done < len; done += written)
6717 {
6718 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006719 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6720 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6722 FALSE, FALSE, context)
6723 || readcnt != todo
6724 || !WriteFile(hTo, buf, todo, &written, NULL)
6725 || written != todo)
6726 break;
6727 }
6728 CloseHandle(hTo);
6729 }
6730
6731 free(to_name);
6732}
6733
6734/*
6735 * Copy info streams from file "from" to file "to".
6736 */
6737 static void
6738copy_infostreams(char_u *from, char_u *to)
6739{
6740 WCHAR *fromw;
6741 WCHAR *tow;
6742 HANDLE sh;
6743 WIN32_STREAM_ID sid;
6744 int headersize;
6745 WCHAR streamname[_MAX_PATH];
6746 DWORD readcount;
6747 void *context = NULL;
6748 DWORD lo, hi;
6749 int len;
6750
6751 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006752 fromw = enc_to_utf16(from, NULL);
6753 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754 if (fromw != NULL && tow != NULL)
6755 {
6756 /* Open the file for reading. */
6757 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6758 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6759 if (sh != INVALID_HANDLE_VALUE)
6760 {
6761 /* Use BackupRead() to find the info streams. Repeat until we
6762 * have done them all.*/
6763 for (;;)
6764 {
6765 /* Get the header to find the length of the stream name. If
6766 * the "readcount" is zero we have done all info streams. */
6767 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006768 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6770 &readcount, FALSE, FALSE, &context)
6771 || readcount == 0)
6772 break;
6773
6774 /* We only deal with streams that have a name. The normal
6775 * file data appears to be without a name, even though docs
6776 * suggest it is called "::$DATA". */
6777 if (sid.dwStreamNameSize > 0)
6778 {
6779 /* Read the stream name. */
6780 if (!BackupRead(sh, (LPBYTE)streamname,
6781 sid.dwStreamNameSize,
6782 &readcount, FALSE, FALSE, &context))
6783 break;
6784
6785 /* Copy an info stream with a name ":anything:$DATA".
6786 * Skip "::$DATA", it has no stream name (examples suggest
6787 * it might be used for the normal file contents).
6788 * Note that BackupRead() counts bytes, but the name is in
6789 * wide characters. */
6790 len = readcount / sizeof(WCHAR);
6791 streamname[len] = 0;
6792 if (len > 7 && wcsicmp(streamname + len - 6,
6793 L":$DATA") == 0)
6794 {
6795 streamname[len - 6] = 0;
6796 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006797 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798 }
6799 }
6800
6801 /* Advance to the next stream. We might try seeking too far,
6802 * but BackupSeek() doesn't skip over stream borders, thus
6803 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006804 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 &lo, &hi, &context);
6806 }
6807
6808 /* Clear the context. */
6809 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6810
6811 CloseHandle(sh);
6812 }
6813 }
6814 vim_free(fromw);
6815 vim_free(tow);
6816}
6817#endif
6818
6819/*
6820 * Copy file attributes from file "from" to file "to".
6821 * For Windows NT and later we copy info streams.
6822 * Always returns zero, errors are ignored.
6823 */
6824 int
6825mch_copy_file_attribute(char_u *from, char_u *to)
6826{
6827#ifdef FEAT_MBYTE
6828 /* File streams only work on Windows NT and later. */
6829 PlatformId();
6830 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6831 copy_infostreams(from, to);
6832#endif
6833 return 0;
6834}
6835
6836#if defined(MYRESETSTKOFLW) || defined(PROTO)
6837/*
6838 * Recreate a destroyed stack guard page in win32.
6839 * Written by Benjamin Peterson.
6840 */
6841
6842/* These magic numbers are from the MS header files */
6843#define MIN_STACK_WIN9X 17
6844#define MIN_STACK_WINNT 2
6845
6846/*
6847 * This function does the same thing as _resetstkoflw(), which is only
6848 * available in DevStudio .net and later.
6849 * Returns 0 for failure, 1 for success.
6850 */
6851 int
6852myresetstkoflw(void)
6853{
6854 BYTE *pStackPtr;
6855 BYTE *pGuardPage;
6856 BYTE *pStackBase;
6857 BYTE *pLowestPossiblePage;
6858 MEMORY_BASIC_INFORMATION mbi;
6859 SYSTEM_INFO si;
6860 DWORD nPageSize;
6861 DWORD dummy;
6862
6863 /* This code will not work on win32s. */
6864 PlatformId();
6865 if (g_PlatformId == VER_PLATFORM_WIN32s)
6866 return 0;
6867
6868 /* We need to know the system page size. */
6869 GetSystemInfo(&si);
6870 nPageSize = si.dwPageSize;
6871
6872 /* ...and the current stack pointer */
6873 pStackPtr = (BYTE*)_alloca(1);
6874
6875 /* ...and the base of the stack. */
6876 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6877 return 0;
6878 pStackBase = (BYTE*)mbi.AllocationBase;
6879
6880 /* ...and the page thats min_stack_req pages away from stack base; this is
6881 * the lowest page we could use. */
6882 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6883 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6884
6885 /* On Win95, we want the next page down from the end of the stack. */
6886 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6887 {
6888 /* Find the page that's only 1 page down from the page that the stack
6889 * ptr is in. */
6890 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6891 / (DWORD)nPageSize) - 1));
6892 if (pGuardPage < pLowestPossiblePage)
6893 return 0;
6894
6895 /* Apply the noaccess attribute to the page -- there's no guard
6896 * attribute in win95-type OSes. */
6897 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6898 return 0;
6899 }
6900 else
6901 {
6902 /* On NT, however, we want the first committed page in the stack Start
6903 * at the stack base and move forward through memory until we find a
6904 * committed block. */
6905 BYTE *pBlock = pStackBase;
6906
Bram Moolenaara466c992005-07-09 21:03:22 +00006907 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908 {
6909 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6910 return 0;
6911
6912 pBlock += mbi.RegionSize;
6913
6914 if (mbi.State & MEM_COMMIT)
6915 break;
6916 }
6917
6918 /* mbi now describes the first committed block in the stack. */
6919 if (mbi.Protect & PAGE_GUARD)
6920 return 1;
6921
6922 /* decide where the guard page should start */
6923 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6924 pGuardPage = pLowestPossiblePage;
6925 else
6926 pGuardPage = (BYTE*)mbi.BaseAddress;
6927
6928 /* allocate the guard page */
6929 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6930 return 0;
6931
6932 /* apply the guard attribute to the page */
6933 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6934 &dummy))
6935 return 0;
6936 }
6937
6938 return 1;
6939}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006940#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006942
6943#if defined(FEAT_MBYTE) || defined(PROTO)
6944/*
6945 * The command line arguments in UCS2
6946 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006947static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006948static LPWSTR *ArglistW = NULL;
6949static int global_argc = 0;
6950static char **global_argv;
6951
6952static int used_file_argc = 0; /* last argument in global_argv[] used
6953 for the argument list. */
6954static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6955 command line arguments added to
6956 the argument list */
6957static int used_file_count = 0; /* nr of entries in used_file_indexes */
6958static int used_file_literal = FALSE; /* take file names literally */
6959static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006960static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006961static int used_alist_count = 0;
6962
6963
6964/*
6965 * Get the command line arguments. Unicode version.
6966 * Returns argc. Zero when something fails.
6967 */
6968 int
6969get_cmd_argsW(char ***argvp)
6970{
6971 char **argv = NULL;
6972 int argc = 0;
6973 int i;
6974
Bram Moolenaar14993322014-09-09 12:25:33 +02006975 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006976 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6977 if (ArglistW != NULL)
6978 {
6979 argv = malloc((nArgsW + 1) * sizeof(char *));
6980 if (argv != NULL)
6981 {
6982 argc = nArgsW;
6983 argv[argc] = NULL;
6984 for (i = 0; i < argc; ++i)
6985 {
6986 int len;
6987
6988 /* Convert each Unicode argument to the current codepage. */
6989 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006990 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006991 (LPSTR *)&argv[i], &len, 0, 0);
6992 if (argv[i] == NULL)
6993 {
6994 /* Out of memory, clear everything. */
6995 while (i > 0)
6996 free(argv[--i]);
6997 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006998 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006999 argc = 0;
7000 }
7001 }
7002 }
7003 }
7004
7005 global_argc = argc;
7006 global_argv = argv;
7007 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007008 {
7009 if (used_file_indexes != NULL)
7010 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007011 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007012 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007013
7014 if (argvp != NULL)
7015 *argvp = argv;
7016 return argc;
7017}
7018
7019 void
7020free_cmd_argsW(void)
7021{
7022 if (ArglistW != NULL)
7023 {
7024 GlobalFree(ArglistW);
7025 ArglistW = NULL;
7026 }
7027}
7028
7029/*
7030 * Remember "name" is an argument that was added to the argument list.
7031 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7032 * is called.
7033 */
7034 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007035used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007036{
7037 int i;
7038
7039 if (used_file_indexes == NULL)
7040 return;
7041 for (i = used_file_argc + 1; i < global_argc; ++i)
7042 if (STRCMP(global_argv[i], name) == 0)
7043 {
7044 used_file_argc = i;
7045 used_file_indexes[used_file_count++] = i;
7046 break;
7047 }
7048 used_file_literal = literal;
7049 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007050 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007051}
7052
7053/*
7054 * Remember the length of the argument list as it was. If it changes then we
7055 * leave it alone when 'encoding' is set.
7056 */
7057 void
7058set_alist_count(void)
7059{
7060 used_alist_count = GARGCOUNT;
7061}
7062
7063/*
7064 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7065 * has been changed while starting up. Use the UCS-2 command line arguments
7066 * and convert them to 'encoding'.
7067 */
7068 void
7069fix_arg_enc(void)
7070{
7071 int i;
7072 int idx;
7073 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007074 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007075
7076 /* Safety checks:
7077 * - if argument count differs between the wide and non-wide argument
7078 * list, something must be wrong.
7079 * - the file name arguments must have been located.
7080 * - the length of the argument list wasn't changed by the user.
7081 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007082 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007083 || ArglistW == NULL
7084 || used_file_indexes == NULL
7085 || used_file_count == 0
7086 || used_alist_count != GARGCOUNT)
7087 return;
7088
Bram Moolenaar86b68352004-12-27 21:59:20 +00007089 /* Remember the buffer numbers for the arguments. */
7090 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7091 if (fnum_list == NULL)
7092 return; /* out of memory */
7093 for (i = 0; i < GARGCOUNT; ++i)
7094 fnum_list[i] = GARGLIST[i].ae_fnum;
7095
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007096 /* Clear the argument list. Make room for the new arguments. */
7097 alist_clear(&global_alist);
7098 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007099 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007100
7101 for (i = 0; i < used_file_count; ++i)
7102 {
7103 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007104 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007105 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007106 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007107#ifdef FEAT_DIFF
7108 /* When using diff mode may need to concatenate file name to
7109 * directory name. Just like it's done in main(). */
7110 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7111 && !mch_isdir(alist_name(&GARGLIST[0])))
7112 {
7113 char_u *r;
7114
7115 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7116 if (r != NULL)
7117 {
7118 vim_free(str);
7119 str = r;
7120 }
7121 }
7122#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007123 /* Re-use the old buffer by renaming it. When not using literal
7124 * names it's done by alist_expand() below. */
7125 if (used_file_literal)
7126 buf_set_name(fnum_list[i], str);
7127
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007128 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007129 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007130 }
7131
7132 if (!used_file_literal)
7133 {
7134 /* Now expand wildcards in the arguments. */
7135 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7136 * filename characters but are excluded from 'isfname' to make
7137 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7138 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007139 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007140 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7141 }
7142
7143 /* If wildcard expansion failed, we are editing the first file of the
7144 * arglist and there is no file name: Edit the first argument now. */
7145 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7146 {
7147 do_cmdline_cmd((char_u *)":rewind");
7148 if (GARGCOUNT == 1 && used_file_full_path)
7149 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7150 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007151
7152 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007153}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007154#endif