blob: dfc0d4d7414246c3df14d3eb6863b0ca43873b7d [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 Moolenaar4445f7e2016-04-20 20:55:56 +02001449#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001450 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001451#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452
1453 if (msec > 0)
1454 /* Wait until the specified time has elapsed. */
1455 dwEndTime = GetTickCount() + msec;
1456 else if (msec < 0)
1457 /* Wait forever. */
1458 dwEndTime = INFINITE;
1459
1460 /* We need to loop until the end of the time period, because
1461 * we might get multiple unusable mouse events in that time.
1462 */
1463 for (;;)
1464 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001465#ifdef MESSAGE_QUEUE
1466 parse_queued_messages();
1467#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001468#ifdef FEAT_MZSCHEME
1469 mzvim_check_threads();
1470#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471#ifdef FEAT_CLIENTSERVER
1472 serverProcessPendingMessages();
1473#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001474
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475 if (0
1476#ifdef FEAT_MOUSE
1477 || g_nMouseClick != -1
1478#endif
1479#ifdef FEAT_CLIENTSERVER
1480 || input_available()
1481#endif
1482 )
1483 return TRUE;
1484
1485 if (msec > 0)
1486 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001487 /* If the specified wait time has passed, return. Beware that
1488 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001490 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491 break;
1492 }
1493 if (msec != 0)
1494 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001495 DWORD dwWaitTime = dwEndTime - dwNow;
1496
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001497#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar9186a272016-02-23 19:34:01 +01001498 /* Check channel while waiting input. */
1499 if (dwWaitTime > 100)
1500 dwWaitTime = 100;
1501#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001502#ifdef FEAT_MZSCHEME
1503 if (mzthreads_allowed() && p_mzq > 0
1504 && (msec < 0 || (long)dwWaitTime > p_mzq))
1505 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1506#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001507#ifdef FEAT_TIMERS
1508 {
1509 long due_time;
1510
1511 /* When waiting very briefly don't trigger timers. */
1512 if (dwWaitTime > 10)
1513 {
1514 /* Trigger timers and then get the time in msec until the
1515 * next one is due. Wait up to that time. */
1516 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001517 if (typebuf.tb_change_cnt != tb_change_cnt)
1518 {
1519 /* timer may have used feedkeys() */
1520 return FALSE;
1521 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001522 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1523 dwWaitTime = due_time;
1524 }
1525 }
1526#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001527#ifdef FEAT_CLIENTSERVER
1528 /* Wait for either an event on the console input or a message in
1529 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001530 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001531 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001533 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534#endif
1535 continue;
1536 }
1537
1538 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001539 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540
1541#ifdef FEAT_MBYTE_IME
1542 if (State & CMDLINE && msg_row == Rows - 1)
1543 {
1544 CONSOLE_SCREEN_BUFFER_INFO csbi;
1545
1546 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1547 {
1548 if (csbi.dwCursorPosition.Y != msg_row)
1549 {
1550 /* The screen is now messed up, must redraw the
1551 * command line and later all the windows. */
1552 redraw_all_later(CLEAR);
1553 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1554 redrawcmd();
1555 }
1556 }
1557 }
1558#endif
1559
1560 if (cRecords > 0)
1561 {
1562 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1563 {
1564#ifdef FEAT_MBYTE_IME
1565 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1566 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001567 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1569 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001570 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571 continue;
1572 }
1573#endif
1574 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1575 NULL, FALSE))
1576 return TRUE;
1577 }
1578
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001579 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580
1581 if (ir.EventType == FOCUS_EVENT)
1582 handle_focus_event(ir);
1583 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1584 shell_resized();
1585#ifdef FEAT_MOUSE
1586 else if (ir.EventType == MOUSE_EVENT
1587 && decode_mouse_event(&ir.Event.MouseEvent))
1588 return TRUE;
1589#endif
1590 }
1591 else if (msec == 0)
1592 break;
1593 }
1594
1595#ifdef FEAT_CLIENTSERVER
1596 /* Something might have been received while we were waiting. */
1597 if (input_available())
1598 return TRUE;
1599#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001600
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601 return FALSE;
1602}
1603
1604#ifndef FEAT_GUI_MSWIN
1605/*
1606 * return non-zero if a character is available
1607 */
1608 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001609mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610{
1611 return WaitForChar(0L);
1612}
1613#endif
1614
1615/*
1616 * Create the console input. Used when reading stdin doesn't work.
1617 */
1618 static void
1619create_conin(void)
1620{
1621 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1622 FILE_SHARE_READ|FILE_SHARE_WRITE,
1623 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001624 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 did_create_conin = TRUE;
1626}
1627
1628/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001629 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001631 static WCHAR
1632tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001634 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001635
1636 for (;;)
1637 {
1638 INPUT_RECORD ir;
1639 DWORD cRecords = 0;
1640
1641#ifdef FEAT_CLIENTSERVER
1642 (void)WaitForChar(-1L);
1643 if (input_available())
1644 return 0;
1645# ifdef FEAT_MOUSE
1646 if (g_nMouseClick != -1)
1647 return 0;
1648# endif
1649#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001650 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651 {
1652 if (did_create_conin)
1653 read_error_exit();
1654 create_conin();
1655 continue;
1656 }
1657
1658 if (ir.EventType == KEY_EVENT)
1659 {
1660 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1661 pmodifiers, TRUE))
1662 return ch;
1663 }
1664 else if (ir.EventType == FOCUS_EVENT)
1665 handle_focus_event(ir);
1666 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1667 shell_resized();
1668#ifdef FEAT_MOUSE
1669 else if (ir.EventType == MOUSE_EVENT)
1670 {
1671 if (decode_mouse_event(&ir.Event.MouseEvent))
1672 return 0;
1673 }
1674#endif
1675 }
1676}
1677#endif /* !FEAT_GUI_W32 */
1678
1679
1680/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001681 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682 * Get one or more characters from the keyboard or the mouse.
1683 * If time == 0, do not wait for characters.
1684 * If time == n, wait a short time for characters.
1685 * If time == -1, wait forever for characters.
1686 * Returns the number of characters read into buf.
1687 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001688/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 int
1690mch_inchar(
1691 char_u *buf,
1692 int maxlen,
1693 long time,
1694 int tb_change_cnt)
1695{
1696#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1697
1698 int len;
1699 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700#define TYPEAHEADLEN 20
1701 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1702 static int typeaheadlen = 0;
1703
1704 /* First use any typeahead that was kept because "buf" was too small. */
1705 if (typeaheadlen > 0)
1706 goto theend;
1707
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 if (time >= 0)
1709 {
1710 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 }
1713 else /* time == -1, wait forever */
1714 {
1715 mch_set_winsize_now(); /* Allow winsize changes from now on */
1716
Bram Moolenaar3918c952005-03-15 22:34:55 +00001717 /*
1718 * If there is no character available within 2 seconds (default)
1719 * write the autoscript file to disk. Or cause the CursorHold event
1720 * to be triggered.
1721 */
1722 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 {
1724#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001725 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001727 buf[0] = K_SPECIAL;
1728 buf[1] = KS_EXTRA;
1729 buf[2] = (int)KE_CURSORHOLD;
1730 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 }
1732#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001733 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734 }
1735 }
1736
1737 /*
1738 * Try to read as many characters as there are, until the buffer is full.
1739 */
1740
1741 /* we will get at least one key. Get more if they are available. */
1742 g_fCBrkPressed = FALSE;
1743
1744#ifdef MCH_WRITE_DUMP
1745 if (fdDump)
1746 fputc('[', fdDump);
1747#endif
1748
1749 /* Keep looping until there is something in the typeahead buffer and more
1750 * to get and still room in the buffer (up to two bytes for a char and
1751 * three bytes for a modifier). */
1752 while ((typeaheadlen == 0 || WaitForChar(0L))
1753 && typeaheadlen + 5 <= TYPEAHEADLEN)
1754 {
1755 if (typebuf_changed(tb_change_cnt))
1756 {
1757 /* "buf" may be invalid now if a client put something in the
1758 * typeahead buffer and "buf" is in the typeahead buffer. */
1759 typeaheadlen = 0;
1760 break;
1761 }
1762#ifdef FEAT_MOUSE
1763 if (g_nMouseClick != -1)
1764 {
1765# ifdef MCH_WRITE_DUMP
1766 if (fdDump)
1767 fprintf(fdDump, "{%02x @ %d, %d}",
1768 g_nMouseClick, g_xMouse, g_yMouse);
1769# endif
1770 typeahead[typeaheadlen++] = ESC + 128;
1771 typeahead[typeaheadlen++] = 'M';
1772 typeahead[typeaheadlen++] = g_nMouseClick;
1773 typeahead[typeaheadlen++] = g_xMouse + '!';
1774 typeahead[typeaheadlen++] = g_yMouse + '!';
1775 g_nMouseClick = -1;
1776 }
1777 else
1778#endif
1779 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001780 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781 int modifiers = 0;
1782
1783 c = tgetch(&modifiers, &ch2);
1784
1785 if (typebuf_changed(tb_change_cnt))
1786 {
1787 /* "buf" may be invalid now if a client put something in the
1788 * typeahead buffer and "buf" is in the typeahead buffer. */
1789 typeaheadlen = 0;
1790 break;
1791 }
1792
1793 if (c == Ctrl_C && ctrl_c_interrupts)
1794 {
1795#if defined(FEAT_CLIENTSERVER)
1796 trash_input_buf();
1797#endif
1798 got_int = TRUE;
1799 }
1800
1801#ifdef FEAT_MOUSE
1802 if (g_nMouseClick == -1)
1803#endif
1804 {
1805 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001806 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001808#ifdef FEAT_MBYTE
1809 if (ch2 == NUL)
1810 {
1811 int i;
1812 char_u *p;
1813 WCHAR ch[2];
1814
1815 ch[0] = c;
1816 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1817 {
1818 ch[1] = tgetch(&modifiers, &ch2);
1819 n++;
1820 }
1821 p = utf16_to_enc(ch, &n);
1822 if (p != NULL)
1823 {
1824 for (i = 0; i < n; i++)
1825 typeahead[typeaheadlen + i] = p[i];
1826 vim_free(p);
1827 }
1828 }
1829 else
1830#endif
1831 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 if (ch2 != NUL)
1833 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001834 typeahead[typeaheadlen + n] = 3;
1835 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001836 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838
Bram Moolenaar45500912014-07-09 20:51:07 +02001839 if (conv)
1840 {
1841 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001842
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001843 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001844 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001845 char_u *e = typeahead + TYPEAHEADLEN;
1846
1847 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001848 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001849 if (*p == K_NUL)
1850 {
1851 ++p;
1852 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1853 *p = 3;
1854 ++n;
1855 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001856 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001857 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001858 }
1859 }
1860
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 /* Use the ALT key to set the 8th bit of the character
1862 * when it's one byte, the 8th bit isn't set yet and not
1863 * using a double-byte encoding (would become a lead
1864 * byte). */
1865 if ((modifiers & MOD_MASK_ALT)
1866 && n == 1
1867 && (typeahead[typeaheadlen] & 0x80) == 0
1868#ifdef FEAT_MBYTE
1869 && !enc_dbcs
1870#endif
1871 )
1872 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001873#ifdef FEAT_MBYTE
1874 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1875 typeahead + typeaheadlen);
1876#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001878#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 modifiers &= ~MOD_MASK_ALT;
1880 }
1881
1882 if (modifiers != 0)
1883 {
1884 /* Prepend modifiers to the character. */
1885 mch_memmove(typeahead + typeaheadlen + 3,
1886 typeahead + typeaheadlen, n);
1887 typeahead[typeaheadlen++] = K_SPECIAL;
1888 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1889 typeahead[typeaheadlen++] = modifiers;
1890 }
1891
1892 typeaheadlen += n;
1893
1894#ifdef MCH_WRITE_DUMP
1895 if (fdDump)
1896 fputc(c, fdDump);
1897#endif
1898 }
1899 }
1900 }
1901
1902#ifdef MCH_WRITE_DUMP
1903 if (fdDump)
1904 {
1905 fputs("]\n", fdDump);
1906 fflush(fdDump);
1907 }
1908#endif
1909
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910theend:
1911 /* Move typeahead to "buf", as much as fits. */
1912 len = 0;
1913 while (len < maxlen && typeaheadlen > 0)
1914 {
1915 buf[len++] = typeahead[0];
1916 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1917 }
1918 return len;
1919
1920#else /* FEAT_GUI_W32 */
1921 return 0;
1922#endif /* FEAT_GUI_W32 */
1923}
1924
Bram Moolenaar82881492012-11-20 16:53:39 +01001925#ifndef PROTO
1926# ifndef __MINGW32__
1927# include <shellapi.h> /* required for FindExecutable() */
1928# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929#endif
1930
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001931/*
1932 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001933 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001934 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001936executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001938 char *dum;
1939 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001940 char *curpath, *newpath;
1941 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001943#ifdef FEAT_MBYTE
1944 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001946 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001947 WCHAR fnamew[_MAX_PATH];
1948 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001949 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001950
1951 if (p != NULL)
1952 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001953 wcurpath = _wgetenv(L"PATH");
1954 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1955 * sizeof(WCHAR));
1956 if (wnewpath == NULL)
1957 return FALSE;
1958 wcscpy(wnewpath, L".;");
1959 wcscat(wnewpath, wcurpath);
1960 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1961 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001962 vim_free(p);
1963 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1964 {
1965 if (n == 0)
1966 return FALSE;
1967 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1968 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001969 if (path != NULL)
1970 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001971 return TRUE;
1972 }
1973 /* Retry with non-wide function (for Windows 98). */
1974 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001976#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001977
1978 curpath = getenv("PATH");
1979 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1980 if (newpath == NULL)
1981 return FALSE;
1982 STRCPY(newpath, ".;");
1983 STRCAT(newpath, curpath);
1984 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1985 vim_free(newpath);
1986 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001987 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001988 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001989 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001990 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001991 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001992 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993}
1994
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001995#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001996 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001997/*
1998 * Bad parameter handler.
1999 *
2000 * Certain MS CRT functions will intentionally crash when passed invalid
2001 * parameters to highlight possible security holes. Setting this function as
2002 * the bad parameter handler will prevent the crash.
2003 *
2004 * In debug builds the parameters contain CRT information that might help track
2005 * down the source of a problem, but in non-debug builds the arguments are all
2006 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2007 * worth allowing these to make debugging of issues easier.
2008 */
2009 static void
2010bad_param_handler(const wchar_t *expression,
2011 const wchar_t *function,
2012 const wchar_t *file,
2013 unsigned int line,
2014 uintptr_t pReserved)
2015{
2016}
2017
2018# define SET_INVALID_PARAM_HANDLER \
2019 ((void)_set_invalid_parameter_handler(bad_param_handler))
2020#else
2021# define SET_INVALID_PARAM_HANDLER
2022#endif
2023
Bram Moolenaar071d4272004-06-13 20:20:40 +00002024#ifdef FEAT_GUI_W32
2025
2026/*
2027 * GUI version of mch_init().
2028 */
2029 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002030mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031{
2032#ifndef __MINGW32__
2033 extern int _fmode;
2034#endif
2035
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002036 /* Silently handle invalid parameters to CRT functions */
2037 SET_INVALID_PARAM_HANDLER;
2038
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039 /* Let critical errors result in a failure, not in a dialog box. Required
2040 * for the timestamp test to work on removed floppies. */
2041 SetErrorMode(SEM_FAILCRITICALERRORS);
2042
2043 _fmode = O_BINARY; /* we do our own CR-LF translation */
2044
2045 /* Specify window size. Is there a place to get the default from? */
2046 Rows = 25;
2047 Columns = 80;
2048
2049 /* Look for 'vimrun' */
2050 if (!gui_is_win32s())
2051 {
2052 char_u vimrun_location[_MAX_PATH + 4];
2053
2054 /* First try in same directory as gvim.exe */
2055 STRCPY(vimrun_location, exe_name);
2056 STRCPY(gettail(vimrun_location), "vimrun.exe");
2057 if (mch_getperm(vimrun_location) >= 0)
2058 {
2059 if (*skiptowhite(vimrun_location) != NUL)
2060 {
2061 /* Enclose path with white space in double quotes. */
2062 mch_memmove(vimrun_location + 1, vimrun_location,
2063 STRLEN(vimrun_location) + 1);
2064 *vimrun_location = '"';
2065 STRCPY(gettail(vimrun_location), "vimrun\" ");
2066 }
2067 else
2068 STRCPY(gettail(vimrun_location), "vimrun ");
2069
2070 vimrun_path = (char *)vim_strsave(vimrun_location);
2071 s_dont_use_vimrun = FALSE;
2072 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002073 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074 s_dont_use_vimrun = FALSE;
2075
2076 /* Don't give the warning for a missing vimrun.exe right now, but only
2077 * when vimrun was supposed to be used. Don't bother people that do
2078 * not need vimrun.exe. */
2079 if (s_dont_use_vimrun)
2080 need_vimrun_warning = TRUE;
2081 }
2082
2083 /*
2084 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2085 * Otherwise the default "findstr /n" is used.
2086 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002087 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002088 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2089
2090#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002091 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092#endif
2093}
2094
2095
2096#else /* FEAT_GUI_W32 */
2097
2098#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2099#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2100
2101/*
2102 * ClearConsoleBuffer()
2103 * Description:
2104 * Clears the entire contents of the console screen buffer, using the
2105 * specified attribute.
2106 * Returns:
2107 * TRUE on success
2108 */
2109 static BOOL
2110ClearConsoleBuffer(WORD wAttribute)
2111{
2112 CONSOLE_SCREEN_BUFFER_INFO csbi;
2113 COORD coord;
2114 DWORD NumCells, dummy;
2115
2116 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2117 return FALSE;
2118
2119 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2120 coord.X = 0;
2121 coord.Y = 0;
2122 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2123 coord, &dummy))
2124 {
2125 return FALSE;
2126 }
2127 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2128 coord, &dummy))
2129 {
2130 return FALSE;
2131 }
2132
2133 return TRUE;
2134}
2135
2136/*
2137 * FitConsoleWindow()
2138 * Description:
2139 * Checks if the console window will fit within given buffer dimensions.
2140 * Also, if requested, will shrink the window to fit.
2141 * Returns:
2142 * TRUE on success
2143 */
2144 static BOOL
2145FitConsoleWindow(
2146 COORD dwBufferSize,
2147 BOOL WantAdjust)
2148{
2149 CONSOLE_SCREEN_BUFFER_INFO csbi;
2150 COORD dwWindowSize;
2151 BOOL NeedAdjust = FALSE;
2152
2153 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2154 {
2155 /*
2156 * A buffer resize will fail if the current console window does
2157 * not lie completely within that buffer. To avoid this, we might
2158 * have to move and possibly shrink the window.
2159 */
2160 if (csbi.srWindow.Right >= dwBufferSize.X)
2161 {
2162 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2163 if (dwWindowSize.X > dwBufferSize.X)
2164 dwWindowSize.X = dwBufferSize.X;
2165 csbi.srWindow.Right = dwBufferSize.X - 1;
2166 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2167 NeedAdjust = TRUE;
2168 }
2169 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2170 {
2171 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2172 if (dwWindowSize.Y > dwBufferSize.Y)
2173 dwWindowSize.Y = dwBufferSize.Y;
2174 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2175 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2176 NeedAdjust = TRUE;
2177 }
2178 if (NeedAdjust && WantAdjust)
2179 {
2180 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2181 return FALSE;
2182 }
2183 return TRUE;
2184 }
2185
2186 return FALSE;
2187}
2188
2189typedef struct ConsoleBufferStruct
2190{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002191 BOOL IsValid;
2192 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002193 PCHAR_INFO Buffer;
2194 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195} ConsoleBuffer;
2196
2197/*
2198 * SaveConsoleBuffer()
2199 * Description:
2200 * Saves important information about the console buffer, including the
2201 * actual buffer contents. The saved information is suitable for later
2202 * restoration by RestoreConsoleBuffer().
2203 * Returns:
2204 * TRUE if all information was saved; FALSE otherwise
2205 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2206 */
2207 static BOOL
2208SaveConsoleBuffer(
2209 ConsoleBuffer *cb)
2210{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002211 DWORD NumCells;
2212 COORD BufferCoord;
2213 SMALL_RECT ReadRegion;
2214 WORD Y, Y_incr;
2215
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216 if (cb == NULL)
2217 return FALSE;
2218
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002219 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220 {
2221 cb->IsValid = FALSE;
2222 return FALSE;
2223 }
2224 cb->IsValid = TRUE;
2225
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002226 /*
2227 * Allocate a buffer large enough to hold the entire console screen
2228 * buffer. If this ConsoleBuffer structure has already been initialized
2229 * with a buffer of the correct size, then just use that one.
2230 */
2231 if (!cb->IsValid || cb->Buffer == NULL ||
2232 cb->BufferSize.X != cb->Info.dwSize.X ||
2233 cb->BufferSize.Y != cb->Info.dwSize.Y)
2234 {
2235 cb->BufferSize.X = cb->Info.dwSize.X;
2236 cb->BufferSize.Y = cb->Info.dwSize.Y;
2237 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2238 vim_free(cb->Buffer);
2239 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2240 if (cb->Buffer == NULL)
2241 return FALSE;
2242 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243
2244 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002245 * We will now copy the console screen buffer into our buffer.
2246 * ReadConsoleOutput() seems to be limited as far as how much you
2247 * can read at a time. Empirically, this number seems to be about
2248 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2249 * in chunks until it is all copied. The chunks will all have the
2250 * same horizontal characteristics, so initialize them now. The
2251 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002252 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002253 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002254 ReadRegion.Left = 0;
2255 ReadRegion.Right = cb->Info.dwSize.X - 1;
2256 Y_incr = 12000 / cb->Info.dwSize.X;
2257 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002259 /*
2260 * Read into position (0, Y) in our buffer.
2261 */
2262 BufferCoord.Y = Y;
2263 /*
2264 * Read the region whose top left corner is (0, Y) and whose bottom
2265 * right corner is (width - 1, Y + Y_incr - 1). This should define
2266 * a region of size width by Y_incr. Don't worry if this region is
2267 * too large for the remaining buffer; it will be cropped.
2268 */
2269 ReadRegion.Top = Y;
2270 ReadRegion.Bottom = Y + Y_incr - 1;
2271 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2272 cb->Buffer, /* our buffer */
2273 cb->BufferSize, /* dimensions of our buffer */
2274 BufferCoord, /* offset in our buffer */
2275 &ReadRegion)) /* region to save */
2276 {
2277 vim_free(cb->Buffer);
2278 cb->Buffer = NULL;
2279 return FALSE;
2280 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 }
2282
2283 return TRUE;
2284}
2285
2286/*
2287 * RestoreConsoleBuffer()
2288 * Description:
2289 * Restores important information about the console buffer, including the
2290 * actual buffer contents, if desired. The information to restore is in
2291 * the same format used by SaveConsoleBuffer().
2292 * Returns:
2293 * TRUE on success
2294 */
2295 static BOOL
2296RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002297 ConsoleBuffer *cb,
2298 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002300 COORD BufferCoord;
2301 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302
2303 if (cb == NULL || !cb->IsValid)
2304 return FALSE;
2305
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002306 /*
2307 * Before restoring the buffer contents, clear the current buffer, and
2308 * restore the cursor position and window information. Doing this now
2309 * prevents old buffer contents from "flashing" onto the screen.
2310 */
2311 if (RestoreScreen)
2312 ClearConsoleBuffer(cb->Info.wAttributes);
2313
2314 FitConsoleWindow(cb->Info.dwSize, TRUE);
2315 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2316 return FALSE;
2317 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2318 return FALSE;
2319
2320 if (!RestoreScreen)
2321 {
2322 /*
2323 * No need to restore the screen buffer contents, so we're done.
2324 */
2325 return TRUE;
2326 }
2327
2328 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2329 return FALSE;
2330 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2331 return FALSE;
2332
2333 /*
2334 * Restore the screen buffer contents.
2335 */
2336 if (cb->Buffer != NULL)
2337 {
2338 BufferCoord.X = 0;
2339 BufferCoord.Y = 0;
2340 WriteRegion.Left = 0;
2341 WriteRegion.Top = 0;
2342 WriteRegion.Right = cb->Info.dwSize.X - 1;
2343 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2344 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2345 cb->Buffer, /* our buffer */
2346 cb->BufferSize, /* dimensions of our buffer */
2347 BufferCoord, /* offset in our buffer */
2348 &WriteRegion)) /* region to restore */
2349 {
2350 return FALSE;
2351 }
2352 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353
2354 return TRUE;
2355}
2356
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002357#define FEAT_RESTORE_ORIG_SCREEN
2358#ifdef FEAT_RESTORE_ORIG_SCREEN
2359static ConsoleBuffer g_cbOrig = { 0 };
2360#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002361static ConsoleBuffer g_cbNonTermcap = { 0 };
2362static ConsoleBuffer g_cbTermcap = { 0 };
2363
2364#ifdef FEAT_TITLE
2365#ifdef __BORLANDC__
2366typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2367#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002368typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369#endif
2370char g_szOrigTitle[256] = { 0 };
2371HWND g_hWnd = NULL; /* also used in os_mswin.c */
2372static HICON g_hOrigIconSmall = NULL;
2373static HICON g_hOrigIcon = NULL;
2374static HICON g_hVimIcon = NULL;
2375static BOOL g_fCanChangeIcon = FALSE;
2376
2377/* ICON* are not defined in VC++ 4.0 */
2378#ifndef ICON_SMALL
2379#define ICON_SMALL 0
2380#endif
2381#ifndef ICON_BIG
2382#define ICON_BIG 1
2383#endif
2384/*
2385 * GetConsoleIcon()
2386 * Description:
2387 * Attempts to retrieve the small icon and/or the big icon currently in
2388 * use by a given window.
2389 * Returns:
2390 * TRUE on success
2391 */
2392 static BOOL
2393GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002394 HWND hWnd,
2395 HICON *phIconSmall,
2396 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397{
2398 if (hWnd == NULL)
2399 return FALSE;
2400
2401 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002402 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2403 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002405 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2406 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407 return TRUE;
2408}
2409
2410/*
2411 * SetConsoleIcon()
2412 * Description:
2413 * Attempts to change the small icon and/or the big icon currently in
2414 * use by a given window.
2415 * Returns:
2416 * TRUE on success
2417 */
2418 static BOOL
2419SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002420 HWND hWnd,
2421 HICON hIconSmall,
2422 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 if (hWnd == NULL)
2425 return FALSE;
2426
2427 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002428 SendMessage(hWnd, WM_SETICON,
2429 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002431 SendMessage(hWnd, WM_SETICON,
2432 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 return TRUE;
2434}
2435
2436/*
2437 * SaveConsoleTitleAndIcon()
2438 * Description:
2439 * Saves the current console window title in g_szOrigTitle, for later
2440 * restoration. Also, attempts to obtain a handle to the console window,
2441 * and use it to save the small and big icons currently in use by the
2442 * console window. This is not always possible on some versions of Windows;
2443 * nor is it possible when running Vim remotely using Telnet (since the
2444 * console window the user sees is owned by a remote process).
2445 */
2446 static void
2447SaveConsoleTitleAndIcon(void)
2448{
2449 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2450
2451 /* Save the original title. */
2452 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2453 return;
2454
2455 /*
2456 * Obtain a handle to the console window using GetConsoleWindow() from
2457 * KERNEL32.DLL; we need to handle in order to change the window icon.
2458 * This function only exists on NT-based Windows, starting with Windows
2459 * 2000. On older operating systems, we can't change the window icon
2460 * anyway.
2461 */
2462 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2463 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2464 "GetConsoleWindow")) != NULL)
2465 {
2466 g_hWnd = (*GetConsoleWindowProc)();
2467 }
2468 if (g_hWnd == NULL)
2469 return;
2470
2471 /* Save the original console window icon. */
2472 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2473 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2474 return;
2475
2476 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002477 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002478 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479 if (g_hVimIcon != NULL)
2480 g_fCanChangeIcon = TRUE;
2481}
2482#endif
2483
2484static int g_fWindInitCalled = FALSE;
2485static int g_fTermcapMode = FALSE;
2486static CONSOLE_CURSOR_INFO g_cci;
2487static DWORD g_cmodein = 0;
2488static DWORD g_cmodeout = 0;
2489
2490/*
2491 * non-GUI version of mch_init().
2492 */
2493 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002494mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002496#ifndef FEAT_RESTORE_ORIG_SCREEN
2497 CONSOLE_SCREEN_BUFFER_INFO csbi;
2498#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499#ifndef __MINGW32__
2500 extern int _fmode;
2501#endif
2502
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002503 /* Silently handle invalid parameters to CRT functions */
2504 SET_INVALID_PARAM_HANDLER;
2505
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506 /* Let critical errors result in a failure, not in a dialog box. Required
2507 * for the timestamp test to work on removed floppies. */
2508 SetErrorMode(SEM_FAILCRITICALERRORS);
2509
2510 _fmode = O_BINARY; /* we do our own CR-LF translation */
2511 out_flush();
2512
2513 /* Obtain handles for the standard Console I/O devices */
2514 if (read_cmd_fd == 0)
2515 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2516 else
2517 create_conin();
2518 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2519
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002520#ifdef FEAT_RESTORE_ORIG_SCREEN
2521 /* Save the initial console buffer for later restoration */
2522 SaveConsoleBuffer(&g_cbOrig);
2523 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2524#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002526 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2527 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2528#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 if (cterm_normal_fg_color == 0)
2530 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2531 if (cterm_normal_bg_color == 0)
2532 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2533
2534 /* set termcap codes to current text attributes */
2535 update_tcap(g_attrCurrent);
2536
2537 GetConsoleCursorInfo(g_hConOut, &g_cci);
2538 GetConsoleMode(g_hConIn, &g_cmodein);
2539 GetConsoleMode(g_hConOut, &g_cmodeout);
2540
2541#ifdef FEAT_TITLE
2542 SaveConsoleTitleAndIcon();
2543 /*
2544 * Set both the small and big icons of the console window to Vim's icon.
2545 * Note that Vim presently only has one size of icon (32x32), but it
2546 * automatically gets scaled down to 16x16 when setting the small icon.
2547 */
2548 if (g_fCanChangeIcon)
2549 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2550#endif
2551
2552 ui_get_shellsize();
2553
2554#ifdef MCH_WRITE_DUMP
2555 fdDump = fopen("dump", "wt");
2556
2557 if (fdDump)
2558 {
2559 time_t t;
2560
2561 time(&t);
2562 fputs(ctime(&t), fdDump);
2563 fflush(fdDump);
2564 }
2565#endif
2566
2567 g_fWindInitCalled = TRUE;
2568
2569#ifdef FEAT_MOUSE
2570 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2571#endif
2572
2573#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002574 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575#endif
2576
2577 /* This will be NULL on anything but NT 4.0 */
2578 s_pfnGetConsoleKeyboardLayoutName =
2579 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2580 "GetConsoleKeyboardLayoutNameA");
2581}
2582
2583/*
2584 * non-GUI version of mch_exit().
2585 * Shut down and exit with status `r'
2586 * Careful: mch_exit() may be called before mch_init()!
2587 */
2588 void
2589mch_exit(int r)
2590{
2591 stoptermcap();
2592
2593 if (g_fWindInitCalled)
2594 settmode(TMODE_COOK);
2595
2596 ml_close_all(TRUE); /* remove all memfiles */
2597
2598 if (g_fWindInitCalled)
2599 {
2600#ifdef FEAT_TITLE
2601 mch_restore_title(3);
2602 /*
2603 * Restore both the small and big icons of the console window to
2604 * what they were at startup. Don't do this when the window is
2605 * closed, Vim would hang here.
2606 */
2607 if (g_fCanChangeIcon && !g_fForceExit)
2608 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2609#endif
2610
2611#ifdef MCH_WRITE_DUMP
2612 if (fdDump)
2613 {
2614 time_t t;
2615
2616 time(&t);
2617 fputs(ctime(&t), fdDump);
2618 fclose(fdDump);
2619 }
2620 fdDump = NULL;
2621#endif
2622 }
2623
2624 SetConsoleCursorInfo(g_hConOut, &g_cci);
2625 SetConsoleMode(g_hConIn, g_cmodein);
2626 SetConsoleMode(g_hConOut, g_cmodeout);
2627
2628#ifdef DYNAMIC_GETTEXT
2629 dyn_libintl_end();
2630#endif
2631
2632 exit(r);
2633}
2634#endif /* !FEAT_GUI_W32 */
2635
Bram Moolenaar071d4272004-06-13 20:20:40 +00002636/*
2637 * Do we have an interactive window?
2638 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002639/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002640 int
2641mch_check_win(
2642 int argc,
2643 char **argv)
2644{
2645 get_exe_name();
2646
2647#ifdef FEAT_GUI_W32
2648 return OK; /* GUI always has a tty */
2649#else
2650 if (isatty(1))
2651 return OK;
2652 return FAIL;
2653#endif
2654}
2655
2656
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002657#ifdef FEAT_MBYTE
2658/*
2659 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2660 * if it already exists. When "len" is > 0, also expand short to long
2661 * filenames.
2662 * Return FAIL if wide functions are not available, OK otherwise.
2663 * NOTE: much of this is identical to fname_case(), keep in sync!
2664 */
2665 static int
2666fname_casew(
2667 WCHAR *name,
2668 int len)
2669{
2670 WCHAR szTrueName[_MAX_PATH + 2];
2671 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2672 WCHAR *ptrue, *ptruePrev;
2673 WCHAR *porig, *porigPrev;
2674 int flen;
2675 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002676 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002677 int c;
2678 int slen;
2679
2680 flen = (int)wcslen(name);
2681 if (flen > _MAX_PATH)
2682 return OK;
2683
2684 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2685
2686 /* Build the new name in szTrueName[] one component at a time. */
2687 porig = name;
2688 ptrue = szTrueName;
2689
2690 if (iswalpha(porig[0]) && porig[1] == L':')
2691 {
2692 /* copy leading drive letter */
2693 *ptrue++ = *porig++;
2694 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002695 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002696 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002697
2698 while (*porig != NUL)
2699 {
2700 /* copy \ characters */
2701 while (*porig == psepc)
2702 *ptrue++ = *porig++;
2703
2704 ptruePrev = ptrue;
2705 porigPrev = porig;
2706 while (*porig != NUL && *porig != psepc)
2707 {
2708 *ptrue++ = *porig++;
2709 }
2710 *ptrue = NUL;
2711
2712 /* To avoid a slow failure append "\*" when searching a directory,
2713 * server or network share. */
2714 wcscpy(szTrueNameTemp, szTrueName);
2715 slen = (int)wcslen(szTrueNameTemp);
2716 if (*porig == psepc && slen + 2 < _MAX_PATH)
2717 wcscpy(szTrueNameTemp + slen, L"\\*");
2718
2719 /* Skip "", "." and "..". */
2720 if (ptrue > ptruePrev
2721 && (ptruePrev[0] != L'.'
2722 || (ptruePrev[1] != NUL
2723 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2724 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2725 != INVALID_HANDLE_VALUE)
2726 {
2727 c = *porig;
2728 *porig = NUL;
2729
2730 /* Only use the match when it's the same name (ignoring case) or
2731 * expansion is allowed and there is a match with the short name
2732 * and there is enough room. */
2733 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2734 || (len > 0
2735 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2736 && (int)(ptruePrev - szTrueName)
2737 + (int)wcslen(fb.cFileName) < len)))
2738 {
2739 wcscpy(ptruePrev, fb.cFileName);
2740
2741 /* Look for exact match and prefer it if found. Must be a
2742 * long name, otherwise there would be only one match. */
2743 while (FindNextFileW(hFind, &fb))
2744 {
2745 if (*fb.cAlternateFileName != NUL
2746 && (wcscoll(porigPrev, fb.cFileName) == 0
2747 || (len > 0
2748 && (_wcsicoll(porigPrev,
2749 fb.cAlternateFileName) == 0
2750 && (int)(ptruePrev - szTrueName)
2751 + (int)wcslen(fb.cFileName) < len))))
2752 {
2753 wcscpy(ptruePrev, fb.cFileName);
2754 break;
2755 }
2756 }
2757 }
2758 FindClose(hFind);
2759 *porig = c;
2760 ptrue = ptruePrev + wcslen(ptruePrev);
2761 }
2762 else if (hFind == INVALID_HANDLE_VALUE
2763 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2764 return FAIL;
2765 }
2766
2767 wcscpy(name, szTrueName);
2768 return OK;
2769}
2770#endif
2771
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772/*
2773 * fname_case(): Set the case of the file name, if it already exists.
2774 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002775 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776 */
2777 void
2778fname_case(
2779 char_u *name,
2780 int len)
2781{
2782 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002783 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002784 char *ptrue, *ptruePrev;
2785 char *porig, *porigPrev;
2786 int flen;
2787 WIN32_FIND_DATA fb;
2788 HANDLE hFind;
2789 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002790 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002792 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002793 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794 return;
2795
2796 slash_adjust(name);
2797
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002798#ifdef FEAT_MBYTE
2799 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2800 {
2801 WCHAR *p = enc_to_utf16(name, NULL);
2802
2803 if (p != NULL)
2804 {
2805 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002806 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002807
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002808 wcsncpy(buf, p, _MAX_PATH);
2809 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002810 vim_free(p);
2811
2812 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2813 {
2814 q = utf16_to_enc(buf, NULL);
2815 if (q != NULL)
2816 {
2817 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2818 vim_free(q);
2819 return;
2820 }
2821 }
2822 }
2823 /* Retry with non-wide function (for Windows 98). */
2824 }
2825#endif
2826
2827 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2828 * So we should check this after calling wide function. */
2829 if (flen > _MAX_PATH)
2830 return;
2831
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002833 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834 ptrue = szTrueName;
2835
2836 if (isalpha(porig[0]) && porig[1] == ':')
2837 {
2838 /* copy leading drive letter */
2839 *ptrue++ = *porig++;
2840 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002841 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002842 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843
2844 while (*porig != NUL)
2845 {
2846 /* copy \ characters */
2847 while (*porig == psepc)
2848 *ptrue++ = *porig++;
2849
2850 ptruePrev = ptrue;
2851 porigPrev = porig;
2852 while (*porig != NUL && *porig != psepc)
2853 {
2854#ifdef FEAT_MBYTE
2855 int l;
2856
2857 if (enc_dbcs)
2858 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002859 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860 while (--l >= 0)
2861 *ptrue++ = *porig++;
2862 }
2863 else
2864#endif
2865 *ptrue++ = *porig++;
2866 }
2867 *ptrue = NUL;
2868
Bram Moolenaar464c9252010-10-13 20:37:41 +02002869 /* To avoid a slow failure append "\*" when searching a directory,
2870 * server or network share. */
2871 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002872 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002873 if (*porig == psepc && slen + 2 < _MAX_PATH)
2874 STRCPY(szTrueNameTemp + slen, "\\*");
2875
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876 /* Skip "", "." and "..". */
2877 if (ptrue > ptruePrev
2878 && (ptruePrev[0] != '.'
2879 || (ptruePrev[1] != NUL
2880 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002881 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002882 != INVALID_HANDLE_VALUE)
2883 {
2884 c = *porig;
2885 *porig = NUL;
2886
2887 /* Only use the match when it's the same name (ignoring case) or
2888 * expansion is allowed and there is a match with the short name
2889 * and there is enough room. */
2890 if (_stricoll(porigPrev, fb.cFileName) == 0
2891 || (len > 0
2892 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2893 && (int)(ptruePrev - szTrueName)
2894 + (int)strlen(fb.cFileName) < len)))
2895 {
2896 STRCPY(ptruePrev, fb.cFileName);
2897
2898 /* Look for exact match and prefer it if found. Must be a
2899 * long name, otherwise there would be only one match. */
2900 while (FindNextFile(hFind, &fb))
2901 {
2902 if (*fb.cAlternateFileName != NUL
2903 && (strcoll(porigPrev, fb.cFileName) == 0
2904 || (len > 0
2905 && (_stricoll(porigPrev,
2906 fb.cAlternateFileName) == 0
2907 && (int)(ptruePrev - szTrueName)
2908 + (int)strlen(fb.cFileName) < len))))
2909 {
2910 STRCPY(ptruePrev, fb.cFileName);
2911 break;
2912 }
2913 }
2914 }
2915 FindClose(hFind);
2916 *porig = c;
2917 ptrue = ptruePrev + strlen(ptruePrev);
2918 }
2919 }
2920
2921 STRCPY(name, szTrueName);
2922}
2923
2924
2925/*
2926 * Insert user name in s[len].
2927 */
2928 int
2929mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002930 char_u *s,
2931 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002933 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 DWORD cch = sizeof szUserName;
2935
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002936#ifdef FEAT_MBYTE
2937 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2938 {
2939 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2940 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2941
2942 if (GetUserNameW(wszUserName, &wcch))
2943 {
2944 char_u *p = utf16_to_enc(wszUserName, NULL);
2945
2946 if (p != NULL)
2947 {
2948 vim_strncpy(s, p, len - 1);
2949 vim_free(p);
2950 return OK;
2951 }
2952 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002953 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2954 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002955 /* Retry with non-wide function (for Windows 98). */
2956 }
2957#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958 if (GetUserName(szUserName, &cch))
2959 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002960 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961 return OK;
2962 }
2963 s[0] = NUL;
2964 return FAIL;
2965}
2966
2967
2968/*
2969 * Insert host name in s[len].
2970 */
2971 void
2972mch_get_host_name(
2973 char_u *s,
2974 int len)
2975{
2976 DWORD cch = len;
2977
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002978#ifdef FEAT_MBYTE
2979 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2980 {
2981 WCHAR wszHostName[256 + 1];
2982 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2983
2984 if (GetComputerNameW(wszHostName, &wcch))
2985 {
2986 char_u *p = utf16_to_enc(wszHostName, NULL);
2987
2988 if (p != NULL)
2989 {
2990 vim_strncpy(s, p, len - 1);
2991 vim_free(p);
2992 return;
2993 }
2994 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002995 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2996 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002997 /* Retry with non-wide function (for Windows 98). */
2998 }
2999#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003000 if (!GetComputerName((LPSTR)s, &cch))
3001 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002}
3003
3004
3005/*
3006 * return process ID
3007 */
3008 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003009mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010{
3011 return (long)GetCurrentProcessId();
3012}
3013
3014
3015/*
3016 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3017 * Return OK for success, FAIL for failure.
3018 */
3019 int
3020mch_dirname(
3021 char_u *buf,
3022 int len)
3023{
3024 /*
3025 * Originally this was:
3026 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3027 * But the Win32s known bug list says that getcwd() doesn't work
3028 * so use the Win32 system call instead. <Negri>
3029 */
3030#ifdef FEAT_MBYTE
3031 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3032 {
3033 WCHAR wbuf[_MAX_PATH + 1];
3034
3035 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3036 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003037 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038
3039 if (p != NULL)
3040 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003041 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042 vim_free(p);
3043 return OK;
3044 }
3045 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003046 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3047 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 /* Retry with non-wide function (for Windows 98). */
3049 }
3050#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003051 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052}
3053
3054/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003055 * Get file permissions for "name".
3056 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 */
3058 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003059mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003061 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003062 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003064 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003065 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066}
3067
3068
3069/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003070 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003071 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003072 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073 */
3074 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003075mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003077 long n = -1;
3078
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079#ifdef FEAT_MBYTE
3080 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3081 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003082 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083
3084 if (p != NULL)
3085 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003086 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003088 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003089 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090 /* Retry with non-wide function (for Windows 98). */
3091 }
3092 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003093 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003095 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003096 if (n == -1)
3097 return FAIL;
3098
3099 win32_set_archive(name);
3100
3101 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102}
3103
3104/*
3105 * Set hidden flag for "name".
3106 */
3107 void
3108mch_hide(char_u *name)
3109{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003110 int attrs = win32_getattrs(name);
3111 if (attrs == -1)
3112 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003114 attrs |= FILE_ATTRIBUTE_HIDDEN;
3115 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116}
3117
3118/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003119 * Return TRUE if file "name" exists and is hidden.
3120 */
3121 int
3122mch_ishidden(char_u *name)
3123{
3124 int f = win32_getattrs(name);
3125
3126 if (f == -1)
3127 return FALSE; /* file does not exist at all */
3128
3129 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3130}
3131
3132/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 * return TRUE if "name" is a directory
3134 * return FALSE if "name" is not a directory or upon error
3135 */
3136 int
3137mch_isdir(char_u *name)
3138{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003139 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140
3141 if (f == -1)
3142 return FALSE; /* file does not exist at all */
3143
3144 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3145}
3146
3147/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003148 * return TRUE if "name" is a directory, NOT a symlink to a directory
3149 * return FALSE if "name" is not a directory
3150 * return FALSE for error
3151 */
3152 int
3153mch_isrealdir(char_u *name)
3154{
3155 return mch_isdir(name) && !mch_is_symbolic_link(name);
3156}
3157
3158/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003159 * Create directory "name".
3160 * Return 0 on success, -1 on error.
3161 */
3162 int
3163mch_mkdir(char_u *name)
3164{
3165#ifdef FEAT_MBYTE
3166 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3167 {
3168 WCHAR *p;
3169 int retval;
3170
3171 p = enc_to_utf16(name, NULL);
3172 if (p == NULL)
3173 return -1;
3174 retval = _wmkdir(p);
3175 vim_free(p);
3176 return retval;
3177 }
3178#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003179 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003180}
3181
3182/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003183 * Delete directory "name".
3184 * Return 0 on success, -1 on error.
3185 */
3186 int
3187mch_rmdir(char_u *name)
3188{
3189#ifdef FEAT_MBYTE
3190 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3191 {
3192 WCHAR *p;
3193 int retval;
3194
3195 p = enc_to_utf16(name, NULL);
3196 if (p == NULL)
3197 return -1;
3198 retval = _wrmdir(p);
3199 vim_free(p);
3200 return retval;
3201 }
3202#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003203 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003204}
3205
3206/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003207 * Return TRUE if file "fname" has more than one link.
3208 */
3209 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003210mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003211{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003212 BY_HANDLE_FILE_INFORMATION info;
3213
3214 return win32_fileinfo(fname, &info) == FILEINFO_OK
3215 && info.nNumberOfLinks > 1;
3216}
3217
3218/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003219 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003220 */
3221 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003222mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003223{
3224 HANDLE hFind;
3225 int res = FALSE;
3226 WIN32_FIND_DATAA findDataA;
3227 DWORD fileFlags = 0, reparseTag = 0;
3228#ifdef FEAT_MBYTE
3229 WCHAR *wn = NULL;
3230 WIN32_FIND_DATAW findDataW;
3231
3232 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003233 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003234 if (wn != NULL)
3235 {
3236 hFind = FindFirstFileW(wn, &findDataW);
3237 vim_free(wn);
3238 if (hFind == INVALID_HANDLE_VALUE
3239 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3240 {
3241 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003242 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003243 if (hFind != INVALID_HANDLE_VALUE)
3244 {
3245 fileFlags = findDataA.dwFileAttributes;
3246 reparseTag = findDataA.dwReserved0;
3247 }
3248 }
3249 else
3250 {
3251 fileFlags = findDataW.dwFileAttributes;
3252 reparseTag = findDataW.dwReserved0;
3253 }
3254 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003255 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003256#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003257 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003258 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003259 if (hFind != INVALID_HANDLE_VALUE)
3260 {
3261 fileFlags = findDataA.dwFileAttributes;
3262 reparseTag = findDataA.dwReserved0;
3263 }
3264 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003265
3266 if (hFind != INVALID_HANDLE_VALUE)
3267 FindClose(hFind);
3268
3269 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003270 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3271 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003272 res = TRUE;
3273
3274 return res;
3275}
3276
3277/*
3278 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3279 * link.
3280 */
3281 int
3282mch_is_linked(char_u *fname)
3283{
3284 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3285 return TRUE;
3286 return FALSE;
3287}
3288
3289/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003290 * Get the by-handle-file-information for "fname".
3291 * Returns FILEINFO_OK when OK.
3292 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3293 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3294 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3295 */
3296 int
3297win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3298{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003299 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003300 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003301#ifdef FEAT_MBYTE
3302 WCHAR *wn = NULL;
3303
3304 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003305 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003306 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003307 if (wn == NULL)
3308 res = FILEINFO_ENC_FAIL;
3309 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003310 if (wn != NULL)
3311 {
3312 hFile = CreateFileW(wn, /* file name */
3313 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003314 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003315 NULL, /* security descriptor */
3316 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003317 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003318 NULL); /* handle to template file */
3319 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003320 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003321 {
3322 /* Retry with non-wide function (for Windows 98). */
3323 vim_free(wn);
3324 wn = NULL;
3325 }
3326 }
3327 if (wn == NULL)
3328#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003329 hFile = CreateFile((LPCSTR)fname, /* file name */
3330 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003331 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003332 NULL, /* security descriptor */
3333 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003334 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003335 NULL); /* handle to template file */
3336
3337 if (hFile != INVALID_HANDLE_VALUE)
3338 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003339 if (GetFileInformationByHandle(hFile, info) != 0)
3340 res = FILEINFO_OK;
3341 else
3342 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003343 CloseHandle(hFile);
3344 }
3345
3346#ifdef FEAT_MBYTE
3347 vim_free(wn);
3348#endif
3349 return res;
3350}
3351
3352/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003353 * get file attributes for `name'
3354 * -1 : error
3355 * else FILE_ATTRIBUTE_* defined in winnt.h
3356 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003357 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003358win32_getattrs(char_u *name)
3359{
3360 int attr;
3361#ifdef FEAT_MBYTE
3362 WCHAR *p = NULL;
3363
3364 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3365 p = enc_to_utf16(name, NULL);
3366
3367 if (p != NULL)
3368 {
3369 attr = GetFileAttributesW(p);
3370 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3371 {
3372 /* Retry with non-wide function (for Windows 98). */
3373 vim_free(p);
3374 p = NULL;
3375 }
3376 }
3377 if (p == NULL)
3378#endif
3379 attr = GetFileAttributes((char *)name);
3380#ifdef FEAT_MBYTE
3381 vim_free(p);
3382#endif
3383 return attr;
3384}
3385
3386/*
3387 * set file attributes for `name' to `attrs'
3388 *
3389 * return -1 for failure, 0 otherwise
3390 */
3391 static
3392 int
3393win32_setattrs(char_u *name, int attrs)
3394{
3395 int res;
3396#ifdef FEAT_MBYTE
3397 WCHAR *p = NULL;
3398
3399 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3400 p = enc_to_utf16(name, NULL);
3401
3402 if (p != NULL)
3403 {
3404 res = SetFileAttributesW(p, attrs);
3405 if (res == FALSE
3406 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3407 {
3408 /* Retry with non-wide function (for Windows 98). */
3409 vim_free(p);
3410 p = NULL;
3411 }
3412 }
3413 if (p == NULL)
3414#endif
3415 res = SetFileAttributes((char *)name, attrs);
3416#ifdef FEAT_MBYTE
3417 vim_free(p);
3418#endif
3419 return res ? 0 : -1;
3420}
3421
3422/*
3423 * Set archive flag for "name".
3424 */
3425 static
3426 int
3427win32_set_archive(char_u *name)
3428{
3429 int attrs = win32_getattrs(name);
3430 if (attrs == -1)
3431 return -1;
3432
3433 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3434 return win32_setattrs(name, attrs);
3435}
3436
3437/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 * Return TRUE if file or directory "name" is writable (not readonly).
3439 * Strange semantics of Win32: a readonly directory is writable, but you can't
3440 * delete a file. Let's say this means it is writable.
3441 */
3442 int
3443mch_writable(char_u *name)
3444{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003445 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003446
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003447 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3448 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449}
3450
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451/*
3452 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003453 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454 * Return -1 if unknown.
3455 */
3456 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003457mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003459 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003460 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003461 char_u *p;
3462
3463 if (len >= _MAX_PATH) /* safety check */
3464 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003465 if (!use_path)
3466 {
3467 /* TODO: check if file is really executable. */
3468 return mch_getperm(name) != -1 && !mch_isdir(name);
3469 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003470
3471 /* If there already is an extension try using the name directly. Also do
3472 * this with a Unix-shell like 'shell'. */
3473 if (vim_strchr(gettail(name), '.') != NULL
3474 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003475 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003476 return TRUE;
3477
3478 /*
3479 * Loop over all extensions in $PATHEXT.
3480 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003481 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003482 p = mch_getenv("PATHEXT");
3483 if (p == NULL)
3484 p = (char_u *)".com;.exe;.bat;.cmd";
3485 while (*p)
3486 {
3487 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3488 {
3489 /* A single "." means no extension is added. */
3490 buf[len] = NUL;
3491 ++p;
3492 if (*p)
3493 ++p;
3494 }
3495 else
3496 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003497 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003498 return TRUE;
3499 }
3500 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502
3503/*
3504 * Check what "name" is:
3505 * NODE_NORMAL: file or directory (or doesn't exist)
3506 * NODE_WRITABLE: writable device, socket, fifo, etc.
3507 * NODE_OTHER: non-writable things
3508 */
3509 int
3510mch_nodetype(char_u *name)
3511{
3512 HANDLE hFile;
3513 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003514#ifdef FEAT_MBYTE
3515 WCHAR *wn = NULL;
3516#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517
Bram Moolenaar043545e2006-10-10 16:44:07 +00003518 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3519 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3520 * here. */
3521 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3522 return NODE_WRITABLE;
3523
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003524#ifdef FEAT_MBYTE
3525 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3526 {
3527 wn = enc_to_utf16(name, NULL);
3528 if (wn != NULL)
3529 {
3530 hFile = CreateFileW(wn, /* file name */
3531 GENERIC_WRITE, /* access mode */
3532 0, /* share mode */
3533 NULL, /* security descriptor */
3534 OPEN_EXISTING, /* creation disposition */
3535 0, /* file attributes */
3536 NULL); /* handle to template file */
3537 if (hFile == INVALID_HANDLE_VALUE
3538 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3539 {
3540 /* Retry with non-wide function (for Windows 98). */
3541 vim_free(wn);
3542 wn = NULL;
3543 }
3544 }
3545 }
3546 if (wn == NULL)
3547#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003548 hFile = CreateFile((LPCSTR)name, /* file name */
3549 GENERIC_WRITE, /* access mode */
3550 0, /* share mode */
3551 NULL, /* security descriptor */
3552 OPEN_EXISTING, /* creation disposition */
3553 0, /* file attributes */
3554 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003556#ifdef FEAT_MBYTE
3557 vim_free(wn);
3558#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559 if (hFile == INVALID_HANDLE_VALUE)
3560 return NODE_NORMAL;
3561
3562 type = GetFileType(hFile);
3563 CloseHandle(hFile);
3564 if (type == FILE_TYPE_CHAR)
3565 return NODE_WRITABLE;
3566 if (type == FILE_TYPE_DISK)
3567 return NODE_NORMAL;
3568 return NODE_OTHER;
3569}
3570
3571#ifdef HAVE_ACL
3572struct my_acl
3573{
3574 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3575 PSID pSidOwner;
3576 PSID pSidGroup;
3577 PACL pDacl;
3578 PACL pSacl;
3579};
3580#endif
3581
3582/*
3583 * Return a pointer to the ACL of file "fname" in allocated memory.
3584 * Return NULL if the ACL is not available for whatever reason.
3585 */
3586 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003587mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588{
3589#ifndef HAVE_ACL
3590 return (vim_acl_T)NULL;
3591#else
3592 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003593 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003594
3595 /* This only works on Windows NT and 2000. */
3596 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3597 {
3598 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3599 if (p != NULL)
3600 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003601# ifdef FEAT_MBYTE
3602 WCHAR *wn = NULL;
3603
3604 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3605 wn = enc_to_utf16(fname, NULL);
3606 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003608 /* Try to retrieve the entire security descriptor. */
3609 err = pGetNamedSecurityInfoW(
3610 wn, // Abstract filename
3611 SE_FILE_OBJECT, // File Object
3612 OWNER_SECURITY_INFORMATION |
3613 GROUP_SECURITY_INFORMATION |
3614 DACL_SECURITY_INFORMATION |
3615 SACL_SECURITY_INFORMATION,
3616 &p->pSidOwner, // Ownership information.
3617 &p->pSidGroup, // Group membership.
3618 &p->pDacl, // Discretionary information.
3619 &p->pSacl, // For auditing purposes.
3620 &p->pSecurityDescriptor);
3621 if (err == ERROR_ACCESS_DENIED ||
3622 err == ERROR_PRIVILEGE_NOT_HELD)
3623 {
3624 /* Retrieve only DACL. */
3625 (void)pGetNamedSecurityInfoW(
3626 wn,
3627 SE_FILE_OBJECT,
3628 DACL_SECURITY_INFORMATION,
3629 NULL,
3630 NULL,
3631 &p->pDacl,
3632 NULL,
3633 &p->pSecurityDescriptor);
3634 }
3635 if (p->pSecurityDescriptor == NULL)
3636 {
3637 mch_free_acl((vim_acl_T)p);
3638 p = NULL;
3639 }
3640 vim_free(wn);
3641 }
3642 else
3643# endif
3644 {
3645 /* Try to retrieve the entire security descriptor. */
3646 err = pGetNamedSecurityInfo(
3647 (LPSTR)fname, // Abstract filename
3648 SE_FILE_OBJECT, // File Object
3649 OWNER_SECURITY_INFORMATION |
3650 GROUP_SECURITY_INFORMATION |
3651 DACL_SECURITY_INFORMATION |
3652 SACL_SECURITY_INFORMATION,
3653 &p->pSidOwner, // Ownership information.
3654 &p->pSidGroup, // Group membership.
3655 &p->pDacl, // Discretionary information.
3656 &p->pSacl, // For auditing purposes.
3657 &p->pSecurityDescriptor);
3658 if (err == ERROR_ACCESS_DENIED ||
3659 err == ERROR_PRIVILEGE_NOT_HELD)
3660 {
3661 /* Retrieve only DACL. */
3662 (void)pGetNamedSecurityInfo(
3663 (LPSTR)fname,
3664 SE_FILE_OBJECT,
3665 DACL_SECURITY_INFORMATION,
3666 NULL,
3667 NULL,
3668 &p->pDacl,
3669 NULL,
3670 &p->pSecurityDescriptor);
3671 }
3672 if (p->pSecurityDescriptor == NULL)
3673 {
3674 mch_free_acl((vim_acl_T)p);
3675 p = NULL;
3676 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677 }
3678 }
3679 }
3680
3681 return (vim_acl_T)p;
3682#endif
3683}
3684
Bram Moolenaar27515922013-06-29 15:36:26 +02003685#ifdef HAVE_ACL
3686/*
3687 * Check if "acl" contains inherited ACE.
3688 */
3689 static BOOL
3690is_acl_inherited(PACL acl)
3691{
3692 DWORD i;
3693 ACL_SIZE_INFORMATION acl_info;
3694 PACCESS_ALLOWED_ACE ace;
3695
3696 acl_info.AceCount = 0;
3697 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3698 for (i = 0; i < acl_info.AceCount; i++)
3699 {
3700 GetAce(acl, i, (LPVOID *)&ace);
3701 if (ace->Header.AceFlags & INHERITED_ACE)
3702 return TRUE;
3703 }
3704 return FALSE;
3705}
3706#endif
3707
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708/*
3709 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3710 * Errors are ignored.
3711 * This must only be called with "acl" equal to what mch_get_acl() returned.
3712 */
3713 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003714mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715{
3716#ifdef HAVE_ACL
3717 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003718 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719
3720 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003721 {
3722# ifdef FEAT_MBYTE
3723 WCHAR *wn = NULL;
3724# endif
3725
3726 /* Set security flags */
3727 if (p->pSidOwner)
3728 sec_info |= OWNER_SECURITY_INFORMATION;
3729 if (p->pSidGroup)
3730 sec_info |= GROUP_SECURITY_INFORMATION;
3731 if (p->pDacl)
3732 {
3733 sec_info |= DACL_SECURITY_INFORMATION;
3734 /* Do not inherit its parent's DACL.
3735 * If the DACL is inherited, Cygwin permissions would be changed.
3736 */
3737 if (!is_acl_inherited(p->pDacl))
3738 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3739 }
3740 if (p->pSacl)
3741 sec_info |= SACL_SECURITY_INFORMATION;
3742
3743# ifdef FEAT_MBYTE
3744 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3745 wn = enc_to_utf16(fname, NULL);
3746 if (wn != NULL)
3747 {
3748 (void)pSetNamedSecurityInfoW(
3749 wn, // Abstract filename
3750 SE_FILE_OBJECT, // File Object
3751 sec_info,
3752 p->pSidOwner, // Ownership information.
3753 p->pSidGroup, // Group membership.
3754 p->pDacl, // Discretionary information.
3755 p->pSacl // For auditing purposes.
3756 );
3757 vim_free(wn);
3758 }
3759 else
3760# endif
3761 {
3762 (void)pSetNamedSecurityInfo(
3763 (LPSTR)fname, // Abstract filename
3764 SE_FILE_OBJECT, // File Object
3765 sec_info,
3766 p->pSidOwner, // Ownership information.
3767 p->pSidGroup, // Group membership.
3768 p->pDacl, // Discretionary information.
3769 p->pSacl // For auditing purposes.
3770 );
3771 }
3772 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773#endif
3774}
3775
3776 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003777mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003778{
3779#ifdef HAVE_ACL
3780 struct my_acl *p = (struct my_acl *)acl;
3781
3782 if (p != NULL)
3783 {
3784 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3785 vim_free(p);
3786 }
3787#endif
3788}
3789
3790#ifndef FEAT_GUI_W32
3791
3792/*
3793 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3794 */
3795 static BOOL WINAPI
3796handler_routine(
3797 DWORD dwCtrlType)
3798{
3799 switch (dwCtrlType)
3800 {
3801 case CTRL_C_EVENT:
3802 if (ctrl_c_interrupts)
3803 g_fCtrlCPressed = TRUE;
3804 return TRUE;
3805
3806 case CTRL_BREAK_EVENT:
3807 g_fCBrkPressed = TRUE;
3808 return TRUE;
3809
3810 /* fatal events: shut down gracefully */
3811 case CTRL_CLOSE_EVENT:
3812 case CTRL_LOGOFF_EVENT:
3813 case CTRL_SHUTDOWN_EVENT:
3814 windgoto((int)Rows - 1, 0);
3815 g_fForceExit = TRUE;
3816
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003817 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 (dwCtrlType == CTRL_CLOSE_EVENT
3819 ? _("close")
3820 : dwCtrlType == CTRL_LOGOFF_EVENT
3821 ? _("logoff")
3822 : _("shutdown")));
3823#ifdef DEBUG
3824 OutputDebugString(IObuff);
3825#endif
3826
3827 preserve_exit(); /* output IObuff, preserve files and exit */
3828
3829 return TRUE; /* not reached */
3830
3831 default:
3832 return FALSE;
3833 }
3834}
3835
3836
3837/*
3838 * set the tty in (raw) ? "raw" : "cooked" mode
3839 */
3840 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003841mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842{
3843 DWORD cmodein;
3844 DWORD cmodeout;
3845 BOOL bEnableHandler;
3846
3847 GetConsoleMode(g_hConIn, &cmodein);
3848 GetConsoleMode(g_hConOut, &cmodeout);
3849 if (tmode == TMODE_RAW)
3850 {
3851 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3852 ENABLE_ECHO_INPUT);
3853#ifdef FEAT_MOUSE
3854 if (g_fMouseActive)
3855 cmodein |= ENABLE_MOUSE_INPUT;
3856#endif
3857 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3858 bEnableHandler = TRUE;
3859 }
3860 else /* cooked */
3861 {
3862 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3863 ENABLE_ECHO_INPUT);
3864 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3865 bEnableHandler = FALSE;
3866 }
3867 SetConsoleMode(g_hConIn, cmodein);
3868 SetConsoleMode(g_hConOut, cmodeout);
3869 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3870
3871#ifdef MCH_WRITE_DUMP
3872 if (fdDump)
3873 {
3874 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3875 tmode == TMODE_RAW ? "raw" :
3876 tmode == TMODE_COOK ? "cooked" : "normal",
3877 cmodein, cmodeout);
3878 fflush(fdDump);
3879 }
3880#endif
3881}
3882
3883
3884/*
3885 * Get the size of the current window in `Rows' and `Columns'
3886 * Return OK when size could be determined, FAIL otherwise.
3887 */
3888 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003889mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890{
3891 CONSOLE_SCREEN_BUFFER_INFO csbi;
3892
3893 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3894 {
3895 /*
3896 * For some reason, we are trying to get the screen dimensions
3897 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3898 * variables are really intended to mean the size of Vim screen
3899 * while in termcap mode.
3900 */
3901 Rows = g_cbTermcap.Info.dwSize.Y;
3902 Columns = g_cbTermcap.Info.dwSize.X;
3903 }
3904 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3905 {
3906 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3907 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3908 }
3909 else
3910 {
3911 Rows = 25;
3912 Columns = 80;
3913 }
3914 return OK;
3915}
3916
3917/*
3918 * Set a console window to `xSize' * `ySize'
3919 */
3920 static void
3921ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003922 HANDLE hConsole,
3923 int xSize,
3924 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925{
3926 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3927 SMALL_RECT srWindowRect; /* hold the new console size */
3928 COORD coordScreen;
3929
3930#ifdef MCH_WRITE_DUMP
3931 if (fdDump)
3932 {
3933 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3934 fflush(fdDump);
3935 }
3936#endif
3937
3938 /* get the largest size we can size the console window to */
3939 coordScreen = GetLargestConsoleWindowSize(hConsole);
3940
3941 /* define the new console window size and scroll position */
3942 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3943 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3944 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3945
3946 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3947 {
3948 int sx, sy;
3949
3950 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3951 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3952 if (sy < ySize || sx < xSize)
3953 {
3954 /*
3955 * Increasing number of lines/columns, do buffer first.
3956 * Use the maximal size in x and y direction.
3957 */
3958 if (sy < ySize)
3959 coordScreen.Y = ySize;
3960 else
3961 coordScreen.Y = sy;
3962 if (sx < xSize)
3963 coordScreen.X = xSize;
3964 else
3965 coordScreen.X = sx;
3966 SetConsoleScreenBufferSize(hConsole, coordScreen);
3967 }
3968 }
3969
3970 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3971 {
3972#ifdef MCH_WRITE_DUMP
3973 if (fdDump)
3974 {
3975 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3976 GetLastError());
3977 fflush(fdDump);
3978 }
3979#endif
3980 }
3981
3982 /* define the new console buffer size */
3983 coordScreen.X = xSize;
3984 coordScreen.Y = ySize;
3985
3986 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3987 {
3988#ifdef MCH_WRITE_DUMP
3989 if (fdDump)
3990 {
3991 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3992 GetLastError());
3993 fflush(fdDump);
3994 }
3995#endif
3996 }
3997}
3998
3999
4000/*
4001 * Set the console window to `Rows' * `Columns'
4002 */
4003 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004004mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004005{
4006 COORD coordScreen;
4007
4008 /* Don't change window size while still starting up */
4009 if (suppress_winsize != 0)
4010 {
4011 suppress_winsize = 2;
4012 return;
4013 }
4014
4015 if (term_console)
4016 {
4017 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4018
4019 /* Clamp Rows and Columns to reasonable values */
4020 if (Rows > coordScreen.Y)
4021 Rows = coordScreen.Y;
4022 if (Columns > coordScreen.X)
4023 Columns = coordScreen.X;
4024
4025 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4026 }
4027}
4028
4029/*
4030 * Rows and/or Columns has changed.
4031 */
4032 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004033mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034{
4035 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4036}
4037
4038
4039/*
4040 * Called when started up, to set the winsize that was delayed.
4041 */
4042 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004043mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004044{
4045 if (suppress_winsize == 2)
4046 {
4047 suppress_winsize = 0;
4048 mch_set_shellsize();
4049 shell_resized();
4050 }
4051 suppress_winsize = 0;
4052}
4053#endif /* FEAT_GUI_W32 */
4054
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004055 static BOOL
4056vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004057 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004058 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004059 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004060 STARTUPINFO *si,
4061 PROCESS_INFORMATION *pi)
4062{
4063# ifdef FEAT_MBYTE
4064 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4065 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004066 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004067
4068 if (wcmd != NULL)
4069 {
4070 BOOL ret;
4071 ret = CreateProcessW(
4072 NULL, /* Executable name */
4073 wcmd, /* Command to execute */
4074 NULL, /* Process security attributes */
4075 NULL, /* Thread security attributes */
4076 inherit_handles, /* Inherit handles */
4077 flags, /* Creation flags */
4078 NULL, /* Environment */
4079 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004080 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004081 pi); /* Process information */
4082 vim_free(wcmd);
4083 return ret;
4084 }
4085 }
4086#endif
4087 return CreateProcess(
4088 NULL, /* Executable name */
4089 cmd, /* Command to execute */
4090 NULL, /* Process security attributes */
4091 NULL, /* Thread security attributes */
4092 inherit_handles, /* Inherit handles */
4093 flags, /* Creation flags */
4094 NULL, /* Environment */
4095 NULL, /* Current directory */
4096 si, /* Startup information */
4097 pi); /* Process information */
4098}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004099
4100
4101#if defined(FEAT_GUI_W32) || defined(PROTO)
4102
4103/*
4104 * Specialised version of system() for Win32 GUI mode.
4105 * This version proceeds as follows:
4106 * 1. Create a console window for use by the subprocess
4107 * 2. Run the subprocess (it gets the allocated console by default)
4108 * 3. Wait for the subprocess to terminate and get its exit code
4109 * 4. Prompt the user to press a key to close the console window
4110 */
4111 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004112mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113{
4114 STARTUPINFO si;
4115 PROCESS_INFORMATION pi;
4116 DWORD ret = 0;
4117 HWND hwnd = GetFocus();
4118
4119 si.cb = sizeof(si);
4120 si.lpReserved = NULL;
4121 si.lpDesktop = NULL;
4122 si.lpTitle = NULL;
4123 si.dwFlags = STARTF_USESHOWWINDOW;
4124 /*
4125 * It's nicer to run a filter command in a minimized window, but in
4126 * Windows 95 this makes the command MUCH slower. We can't do it under
4127 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004128 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129 */
4130 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004131 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 else
4133 si.wShowWindow = SW_SHOWNORMAL;
4134 si.cbReserved2 = 0;
4135 si.lpReserved2 = NULL;
4136
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004137 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 * When the "c:\\" is left out it works OK...? */
4139 if (mch_windows95()
4140 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4141 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4142 cmd += 3;
4143
4144 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004145 vim_create_process(cmd, FALSE,
4146 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147
4148 /* Wait for the command to terminate before continuing */
4149 if (g_PlatformId != VER_PLATFORM_WIN32s)
4150 {
4151#ifdef FEAT_GUI
4152 int delay = 1;
4153
4154 /* Keep updating the window while waiting for the shell to finish. */
4155 for (;;)
4156 {
4157 MSG msg;
4158
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004159 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160 {
4161 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004162 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004163 delay = 1;
4164 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165 }
4166 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4167 break;
4168
4169 /* We start waiting for a very short time and then increase it, so
4170 * that we respond quickly when the process is quick, and don't
4171 * consume too much overhead when it's slow. */
4172 if (delay < 50)
4173 delay += 10;
4174 }
4175#else
4176 WaitForSingleObject(pi.hProcess, INFINITE);
4177#endif
4178
4179 /* Get the command exit code */
4180 GetExitCodeProcess(pi.hProcess, &ret);
4181 }
4182 else
4183 {
4184 /*
4185 * This ugly code is the only quick way of performing
4186 * a synchronous spawn under Win32s. Yuk.
4187 */
4188 num_windows = 0;
4189 EnumWindows(win32ssynch_cb, 0);
4190 old_num_windows = num_windows;
4191 do
4192 {
4193 Sleep(1000);
4194 num_windows = 0;
4195 EnumWindows(win32ssynch_cb, 0);
4196 } while (num_windows == old_num_windows);
4197 ret = 0;
4198 }
4199
4200 /* Close the handles to the subprocess, so that it goes away */
4201 CloseHandle(pi.hThread);
4202 CloseHandle(pi.hProcess);
4203
4204 /* Try to get input focus back. Doesn't always work though. */
4205 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4206
4207 return ret;
4208}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004209
4210/*
4211 * Thread launched by the gui to send the current buffer data to the
4212 * process. This way avoid to hang up vim totally if the children
4213 * process take a long time to process the lines.
4214 */
4215 static DWORD WINAPI
4216sub_process_writer(LPVOID param)
4217{
4218 HANDLE g_hChildStd_IN_Wr = param;
4219 linenr_T lnum = curbuf->b_op_start.lnum;
4220 DWORD len = 0;
4221 DWORD l;
4222 char_u *lp = ml_get(lnum);
4223 char_u *s;
4224 int written = 0;
4225
4226 for (;;)
4227 {
4228 l = (DWORD)STRLEN(lp + written);
4229 if (l == 0)
4230 len = 0;
4231 else if (lp[written] == NL)
4232 {
4233 /* NL -> NUL translation */
4234 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4235 }
4236 else
4237 {
4238 s = vim_strchr(lp + written, NL);
4239 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4240 s == NULL ? l : (DWORD)(s - (lp + written)),
4241 &len, NULL);
4242 }
4243 if (len == (int)l)
4244 {
4245 /* Finished a line, add a NL, unless this line should not have
4246 * one. */
4247 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004248 || (!curbuf->b_p_bin
4249 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004250 || (lnum != curbuf->b_no_eol_lnum
4251 && (lnum != curbuf->b_ml.ml_line_count
4252 || curbuf->b_p_eol)))
4253 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004254 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004255 }
4256
4257 ++lnum;
4258 if (lnum > curbuf->b_op_end.lnum)
4259 break;
4260
4261 lp = ml_get(lnum);
4262 written = 0;
4263 }
4264 else if (len > 0)
4265 written += len;
4266 }
4267
4268 /* finished all the lines, close pipe */
4269 CloseHandle(g_hChildStd_IN_Wr);
4270 ExitThread(0);
4271}
4272
4273
4274# define BUFLEN 100 /* length for buffer, stolen from unix version */
4275
4276/*
4277 * This function read from the children's stdout and write the
4278 * data on screen or in the buffer accordingly.
4279 */
4280 static void
4281dump_pipe(int options,
4282 HANDLE g_hChildStd_OUT_Rd,
4283 garray_T *ga,
4284 char_u buffer[],
4285 DWORD *buffer_off)
4286{
4287 DWORD availableBytes = 0;
4288 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004289 int ret;
4290 DWORD len;
4291 DWORD toRead;
4292 int repeatCount;
4293
4294 /* we query the pipe to see if there is any data to read
4295 * to avoid to perform a blocking read */
4296 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4297 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004298 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004299 NULL, /* number of read bytes */
4300 &availableBytes, /* available bytes total */
4301 NULL); /* byteLeft */
4302
4303 repeatCount = 0;
4304 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004305 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004306 {
4307 repeatCount++;
4308 toRead =
4309# ifdef FEAT_MBYTE
4310 (DWORD)(BUFLEN - *buffer_off);
4311# else
4312 (DWORD)BUFLEN;
4313# endif
4314 toRead = availableBytes < toRead ? availableBytes : toRead;
4315 ReadFile(g_hChildStd_OUT_Rd, buffer
4316# ifdef FEAT_MBYTE
4317 + *buffer_off, toRead
4318# else
4319 , toRead
4320# endif
4321 , &len, NULL);
4322
4323 /* If we haven't read anything, there is a problem */
4324 if (len == 0)
4325 break;
4326
4327 availableBytes -= len;
4328
4329 if (options & SHELL_READ)
4330 {
4331 /* Do NUL -> NL translation, append NL separated
4332 * lines to the current buffer. */
4333 for (i = 0; i < len; ++i)
4334 {
4335 if (buffer[i] == NL)
4336 append_ga_line(ga);
4337 else if (buffer[i] == NUL)
4338 ga_append(ga, NL);
4339 else
4340 ga_append(ga, buffer[i]);
4341 }
4342 }
4343# ifdef FEAT_MBYTE
4344 else if (has_mbyte)
4345 {
4346 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004347 int c;
4348 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004349
4350 len += *buffer_off;
4351 buffer[len] = NUL;
4352
4353 /* Check if the last character in buffer[] is
4354 * incomplete, keep these bytes for the next
4355 * round. */
4356 for (p = buffer; p < buffer + len; p += l)
4357 {
4358 l = mb_cptr2len(p);
4359 if (l == 0)
4360 l = 1; /* NUL byte? */
4361 else if (MB_BYTE2LEN(*p) != l)
4362 break;
4363 }
4364 if (p == buffer) /* no complete character */
4365 {
4366 /* avoid getting stuck at an illegal byte */
4367 if (len >= 12)
4368 ++p;
4369 else
4370 {
4371 *buffer_off = len;
4372 return;
4373 }
4374 }
4375 c = *p;
4376 *p = NUL;
4377 msg_puts(buffer);
4378 if (p < buffer + len)
4379 {
4380 *p = c;
4381 *buffer_off = (DWORD)((buffer + len) - p);
4382 mch_memmove(buffer, p, *buffer_off);
4383 return;
4384 }
4385 *buffer_off = 0;
4386 }
4387# endif /* FEAT_MBYTE */
4388 else
4389 {
4390 buffer[len] = NUL;
4391 msg_puts(buffer);
4392 }
4393
4394 windgoto(msg_row, msg_col);
4395 cursor_on();
4396 out_flush();
4397 }
4398}
4399
4400/*
4401 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4402 * for communication and doesn't open any new window.
4403 */
4404 static int
4405mch_system_piped(char *cmd, int options)
4406{
4407 STARTUPINFO si;
4408 PROCESS_INFORMATION pi;
4409 DWORD ret = 0;
4410
4411 HANDLE g_hChildStd_IN_Rd = NULL;
4412 HANDLE g_hChildStd_IN_Wr = NULL;
4413 HANDLE g_hChildStd_OUT_Rd = NULL;
4414 HANDLE g_hChildStd_OUT_Wr = NULL;
4415
4416 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4417 DWORD len;
4418
4419 /* buffer used to receive keys */
4420 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4421 int ta_len = 0; /* valid bytes in ta_buf[] */
4422
4423 DWORD i;
4424 int c;
4425 int noread_cnt = 0;
4426 garray_T ga;
4427 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004428 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004429 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004430
4431 SECURITY_ATTRIBUTES saAttr;
4432
4433 /* Set the bInheritHandle flag so pipe handles are inherited. */
4434 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4435 saAttr.bInheritHandle = TRUE;
4436 saAttr.lpSecurityDescriptor = NULL;
4437
4438 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4439 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4440 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4441 /* Create a pipe for the child process's STDIN. */
4442 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4443 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4444 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4445 {
4446 CloseHandle(g_hChildStd_IN_Rd);
4447 CloseHandle(g_hChildStd_IN_Wr);
4448 CloseHandle(g_hChildStd_OUT_Rd);
4449 CloseHandle(g_hChildStd_OUT_Wr);
4450 MSG_PUTS(_("\nCannot create pipes\n"));
4451 }
4452
4453 si.cb = sizeof(si);
4454 si.lpReserved = NULL;
4455 si.lpDesktop = NULL;
4456 si.lpTitle = NULL;
4457 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4458
4459 /* set-up our file redirection */
4460 si.hStdError = g_hChildStd_OUT_Wr;
4461 si.hStdOutput = g_hChildStd_OUT_Wr;
4462 si.hStdInput = g_hChildStd_IN_Rd;
4463 si.wShowWindow = SW_HIDE;
4464 si.cbReserved2 = 0;
4465 si.lpReserved2 = NULL;
4466
4467 if (options & SHELL_READ)
4468 ga_init2(&ga, 1, BUFLEN);
4469
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004470 if (cmd != NULL)
4471 {
4472 p = (char *)vim_strsave((char_u *)cmd);
4473 if (p != NULL)
4474 unescape_shellxquote((char_u *)p, p_sxe);
4475 else
4476 p = cmd;
4477 }
4478
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004479 /* Now, run the command.
4480 * About "Inherit handles" being TRUE: this command can be litigious,
4481 * handle inheritance was deactivated for pending temp file, but, if we
4482 * deactivate it, the pipes don't work for some reason. */
4483 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004484
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004485 if (p != cmd)
4486 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004487
4488 /* Close our unused side of the pipes */
4489 CloseHandle(g_hChildStd_IN_Rd);
4490 CloseHandle(g_hChildStd_OUT_Wr);
4491
4492 if (options & SHELL_WRITE)
4493 {
4494 HANDLE thread =
4495 CreateThread(NULL, /* security attributes */
4496 0, /* default stack size */
4497 sub_process_writer, /* function to be executed */
4498 g_hChildStd_IN_Wr, /* parameter */
4499 0, /* creation flag, start immediately */
4500 NULL); /* we don't care about thread id */
4501 CloseHandle(thread);
4502 g_hChildStd_IN_Wr = NULL;
4503 }
4504
4505 /* Keep updating the window while waiting for the shell to finish. */
4506 for (;;)
4507 {
4508 MSG msg;
4509
Bram Moolenaar175d0702013-12-11 18:36:33 +01004510 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004511 {
4512 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004513 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004514 }
4515
4516 /* write pipe information in the window */
4517 if ((options & (SHELL_READ|SHELL_WRITE))
4518# ifdef FEAT_GUI
4519 || gui.in_use
4520# endif
4521 )
4522 {
4523 len = 0;
4524 if (!(options & SHELL_EXPAND)
4525 && ((options &
4526 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4527 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4528# ifdef FEAT_GUI
4529 || gui.in_use
4530# endif
4531 )
4532 && (ta_len > 0 || noread_cnt > 4))
4533 {
4534 if (ta_len == 0)
4535 {
4536 /* Get extra characters when we don't have any. Reset the
4537 * counter and timer. */
4538 noread_cnt = 0;
4539# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4540 gettimeofday(&start_tv, NULL);
4541# endif
4542 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4543 }
4544 if (ta_len > 0 || len > 0)
4545 {
4546 /*
4547 * For pipes: Check for CTRL-C: send interrupt signal to
4548 * child. Check for CTRL-D: EOF, close pipe to child.
4549 */
4550 if (len == 1 && cmd != NULL)
4551 {
4552 if (ta_buf[ta_len] == Ctrl_C)
4553 {
4554 /* Learn what exit code is expected, for
4555 * now put 9 as SIGKILL */
4556 TerminateProcess(pi.hProcess, 9);
4557 }
4558 if (ta_buf[ta_len] == Ctrl_D)
4559 {
4560 CloseHandle(g_hChildStd_IN_Wr);
4561 g_hChildStd_IN_Wr = NULL;
4562 }
4563 }
4564
4565 /* replace K_BS by <BS> and K_DEL by <DEL> */
4566 for (i = ta_len; i < ta_len + len; ++i)
4567 {
4568 if (ta_buf[i] == CSI && len - i > 2)
4569 {
4570 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4571 if (c == K_DEL || c == K_KDEL || c == K_BS)
4572 {
4573 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4574 (size_t)(len - i - 2));
4575 if (c == K_DEL || c == K_KDEL)
4576 ta_buf[i] = DEL;
4577 else
4578 ta_buf[i] = Ctrl_H;
4579 len -= 2;
4580 }
4581 }
4582 else if (ta_buf[i] == '\r')
4583 ta_buf[i] = '\n';
4584# ifdef FEAT_MBYTE
4585 if (has_mbyte)
4586 i += (*mb_ptr2len_len)(ta_buf + i,
4587 ta_len + len - i) - 1;
4588# endif
4589 }
4590
4591 /*
4592 * For pipes: echo the typed characters. For a pty this
4593 * does not seem to work.
4594 */
4595 for (i = ta_len; i < ta_len + len; ++i)
4596 {
4597 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4598 msg_putchar(ta_buf[i]);
4599# ifdef FEAT_MBYTE
4600 else if (has_mbyte)
4601 {
4602 int l = (*mb_ptr2len)(ta_buf + i);
4603
4604 msg_outtrans_len(ta_buf + i, l);
4605 i += l - 1;
4606 }
4607# endif
4608 else
4609 msg_outtrans_len(ta_buf + i, 1);
4610 }
4611 windgoto(msg_row, msg_col);
4612 out_flush();
4613
4614 ta_len += len;
4615
4616 /*
4617 * Write the characters to the child, unless EOF has been
4618 * typed for pipes. Write one character at a time, to
4619 * avoid losing too much typeahead. When writing buffer
4620 * lines, drop the typed characters (only check for
4621 * CTRL-C).
4622 */
4623 if (options & SHELL_WRITE)
4624 ta_len = 0;
4625 else if (g_hChildStd_IN_Wr != NULL)
4626 {
4627 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4628 1, &len, NULL);
4629 // if we are typing in, we want to keep things reactive
4630 delay = 1;
4631 if (len > 0)
4632 {
4633 ta_len -= len;
4634 mch_memmove(ta_buf, ta_buf + len, ta_len);
4635 }
4636 }
4637 }
4638 }
4639 }
4640
4641 if (ta_len)
4642 ui_inchar_undo(ta_buf, ta_len);
4643
4644 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4645 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004646 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004647 break;
4648 }
4649
4650 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004651 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004652
4653 /* We start waiting for a very short time and then increase it, so
4654 * that we respond quickly when the process is quick, and don't
4655 * consume too much overhead when it's slow. */
4656 if (delay < 50)
4657 delay += 10;
4658 }
4659
4660 /* Close the pipe */
4661 CloseHandle(g_hChildStd_OUT_Rd);
4662 if (g_hChildStd_IN_Wr != NULL)
4663 CloseHandle(g_hChildStd_IN_Wr);
4664
4665 WaitForSingleObject(pi.hProcess, INFINITE);
4666
4667 /* Get the command exit code */
4668 GetExitCodeProcess(pi.hProcess, &ret);
4669
4670 if (options & SHELL_READ)
4671 {
4672 if (ga.ga_len > 0)
4673 {
4674 append_ga_line(&ga);
4675 /* remember that the NL was missing */
4676 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4677 }
4678 else
4679 curbuf->b_no_eol_lnum = 0;
4680 ga_clear(&ga);
4681 }
4682
4683 /* Close the handles to the subprocess, so that it goes away */
4684 CloseHandle(pi.hThread);
4685 CloseHandle(pi.hProcess);
4686
4687 return ret;
4688}
4689
4690 static int
4691mch_system(char *cmd, int options)
4692{
4693 /* if we can pipe and the shelltemp option is off */
4694 if (allowPiping && !p_stmp)
4695 return mch_system_piped(cmd, options);
4696 else
4697 return mch_system_classic(cmd, options);
4698}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004699#else
4700
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004701# ifdef FEAT_MBYTE
4702 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004703mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004704{
4705 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4706 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004707 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004708 if (wcmd != NULL)
4709 {
4710 int ret = _wsystem(wcmd);
4711 vim_free(wcmd);
4712 return ret;
4713 }
4714 }
4715 return system(cmd);
4716}
4717# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004718# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004719# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004720
4721#endif
4722
4723/*
4724 * Either execute a command by calling the shell or start a new shell
4725 */
4726 int
4727mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004728 char_u *cmd,
4729 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004730{
4731 int x = 0;
4732 int tmode = cur_tmode;
4733#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004734 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004735# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004736 int did_set_title = FALSE;
4737
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004738 /* Change the title to reflect that we are in a subshell. */
4739 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4740 {
4741 WCHAR szShellTitle[512];
4742
4743 if (GetConsoleTitleW(szShellTitle,
4744 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4745 {
4746 if (cmd == NULL)
4747 wcscat(szShellTitle, L" :sh");
4748 else
4749 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004750 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004751
4752 if (wn != NULL)
4753 {
4754 wcscat(szShellTitle, L" - !");
4755 if ((wcslen(szShellTitle) + wcslen(wn) <
4756 sizeof(szShellTitle)/sizeof(WCHAR)))
4757 wcscat(szShellTitle, wn);
4758 SetConsoleTitleW(szShellTitle);
4759 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004760 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004761 }
4762 }
4763 }
4764 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004765 if (!did_set_title)
4766# endif
4767 /* Change the title to reflect that we are in a subshell. */
4768 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004770 if (cmd == NULL)
4771 strcat(szShellTitle, " :sh");
4772 else
4773 {
4774 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004775 if ((strlen(szShellTitle) + strlen((char *)cmd)
4776 < sizeof(szShellTitle)))
4777 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004778 }
4779 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781#endif
4782
4783 out_flush();
4784
4785#ifdef MCH_WRITE_DUMP
4786 if (fdDump)
4787 {
4788 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4789 fflush(fdDump);
4790 }
4791#endif
4792
4793 /*
4794 * Catch all deadly signals while running the external command, because a
4795 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4796 */
4797 signal(SIGINT, SIG_IGN);
4798#if defined(__GNUC__) && !defined(__MINGW32__)
4799 signal(SIGKILL, SIG_IGN);
4800#else
4801 signal(SIGBREAK, SIG_IGN);
4802#endif
4803 signal(SIGILL, SIG_IGN);
4804 signal(SIGFPE, SIG_IGN);
4805 signal(SIGSEGV, SIG_IGN);
4806 signal(SIGTERM, SIG_IGN);
4807 signal(SIGABRT, SIG_IGN);
4808
4809 if (options & SHELL_COOKED)
4810 settmode(TMODE_COOK); /* set to normal mode */
4811
4812 if (cmd == NULL)
4813 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004814 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004815 }
4816 else
4817 {
4818 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004819 char_u *newcmd = NULL;
4820 char_u *cmdbase = cmd;
4821 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004822
4823 /* Skip a leading ", ( and "(. */
4824 if (*cmdbase == '"' )
4825 ++cmdbase;
4826 if (*cmdbase == '(')
4827 ++cmdbase;
4828
4829 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4830 {
4831 STARTUPINFO si;
4832 PROCESS_INFORMATION pi;
4833 DWORD flags = CREATE_NEW_CONSOLE;
4834 char_u *p;
4835
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004836 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004837 si.cb = sizeof(si);
4838 si.lpReserved = NULL;
4839 si.lpDesktop = NULL;
4840 si.lpTitle = NULL;
4841 si.dwFlags = 0;
4842 si.cbReserved2 = 0;
4843 si.lpReserved2 = NULL;
4844
4845 cmdbase = skipwhite(cmdbase + 5);
4846 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4847 && vim_iswhite(cmdbase[4]))
4848 {
4849 cmdbase = skipwhite(cmdbase + 4);
4850 si.dwFlags = STARTF_USESHOWWINDOW;
4851 si.wShowWindow = SW_SHOWMINNOACTIVE;
4852 }
4853 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4854 && vim_iswhite(cmdbase[2]))
4855 {
4856 cmdbase = skipwhite(cmdbase + 2);
4857 flags = CREATE_NO_WINDOW;
4858 si.dwFlags = STARTF_USESTDHANDLES;
4859 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004860 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004861 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004862 NULL, // Security att.
4863 OPEN_EXISTING, // Open flags
4864 FILE_ATTRIBUTE_NORMAL, // File att.
4865 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004866 si.hStdOutput = si.hStdInput;
4867 si.hStdError = si.hStdInput;
4868 }
4869
4870 /* Remove a trailing ", ) and )" if they have a match
4871 * at the start of the command. */
4872 if (cmdbase > cmd)
4873 {
4874 p = cmdbase + STRLEN(cmdbase);
4875 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4876 *--p = NUL;
4877 if (p > cmdbase && p[-1] == ')'
4878 && (*cmd =='(' || cmd[1] == '('))
4879 *--p = NUL;
4880 }
4881
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004882 newcmd = cmdbase;
4883 unescape_shellxquote(cmdbase, p_sxe);
4884
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004885 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004886 * If creating new console, arguments are passed to the
4887 * 'cmd.exe' as-is. If it's not, arguments are not treated
4888 * correctly for current 'cmd.exe'. So unescape characters in
4889 * shellxescape except '|' for avoiding to be treated as
4890 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004891 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004892 if (flags != CREATE_NEW_CONSOLE)
4893 {
4894 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004895 char_u *cmd_shell = mch_getenv("COMSPEC");
4896
4897 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004898 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004899
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004900 subcmd = vim_strsave_escaped_ext(cmdbase,
4901 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004902 if (subcmd != NULL)
4903 {
4904 /* make "cmd.exe /c arguments" */
4905 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004906 newcmd = lalloc(cmdlen, TRUE);
4907 if (newcmd != NULL)
4908 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004909 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004910 else
4911 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004912 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004913 }
4914 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004915
4916 /*
4917 * Now, start the command as a process, so that it doesn't
4918 * inherit our handles which causes unpleasant dangling swap
4919 * files if we exit before the spawned process
4920 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004921 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004922 x = 0;
4923 else
4924 {
4925 x = -1;
4926#ifdef FEAT_GUI_W32
4927 EMSG(_("E371: Command not found"));
4928#endif
4929 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004930
4931 if (newcmd != cmdbase)
4932 vim_free(newcmd);
4933
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004934 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004935 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004936 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004937 CloseHandle(si.hStdInput);
4938 }
4939 /* Close the handles to the subprocess, so that it goes away */
4940 CloseHandle(pi.hThread);
4941 CloseHandle(pi.hProcess);
4942 }
4943 else
4944 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004945 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004946#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004947 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004948#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004949 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4950
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004951 newcmd = lalloc(cmdlen, TRUE);
4952 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953 {
4954#if defined(FEAT_GUI_W32)
4955 if (need_vimrun_warning)
4956 {
4957 MessageBox(NULL,
4958 _("VIMRUN.EXE not found in your $PATH.\n"
4959 "External commands will not pause after completion.\n"
4960 "See :help win32-vimrun for more information."),
4961 _("Vim Warning"),
4962 MB_ICONWARNING);
4963 need_vimrun_warning = FALSE;
4964 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004965 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004966 /* Use vimrun to execute the command. It opens a console
4967 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004968 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004969 vimrun_path,
4970 (msg_silent != 0 || (options & SHELL_DOOUT))
4971 ? "-s " : "",
4972 p_sh, p_shcf, cmd);
4973 else
4974#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004975 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004976 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004978 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004980 }
4981 }
4982
4983 if (tmode == TMODE_RAW)
4984 settmode(TMODE_RAW); /* set to raw mode */
4985
4986 /* Print the return value, unless "vimrun" was used. */
4987 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4988#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004989 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4990 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004991#endif
4992 )
4993 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004994 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995 msg_putchar('\n');
4996 }
4997#ifdef FEAT_TITLE
4998 resettitle();
4999#endif
5000
5001 signal(SIGINT, SIG_DFL);
5002#if defined(__GNUC__) && !defined(__MINGW32__)
5003 signal(SIGKILL, SIG_DFL);
5004#else
5005 signal(SIGBREAK, SIG_DFL);
5006#endif
5007 signal(SIGILL, SIG_DFL);
5008 signal(SIGFPE, SIG_DFL);
5009 signal(SIGSEGV, SIG_DFL);
5010 signal(SIGTERM, SIG_DFL);
5011 signal(SIGABRT, SIG_DFL);
5012
5013 return x;
5014}
5015
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005016#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005017 static HANDLE
5018job_io_file_open(
5019 char_u *fname,
5020 DWORD dwDesiredAccess,
5021 DWORD dwShareMode,
5022 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5023 DWORD dwCreationDisposition,
5024 DWORD dwFlagsAndAttributes)
5025{
5026 HANDLE h;
5027# ifdef FEAT_MBYTE
5028 WCHAR *wn = NULL;
5029 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5030 {
5031 wn = enc_to_utf16(fname, NULL);
5032 if (wn != NULL)
5033 {
5034 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5035 lpSecurityAttributes, dwCreationDisposition,
5036 dwFlagsAndAttributes, NULL);
5037 vim_free(wn);
5038 if (h == INVALID_HANDLE_VALUE
5039 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5040 wn = NULL;
5041 }
5042 }
5043 if (wn == NULL)
5044# endif
5045
5046 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5047 lpSecurityAttributes, dwCreationDisposition,
5048 dwFlagsAndAttributes, NULL);
5049 return h;
5050}
5051
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005052 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005053mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005054{
5055 STARTUPINFO si;
5056 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005057 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005058 SECURITY_ATTRIBUTES saAttr;
5059 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005060 HANDLE ifd[2];
5061 HANDLE ofd[2];
5062 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005063
5064 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5065 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5066 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5067 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5068 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5069 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5070 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5071
5072 if (use_out_for_err && use_null_for_out)
5073 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005074
5075 ifd[0] = INVALID_HANDLE_VALUE;
5076 ifd[1] = INVALID_HANDLE_VALUE;
5077 ofd[0] = INVALID_HANDLE_VALUE;
5078 ofd[1] = INVALID_HANDLE_VALUE;
5079 efd[0] = INVALID_HANDLE_VALUE;
5080 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005081
Bram Moolenaar76467df2016-02-12 19:30:26 +01005082 jo = CreateJobObject(NULL, NULL);
5083 if (jo == NULL)
5084 {
5085 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005086 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005087 }
5088
5089 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005090 ZeroMemory(&si, sizeof(si));
5091 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005092 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005093 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005094
Bram Moolenaard8070362016-02-15 21:56:54 +01005095 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5096 saAttr.bInheritHandle = TRUE;
5097 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005098
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005099 if (use_file_for_in)
5100 {
5101 char_u *fname = options->jo_io_name[PART_IN];
5102
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005103 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5104 FILE_SHARE_READ | FILE_SHARE_WRITE,
5105 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5106 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005107 {
5108 EMSG2(_(e_notopen), fname);
5109 goto failed;
5110 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005111 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005112 else if (!use_null_for_in &&
5113 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5114 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005115 goto failed;
5116
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005117 if (use_file_for_out)
5118 {
5119 char_u *fname = options->jo_io_name[PART_OUT];
5120
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005121 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5122 FILE_SHARE_READ | FILE_SHARE_WRITE,
5123 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5124 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005125 {
5126 EMSG2(_(e_notopen), fname);
5127 goto failed;
5128 }
5129 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005130 else if (!use_null_for_out &&
5131 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5132 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005133 goto failed;
5134
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005135 if (use_file_for_err)
5136 {
5137 char_u *fname = options->jo_io_name[PART_ERR];
5138
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005139 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5140 FILE_SHARE_READ | FILE_SHARE_WRITE,
5141 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5142 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005143 {
5144 EMSG2(_(e_notopen), fname);
5145 goto failed;
5146 }
5147 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005148 else if (!use_out_for_err && !use_null_for_err &&
5149 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005150 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005151 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005152
Bram Moolenaard8070362016-02-15 21:56:54 +01005153 si.dwFlags |= STARTF_USESTDHANDLES;
5154 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005155 si.hStdOutput = ofd[1];
5156 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5157
5158 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5159 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005160 if (options->jo_set & JO_CHANNEL)
5161 {
5162 channel = options->jo_channel;
5163 if (channel != NULL)
5164 ++channel->ch_refcount;
5165 }
5166 else
5167 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005168 if (channel == NULL)
5169 goto failed;
5170 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005171
5172 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005173 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005174 CREATE_DEFAULT_ERROR_MODE |
5175 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005176 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005177 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005178 {
5179 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005180 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005181 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005182 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005183
5184 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005185 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005186 /* if failing, switch the way to terminate
5187 * process with TerminateProcess. */
5188 CloseHandle(jo);
5189 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005190 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005191 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005192 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005193 job->jv_proc_info = pi;
5194 job->jv_job_object = jo;
5195 job->jv_status = JOB_STARTED;
5196
Bram Moolenaar94d01912016-03-08 13:48:51 +01005197 if (!use_file_for_in)
5198 CloseHandle(ifd[0]);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005199 if (!use_file_for_out)
5200 CloseHandle(ofd[1]);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005201 if (!use_out_for_err && !use_file_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005202 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005203
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005204 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005205 if (channel != NULL)
5206 {
5207 channel_set_pipes(channel,
5208 use_file_for_in || use_null_for_in
5209 ? INVALID_FD : (sock_T)ifd[1],
5210 use_file_for_out || use_null_for_out
5211 ? INVALID_FD : (sock_T)ofd[0],
5212 use_out_for_err || use_file_for_err || use_null_for_err
5213 ? INVALID_FD : (sock_T)efd[0]);
5214 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005215 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005216 return;
5217
5218failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005219 CloseHandle(ifd[0]);
5220 CloseHandle(ofd[0]);
5221 CloseHandle(efd[0]);
5222 CloseHandle(ifd[1]);
5223 CloseHandle(ofd[1]);
5224 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005225 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005226}
5227
5228 char *
5229mch_job_status(job_T *job)
5230{
5231 DWORD dwExitCode = 0;
5232
Bram Moolenaar76467df2016-02-12 19:30:26 +01005233 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5234 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005235 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005236 job->jv_status = JOB_ENDED;
Bram Moolenaareab089d2016-02-21 19:32:02 +01005237 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005238 return "dead";
5239 }
5240 return "run";
5241}
5242
5243 int
5244mch_stop_job(job_T *job, char_u *how)
5245{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005246 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005247
Bram Moolenaar923d9262016-02-25 20:56:01 +01005248 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005249 {
5250 if (job->jv_job_object != NULL)
5251 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5252 else
5253 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5254 }
5255
5256 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5257 return FAIL;
5258 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005259 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5260 job->jv_proc_info.dwProcessId)
5261 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005262 FreeConsole();
5263 return ret;
5264}
5265
5266/*
5267 * Clear the data related to "job".
5268 */
5269 void
5270mch_clear_job(job_T *job)
5271{
5272 if (job->jv_status != JOB_FAILED)
5273 {
5274 if (job->jv_job_object != NULL)
5275 CloseHandle(job->jv_job_object);
5276 CloseHandle(job->jv_proc_info.hProcess);
5277 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005278}
5279#endif
5280
Bram Moolenaar071d4272004-06-13 20:20:40 +00005281
5282#ifndef FEAT_GUI_W32
5283
5284/*
5285 * Start termcap mode
5286 */
5287 static void
5288termcap_mode_start(void)
5289{
5290 DWORD cmodein;
5291
5292 if (g_fTermcapMode)
5293 return;
5294
5295 SaveConsoleBuffer(&g_cbNonTermcap);
5296
5297 if (g_cbTermcap.IsValid)
5298 {
5299 /*
5300 * We've been in termcap mode before. Restore certain screen
5301 * characteristics, including the buffer size and the window
5302 * size. Since we will be redrawing the screen, we don't need
5303 * to restore the actual contents of the buffer.
5304 */
5305 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5306 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5307 Rows = g_cbTermcap.Info.dwSize.Y;
5308 Columns = g_cbTermcap.Info.dwSize.X;
5309 }
5310 else
5311 {
5312 /*
5313 * This is our first time entering termcap mode. Clear the console
5314 * screen buffer, and resize the buffer to match the current window
5315 * size. We will use this as the size of our editing environment.
5316 */
5317 ClearConsoleBuffer(g_attrCurrent);
5318 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5319 }
5320
5321#ifdef FEAT_TITLE
5322 resettitle();
5323#endif
5324
5325 GetConsoleMode(g_hConIn, &cmodein);
5326#ifdef FEAT_MOUSE
5327 if (g_fMouseActive)
5328 cmodein |= ENABLE_MOUSE_INPUT;
5329 else
5330 cmodein &= ~ENABLE_MOUSE_INPUT;
5331#endif
5332 cmodein |= ENABLE_WINDOW_INPUT;
5333 SetConsoleMode(g_hConIn, cmodein);
5334
5335 redraw_later_clear();
5336 g_fTermcapMode = TRUE;
5337}
5338
5339
5340/*
5341 * End termcap mode
5342 */
5343 static void
5344termcap_mode_end(void)
5345{
5346 DWORD cmodein;
5347 ConsoleBuffer *cb;
5348 COORD coord;
5349 DWORD dwDummy;
5350
5351 if (!g_fTermcapMode)
5352 return;
5353
5354 SaveConsoleBuffer(&g_cbTermcap);
5355
5356 GetConsoleMode(g_hConIn, &cmodein);
5357 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5358 SetConsoleMode(g_hConIn, cmodein);
5359
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005360#ifdef FEAT_RESTORE_ORIG_SCREEN
5361 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5362#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005363 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005364#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005365 RestoreConsoleBuffer(cb, p_rs);
5366 SetConsoleCursorInfo(g_hConOut, &g_cci);
5367
5368 if (p_rs || exiting)
5369 {
5370 /*
5371 * Clear anything that happens to be on the current line.
5372 */
5373 coord.X = 0;
5374 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5375 FillConsoleOutputCharacter(g_hConOut, ' ',
5376 cb->Info.dwSize.X, coord, &dwDummy);
5377 /*
5378 * The following is just for aesthetics. If we are exiting without
5379 * restoring the screen, then we want to have a prompt string
5380 * appear at the bottom line. However, the command interpreter
5381 * seems to always advance the cursor one line before displaying
5382 * the prompt string, which causes the screen to scroll. To
5383 * counter this, move the cursor up one line before exiting.
5384 */
5385 if (exiting && !p_rs)
5386 coord.Y--;
5387 /*
5388 * Position the cursor at the leftmost column of the desired row.
5389 */
5390 SetConsoleCursorPosition(g_hConOut, coord);
5391 }
5392
5393 g_fTermcapMode = FALSE;
5394}
5395#endif /* FEAT_GUI_W32 */
5396
5397
5398#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005399/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005400 void
5401mch_write(
5402 char_u *s,
5403 int len)
5404{
5405 /* never used */
5406}
5407
5408#else
5409
5410/*
5411 * clear `n' chars, starting from `coord'
5412 */
5413 static void
5414clear_chars(
5415 COORD coord,
5416 DWORD n)
5417{
5418 DWORD dwDummy;
5419
5420 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5421 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5422}
5423
5424
5425/*
5426 * Clear the screen
5427 */
5428 static void
5429clear_screen(void)
5430{
5431 g_coord.X = g_coord.Y = 0;
5432 clear_chars(g_coord, Rows * Columns);
5433}
5434
5435
5436/*
5437 * Clear to end of display
5438 */
5439 static void
5440clear_to_end_of_display(void)
5441{
5442 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5443 * Columns + (Columns - g_coord.X));
5444}
5445
5446
5447/*
5448 * Clear to end of line
5449 */
5450 static void
5451clear_to_end_of_line(void)
5452{
5453 clear_chars(g_coord, Columns - g_coord.X);
5454}
5455
5456
5457/*
5458 * Scroll the scroll region up by `cLines' lines
5459 */
5460 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005461scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005462{
5463 COORD oldcoord = g_coord;
5464
5465 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5466 delete_lines(cLines);
5467
5468 g_coord = oldcoord;
5469}
5470
5471
5472/*
5473 * Set the scroll region
5474 */
5475 static void
5476set_scroll_region(
5477 unsigned left,
5478 unsigned top,
5479 unsigned right,
5480 unsigned bottom)
5481{
5482 if (left >= right
5483 || top >= bottom
5484 || right > (unsigned) Columns - 1
5485 || bottom > (unsigned) Rows - 1)
5486 return;
5487
5488 g_srScrollRegion.Left = left;
5489 g_srScrollRegion.Top = top;
5490 g_srScrollRegion.Right = right;
5491 g_srScrollRegion.Bottom = bottom;
5492}
5493
5494
5495/*
5496 * Insert `cLines' lines at the current cursor position
5497 */
5498 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005499insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500{
5501 SMALL_RECT source;
5502 COORD dest;
5503 CHAR_INFO fill;
5504
5505 dest.X = 0;
5506 dest.Y = g_coord.Y + cLines;
5507
5508 source.Left = 0;
5509 source.Top = g_coord.Y;
5510 source.Right = g_srScrollRegion.Right;
5511 source.Bottom = g_srScrollRegion.Bottom - cLines;
5512
5513 fill.Char.AsciiChar = ' ';
5514 fill.Attributes = g_attrCurrent;
5515
5516 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5517
5518 /* Here we have to deal with a win32 console flake: If the scroll
5519 * region looks like abc and we scroll c to a and fill with d we get
5520 * cbd... if we scroll block c one line at a time to a, we get cdd...
5521 * vim expects cdd consistently... So we have to deal with that
5522 * here... (this also occurs scrolling the same way in the other
5523 * direction). */
5524
5525 if (source.Bottom < dest.Y)
5526 {
5527 COORD coord;
5528
5529 coord.X = 0;
5530 coord.Y = source.Bottom;
5531 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5532 }
5533}
5534
5535
5536/*
5537 * Delete `cLines' lines at the current cursor position
5538 */
5539 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005540delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005541{
5542 SMALL_RECT source;
5543 COORD dest;
5544 CHAR_INFO fill;
5545 int nb;
5546
5547 dest.X = 0;
5548 dest.Y = g_coord.Y;
5549
5550 source.Left = 0;
5551 source.Top = g_coord.Y + cLines;
5552 source.Right = g_srScrollRegion.Right;
5553 source.Bottom = g_srScrollRegion.Bottom;
5554
5555 fill.Char.AsciiChar = ' ';
5556 fill.Attributes = g_attrCurrent;
5557
5558 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5559
5560 /* Here we have to deal with a win32 console flake: If the scroll
5561 * region looks like abc and we scroll c to a and fill with d we get
5562 * cbd... if we scroll block c one line at a time to a, we get cdd...
5563 * vim expects cdd consistently... So we have to deal with that
5564 * here... (this also occurs scrolling the same way in the other
5565 * direction). */
5566
5567 nb = dest.Y + (source.Bottom - source.Top) + 1;
5568
5569 if (nb < source.Top)
5570 {
5571 COORD coord;
5572
5573 coord.X = 0;
5574 coord.Y = nb;
5575 clear_chars(coord, Columns * (source.Top - nb));
5576 }
5577}
5578
5579
5580/*
5581 * Set the cursor position
5582 */
5583 static void
5584gotoxy(
5585 unsigned x,
5586 unsigned y)
5587{
5588 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5589 return;
5590
5591 /* external cursor coords are 1-based; internal are 0-based */
5592 g_coord.X = x - 1;
5593 g_coord.Y = y - 1;
5594 SetConsoleCursorPosition(g_hConOut, g_coord);
5595}
5596
5597
5598/*
5599 * Set the current text attribute = (foreground | background)
5600 * See ../doc/os_win32.txt for the numbers.
5601 */
5602 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005603textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005604{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005605 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005606
5607 SetConsoleTextAttribute(g_hConOut, wAttr);
5608}
5609
5610
5611 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005612textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005613{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005614 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615
5616 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5617}
5618
5619
5620 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005621textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005622{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005623 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624
5625 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5626}
5627
5628
5629/*
5630 * restore the default text attribute (whatever we started with)
5631 */
5632 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005633normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634{
5635 textattr(g_attrDefault);
5636}
5637
5638
5639static WORD g_attrPreStandout = 0;
5640
5641/*
5642 * Make the text standout, by brightening it
5643 */
5644 static void
5645standout(void)
5646{
5647 g_attrPreStandout = g_attrCurrent;
5648 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5649}
5650
5651
5652/*
5653 * Turn off standout mode
5654 */
5655 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005656standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657{
5658 if (g_attrPreStandout)
5659 {
5660 textattr(g_attrPreStandout);
5661 g_attrPreStandout = 0;
5662 }
5663}
5664
5665
5666/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005667 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 */
5669 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005670mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671{
5672 char_u *p;
5673 int n;
5674
5675 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5676 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5677 if (T_ME[0] == ESC && T_ME[1] == '|')
5678 {
5679 p = T_ME + 2;
5680 n = getdigits(&p);
5681 if (*p == 'm' && n > 0)
5682 {
5683 cterm_normal_fg_color = (n & 0xf) + 1;
5684 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5685 }
5686 }
5687}
5688
5689
5690/*
5691 * visual bell: flash the screen
5692 */
5693 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005694visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695{
5696 COORD coordOrigin = {0, 0};
5697 WORD attrFlash = ~g_attrCurrent & 0xff;
5698
5699 DWORD dwDummy;
5700 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5701
5702 if (oldattrs == NULL)
5703 return;
5704 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5705 coordOrigin, &dwDummy);
5706 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5707 coordOrigin, &dwDummy);
5708
5709 Sleep(15); /* wait for 15 msec */
5710 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5711 coordOrigin, &dwDummy);
5712 vim_free(oldattrs);
5713}
5714
5715
5716/*
5717 * Make the cursor visible or invisible
5718 */
5719 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005720cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721{
5722 s_cursor_visible = fVisible;
5723#ifdef MCH_CURSOR_SHAPE
5724 mch_update_cursor();
5725#endif
5726}
5727
5728
5729/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005730 * write `cbToWrite' bytes in `pchBuf' to the screen
5731 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005732 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005733 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005735 char_u *pchBuf,
5736 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005737{
5738 COORD coord = g_coord;
5739 DWORD written;
5740
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005741#ifdef FEAT_MBYTE
5742 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5743 {
5744 static WCHAR *unicodebuf = NULL;
5745 static int unibuflen = 0;
5746 int length;
5747 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005749 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5750 if (unicodebuf == NULL || length > unibuflen)
5751 {
5752 vim_free(unicodebuf);
5753 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5754 unibuflen = length;
5755 }
5756 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5757 unicodebuf, unibuflen);
5758
5759 cells = mb_string2cells(pchBuf, cbToWrite);
5760 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5761 coord, &written);
5762 /* When writing fails or didn't write a single character, pretend one
5763 * character was written, otherwise we get stuck. */
5764 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5765 coord, &cchwritten) == 0
5766 || cchwritten == 0)
5767 cchwritten = 1;
5768
5769 if (cchwritten == length)
5770 {
5771 written = cbToWrite;
5772 g_coord.X += (SHORT)cells;
5773 }
5774 else
5775 {
5776 char_u *p = pchBuf;
5777 for (n = 0; n < cchwritten; n++)
5778 mb_cptr_adv(p);
5779 written = p - pchBuf;
5780 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5781 }
5782 }
5783 else
5784#endif
5785 {
5786 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5787 coord, &written);
5788 /* When writing fails or didn't write a single character, pretend one
5789 * character was written, otherwise we get stuck. */
5790 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5791 coord, &written) == 0
5792 || written == 0)
5793 written = 1;
5794
5795 g_coord.X += (SHORT) written;
5796 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797
5798 while (g_coord.X > g_srScrollRegion.Right)
5799 {
5800 g_coord.X -= (SHORT) Columns;
5801 if (g_coord.Y < g_srScrollRegion.Bottom)
5802 g_coord.Y++;
5803 }
5804
5805 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5806
5807 return written;
5808}
5809
5810
5811/*
5812 * mch_write(): write the output buffer to the screen, translating ESC
5813 * sequences into calls to console output routines.
5814 */
5815 void
5816mch_write(
5817 char_u *s,
5818 int len)
5819{
5820 s[len] = NUL;
5821
5822 if (!term_console)
5823 {
5824 write(1, s, (unsigned)len);
5825 return;
5826 }
5827
5828 /* translate ESC | sequences into faked bios calls */
5829 while (len--)
5830 {
5831 /* optimization: use one single write_chars for runs of text,
5832 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005833 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834
5835 if (p_wd)
5836 {
5837 WaitForChar(p_wd);
5838 if (prefix != 0)
5839 prefix = 1;
5840 }
5841
5842 if (prefix != 0)
5843 {
5844 DWORD nWritten;
5845
5846 nWritten = write_chars(s, prefix);
5847#ifdef MCH_WRITE_DUMP
5848 if (fdDump)
5849 {
5850 fputc('>', fdDump);
5851 fwrite(s, sizeof(char_u), nWritten, fdDump);
5852 fputs("<\n", fdDump);
5853 }
5854#endif
5855 len -= (nWritten - 1);
5856 s += nWritten;
5857 }
5858 else if (s[0] == '\n')
5859 {
5860 /* \n, newline: go to the beginning of the next line or scroll */
5861 if (g_coord.Y == g_srScrollRegion.Bottom)
5862 {
5863 scroll(1);
5864 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5865 }
5866 else
5867 {
5868 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5869 }
5870#ifdef MCH_WRITE_DUMP
5871 if (fdDump)
5872 fputs("\\n\n", fdDump);
5873#endif
5874 s++;
5875 }
5876 else if (s[0] == '\r')
5877 {
5878 /* \r, carriage return: go to beginning of line */
5879 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5880#ifdef MCH_WRITE_DUMP
5881 if (fdDump)
5882 fputs("\\r\n", fdDump);
5883#endif
5884 s++;
5885 }
5886 else if (s[0] == '\b')
5887 {
5888 /* \b, backspace: move cursor one position left */
5889 if (g_coord.X > g_srScrollRegion.Left)
5890 g_coord.X--;
5891 else if (g_coord.Y > g_srScrollRegion.Top)
5892 {
5893 g_coord.X = g_srScrollRegion.Right;
5894 g_coord.Y--;
5895 }
5896 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5897#ifdef MCH_WRITE_DUMP
5898 if (fdDump)
5899 fputs("\\b\n", fdDump);
5900#endif
5901 s++;
5902 }
5903 else if (s[0] == '\a')
5904 {
5905 /* \a, bell */
5906 MessageBeep(0xFFFFFFFF);
5907#ifdef MCH_WRITE_DUMP
5908 if (fdDump)
5909 fputs("\\a\n", fdDump);
5910#endif
5911 s++;
5912 }
5913 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5914 {
5915#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005916 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005918 char_u *p;
5919 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920
5921 switch (s[2])
5922 {
5923 /* one or two numeric arguments, separated by ';' */
5924
5925 case '0': case '1': case '2': case '3': case '4':
5926 case '5': case '6': case '7': case '8': case '9':
5927 p = s + 2;
5928 arg1 = getdigits(&p); /* no check for length! */
5929 if (p > s + len)
5930 break;
5931
5932 if (*p == ';')
5933 {
5934 ++p;
5935 arg2 = getdigits(&p); /* no check for length! */
5936 if (p > s + len)
5937 break;
5938
5939 if (*p == 'H')
5940 gotoxy(arg2, arg1);
5941 else if (*p == 'r')
5942 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5943 }
5944 else if (*p == 'A')
5945 {
5946 /* move cursor up arg1 lines in same column */
5947 gotoxy(g_coord.X + 1,
5948 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5949 }
5950 else if (*p == 'C')
5951 {
5952 /* move cursor right arg1 columns in same line */
5953 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5954 g_coord.Y + 1);
5955 }
5956 else if (*p == 'H')
5957 {
5958 gotoxy(1, arg1);
5959 }
5960 else if (*p == 'L')
5961 {
5962 insert_lines(arg1);
5963 }
5964 else if (*p == 'm')
5965 {
5966 if (arg1 == 0)
5967 normvideo();
5968 else
5969 textattr((WORD) arg1);
5970 }
5971 else if (*p == 'f')
5972 {
5973 textcolor((WORD) arg1);
5974 }
5975 else if (*p == 'b')
5976 {
5977 textbackground((WORD) arg1);
5978 }
5979 else if (*p == 'M')
5980 {
5981 delete_lines(arg1);
5982 }
5983
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005984 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005985 s = p + 1;
5986 break;
5987
5988
5989 /* Three-character escape sequences */
5990
5991 case 'A':
5992 /* move cursor up one line in same column */
5993 gotoxy(g_coord.X + 1,
5994 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5995 goto got3;
5996
5997 case 'B':
5998 visual_bell();
5999 goto got3;
6000
6001 case 'C':
6002 /* move cursor right one column in same line */
6003 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6004 g_coord.Y + 1);
6005 goto got3;
6006
6007 case 'E':
6008 termcap_mode_end();
6009 goto got3;
6010
6011 case 'F':
6012 standout();
6013 goto got3;
6014
6015 case 'f':
6016 standend();
6017 goto got3;
6018
6019 case 'H':
6020 gotoxy(1, 1);
6021 goto got3;
6022
6023 case 'j':
6024 clear_to_end_of_display();
6025 goto got3;
6026
6027 case 'J':
6028 clear_screen();
6029 goto got3;
6030
6031 case 'K':
6032 clear_to_end_of_line();
6033 goto got3;
6034
6035 case 'L':
6036 insert_lines(1);
6037 goto got3;
6038
6039 case 'M':
6040 delete_lines(1);
6041 goto got3;
6042
6043 case 'S':
6044 termcap_mode_start();
6045 goto got3;
6046
6047 case 'V':
6048 cursor_visible(TRUE);
6049 goto got3;
6050
6051 case 'v':
6052 cursor_visible(FALSE);
6053 goto got3;
6054
6055 got3:
6056 s += 3;
6057 len -= 2;
6058 }
6059
6060#ifdef MCH_WRITE_DUMP
6061 if (fdDump)
6062 {
6063 fputs("ESC | ", fdDump);
6064 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6065 fputc('\n', fdDump);
6066 }
6067#endif
6068 }
6069 else
6070 {
6071 /* Write a single character */
6072 DWORD nWritten;
6073
6074 nWritten = write_chars(s, 1);
6075#ifdef MCH_WRITE_DUMP
6076 if (fdDump)
6077 {
6078 fputc('>', fdDump);
6079 fwrite(s, sizeof(char_u), nWritten, fdDump);
6080 fputs("<\n", fdDump);
6081 }
6082#endif
6083
6084 len -= (nWritten - 1);
6085 s += nWritten;
6086 }
6087 }
6088
6089#ifdef MCH_WRITE_DUMP
6090 if (fdDump)
6091 fflush(fdDump);
6092#endif
6093}
6094
6095#endif /* FEAT_GUI_W32 */
6096
6097
6098/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006099 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006101/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102 void
6103mch_delay(
6104 long msec,
6105 int ignoreinput)
6106{
6107#ifdef FEAT_GUI_W32
6108 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006109#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006111# ifdef FEAT_MZSCHEME
6112 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6113 {
6114 int towait = p_mzq;
6115
6116 /* if msec is large enough, wait by portions in p_mzq */
6117 while (msec > 0)
6118 {
6119 mzvim_check_threads();
6120 if (msec < towait)
6121 towait = msec;
6122 Sleep(towait);
6123 msec -= towait;
6124 }
6125 }
6126 else
6127# endif
6128 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129 else
6130 WaitForChar(msec);
6131#endif
6132}
6133
6134
6135/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006136 * This version of remove is not scared by a readonly (backup) file.
6137 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138 * Return 0 for success, -1 for failure.
6139 */
6140 int
6141mch_remove(char_u *name)
6142{
6143#ifdef FEAT_MBYTE
6144 WCHAR *wn = NULL;
6145 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006146#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147
Bram Moolenaar203258c2016-01-17 22:15:16 +01006148 /*
6149 * On Windows, deleting a directory's symbolic link is done by
6150 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6151 */
6152 if (mch_isdir(name) && mch_is_symbolic_link(name))
6153 return mch_rmdir(name);
6154
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006155 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6156
6157#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006158 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6159 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006160 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 if (wn != NULL)
6162 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006163 n = DeleteFileW(wn) ? 0 : -1;
6164 vim_free(wn);
6165 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6166 return n;
6167 /* Retry with non-wide function (for Windows 98). */
6168 }
6169 }
6170#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006171 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172}
6173
6174
6175/*
6176 * check for an "interrupt signal": CTRL-break or CTRL-C
6177 */
6178 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006179mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180{
6181#ifndef FEAT_GUI_W32 /* never used */
6182 if (g_fCtrlCPressed || g_fCBrkPressed)
6183 {
6184 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6185 got_int = TRUE;
6186 }
6187#endif
6188}
6189
Bram Moolenaaree273972016-01-02 21:11:51 +01006190/* physical RAM to leave for the OS */
6191#define WINNT_RESERVE_BYTES (256*1024*1024)
6192#define WIN95_RESERVE_BYTES (8*1024*1024)
6193
6194/*
6195 * How much main memory in KiB that can be used by VIM.
6196 */
6197/*ARGSUSED*/
6198 long_u
6199mch_total_mem(int special)
6200{
6201 PlatformId();
6202#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6203 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6204 {
6205 MEMORYSTATUSEX ms;
6206
6207 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6208 * what fits in 32 bits. But it's not always available. */
6209 ms.dwLength = sizeof(MEMORYSTATUSEX);
6210 GlobalMemoryStatusEx(&ms);
6211 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6212 {
6213 /* Process address space fits in physical RAM, use all of it. */
6214 return (long_u)(ms.ullAvailVirtual / 1024);
6215 }
6216 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6217 {
6218 /* Catch old NT box or perverse hardware setup. */
6219 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6220 }
6221 /* Use physical RAM less reserve for OS + data. */
6222 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6223 }
6224 else
6225#endif
6226 {
6227 /* Pre-XP or 95 OS handling. */
6228 MEMORYSTATUS ms;
6229 long_u os_reserve_bytes;
6230
6231 ms.dwLength = sizeof(MEMORYSTATUS);
6232 GlobalMemoryStatus(&ms);
6233 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6234 {
6235 /* Process address space fits in physical RAM, use all of it. */
6236 return (long_u)(ms.dwAvailVirtual / 1024);
6237 }
6238 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6239 ? WINNT_RESERVE_BYTES
6240 : WIN95_RESERVE_BYTES;
6241 if (ms.dwTotalPhys <= os_reserve_bytes)
6242 {
6243 /* Catch old boxes or perverse hardware setup. */
6244 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6245 }
6246 /* Use physical RAM less reserve for OS + data. */
6247 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6248 }
6249}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251#ifdef FEAT_MBYTE
6252/*
6253 * Same code as below, but with wide functions and no comments.
6254 * Return 0 for success, non-zero for failure.
6255 */
6256 int
6257mch_wrename(WCHAR *wold, WCHAR *wnew)
6258{
6259 WCHAR *p;
6260 int i;
6261 WCHAR szTempFile[_MAX_PATH + 1];
6262 WCHAR szNewPath[_MAX_PATH + 1];
6263 HANDLE hf;
6264
6265 if (!mch_windows95())
6266 {
6267 p = wold;
6268 for (i = 0; wold[i] != NUL; ++i)
6269 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6270 && wold[i + 1] != 0)
6271 p = wold + i + 1;
6272 if ((int)(wold + i - p) < 8 || p[6] != '~')
6273 return (MoveFileW(wold, wnew) == 0);
6274 }
6275
6276 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6277 return -1;
6278 *p = NUL;
6279
6280 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6281 return -2;
6282
6283 if (!DeleteFileW(szTempFile))
6284 return -3;
6285
6286 if (!MoveFileW(wold, szTempFile))
6287 return -4;
6288
6289 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6290 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6291 return -5;
6292 if (!CloseHandle(hf))
6293 return -6;
6294
6295 if (!MoveFileW(szTempFile, wnew))
6296 {
6297 (void)MoveFileW(szTempFile, wold);
6298 return -7;
6299 }
6300
6301 DeleteFileW(szTempFile);
6302
6303 if (!DeleteFileW(wold))
6304 return -8;
6305
6306 return 0;
6307}
6308#endif
6309
6310
6311/*
6312 * mch_rename() works around a bug in rename (aka MoveFile) in
6313 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6314 * file whose short file name is "FOO.BAR" (its long file name will
6315 * be correct: "foo.bar~"). Because a file can be accessed by
6316 * either its SFN or its LFN, "foo.bar" has effectively been
6317 * renamed to "foo.bar", which is not at all what was wanted. This
6318 * seems to happen only when renaming files with three-character
6319 * extensions by appending a suffix that does not include ".".
6320 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6321 *
6322 * There is another problem, which isn't really a bug but isn't right either:
6323 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6324 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6325 * service pack 6. Doesn't seem to happen on Windows 98.
6326 *
6327 * Like rename(), returns 0 upon success, non-zero upon failure.
6328 * Should probably set errno appropriately when errors occur.
6329 */
6330 int
6331mch_rename(
6332 const char *pszOldFile,
6333 const char *pszNewFile)
6334{
6335 char szTempFile[_MAX_PATH+1];
6336 char szNewPath[_MAX_PATH+1];
6337 char *pszFilePart;
6338 HANDLE hf;
6339#ifdef FEAT_MBYTE
6340 WCHAR *wold = NULL;
6341 WCHAR *wnew = NULL;
6342 int retval = -1;
6343
6344 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6345 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006346 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6347 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348 if (wold != NULL && wnew != NULL)
6349 retval = mch_wrename(wold, wnew);
6350 vim_free(wold);
6351 vim_free(wnew);
6352 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6353 return retval;
6354 /* Retry with non-wide function (for Windows 98). */
6355 }
6356#endif
6357
6358 /*
6359 * No need to play tricks if not running Windows 95, unless the file name
6360 * contains a "~" as the seventh character.
6361 */
6362 if (!mch_windows95())
6363 {
6364 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6365 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6366 return rename(pszOldFile, pszNewFile);
6367 }
6368
6369 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6370 * a directory, no error is returned and pszFilePart will be NULL. */
6371 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6372 || pszFilePart == NULL)
6373 return -1;
6374 *pszFilePart = NUL;
6375
6376 /* Get (and create) a unique temporary file name in directory of new file */
6377 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6378 return -2;
6379
6380 /* blow the temp file away */
6381 if (!DeleteFile(szTempFile))
6382 return -3;
6383
6384 /* rename old file to the temp file */
6385 if (!MoveFile(pszOldFile, szTempFile))
6386 return -4;
6387
6388 /* now create an empty file called pszOldFile; this prevents the operating
6389 * system using pszOldFile as an alias (SFN) if we're renaming within the
6390 * same directory. For example, we're editing a file called
6391 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6392 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6393 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006394 * cause all sorts of problems later in buf_write(). So, we create an
6395 * empty file called filena~1.txt and the system will have to find some
6396 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397 */
6398 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6399 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6400 return -5;
6401 if (!CloseHandle(hf))
6402 return -6;
6403
6404 /* rename the temp file to the new file */
6405 if (!MoveFile(szTempFile, pszNewFile))
6406 {
6407 /* Renaming failed. Rename the file back to its old name, so that it
6408 * looks like nothing happened. */
6409 (void)MoveFile(szTempFile, pszOldFile);
6410
6411 return -7;
6412 }
6413
6414 /* Seems to be left around on Novell filesystems */
6415 DeleteFile(szTempFile);
6416
6417 /* finally, remove the empty old file */
6418 if (!DeleteFile(pszOldFile))
6419 return -8;
6420
6421 return 0; /* success */
6422}
6423
6424/*
6425 * Get the default shell for the current hardware platform
6426 */
6427 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006428default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429{
6430 char* psz = NULL;
6431
6432 PlatformId();
6433
6434 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6435 psz = "cmd.exe";
6436 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6437 psz = "command.com";
6438
6439 return psz;
6440}
6441
6442/*
6443 * mch_access() extends access() to do more detailed check on network drives.
6444 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6445 */
6446 int
6447mch_access(char *n, int p)
6448{
6449 HANDLE hFile;
6450 DWORD am;
6451 int retval = -1; /* default: fail */
6452#ifdef FEAT_MBYTE
6453 WCHAR *wn = NULL;
6454
6455 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006456 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006457#endif
6458
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006459 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006460 {
6461 char TempName[_MAX_PATH + 16] = "";
6462#ifdef FEAT_MBYTE
6463 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6464#endif
6465
6466 if (p & R_OK)
6467 {
6468 /* Read check is performed by seeing if we can do a find file on
6469 * the directory for any file. */
6470#ifdef FEAT_MBYTE
6471 if (wn != NULL)
6472 {
6473 int i;
6474 WIN32_FIND_DATAW d;
6475
6476 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6477 TempNameW[i] = wn[i];
6478 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6479 TempNameW[i++] = '\\';
6480 TempNameW[i++] = '*';
6481 TempNameW[i++] = 0;
6482
6483 hFile = FindFirstFileW(TempNameW, &d);
6484 if (hFile == INVALID_HANDLE_VALUE)
6485 {
6486 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6487 goto getout;
6488
6489 /* Retry with non-wide function (for Windows 98). */
6490 vim_free(wn);
6491 wn = NULL;
6492 }
6493 else
6494 (void)FindClose(hFile);
6495 }
6496 if (wn == NULL)
6497#endif
6498 {
6499 char *pch;
6500 WIN32_FIND_DATA d;
6501
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006502 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 pch = TempName + STRLEN(TempName) - 1;
6504 if (*pch != '\\' && *pch != '/')
6505 *++pch = '\\';
6506 *++pch = '*';
6507 *++pch = NUL;
6508
6509 hFile = FindFirstFile(TempName, &d);
6510 if (hFile == INVALID_HANDLE_VALUE)
6511 goto getout;
6512 (void)FindClose(hFile);
6513 }
6514 }
6515
6516 if (p & W_OK)
6517 {
6518 /* Trying to create a temporary file in the directory should catch
6519 * directories on read-only network shares. However, in
6520 * directories whose ACL allows writes but denies deletes will end
6521 * up keeping the temporary file :-(. */
6522#ifdef FEAT_MBYTE
6523 if (wn != NULL)
6524 {
6525 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6526 {
6527 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6528 goto getout;
6529
6530 /* Retry with non-wide function (for Windows 98). */
6531 vim_free(wn);
6532 wn = NULL;
6533 }
6534 else
6535 DeleteFileW(TempNameW);
6536 }
6537 if (wn == NULL)
6538#endif
6539 {
6540 if (!GetTempFileName(n, "VIM", 0, TempName))
6541 goto getout;
6542 mch_remove((char_u *)TempName);
6543 }
6544 }
6545 }
6546 else
6547 {
6548 /* Trying to open the file for the required access does ACL, read-only
6549 * network share, and file attribute checks. */
6550 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6551 | ((p & R_OK) ? GENERIC_READ : 0);
6552#ifdef FEAT_MBYTE
6553 if (wn != NULL)
6554 {
6555 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6556 if (hFile == INVALID_HANDLE_VALUE
6557 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6558 {
6559 /* Retry with non-wide function (for Windows 98). */
6560 vim_free(wn);
6561 wn = NULL;
6562 }
6563 }
6564 if (wn == NULL)
6565#endif
6566 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6567 if (hFile == INVALID_HANDLE_VALUE)
6568 goto getout;
6569 CloseHandle(hFile);
6570 }
6571
6572 retval = 0; /* success */
6573getout:
6574#ifdef FEAT_MBYTE
6575 vim_free(wn);
6576#endif
6577 return retval;
6578}
6579
6580#if defined(FEAT_MBYTE) || defined(PROTO)
6581/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006582 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583 */
6584 int
6585mch_open(char *name, int flags, int mode)
6586{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006587 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6588# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589 WCHAR *wn;
6590 int f;
6591
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006592 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006594 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595 if (wn != NULL)
6596 {
6597 f = _wopen(wn, flags, mode);
6598 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006599 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600 return f;
6601 /* Retry with non-wide function (for Windows 98). Can't use
6602 * GetLastError() here and it's unclear what errno gets set to if
6603 * the _wopen() fails for missing wide functions. */
6604 }
6605 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006606# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006608 /* open() can open a file which name is longer than _MAX_PATH bytes
6609 * and shorter than _MAX_PATH characters successfully, but sometimes it
6610 * causes unexpected error in another part. We make it an error explicitly
6611 * here. */
6612 if (strlen(name) >= _MAX_PATH)
6613 return -1;
6614
Bram Moolenaar071d4272004-06-13 20:20:40 +00006615 return open(name, flags, mode);
6616}
6617
6618/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006619 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 */
6621 FILE *
6622mch_fopen(char *name, char *mode)
6623{
6624 WCHAR *wn, *wm;
6625 FILE *f = NULL;
6626
6627 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6628# ifdef __BORLANDC__
6629 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6630 && g_PlatformId == VER_PLATFORM_WIN32_NT
6631# endif
6632 )
6633 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006634# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006635 /* Work around an annoying assertion in the Microsoft debug CRT
6636 * when mode's text/binary setting doesn't match _get_fmode(). */
6637 char newMode = mode[strlen(mode) - 1];
6638 int oldMode = 0;
6639
6640 _get_fmode(&oldMode);
6641 if (newMode == 't')
6642 _set_fmode(_O_TEXT);
6643 else if (newMode == 'b')
6644 _set_fmode(_O_BINARY);
6645# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006646 wn = enc_to_utf16((char_u *)name, NULL);
6647 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 if (wn != NULL && wm != NULL)
6649 f = _wfopen(wn, wm);
6650 vim_free(wn);
6651 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006652
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006653# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006654 _set_fmode(oldMode);
6655# endif
6656
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006657 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658 return f;
6659 /* Retry with non-wide function (for Windows 98). Can't use
6660 * GetLastError() here and it's unclear what errno gets set to if
6661 * the _wfopen() fails for missing wide functions. */
6662 }
6663
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006664 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6665 * and shorter than _MAX_PATH characters successfully, but sometimes it
6666 * causes unexpected error in another part. We make it an error explicitly
6667 * here. */
6668 if (strlen(name) >= _MAX_PATH)
6669 return NULL;
6670
Bram Moolenaar071d4272004-06-13 20:20:40 +00006671 return fopen(name, mode);
6672}
6673#endif
6674
6675#ifdef FEAT_MBYTE
6676/*
6677 * SUB STREAM (aka info stream) handling:
6678 *
6679 * NTFS can have sub streams for each file. Normal contents of file is
6680 * stored in the main stream, and extra contents (author information and
6681 * title and so on) can be stored in sub stream. After Windows 2000, user
6682 * can access and store those informations in sub streams via explorer's
6683 * property menuitem in right click menu. Those informations in sub streams
6684 * were lost when copying only the main stream. So we have to copy sub
6685 * streams.
6686 *
6687 * Incomplete explanation:
6688 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6689 * More useful info and an example:
6690 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6691 */
6692
6693/*
6694 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6695 * and write to stream "substream" of file "to".
6696 * Errors are ignored.
6697 */
6698 static void
6699copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6700{
6701 HANDLE hTo;
6702 WCHAR *to_name;
6703
6704 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6705 wcscpy(to_name, to);
6706 wcscat(to_name, substream);
6707
6708 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6709 FILE_ATTRIBUTE_NORMAL, NULL);
6710 if (hTo != INVALID_HANDLE_VALUE)
6711 {
6712 long done;
6713 DWORD todo;
6714 DWORD readcnt, written;
6715 char buf[4096];
6716
6717 /* Copy block of bytes at a time. Abort when something goes wrong. */
6718 for (done = 0; done < len; done += written)
6719 {
6720 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006721 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6722 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6724 FALSE, FALSE, context)
6725 || readcnt != todo
6726 || !WriteFile(hTo, buf, todo, &written, NULL)
6727 || written != todo)
6728 break;
6729 }
6730 CloseHandle(hTo);
6731 }
6732
6733 free(to_name);
6734}
6735
6736/*
6737 * Copy info streams from file "from" to file "to".
6738 */
6739 static void
6740copy_infostreams(char_u *from, char_u *to)
6741{
6742 WCHAR *fromw;
6743 WCHAR *tow;
6744 HANDLE sh;
6745 WIN32_STREAM_ID sid;
6746 int headersize;
6747 WCHAR streamname[_MAX_PATH];
6748 DWORD readcount;
6749 void *context = NULL;
6750 DWORD lo, hi;
6751 int len;
6752
6753 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006754 fromw = enc_to_utf16(from, NULL);
6755 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756 if (fromw != NULL && tow != NULL)
6757 {
6758 /* Open the file for reading. */
6759 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6760 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6761 if (sh != INVALID_HANDLE_VALUE)
6762 {
6763 /* Use BackupRead() to find the info streams. Repeat until we
6764 * have done them all.*/
6765 for (;;)
6766 {
6767 /* Get the header to find the length of the stream name. If
6768 * the "readcount" is zero we have done all info streams. */
6769 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006770 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6772 &readcount, FALSE, FALSE, &context)
6773 || readcount == 0)
6774 break;
6775
6776 /* We only deal with streams that have a name. The normal
6777 * file data appears to be without a name, even though docs
6778 * suggest it is called "::$DATA". */
6779 if (sid.dwStreamNameSize > 0)
6780 {
6781 /* Read the stream name. */
6782 if (!BackupRead(sh, (LPBYTE)streamname,
6783 sid.dwStreamNameSize,
6784 &readcount, FALSE, FALSE, &context))
6785 break;
6786
6787 /* Copy an info stream with a name ":anything:$DATA".
6788 * Skip "::$DATA", it has no stream name (examples suggest
6789 * it might be used for the normal file contents).
6790 * Note that BackupRead() counts bytes, but the name is in
6791 * wide characters. */
6792 len = readcount / sizeof(WCHAR);
6793 streamname[len] = 0;
6794 if (len > 7 && wcsicmp(streamname + len - 6,
6795 L":$DATA") == 0)
6796 {
6797 streamname[len - 6] = 0;
6798 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006799 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800 }
6801 }
6802
6803 /* Advance to the next stream. We might try seeking too far,
6804 * but BackupSeek() doesn't skip over stream borders, thus
6805 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006806 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807 &lo, &hi, &context);
6808 }
6809
6810 /* Clear the context. */
6811 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6812
6813 CloseHandle(sh);
6814 }
6815 }
6816 vim_free(fromw);
6817 vim_free(tow);
6818}
6819#endif
6820
6821/*
6822 * Copy file attributes from file "from" to file "to".
6823 * For Windows NT and later we copy info streams.
6824 * Always returns zero, errors are ignored.
6825 */
6826 int
6827mch_copy_file_attribute(char_u *from, char_u *to)
6828{
6829#ifdef FEAT_MBYTE
6830 /* File streams only work on Windows NT and later. */
6831 PlatformId();
6832 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6833 copy_infostreams(from, to);
6834#endif
6835 return 0;
6836}
6837
6838#if defined(MYRESETSTKOFLW) || defined(PROTO)
6839/*
6840 * Recreate a destroyed stack guard page in win32.
6841 * Written by Benjamin Peterson.
6842 */
6843
6844/* These magic numbers are from the MS header files */
6845#define MIN_STACK_WIN9X 17
6846#define MIN_STACK_WINNT 2
6847
6848/*
6849 * This function does the same thing as _resetstkoflw(), which is only
6850 * available in DevStudio .net and later.
6851 * Returns 0 for failure, 1 for success.
6852 */
6853 int
6854myresetstkoflw(void)
6855{
6856 BYTE *pStackPtr;
6857 BYTE *pGuardPage;
6858 BYTE *pStackBase;
6859 BYTE *pLowestPossiblePage;
6860 MEMORY_BASIC_INFORMATION mbi;
6861 SYSTEM_INFO si;
6862 DWORD nPageSize;
6863 DWORD dummy;
6864
6865 /* This code will not work on win32s. */
6866 PlatformId();
6867 if (g_PlatformId == VER_PLATFORM_WIN32s)
6868 return 0;
6869
6870 /* We need to know the system page size. */
6871 GetSystemInfo(&si);
6872 nPageSize = si.dwPageSize;
6873
6874 /* ...and the current stack pointer */
6875 pStackPtr = (BYTE*)_alloca(1);
6876
6877 /* ...and the base of the stack. */
6878 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6879 return 0;
6880 pStackBase = (BYTE*)mbi.AllocationBase;
6881
6882 /* ...and the page thats min_stack_req pages away from stack base; this is
6883 * the lowest page we could use. */
6884 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6885 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6886
6887 /* On Win95, we want the next page down from the end of the stack. */
6888 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6889 {
6890 /* Find the page that's only 1 page down from the page that the stack
6891 * ptr is in. */
6892 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6893 / (DWORD)nPageSize) - 1));
6894 if (pGuardPage < pLowestPossiblePage)
6895 return 0;
6896
6897 /* Apply the noaccess attribute to the page -- there's no guard
6898 * attribute in win95-type OSes. */
6899 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6900 return 0;
6901 }
6902 else
6903 {
6904 /* On NT, however, we want the first committed page in the stack Start
6905 * at the stack base and move forward through memory until we find a
6906 * committed block. */
6907 BYTE *pBlock = pStackBase;
6908
Bram Moolenaara466c992005-07-09 21:03:22 +00006909 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 {
6911 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6912 return 0;
6913
6914 pBlock += mbi.RegionSize;
6915
6916 if (mbi.State & MEM_COMMIT)
6917 break;
6918 }
6919
6920 /* mbi now describes the first committed block in the stack. */
6921 if (mbi.Protect & PAGE_GUARD)
6922 return 1;
6923
6924 /* decide where the guard page should start */
6925 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6926 pGuardPage = pLowestPossiblePage;
6927 else
6928 pGuardPage = (BYTE*)mbi.BaseAddress;
6929
6930 /* allocate the guard page */
6931 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6932 return 0;
6933
6934 /* apply the guard attribute to the page */
6935 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6936 &dummy))
6937 return 0;
6938 }
6939
6940 return 1;
6941}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006942#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006944
6945#if defined(FEAT_MBYTE) || defined(PROTO)
6946/*
6947 * The command line arguments in UCS2
6948 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006949static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006950static LPWSTR *ArglistW = NULL;
6951static int global_argc = 0;
6952static char **global_argv;
6953
6954static int used_file_argc = 0; /* last argument in global_argv[] used
6955 for the argument list. */
6956static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6957 command line arguments added to
6958 the argument list */
6959static int used_file_count = 0; /* nr of entries in used_file_indexes */
6960static int used_file_literal = FALSE; /* take file names literally */
6961static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006962static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006963static int used_alist_count = 0;
6964
6965
6966/*
6967 * Get the command line arguments. Unicode version.
6968 * Returns argc. Zero when something fails.
6969 */
6970 int
6971get_cmd_argsW(char ***argvp)
6972{
6973 char **argv = NULL;
6974 int argc = 0;
6975 int i;
6976
Bram Moolenaar14993322014-09-09 12:25:33 +02006977 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006978 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6979 if (ArglistW != NULL)
6980 {
6981 argv = malloc((nArgsW + 1) * sizeof(char *));
6982 if (argv != NULL)
6983 {
6984 argc = nArgsW;
6985 argv[argc] = NULL;
6986 for (i = 0; i < argc; ++i)
6987 {
6988 int len;
6989
6990 /* Convert each Unicode argument to the current codepage. */
6991 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006992 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006993 (LPSTR *)&argv[i], &len, 0, 0);
6994 if (argv[i] == NULL)
6995 {
6996 /* Out of memory, clear everything. */
6997 while (i > 0)
6998 free(argv[--i]);
6999 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007000 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007001 argc = 0;
7002 }
7003 }
7004 }
7005 }
7006
7007 global_argc = argc;
7008 global_argv = argv;
7009 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007010 {
7011 if (used_file_indexes != NULL)
7012 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007013 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007014 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007015
7016 if (argvp != NULL)
7017 *argvp = argv;
7018 return argc;
7019}
7020
7021 void
7022free_cmd_argsW(void)
7023{
7024 if (ArglistW != NULL)
7025 {
7026 GlobalFree(ArglistW);
7027 ArglistW = NULL;
7028 }
7029}
7030
7031/*
7032 * Remember "name" is an argument that was added to the argument list.
7033 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7034 * is called.
7035 */
7036 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007037used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007038{
7039 int i;
7040
7041 if (used_file_indexes == NULL)
7042 return;
7043 for (i = used_file_argc + 1; i < global_argc; ++i)
7044 if (STRCMP(global_argv[i], name) == 0)
7045 {
7046 used_file_argc = i;
7047 used_file_indexes[used_file_count++] = i;
7048 break;
7049 }
7050 used_file_literal = literal;
7051 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007052 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007053}
7054
7055/*
7056 * Remember the length of the argument list as it was. If it changes then we
7057 * leave it alone when 'encoding' is set.
7058 */
7059 void
7060set_alist_count(void)
7061{
7062 used_alist_count = GARGCOUNT;
7063}
7064
7065/*
7066 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7067 * has been changed while starting up. Use the UCS-2 command line arguments
7068 * and convert them to 'encoding'.
7069 */
7070 void
7071fix_arg_enc(void)
7072{
7073 int i;
7074 int idx;
7075 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007076 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007077
7078 /* Safety checks:
7079 * - if argument count differs between the wide and non-wide argument
7080 * list, something must be wrong.
7081 * - the file name arguments must have been located.
7082 * - the length of the argument list wasn't changed by the user.
7083 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007084 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007085 || ArglistW == NULL
7086 || used_file_indexes == NULL
7087 || used_file_count == 0
7088 || used_alist_count != GARGCOUNT)
7089 return;
7090
Bram Moolenaar86b68352004-12-27 21:59:20 +00007091 /* Remember the buffer numbers for the arguments. */
7092 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7093 if (fnum_list == NULL)
7094 return; /* out of memory */
7095 for (i = 0; i < GARGCOUNT; ++i)
7096 fnum_list[i] = GARGLIST[i].ae_fnum;
7097
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007098 /* Clear the argument list. Make room for the new arguments. */
7099 alist_clear(&global_alist);
7100 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007101 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007102
7103 for (i = 0; i < used_file_count; ++i)
7104 {
7105 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007106 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007107 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007108 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007109#ifdef FEAT_DIFF
7110 /* When using diff mode may need to concatenate file name to
7111 * directory name. Just like it's done in main(). */
7112 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7113 && !mch_isdir(alist_name(&GARGLIST[0])))
7114 {
7115 char_u *r;
7116
7117 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7118 if (r != NULL)
7119 {
7120 vim_free(str);
7121 str = r;
7122 }
7123 }
7124#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007125 /* Re-use the old buffer by renaming it. When not using literal
7126 * names it's done by alist_expand() below. */
7127 if (used_file_literal)
7128 buf_set_name(fnum_list[i], str);
7129
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007130 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007131 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007132 }
7133
7134 if (!used_file_literal)
7135 {
7136 /* Now expand wildcards in the arguments. */
7137 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7138 * filename characters but are excluded from 'isfname' to make
7139 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7140 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007141 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007142 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7143 }
7144
7145 /* If wildcard expansion failed, we are editing the first file of the
7146 * arglist and there is no file name: Edit the first argument now. */
7147 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7148 {
7149 do_cmdline_cmd((char_u *)":rewind");
7150 if (GARGCOUNT == 1 && used_file_full_path)
7151 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7152 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007153
7154 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007155}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007156#endif