blob: c5b23ca7dbb53fb152e6066aeb7560f0f70784d4 [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
94#define WINBASEAPI
95typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000096typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000097typedef int ACCESS_MASK;
98typedef int BOOL;
99typedef int COLORREF;
100typedef int CONSOLE_CURSOR_INFO;
101typedef int COORD;
102typedef int DWORD;
103typedef int HANDLE;
104typedef 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
150/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
151#ifndef WINBASEAPI
152# define WINBASEAPI __stdcall
153#endif
154#if defined(__BORLANDC__)
155typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
156#else
157typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
158#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);
217static WCHAR tgetch(int *pmodifiers, WCHAR *pch2);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218static void create_conin(void);
219static int s_cursor_visible = TRUE;
220static int did_create_conin = FALSE;
221#else
222static int s_dont_use_vimrun = TRUE;
223static int need_vimrun_warning = FALSE;
224static char *vimrun_path = "vimrun ";
225#endif
226
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200227static int win32_getattrs(char_u *name);
228static int win32_setattrs(char_u *name, int attrs);
229static int win32_set_archive(char_u *name);
230
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231#ifndef FEAT_GUI_W32
232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
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 Moolenaarbb86ebb2015-08-04 19:27:05 +0200328 static DWORD
329msg_wait_for_multiple_objects(
330 DWORD nCount,
331 LPHANDLE pHandles,
332 BOOL fWaitAll,
333 DWORD dwMilliseconds,
334 DWORD dwWakeMask)
335{
336 if (read_console_input(NULL, NULL, -2, NULL))
337 return WAIT_OBJECT_0;
338 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
339 dwMilliseconds, dwWakeMask);
340}
341
342 static DWORD
343wait_for_single_object(
344 HANDLE hHandle,
345 DWORD dwMilliseconds)
346{
347 if (read_console_input(NULL, NULL, -2, NULL))
348 return WAIT_OBJECT_0;
349 return WaitForSingleObject(hHandle, dwMilliseconds);
350}
351
Bram Moolenaar071d4272004-06-13 20:20:40 +0000352 static void
353get_exe_name(void)
354{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100355 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
356 * as the maximum length that works (plus a NUL byte). */
357#define MAX_ENV_PATH_LEN 8192
358 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200359 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360
361 if (exe_name == NULL)
362 {
363 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100364 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365 if (*temp != NUL)
366 exe_name = FullName_save((char_u *)temp, FALSE);
367 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000368
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200369 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000370 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200371 exe_path = vim_strnsave(exe_name,
372 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200373 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000374 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200375 /* Append our starting directory to $PATH, so that when doing
376 * "!xxd" it's found in our starting directory. Needed because
377 * SearchPath() also looks there. */
378 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100379 if (p == NULL
380 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200381 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100382 if (p == NULL || *p == NUL)
383 temp[0] = NUL;
384 else
385 {
386 STRCPY(temp, p);
387 STRCAT(temp, ";");
388 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200389 STRCAT(temp, exe_path);
390 vim_setenv((char_u *)"PATH", temp);
391 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000392 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000393 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394}
395
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200396/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100397 * Unescape characters in "p" that appear in "escaped".
398 */
399 static void
400unescape_shellxquote(char_u *p, char_u *escaped)
401{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100402 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100403 int n;
404
405 while (*p != NUL)
406 {
407 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
408 mch_memmove(p, p + 1, l--);
409#ifdef FEAT_MBYTE
410 n = (*mb_ptr2len)(p);
411#else
412 n = 1;
413#endif
414 p += n;
415 l -= n;
416 }
417}
418
419/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200420 * Load library "name".
421 */
422 HINSTANCE
423vimLoadLib(char *name)
424{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200425 HINSTANCE dll = NULL;
426 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200428 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
429 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200430 if (exe_path == NULL)
431 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200432 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200433 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200434#ifdef FEAT_MBYTE
435 WCHAR old_dirw[MAXPATHL];
436
437 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
438 {
439 /* Change directory to where the executable is, both to make
440 * sure we find a .dll there and to avoid looking for a .dll
441 * in the current directory. */
442 SetCurrentDirectory(exe_path);
443 dll = LoadLibrary(name);
444 SetCurrentDirectoryW(old_dirw);
445 return dll;
446 }
447 /* Retry with non-wide function (for Windows 98). */
448 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
449#endif
450 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
451 {
452 /* Change directory to where the executable is, both to make
453 * sure we find a .dll there and to avoid looking for a .dll
454 * in the current directory. */
455 SetCurrentDirectory(exe_path);
456 dll = LoadLibrary(name);
457 SetCurrentDirectory(old_dir);
458 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200459 }
460 return dll;
461}
462
Bram Moolenaar071d4272004-06-13 20:20:40 +0000463#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
464# ifndef GETTEXT_DLL
465# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100466# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200468/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000469static char *null_libintl_gettext(const char *);
470static char *null_libintl_textdomain(const char *);
471static char *null_libintl_bindtextdomain(const char *, const char *);
472static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000475char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
476char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
477char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000479char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
480 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481
482 int
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100483dyn_libintl_init()
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484{
485 int i;
486 static struct
487 {
488 char *name;
489 FARPROC *ptr;
490 } libintl_entry[] =
491 {
492 {"gettext", (FARPROC*)&dyn_libintl_gettext},
493 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
494 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
495 {NULL, NULL}
496 };
497
498 /* No need to initialize twice. */
499 if (hLibintlDLL)
500 return 1;
501 /* Load gettext library (libintl.dll) */
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100502 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
503 if (!hLibintlDLL)
504 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505 if (!hLibintlDLL)
506 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200507 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200509 verbose_enter();
510 EMSG2(_(e_loadlib), GETTEXT_DLL);
511 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200513 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514 }
515 for (i = 0; libintl_entry[i].name != NULL
516 && libintl_entry[i].ptr != NULL; ++i)
517 {
518 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
519 libintl_entry[i].name)) == NULL)
520 {
521 dyn_libintl_end();
522 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000523 {
524 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000526 verbose_leave();
527 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000528 return 0;
529 }
530 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000531
532 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000533 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000534 "bind_textdomain_codeset");
535 if (dyn_libintl_bind_textdomain_codeset == NULL)
536 dyn_libintl_bind_textdomain_codeset =
537 null_libintl_bind_textdomain_codeset;
538
Bram Moolenaar071d4272004-06-13 20:20:40 +0000539 return 1;
540}
541
542 void
543dyn_libintl_end()
544{
545 if (hLibintlDLL)
546 FreeLibrary(hLibintlDLL);
547 hLibintlDLL = NULL;
548 dyn_libintl_gettext = null_libintl_gettext;
549 dyn_libintl_textdomain = null_libintl_textdomain;
550 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000551 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552}
553
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000554/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000556null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000557{
558 return (char*)msgid;
559}
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_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000564{
565 return NULL;
566}
567
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000568/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000570null_libintl_bind_textdomain_codeset(const char *domainname,
571 const char *codeset)
572{
573 return NULL;
574}
575
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000576/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000577 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000578null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000579{
580 return NULL;
581}
582
583#endif /* DYNAMIC_GETTEXT */
584
585/* This symbol is not defined in older versions of the SDK or Visual C++ */
586
587#ifndef VER_PLATFORM_WIN32_WINDOWS
588# define VER_PLATFORM_WIN32_WINDOWS 1
589#endif
590
591DWORD g_PlatformId;
592
593#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100594# ifndef PROTO
595# include <aclapi.h>
596# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200597# ifndef PROTECTED_DACL_SECURITY_INFORMATION
598# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
599# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100600
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601/*
602 * These are needed to dynamically load the ADVAPI DLL, which is not
603 * implemented under Windows 95 (and causes VIM to crash)
604 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200605typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200607typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
609 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200610# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200611typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200612 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200613typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200614 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
615 PSECURITY_DESCRIPTOR *);
616# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617
618static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
619static PSNSECINFO pSetNamedSecurityInfo;
620static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200621# ifdef FEAT_MBYTE
622static PSNSECINFOW pSetNamedSecurityInfoW;
623static PGNSECINFOW pGetNamedSecurityInfoW;
624# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000625#endif
626
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200627typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
628
629static BOOL allowPiping = FALSE;
630static PSETHANDLEINFORMATION pSetHandleInformation;
631
Bram Moolenaar27515922013-06-29 15:36:26 +0200632#ifdef HAVE_ACL
633/*
634 * Enables or disables the specified privilege.
635 */
636 static BOOL
637win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
638{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100639 BOOL bResult;
640 LUID luid;
641 HANDLE hToken;
642 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200643
644 if (!OpenProcessToken(GetCurrentProcess(),
645 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
646 return FALSE;
647
648 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
649 {
650 CloseHandle(hToken);
651 return FALSE;
652 }
653
Bram Moolenaar45500912014-07-09 20:51:07 +0200654 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200655 tokenPrivileges.Privileges[0].Luid = luid;
656 tokenPrivileges.Privileges[0].Attributes = bEnable ?
657 SE_PRIVILEGE_ENABLED : 0;
658
659 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
660 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
661
662 CloseHandle(hToken);
663
664 return bResult && GetLastError() == ERROR_SUCCESS;
665}
666#endif
667
Bram Moolenaar071d4272004-06-13 20:20:40 +0000668/*
669 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
670 * VER_PLATFORM_WIN32_WINDOWS (Win95).
671 */
672 void
673PlatformId(void)
674{
675 static int done = FALSE;
676
677 if (!done)
678 {
679 OSVERSIONINFO ovi;
680
681 ovi.dwOSVersionInfoSize = sizeof(ovi);
682 GetVersionEx(&ovi);
683
684 g_PlatformId = ovi.dwPlatformId;
685
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100686 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
687 || ovi.dwMajorVersion > 6)
688 win8_or_later = TRUE;
689
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690#ifdef HAVE_ACL
691 /*
692 * Load the ADVAPI runtime if we are on anything
693 * other than Windows 95
694 */
695 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
696 {
697 /*
698 * do this load. Problems: Doesn't unload at end of run (this is
699 * theoretically okay, since Windows should unload it when VIM
700 * terminates). Should we be using the 'mch_libcall' routines?
701 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
702 * time we verify security...
703 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200704 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 if (advapi_lib != NULL)
706 {
707 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
708 "SetNamedSecurityInfoA");
709 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
710 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200711# ifdef FEAT_MBYTE
712 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
713 "SetNamedSecurityInfoW");
714 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
715 "GetNamedSecurityInfoW");
716# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200718 || pGetNamedSecurityInfo == NULL
719# ifdef FEAT_MBYTE
720 || pSetNamedSecurityInfoW == NULL
721 || pGetNamedSecurityInfoW == NULL
722# endif
723 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724 {
725 /* If we can't get the function addresses, set advapi_lib
726 * to NULL so that we don't use them. */
727 FreeLibrary(advapi_lib);
728 advapi_lib = NULL;
729 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200730 /* Enable privilege for getting or setting SACLs. */
731 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732 }
733 }
734#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200735 /*
736 * If we are on windows NT, try to load the pipe functions, only
737 * available from Win2K.
738 */
739 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
740 {
741 HANDLE kernel32 = GetModuleHandle("kernel32");
742 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
743 kernel32, "SetHandleInformation");
744
745 allowPiping = pSetHandleInformation != NULL;
746 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747 done = TRUE;
748 }
749}
750
751/*
752 * Return TRUE when running on Windows 95 (or 98 or ME).
753 * Only to be used after mch_init().
754 */
755 int
756mch_windows95(void)
757{
758 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
759}
760
761#ifdef FEAT_GUI_W32
762/*
763 * Used to work around the "can't do synchronous spawn"
764 * problem on Win32s, without resorting to Universal Thunk.
765 */
766static int old_num_windows;
767static int num_windows;
768
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000769/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770 static BOOL CALLBACK
771win32ssynch_cb(HWND hwnd, LPARAM lparam)
772{
773 num_windows++;
774 return TRUE;
775}
776#endif
777
778#ifndef FEAT_GUI_W32
779
780#define SHIFT (SHIFT_PRESSED)
781#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
782#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
783#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
784
785
786/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
787 * We map function keys to their ANSI terminal equivalents, as produced
788 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
789 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
790 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
791 * combinations of function/arrow/etc keys.
792 */
793
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000794static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000795{
796 WORD wVirtKey;
797 BOOL fAnsiKey;
798 int chAlone;
799 int chShift;
800 int chCtrl;
801 int chAlt;
802} VirtKeyMap[] =
803{
804
805/* Key ANSI alone shift ctrl alt */
806 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
807
808 { VK_F1, TRUE, ';', 'T', '^', 'h', },
809 { VK_F2, TRUE, '<', 'U', '_', 'i', },
810 { VK_F3, TRUE, '=', 'V', '`', 'j', },
811 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
812 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
813 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
814 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
815 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
816 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
817 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
818 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
819 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
820
821 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
822 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
823 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
824 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
825 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
826 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
827 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
828 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
829 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
830 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
831
832 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
833
834#if 0
835 /* Most people don't have F13-F20, but what the hell... */
836 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
837 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
838 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
839 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
840 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
841 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
842 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
843 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
844#endif
845 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
846 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
847 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
848 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
849
850 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
851 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
852 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
853 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
854 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
855 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
856 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
857 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
858 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
859 /* Sorry, out of number space! <negri>*/
860 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
861
862};
863
864
865#ifdef _MSC_VER
866// The ToAscii bug destroys several registers. Need to turn off optimization
867// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000868# pragma warning(push)
869# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000870# pragma optimize("", off)
871#endif
872
873#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200874# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200876# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877#endif
878
879/* The return code indicates key code size. */
880 static int
881#ifdef __BORLANDC__
882 __stdcall
883#endif
884win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000885 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000886{
887 UINT uMods = pker->dwControlKeyState;
888 static int s_iIsDead = 0;
889 static WORD awAnsiCode[2];
890 static BYTE abKeystate[256];
891
892
893 if (s_iIsDead == 2)
894 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200895 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 s_iIsDead = 0;
897 return 1;
898 }
899
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200900 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 return 1;
902
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200903 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904
905 // Should only be non-NULL on NT 4.0
906 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
907 {
908 CHAR szKLID[KL_NAMELENGTH];
909
910 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
911 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
912 }
913
914 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200915 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916
917 if (uMods & SHIFT_PRESSED)
918 abKeystate[VK_SHIFT] = 0x80;
919 if (uMods & CAPSLOCK_ON)
920 abKeystate[VK_CAPITAL] = 1;
921
922 if ((uMods & ALT_GR) == ALT_GR)
923 {
924 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
925 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
926 }
927
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200928 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
929 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930
931 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200932 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933
934 return s_iIsDead;
935}
936
937#ifdef _MSC_VER
938/* MUST switch optimization on again here, otherwise a call to
939 * decode_key_event() may crash (e.g. when hitting caps-lock) */
940# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000941# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942
943# if (_MSC_VER < 1100)
944/* MUST turn off global optimisation for this next function, or
945 * pressing ctrl-minus in insert mode crashes Vim when built with
946 * VC4.1. -- negri. */
947# pragma optimize("g", off)
948# endif
949#endif
950
951static BOOL g_fJustGotFocus = FALSE;
952
953/*
954 * Decode a KEY_EVENT into one or two keystrokes
955 */
956 static BOOL
957decode_key_event(
958 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200959 WCHAR *pch,
960 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961 int *pmodifiers,
962 BOOL fDoPost)
963{
964 int i;
965 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
966
967 *pch = *pch2 = NUL;
968 g_fJustGotFocus = FALSE;
969
970 /* ignore key up events */
971 if (!pker->bKeyDown)
972 return FALSE;
973
974 /* ignore some keystrokes */
975 switch (pker->wVirtualKeyCode)
976 {
977 /* modifiers */
978 case VK_SHIFT:
979 case VK_CONTROL:
980 case VK_MENU: /* Alt key */
981 return FALSE;
982
983 default:
984 break;
985 }
986
987 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200988 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989 {
990 /* Ctrl-6 is Ctrl-^ */
991 if (pker->wVirtualKeyCode == '6')
992 {
993 *pch = Ctrl_HAT;
994 return TRUE;
995 }
996 /* Ctrl-2 is Ctrl-@ */
997 else if (pker->wVirtualKeyCode == '2')
998 {
999 *pch = NUL;
1000 return TRUE;
1001 }
1002 /* Ctrl-- is Ctrl-_ */
1003 else if (pker->wVirtualKeyCode == 0xBD)
1004 {
1005 *pch = Ctrl__;
1006 return TRUE;
1007 }
1008 }
1009
1010 /* Shift-TAB */
1011 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1012 {
1013 *pch = K_NUL;
1014 *pch2 = '\017';
1015 return TRUE;
1016 }
1017
1018 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1019 {
1020 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1021 {
1022 if (nModifs == 0)
1023 *pch = VirtKeyMap[i].chAlone;
1024 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1025 *pch = VirtKeyMap[i].chShift;
1026 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1027 *pch = VirtKeyMap[i].chCtrl;
1028 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1029 *pch = VirtKeyMap[i].chAlt;
1030
1031 if (*pch != 0)
1032 {
1033 if (VirtKeyMap[i].fAnsiKey)
1034 {
1035 *pch2 = *pch;
1036 *pch = K_NUL;
1037 }
1038
1039 return TRUE;
1040 }
1041 }
1042 }
1043
1044 i = win32_kbd_patch_key(pker);
1045
1046 if (i < 0)
1047 *pch = NUL;
1048 else
1049 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001050 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051
1052 if (pmodifiers != NULL)
1053 {
1054 /* Pass on the ALT key as a modifier, but only when not combined
1055 * with CTRL (which is ALTGR). */
1056 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1057 *pmodifiers |= MOD_MASK_ALT;
1058
1059 /* Pass on SHIFT only for special keys, because we don't know when
1060 * it's already included with the character. */
1061 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1062 *pmodifiers |= MOD_MASK_SHIFT;
1063
1064 /* Pass on CTRL only for non-special keys, because we don't know
1065 * when it's already included with the character. And not when
1066 * combined with ALT (which is ALTGR). */
1067 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1068 && *pch >= 0x20 && *pch < 0x80)
1069 *pmodifiers |= MOD_MASK_CTRL;
1070 }
1071 }
1072
1073 return (*pch != NUL);
1074}
1075
1076#ifdef _MSC_VER
1077# pragma optimize("", on)
1078#endif
1079
1080#endif /* FEAT_GUI_W32 */
1081
1082
1083#ifdef FEAT_MOUSE
1084
1085/*
1086 * For the GUI the mouse handling is in gui_w32.c.
1087 */
1088# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001089/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001090 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001091mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092{
1093}
1094# else
1095static int g_fMouseAvail = FALSE; /* mouse present */
1096static int g_fMouseActive = FALSE; /* mouse enabled */
1097static int g_nMouseClick = -1; /* mouse status */
1098static int g_xMouse; /* mouse x coordinate */
1099static int g_yMouse; /* mouse y coordinate */
1100
1101/*
1102 * Enable or disable mouse input
1103 */
1104 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001105mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106{
1107 DWORD cmodein;
1108
1109 if (!g_fMouseAvail)
1110 return;
1111
1112 g_fMouseActive = on;
1113 GetConsoleMode(g_hConIn, &cmodein);
1114
1115 if (g_fMouseActive)
1116 cmodein |= ENABLE_MOUSE_INPUT;
1117 else
1118 cmodein &= ~ENABLE_MOUSE_INPUT;
1119
1120 SetConsoleMode(g_hConIn, cmodein);
1121}
1122
1123
1124/*
1125 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1126 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1127 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1128 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1129 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1130 * and we return the mouse position in g_xMouse and g_yMouse.
1131 *
1132 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1133 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1134 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1135 *
1136 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1137 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1138 *
1139 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1140 * moves, even if it stays within the same character cell. We ignore
1141 * all MOUSE_MOVED messages if the position hasn't really changed, and
1142 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1143 * we're only interested in MOUSE_DRAG).
1144 *
1145 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1146 * 2-button mouses by pressing the left & right buttons simultaneously.
1147 * In practice, it's almost impossible to click both at the same time,
1148 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1149 * in such cases, if the user is clicking quickly.
1150 */
1151 static BOOL
1152decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001153 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154{
1155 static int s_nOldButton = -1;
1156 static int s_nOldMouseClick = -1;
1157 static int s_xOldMouse = -1;
1158 static int s_yOldMouse = -1;
1159 static linenr_T s_old_topline = 0;
1160#ifdef FEAT_DIFF
1161 static int s_old_topfill = 0;
1162#endif
1163 static int s_cClicks = 1;
1164 static BOOL s_fReleased = TRUE;
1165 static DWORD s_dwLastClickTime = 0;
1166 static BOOL s_fNextIsMiddle = FALSE;
1167
1168 static DWORD cButtons = 0; /* number of buttons supported */
1169
1170 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1171 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1172 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1173 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1174
1175 int nButton;
1176
1177 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1178 cButtons = 2;
1179
1180 if (!g_fMouseAvail || !g_fMouseActive)
1181 {
1182 g_nMouseClick = -1;
1183 return FALSE;
1184 }
1185
1186 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1187 if (g_fJustGotFocus)
1188 {
1189 g_fJustGotFocus = FALSE;
1190 return FALSE;
1191 }
1192
1193 /* unprocessed mouse click? */
1194 if (g_nMouseClick != -1)
1195 return TRUE;
1196
1197 nButton = -1;
1198 g_xMouse = pmer->dwMousePosition.X;
1199 g_yMouse = pmer->dwMousePosition.Y;
1200
1201 if (pmer->dwEventFlags == MOUSE_MOVED)
1202 {
1203 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1204 * events even when the mouse moves only within a char cell.) */
1205 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1206 return FALSE;
1207 }
1208
1209 /* If no buttons are pressed... */
1210 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1211 {
1212 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1213 if (s_fReleased)
1214 return FALSE;
1215
1216 nButton = MOUSE_RELEASE;
1217 s_fReleased = TRUE;
1218 }
1219 else /* one or more buttons pressed */
1220 {
1221 /* on a 2-button mouse, hold down left and right buttons
1222 * simultaneously to get MIDDLE. */
1223
1224 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1225 {
1226 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1227
1228 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001229 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230 if (dwLR == LEFT || dwLR == RIGHT)
1231 {
1232 for (;;)
1233 {
1234 /* wait a short time for next input event */
1235 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1236 != WAIT_OBJECT_0)
1237 break;
1238 else
1239 {
1240 DWORD cRecords = 0;
1241 INPUT_RECORD ir;
1242 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1243
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001244 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001245
1246 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1247 || !(pmer2->dwButtonState & LEFT_RIGHT))
1248 break;
1249 else
1250 {
1251 if (pmer2->dwEventFlags != MOUSE_MOVED)
1252 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001253 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001254
1255 return decode_mouse_event(pmer2);
1256 }
1257 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1258 s_yOldMouse == pmer2->dwMousePosition.Y)
1259 {
1260 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001261 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001262
1263 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001264 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265
1266 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1267 break;
1268 }
1269 else
1270 break;
1271 }
1272 }
1273 }
1274 }
1275 }
1276
1277 if (s_fNextIsMiddle)
1278 {
1279 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1280 ? MOUSE_DRAG : MOUSE_MIDDLE;
1281 s_fNextIsMiddle = FALSE;
1282 }
1283 else if (cButtons == 2 &&
1284 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1285 {
1286 nButton = MOUSE_MIDDLE;
1287
1288 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1289 {
1290 s_fNextIsMiddle = TRUE;
1291 nButton = MOUSE_RELEASE;
1292 }
1293 }
1294 else if ((pmer->dwButtonState & LEFT) == LEFT)
1295 nButton = MOUSE_LEFT;
1296 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1297 nButton = MOUSE_MIDDLE;
1298 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1299 nButton = MOUSE_RIGHT;
1300
1301 if (! s_fReleased && ! s_fNextIsMiddle
1302 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1303 return FALSE;
1304
1305 s_fReleased = s_fNextIsMiddle;
1306 }
1307
1308 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1309 {
1310 /* button pressed or released, without mouse moving */
1311 if (nButton != -1 && nButton != MOUSE_RELEASE)
1312 {
1313 DWORD dwCurrentTime = GetTickCount();
1314
1315 if (s_xOldMouse != g_xMouse
1316 || s_yOldMouse != g_yMouse
1317 || s_nOldButton != nButton
1318 || s_old_topline != curwin->w_topline
1319#ifdef FEAT_DIFF
1320 || s_old_topfill != curwin->w_topfill
1321#endif
1322 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1323 {
1324 s_cClicks = 1;
1325 }
1326 else if (++s_cClicks > 4)
1327 {
1328 s_cClicks = 1;
1329 }
1330
1331 s_dwLastClickTime = dwCurrentTime;
1332 }
1333 }
1334 else if (pmer->dwEventFlags == MOUSE_MOVED)
1335 {
1336 if (nButton != -1 && nButton != MOUSE_RELEASE)
1337 nButton = MOUSE_DRAG;
1338
1339 s_cClicks = 1;
1340 }
1341
1342 if (nButton == -1)
1343 return FALSE;
1344
1345 if (nButton != MOUSE_RELEASE)
1346 s_nOldButton = nButton;
1347
1348 g_nMouseClick = nButton;
1349
1350 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1351 g_nMouseClick |= MOUSE_SHIFT;
1352 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1353 g_nMouseClick |= MOUSE_CTRL;
1354 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1355 g_nMouseClick |= MOUSE_ALT;
1356
1357 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1358 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1359
1360 /* only pass on interesting (i.e., different) mouse events */
1361 if (s_xOldMouse == g_xMouse
1362 && s_yOldMouse == g_yMouse
1363 && s_nOldMouseClick == g_nMouseClick)
1364 {
1365 g_nMouseClick = -1;
1366 return FALSE;
1367 }
1368
1369 s_xOldMouse = g_xMouse;
1370 s_yOldMouse = g_yMouse;
1371 s_old_topline = curwin->w_topline;
1372#ifdef FEAT_DIFF
1373 s_old_topfill = curwin->w_topfill;
1374#endif
1375 s_nOldMouseClick = g_nMouseClick;
1376
1377 return TRUE;
1378}
1379
1380# endif /* FEAT_GUI_W32 */
1381#endif /* FEAT_MOUSE */
1382
1383
1384#ifdef MCH_CURSOR_SHAPE
1385/*
1386 * Set the shape of the cursor.
1387 * 'thickness' can be from 1 (thin) to 99 (block)
1388 */
1389 static void
1390mch_set_cursor_shape(int thickness)
1391{
1392 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1393 ConsoleCursorInfo.dwSize = thickness;
1394 ConsoleCursorInfo.bVisible = s_cursor_visible;
1395
1396 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1397 if (s_cursor_visible)
1398 SetConsoleCursorPosition(g_hConOut, g_coord);
1399}
1400
1401 void
1402mch_update_cursor(void)
1403{
1404 int idx;
1405 int thickness;
1406
1407 /*
1408 * How the cursor is drawn depends on the current mode.
1409 */
1410 idx = get_shape_idx(FALSE);
1411
1412 if (shape_table[idx].shape == SHAPE_BLOCK)
1413 thickness = 99; /* 100 doesn't work on W95 */
1414 else
1415 thickness = shape_table[idx].percentage;
1416 mch_set_cursor_shape(thickness);
1417}
1418#endif
1419
1420#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1421/*
1422 * Handle FOCUS_EVENT.
1423 */
1424 static void
1425handle_focus_event(INPUT_RECORD ir)
1426{
1427 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1428 ui_focus_change((int)g_fJustGotFocus);
1429}
1430
1431/*
1432 * Wait until console input from keyboard or mouse is available,
1433 * or the time is up.
1434 * Return TRUE if something is available FALSE if not.
1435 */
1436 static int
1437WaitForChar(long msec)
1438{
1439 DWORD dwNow = 0, dwEndTime = 0;
1440 INPUT_RECORD ir;
1441 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001442 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001443
1444 if (msec > 0)
1445 /* Wait until the specified time has elapsed. */
1446 dwEndTime = GetTickCount() + msec;
1447 else if (msec < 0)
1448 /* Wait forever. */
1449 dwEndTime = INFINITE;
1450
1451 /* We need to loop until the end of the time period, because
1452 * we might get multiple unusable mouse events in that time.
1453 */
1454 for (;;)
1455 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001456#ifdef FEAT_MZSCHEME
1457 mzvim_check_threads();
1458#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459#ifdef FEAT_CLIENTSERVER
1460 serverProcessPendingMessages();
1461#endif
1462 if (0
1463#ifdef FEAT_MOUSE
1464 || g_nMouseClick != -1
1465#endif
1466#ifdef FEAT_CLIENTSERVER
1467 || input_available()
1468#endif
1469 )
1470 return TRUE;
1471
1472 if (msec > 0)
1473 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001474 /* If the specified wait time has passed, return. Beware that
1475 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001476 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001477 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001478 break;
1479 }
1480 if (msec != 0)
1481 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001482 DWORD dwWaitTime = dwEndTime - dwNow;
1483
1484#ifdef FEAT_MZSCHEME
1485 if (mzthreads_allowed() && p_mzq > 0
1486 && (msec < 0 || (long)dwWaitTime > p_mzq))
1487 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1488#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489#ifdef FEAT_CLIENTSERVER
1490 /* Wait for either an event on the console input or a message in
1491 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001492 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001493 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001495 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496#endif
1497 continue;
1498 }
1499
1500 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001501 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001502
1503#ifdef FEAT_MBYTE_IME
1504 if (State & CMDLINE && msg_row == Rows - 1)
1505 {
1506 CONSOLE_SCREEN_BUFFER_INFO csbi;
1507
1508 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1509 {
1510 if (csbi.dwCursorPosition.Y != msg_row)
1511 {
1512 /* The screen is now messed up, must redraw the
1513 * command line and later all the windows. */
1514 redraw_all_later(CLEAR);
1515 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1516 redrawcmd();
1517 }
1518 }
1519 }
1520#endif
1521
1522 if (cRecords > 0)
1523 {
1524 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1525 {
1526#ifdef FEAT_MBYTE_IME
1527 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1528 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001529 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1531 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001532 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 continue;
1534 }
1535#endif
1536 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1537 NULL, FALSE))
1538 return TRUE;
1539 }
1540
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001541 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001542
1543 if (ir.EventType == FOCUS_EVENT)
1544 handle_focus_event(ir);
1545 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1546 shell_resized();
1547#ifdef FEAT_MOUSE
1548 else if (ir.EventType == MOUSE_EVENT
1549 && decode_mouse_event(&ir.Event.MouseEvent))
1550 return TRUE;
1551#endif
1552 }
1553 else if (msec == 0)
1554 break;
1555 }
1556
1557#ifdef FEAT_CLIENTSERVER
1558 /* Something might have been received while we were waiting. */
1559 if (input_available())
1560 return TRUE;
1561#endif
1562 return FALSE;
1563}
1564
1565#ifndef FEAT_GUI_MSWIN
1566/*
1567 * return non-zero if a character is available
1568 */
1569 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001570mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571{
1572 return WaitForChar(0L);
1573}
1574#endif
1575
1576/*
1577 * Create the console input. Used when reading stdin doesn't work.
1578 */
1579 static void
1580create_conin(void)
1581{
1582 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1583 FILE_SHARE_READ|FILE_SHARE_WRITE,
1584 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001585 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586 did_create_conin = TRUE;
1587}
1588
1589/*
1590 * Get a keystroke or a mouse event
1591 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001592 static WCHAR
1593tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001595 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596
1597 for (;;)
1598 {
1599 INPUT_RECORD ir;
1600 DWORD cRecords = 0;
1601
1602#ifdef FEAT_CLIENTSERVER
1603 (void)WaitForChar(-1L);
1604 if (input_available())
1605 return 0;
1606# ifdef FEAT_MOUSE
1607 if (g_nMouseClick != -1)
1608 return 0;
1609# endif
1610#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001611 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 {
1613 if (did_create_conin)
1614 read_error_exit();
1615 create_conin();
1616 continue;
1617 }
1618
1619 if (ir.EventType == KEY_EVENT)
1620 {
1621 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1622 pmodifiers, TRUE))
1623 return ch;
1624 }
1625 else if (ir.EventType == FOCUS_EVENT)
1626 handle_focus_event(ir);
1627 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1628 shell_resized();
1629#ifdef FEAT_MOUSE
1630 else if (ir.EventType == MOUSE_EVENT)
1631 {
1632 if (decode_mouse_event(&ir.Event.MouseEvent))
1633 return 0;
1634 }
1635#endif
1636 }
1637}
1638#endif /* !FEAT_GUI_W32 */
1639
1640
1641/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001642 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643 * Get one or more characters from the keyboard or the mouse.
1644 * If time == 0, do not wait for characters.
1645 * If time == n, wait a short time for characters.
1646 * If time == -1, wait forever for characters.
1647 * Returns the number of characters read into buf.
1648 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001649/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650 int
1651mch_inchar(
1652 char_u *buf,
1653 int maxlen,
1654 long time,
1655 int tb_change_cnt)
1656{
1657#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1658
1659 int len;
1660 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661#define TYPEAHEADLEN 20
1662 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1663 static int typeaheadlen = 0;
1664
1665 /* First use any typeahead that was kept because "buf" was too small. */
1666 if (typeaheadlen > 0)
1667 goto theend;
1668
1669#ifdef FEAT_SNIFF
1670 if (want_sniff_request)
1671 {
1672 if (sniff_request_waiting)
1673 {
1674 /* return K_SNIFF */
1675 typeahead[typeaheadlen++] = CSI;
1676 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1677 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1678 sniff_request_waiting = 0;
1679 want_sniff_request = 0;
1680 goto theend;
1681 }
1682 else if (time < 0 || time > 250)
1683 {
1684 /* don't wait too long, a request might be pending */
1685 time = 250;
1686 }
1687 }
1688#endif
1689
1690 if (time >= 0)
1691 {
1692 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 }
1695 else /* time == -1, wait forever */
1696 {
1697 mch_set_winsize_now(); /* Allow winsize changes from now on */
1698
Bram Moolenaar3918c952005-03-15 22:34:55 +00001699 /*
1700 * If there is no character available within 2 seconds (default)
1701 * write the autoscript file to disk. Or cause the CursorHold event
1702 * to be triggered.
1703 */
1704 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001705 {
1706#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001707 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001709 buf[0] = K_SPECIAL;
1710 buf[1] = KS_EXTRA;
1711 buf[2] = (int)KE_CURSORHOLD;
1712 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 }
1714#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001715 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716 }
1717 }
1718
1719 /*
1720 * Try to read as many characters as there are, until the buffer is full.
1721 */
1722
1723 /* we will get at least one key. Get more if they are available. */
1724 g_fCBrkPressed = FALSE;
1725
1726#ifdef MCH_WRITE_DUMP
1727 if (fdDump)
1728 fputc('[', fdDump);
1729#endif
1730
1731 /* Keep looping until there is something in the typeahead buffer and more
1732 * to get and still room in the buffer (up to two bytes for a char and
1733 * three bytes for a modifier). */
1734 while ((typeaheadlen == 0 || WaitForChar(0L))
1735 && typeaheadlen + 5 <= TYPEAHEADLEN)
1736 {
1737 if (typebuf_changed(tb_change_cnt))
1738 {
1739 /* "buf" may be invalid now if a client put something in the
1740 * typeahead buffer and "buf" is in the typeahead buffer. */
1741 typeaheadlen = 0;
1742 break;
1743 }
1744#ifdef FEAT_MOUSE
1745 if (g_nMouseClick != -1)
1746 {
1747# ifdef MCH_WRITE_DUMP
1748 if (fdDump)
1749 fprintf(fdDump, "{%02x @ %d, %d}",
1750 g_nMouseClick, g_xMouse, g_yMouse);
1751# endif
1752 typeahead[typeaheadlen++] = ESC + 128;
1753 typeahead[typeaheadlen++] = 'M';
1754 typeahead[typeaheadlen++] = g_nMouseClick;
1755 typeahead[typeaheadlen++] = g_xMouse + '!';
1756 typeahead[typeaheadlen++] = g_yMouse + '!';
1757 g_nMouseClick = -1;
1758 }
1759 else
1760#endif
1761 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001762 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763 int modifiers = 0;
1764
1765 c = tgetch(&modifiers, &ch2);
1766
1767 if (typebuf_changed(tb_change_cnt))
1768 {
1769 /* "buf" may be invalid now if a client put something in the
1770 * typeahead buffer and "buf" is in the typeahead buffer. */
1771 typeaheadlen = 0;
1772 break;
1773 }
1774
1775 if (c == Ctrl_C && ctrl_c_interrupts)
1776 {
1777#if defined(FEAT_CLIENTSERVER)
1778 trash_input_buf();
1779#endif
1780 got_int = TRUE;
1781 }
1782
1783#ifdef FEAT_MOUSE
1784 if (g_nMouseClick == -1)
1785#endif
1786 {
1787 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001788 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001790#ifdef FEAT_MBYTE
1791 if (ch2 == NUL)
1792 {
1793 int i;
1794 char_u *p;
1795 WCHAR ch[2];
1796
1797 ch[0] = c;
1798 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1799 {
1800 ch[1] = tgetch(&modifiers, &ch2);
1801 n++;
1802 }
1803 p = utf16_to_enc(ch, &n);
1804 if (p != NULL)
1805 {
1806 for (i = 0; i < n; i++)
1807 typeahead[typeaheadlen + i] = p[i];
1808 vim_free(p);
1809 }
1810 }
1811 else
1812#endif
1813 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 if (ch2 != NUL)
1815 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001816 typeahead[typeaheadlen + n] = 3;
1817 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001818 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820
Bram Moolenaar45500912014-07-09 20:51:07 +02001821 if (conv)
1822 {
1823 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001824
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001825 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001826 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001827 char_u *e = typeahead + TYPEAHEADLEN;
1828
1829 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001830 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001831 if (*p == K_NUL)
1832 {
1833 ++p;
1834 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1835 *p = 3;
1836 ++n;
1837 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001838 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001839 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001840 }
1841 }
1842
Bram Moolenaar071d4272004-06-13 20:20:40 +00001843 /* Use the ALT key to set the 8th bit of the character
1844 * when it's one byte, the 8th bit isn't set yet and not
1845 * using a double-byte encoding (would become a lead
1846 * byte). */
1847 if ((modifiers & MOD_MASK_ALT)
1848 && n == 1
1849 && (typeahead[typeaheadlen] & 0x80) == 0
1850#ifdef FEAT_MBYTE
1851 && !enc_dbcs
1852#endif
1853 )
1854 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001855#ifdef FEAT_MBYTE
1856 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1857 typeahead + typeaheadlen);
1858#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001860#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 modifiers &= ~MOD_MASK_ALT;
1862 }
1863
1864 if (modifiers != 0)
1865 {
1866 /* Prepend modifiers to the character. */
1867 mch_memmove(typeahead + typeaheadlen + 3,
1868 typeahead + typeaheadlen, n);
1869 typeahead[typeaheadlen++] = K_SPECIAL;
1870 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1871 typeahead[typeaheadlen++] = modifiers;
1872 }
1873
1874 typeaheadlen += n;
1875
1876#ifdef MCH_WRITE_DUMP
1877 if (fdDump)
1878 fputc(c, fdDump);
1879#endif
1880 }
1881 }
1882 }
1883
1884#ifdef MCH_WRITE_DUMP
1885 if (fdDump)
1886 {
1887 fputs("]\n", fdDump);
1888 fflush(fdDump);
1889 }
1890#endif
1891
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892theend:
1893 /* Move typeahead to "buf", as much as fits. */
1894 len = 0;
1895 while (len < maxlen && typeaheadlen > 0)
1896 {
1897 buf[len++] = typeahead[0];
1898 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1899 }
1900 return len;
1901
1902#else /* FEAT_GUI_W32 */
1903 return 0;
1904#endif /* FEAT_GUI_W32 */
1905}
1906
Bram Moolenaar82881492012-11-20 16:53:39 +01001907#ifndef PROTO
1908# ifndef __MINGW32__
1909# include <shellapi.h> /* required for FindExecutable() */
1910# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001911#endif
1912
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001913/*
1914 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001915 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001916 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001918executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001919{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001920 char *dum;
1921 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001922 char *curpath, *newpath;
1923 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001925#ifdef FEAT_MBYTE
1926 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001928 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001929 WCHAR fnamew[_MAX_PATH];
1930 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001931 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001932
1933 if (p != NULL)
1934 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001935 wcurpath = _wgetenv(L"PATH");
1936 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1937 * sizeof(WCHAR));
1938 if (wnewpath == NULL)
1939 return FALSE;
1940 wcscpy(wnewpath, L".;");
1941 wcscat(wnewpath, wcurpath);
1942 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1943 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001944 vim_free(p);
1945 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1946 {
1947 if (n == 0)
1948 return FALSE;
1949 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1950 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001951 if (path != NULL)
1952 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001953 return TRUE;
1954 }
1955 /* Retry with non-wide function (for Windows 98). */
1956 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001958#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001959
1960 curpath = getenv("PATH");
1961 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1962 if (newpath == NULL)
1963 return FALSE;
1964 STRCPY(newpath, ".;");
1965 STRCAT(newpath, curpath);
1966 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1967 vim_free(newpath);
1968 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001969 return FALSE;
1970 if (mch_isdir(fname))
1971 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001972 if (path != NULL)
1973 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001974 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975}
1976
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001977#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001978 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001979/*
1980 * Bad parameter handler.
1981 *
1982 * Certain MS CRT functions will intentionally crash when passed invalid
1983 * parameters to highlight possible security holes. Setting this function as
1984 * the bad parameter handler will prevent the crash.
1985 *
1986 * In debug builds the parameters contain CRT information that might help track
1987 * down the source of a problem, but in non-debug builds the arguments are all
1988 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1989 * worth allowing these to make debugging of issues easier.
1990 */
1991 static void
1992bad_param_handler(const wchar_t *expression,
1993 const wchar_t *function,
1994 const wchar_t *file,
1995 unsigned int line,
1996 uintptr_t pReserved)
1997{
1998}
1999
2000# define SET_INVALID_PARAM_HANDLER \
2001 ((void)_set_invalid_parameter_handler(bad_param_handler))
2002#else
2003# define SET_INVALID_PARAM_HANDLER
2004#endif
2005
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006#ifdef FEAT_GUI_W32
2007
2008/*
2009 * GUI version of mch_init().
2010 */
2011 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002012mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013{
2014#ifndef __MINGW32__
2015 extern int _fmode;
2016#endif
2017
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002018 /* Silently handle invalid parameters to CRT functions */
2019 SET_INVALID_PARAM_HANDLER;
2020
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 /* Let critical errors result in a failure, not in a dialog box. Required
2022 * for the timestamp test to work on removed floppies. */
2023 SetErrorMode(SEM_FAILCRITICALERRORS);
2024
2025 _fmode = O_BINARY; /* we do our own CR-LF translation */
2026
2027 /* Specify window size. Is there a place to get the default from? */
2028 Rows = 25;
2029 Columns = 80;
2030
2031 /* Look for 'vimrun' */
2032 if (!gui_is_win32s())
2033 {
2034 char_u vimrun_location[_MAX_PATH + 4];
2035
2036 /* First try in same directory as gvim.exe */
2037 STRCPY(vimrun_location, exe_name);
2038 STRCPY(gettail(vimrun_location), "vimrun.exe");
2039 if (mch_getperm(vimrun_location) >= 0)
2040 {
2041 if (*skiptowhite(vimrun_location) != NUL)
2042 {
2043 /* Enclose path with white space in double quotes. */
2044 mch_memmove(vimrun_location + 1, vimrun_location,
2045 STRLEN(vimrun_location) + 1);
2046 *vimrun_location = '"';
2047 STRCPY(gettail(vimrun_location), "vimrun\" ");
2048 }
2049 else
2050 STRCPY(gettail(vimrun_location), "vimrun ");
2051
2052 vimrun_path = (char *)vim_strsave(vimrun_location);
2053 s_dont_use_vimrun = FALSE;
2054 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002055 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056 s_dont_use_vimrun = FALSE;
2057
2058 /* Don't give the warning for a missing vimrun.exe right now, but only
2059 * when vimrun was supposed to be used. Don't bother people that do
2060 * not need vimrun.exe. */
2061 if (s_dont_use_vimrun)
2062 need_vimrun_warning = TRUE;
2063 }
2064
2065 /*
2066 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2067 * Otherwise the default "findstr /n" is used.
2068 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002069 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2071
2072#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002073 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074#endif
2075}
2076
2077
2078#else /* FEAT_GUI_W32 */
2079
2080#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2081#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2082
2083/*
2084 * ClearConsoleBuffer()
2085 * Description:
2086 * Clears the entire contents of the console screen buffer, using the
2087 * specified attribute.
2088 * Returns:
2089 * TRUE on success
2090 */
2091 static BOOL
2092ClearConsoleBuffer(WORD wAttribute)
2093{
2094 CONSOLE_SCREEN_BUFFER_INFO csbi;
2095 COORD coord;
2096 DWORD NumCells, dummy;
2097
2098 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2099 return FALSE;
2100
2101 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2102 coord.X = 0;
2103 coord.Y = 0;
2104 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2105 coord, &dummy))
2106 {
2107 return FALSE;
2108 }
2109 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2110 coord, &dummy))
2111 {
2112 return FALSE;
2113 }
2114
2115 return TRUE;
2116}
2117
2118/*
2119 * FitConsoleWindow()
2120 * Description:
2121 * Checks if the console window will fit within given buffer dimensions.
2122 * Also, if requested, will shrink the window to fit.
2123 * Returns:
2124 * TRUE on success
2125 */
2126 static BOOL
2127FitConsoleWindow(
2128 COORD dwBufferSize,
2129 BOOL WantAdjust)
2130{
2131 CONSOLE_SCREEN_BUFFER_INFO csbi;
2132 COORD dwWindowSize;
2133 BOOL NeedAdjust = FALSE;
2134
2135 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2136 {
2137 /*
2138 * A buffer resize will fail if the current console window does
2139 * not lie completely within that buffer. To avoid this, we might
2140 * have to move and possibly shrink the window.
2141 */
2142 if (csbi.srWindow.Right >= dwBufferSize.X)
2143 {
2144 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2145 if (dwWindowSize.X > dwBufferSize.X)
2146 dwWindowSize.X = dwBufferSize.X;
2147 csbi.srWindow.Right = dwBufferSize.X - 1;
2148 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2149 NeedAdjust = TRUE;
2150 }
2151 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2152 {
2153 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2154 if (dwWindowSize.Y > dwBufferSize.Y)
2155 dwWindowSize.Y = dwBufferSize.Y;
2156 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2157 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2158 NeedAdjust = TRUE;
2159 }
2160 if (NeedAdjust && WantAdjust)
2161 {
2162 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2163 return FALSE;
2164 }
2165 return TRUE;
2166 }
2167
2168 return FALSE;
2169}
2170
2171typedef struct ConsoleBufferStruct
2172{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002173 BOOL IsValid;
2174 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002175 PCHAR_INFO Buffer;
2176 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177} ConsoleBuffer;
2178
2179/*
2180 * SaveConsoleBuffer()
2181 * Description:
2182 * Saves important information about the console buffer, including the
2183 * actual buffer contents. The saved information is suitable for later
2184 * restoration by RestoreConsoleBuffer().
2185 * Returns:
2186 * TRUE if all information was saved; FALSE otherwise
2187 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2188 */
2189 static BOOL
2190SaveConsoleBuffer(
2191 ConsoleBuffer *cb)
2192{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002193 DWORD NumCells;
2194 COORD BufferCoord;
2195 SMALL_RECT ReadRegion;
2196 WORD Y, Y_incr;
2197
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 if (cb == NULL)
2199 return FALSE;
2200
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002201 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202 {
2203 cb->IsValid = FALSE;
2204 return FALSE;
2205 }
2206 cb->IsValid = TRUE;
2207
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002208 /*
2209 * Allocate a buffer large enough to hold the entire console screen
2210 * buffer. If this ConsoleBuffer structure has already been initialized
2211 * with a buffer of the correct size, then just use that one.
2212 */
2213 if (!cb->IsValid || cb->Buffer == NULL ||
2214 cb->BufferSize.X != cb->Info.dwSize.X ||
2215 cb->BufferSize.Y != cb->Info.dwSize.Y)
2216 {
2217 cb->BufferSize.X = cb->Info.dwSize.X;
2218 cb->BufferSize.Y = cb->Info.dwSize.Y;
2219 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2220 vim_free(cb->Buffer);
2221 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2222 if (cb->Buffer == NULL)
2223 return FALSE;
2224 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225
2226 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002227 * We will now copy the console screen buffer into our buffer.
2228 * ReadConsoleOutput() seems to be limited as far as how much you
2229 * can read at a time. Empirically, this number seems to be about
2230 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2231 * in chunks until it is all copied. The chunks will all have the
2232 * same horizontal characteristics, so initialize them now. The
2233 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002234 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002235 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002236 ReadRegion.Left = 0;
2237 ReadRegion.Right = cb->Info.dwSize.X - 1;
2238 Y_incr = 12000 / cb->Info.dwSize.X;
2239 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002241 /*
2242 * Read into position (0, Y) in our buffer.
2243 */
2244 BufferCoord.Y = Y;
2245 /*
2246 * Read the region whose top left corner is (0, Y) and whose bottom
2247 * right corner is (width - 1, Y + Y_incr - 1). This should define
2248 * a region of size width by Y_incr. Don't worry if this region is
2249 * too large for the remaining buffer; it will be cropped.
2250 */
2251 ReadRegion.Top = Y;
2252 ReadRegion.Bottom = Y + Y_incr - 1;
2253 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2254 cb->Buffer, /* our buffer */
2255 cb->BufferSize, /* dimensions of our buffer */
2256 BufferCoord, /* offset in our buffer */
2257 &ReadRegion)) /* region to save */
2258 {
2259 vim_free(cb->Buffer);
2260 cb->Buffer = NULL;
2261 return FALSE;
2262 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002263 }
2264
2265 return TRUE;
2266}
2267
2268/*
2269 * RestoreConsoleBuffer()
2270 * Description:
2271 * Restores important information about the console buffer, including the
2272 * actual buffer contents, if desired. The information to restore is in
2273 * the same format used by SaveConsoleBuffer().
2274 * Returns:
2275 * TRUE on success
2276 */
2277 static BOOL
2278RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002279 ConsoleBuffer *cb,
2280 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002282 COORD BufferCoord;
2283 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284
2285 if (cb == NULL || !cb->IsValid)
2286 return FALSE;
2287
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002288 /*
2289 * Before restoring the buffer contents, clear the current buffer, and
2290 * restore the cursor position and window information. Doing this now
2291 * prevents old buffer contents from "flashing" onto the screen.
2292 */
2293 if (RestoreScreen)
2294 ClearConsoleBuffer(cb->Info.wAttributes);
2295
2296 FitConsoleWindow(cb->Info.dwSize, TRUE);
2297 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2298 return FALSE;
2299 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2300 return FALSE;
2301
2302 if (!RestoreScreen)
2303 {
2304 /*
2305 * No need to restore the screen buffer contents, so we're done.
2306 */
2307 return TRUE;
2308 }
2309
2310 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2311 return FALSE;
2312 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2313 return FALSE;
2314
2315 /*
2316 * Restore the screen buffer contents.
2317 */
2318 if (cb->Buffer != NULL)
2319 {
2320 BufferCoord.X = 0;
2321 BufferCoord.Y = 0;
2322 WriteRegion.Left = 0;
2323 WriteRegion.Top = 0;
2324 WriteRegion.Right = cb->Info.dwSize.X - 1;
2325 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2326 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2327 cb->Buffer, /* our buffer */
2328 cb->BufferSize, /* dimensions of our buffer */
2329 BufferCoord, /* offset in our buffer */
2330 &WriteRegion)) /* region to restore */
2331 {
2332 return FALSE;
2333 }
2334 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335
2336 return TRUE;
2337}
2338
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002339#define FEAT_RESTORE_ORIG_SCREEN
2340#ifdef FEAT_RESTORE_ORIG_SCREEN
2341static ConsoleBuffer g_cbOrig = { 0 };
2342#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002343static ConsoleBuffer g_cbNonTermcap = { 0 };
2344static ConsoleBuffer g_cbTermcap = { 0 };
2345
2346#ifdef FEAT_TITLE
2347#ifdef __BORLANDC__
2348typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2349#else
2350typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2351#endif
2352char g_szOrigTitle[256] = { 0 };
2353HWND g_hWnd = NULL; /* also used in os_mswin.c */
2354static HICON g_hOrigIconSmall = NULL;
2355static HICON g_hOrigIcon = NULL;
2356static HICON g_hVimIcon = NULL;
2357static BOOL g_fCanChangeIcon = FALSE;
2358
2359/* ICON* are not defined in VC++ 4.0 */
2360#ifndef ICON_SMALL
2361#define ICON_SMALL 0
2362#endif
2363#ifndef ICON_BIG
2364#define ICON_BIG 1
2365#endif
2366/*
2367 * GetConsoleIcon()
2368 * Description:
2369 * Attempts to retrieve the small icon and/or the big icon currently in
2370 * use by a given window.
2371 * Returns:
2372 * TRUE on success
2373 */
2374 static BOOL
2375GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002376 HWND hWnd,
2377 HICON *phIconSmall,
2378 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379{
2380 if (hWnd == NULL)
2381 return FALSE;
2382
2383 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002384 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2385 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002387 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2388 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389 return TRUE;
2390}
2391
2392/*
2393 * SetConsoleIcon()
2394 * Description:
2395 * Attempts to change the small icon and/or the big icon currently in
2396 * use by a given window.
2397 * Returns:
2398 * TRUE on success
2399 */
2400 static BOOL
2401SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002402 HWND hWnd,
2403 HICON hIconSmall,
2404 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002406 HICON hPrevIconSmall;
2407 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408
2409 if (hWnd == NULL)
2410 return FALSE;
2411
2412 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002413 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2414 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002416 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2417 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 return TRUE;
2419}
2420
2421/*
2422 * SaveConsoleTitleAndIcon()
2423 * Description:
2424 * Saves the current console window title in g_szOrigTitle, for later
2425 * restoration. Also, attempts to obtain a handle to the console window,
2426 * and use it to save the small and big icons currently in use by the
2427 * console window. This is not always possible on some versions of Windows;
2428 * nor is it possible when running Vim remotely using Telnet (since the
2429 * console window the user sees is owned by a remote process).
2430 */
2431 static void
2432SaveConsoleTitleAndIcon(void)
2433{
2434 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2435
2436 /* Save the original title. */
2437 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2438 return;
2439
2440 /*
2441 * Obtain a handle to the console window using GetConsoleWindow() from
2442 * KERNEL32.DLL; we need to handle in order to change the window icon.
2443 * This function only exists on NT-based Windows, starting with Windows
2444 * 2000. On older operating systems, we can't change the window icon
2445 * anyway.
2446 */
2447 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2448 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2449 "GetConsoleWindow")) != NULL)
2450 {
2451 g_hWnd = (*GetConsoleWindowProc)();
2452 }
2453 if (g_hWnd == NULL)
2454 return;
2455
2456 /* Save the original console window icon. */
2457 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2458 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2459 return;
2460
2461 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002462 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2463 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464 if (g_hVimIcon != NULL)
2465 g_fCanChangeIcon = TRUE;
2466}
2467#endif
2468
2469static int g_fWindInitCalled = FALSE;
2470static int g_fTermcapMode = FALSE;
2471static CONSOLE_CURSOR_INFO g_cci;
2472static DWORD g_cmodein = 0;
2473static DWORD g_cmodeout = 0;
2474
2475/*
2476 * non-GUI version of mch_init().
2477 */
2478 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002479mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002481#ifndef FEAT_RESTORE_ORIG_SCREEN
2482 CONSOLE_SCREEN_BUFFER_INFO csbi;
2483#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484#ifndef __MINGW32__
2485 extern int _fmode;
2486#endif
2487
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002488 /* Silently handle invalid parameters to CRT functions */
2489 SET_INVALID_PARAM_HANDLER;
2490
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 /* Let critical errors result in a failure, not in a dialog box. Required
2492 * for the timestamp test to work on removed floppies. */
2493 SetErrorMode(SEM_FAILCRITICALERRORS);
2494
2495 _fmode = O_BINARY; /* we do our own CR-LF translation */
2496 out_flush();
2497
2498 /* Obtain handles for the standard Console I/O devices */
2499 if (read_cmd_fd == 0)
2500 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2501 else
2502 create_conin();
2503 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2504
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002505#ifdef FEAT_RESTORE_ORIG_SCREEN
2506 /* Save the initial console buffer for later restoration */
2507 SaveConsoleBuffer(&g_cbOrig);
2508 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2509#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002511 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2512 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2513#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 if (cterm_normal_fg_color == 0)
2515 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2516 if (cterm_normal_bg_color == 0)
2517 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2518
2519 /* set termcap codes to current text attributes */
2520 update_tcap(g_attrCurrent);
2521
2522 GetConsoleCursorInfo(g_hConOut, &g_cci);
2523 GetConsoleMode(g_hConIn, &g_cmodein);
2524 GetConsoleMode(g_hConOut, &g_cmodeout);
2525
2526#ifdef FEAT_TITLE
2527 SaveConsoleTitleAndIcon();
2528 /*
2529 * Set both the small and big icons of the console window to Vim's icon.
2530 * Note that Vim presently only has one size of icon (32x32), but it
2531 * automatically gets scaled down to 16x16 when setting the small icon.
2532 */
2533 if (g_fCanChangeIcon)
2534 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2535#endif
2536
2537 ui_get_shellsize();
2538
2539#ifdef MCH_WRITE_DUMP
2540 fdDump = fopen("dump", "wt");
2541
2542 if (fdDump)
2543 {
2544 time_t t;
2545
2546 time(&t);
2547 fputs(ctime(&t), fdDump);
2548 fflush(fdDump);
2549 }
2550#endif
2551
2552 g_fWindInitCalled = TRUE;
2553
2554#ifdef FEAT_MOUSE
2555 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2556#endif
2557
2558#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002559 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560#endif
2561
2562 /* This will be NULL on anything but NT 4.0 */
2563 s_pfnGetConsoleKeyboardLayoutName =
2564 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2565 "GetConsoleKeyboardLayoutNameA");
2566}
2567
2568/*
2569 * non-GUI version of mch_exit().
2570 * Shut down and exit with status `r'
2571 * Careful: mch_exit() may be called before mch_init()!
2572 */
2573 void
2574mch_exit(int r)
2575{
2576 stoptermcap();
2577
2578 if (g_fWindInitCalled)
2579 settmode(TMODE_COOK);
2580
2581 ml_close_all(TRUE); /* remove all memfiles */
2582
2583 if (g_fWindInitCalled)
2584 {
2585#ifdef FEAT_TITLE
2586 mch_restore_title(3);
2587 /*
2588 * Restore both the small and big icons of the console window to
2589 * what they were at startup. Don't do this when the window is
2590 * closed, Vim would hang here.
2591 */
2592 if (g_fCanChangeIcon && !g_fForceExit)
2593 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2594#endif
2595
2596#ifdef MCH_WRITE_DUMP
2597 if (fdDump)
2598 {
2599 time_t t;
2600
2601 time(&t);
2602 fputs(ctime(&t), fdDump);
2603 fclose(fdDump);
2604 }
2605 fdDump = NULL;
2606#endif
2607 }
2608
2609 SetConsoleCursorInfo(g_hConOut, &g_cci);
2610 SetConsoleMode(g_hConIn, g_cmodein);
2611 SetConsoleMode(g_hConOut, g_cmodeout);
2612
2613#ifdef DYNAMIC_GETTEXT
2614 dyn_libintl_end();
2615#endif
2616
2617 exit(r);
2618}
2619#endif /* !FEAT_GUI_W32 */
2620
Bram Moolenaar071d4272004-06-13 20:20:40 +00002621/*
2622 * Do we have an interactive window?
2623 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002624/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 int
2626mch_check_win(
2627 int argc,
2628 char **argv)
2629{
2630 get_exe_name();
2631
2632#ifdef FEAT_GUI_W32
2633 return OK; /* GUI always has a tty */
2634#else
2635 if (isatty(1))
2636 return OK;
2637 return FAIL;
2638#endif
2639}
2640
2641
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002642#ifdef FEAT_MBYTE
2643/*
2644 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2645 * if it already exists. When "len" is > 0, also expand short to long
2646 * filenames.
2647 * Return FAIL if wide functions are not available, OK otherwise.
2648 * NOTE: much of this is identical to fname_case(), keep in sync!
2649 */
2650 static int
2651fname_casew(
2652 WCHAR *name,
2653 int len)
2654{
2655 WCHAR szTrueName[_MAX_PATH + 2];
2656 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2657 WCHAR *ptrue, *ptruePrev;
2658 WCHAR *porig, *porigPrev;
2659 int flen;
2660 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002661 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002662 int c;
2663 int slen;
2664
2665 flen = (int)wcslen(name);
2666 if (flen > _MAX_PATH)
2667 return OK;
2668
2669 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2670
2671 /* Build the new name in szTrueName[] one component at a time. */
2672 porig = name;
2673 ptrue = szTrueName;
2674
2675 if (iswalpha(porig[0]) && porig[1] == L':')
2676 {
2677 /* copy leading drive letter */
2678 *ptrue++ = *porig++;
2679 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002680 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002681 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002682
2683 while (*porig != NUL)
2684 {
2685 /* copy \ characters */
2686 while (*porig == psepc)
2687 *ptrue++ = *porig++;
2688
2689 ptruePrev = ptrue;
2690 porigPrev = porig;
2691 while (*porig != NUL && *porig != psepc)
2692 {
2693 *ptrue++ = *porig++;
2694 }
2695 *ptrue = NUL;
2696
2697 /* To avoid a slow failure append "\*" when searching a directory,
2698 * server or network share. */
2699 wcscpy(szTrueNameTemp, szTrueName);
2700 slen = (int)wcslen(szTrueNameTemp);
2701 if (*porig == psepc && slen + 2 < _MAX_PATH)
2702 wcscpy(szTrueNameTemp + slen, L"\\*");
2703
2704 /* Skip "", "." and "..". */
2705 if (ptrue > ptruePrev
2706 && (ptruePrev[0] != L'.'
2707 || (ptruePrev[1] != NUL
2708 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2709 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2710 != INVALID_HANDLE_VALUE)
2711 {
2712 c = *porig;
2713 *porig = NUL;
2714
2715 /* Only use the match when it's the same name (ignoring case) or
2716 * expansion is allowed and there is a match with the short name
2717 * and there is enough room. */
2718 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2719 || (len > 0
2720 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2721 && (int)(ptruePrev - szTrueName)
2722 + (int)wcslen(fb.cFileName) < len)))
2723 {
2724 wcscpy(ptruePrev, fb.cFileName);
2725
2726 /* Look for exact match and prefer it if found. Must be a
2727 * long name, otherwise there would be only one match. */
2728 while (FindNextFileW(hFind, &fb))
2729 {
2730 if (*fb.cAlternateFileName != NUL
2731 && (wcscoll(porigPrev, fb.cFileName) == 0
2732 || (len > 0
2733 && (_wcsicoll(porigPrev,
2734 fb.cAlternateFileName) == 0
2735 && (int)(ptruePrev - szTrueName)
2736 + (int)wcslen(fb.cFileName) < len))))
2737 {
2738 wcscpy(ptruePrev, fb.cFileName);
2739 break;
2740 }
2741 }
2742 }
2743 FindClose(hFind);
2744 *porig = c;
2745 ptrue = ptruePrev + wcslen(ptruePrev);
2746 }
2747 else if (hFind == INVALID_HANDLE_VALUE
2748 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2749 return FAIL;
2750 }
2751
2752 wcscpy(name, szTrueName);
2753 return OK;
2754}
2755#endif
2756
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757/*
2758 * fname_case(): Set the case of the file name, if it already exists.
2759 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002760 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002761 */
2762 void
2763fname_case(
2764 char_u *name,
2765 int len)
2766{
2767 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002768 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002769 char *ptrue, *ptruePrev;
2770 char *porig, *porigPrev;
2771 int flen;
2772 WIN32_FIND_DATA fb;
2773 HANDLE hFind;
2774 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002775 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002777 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002778 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779 return;
2780
2781 slash_adjust(name);
2782
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002783#ifdef FEAT_MBYTE
2784 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2785 {
2786 WCHAR *p = enc_to_utf16(name, NULL);
2787
2788 if (p != NULL)
2789 {
2790 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002791 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002792
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002793 wcsncpy(buf, p, _MAX_PATH);
2794 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002795 vim_free(p);
2796
2797 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2798 {
2799 q = utf16_to_enc(buf, NULL);
2800 if (q != NULL)
2801 {
2802 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2803 vim_free(q);
2804 return;
2805 }
2806 }
2807 }
2808 /* Retry with non-wide function (for Windows 98). */
2809 }
2810#endif
2811
2812 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2813 * So we should check this after calling wide function. */
2814 if (flen > _MAX_PATH)
2815 return;
2816
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817 /* Build the new name in szTrueName[] one component at a time. */
2818 porig = name;
2819 ptrue = szTrueName;
2820
2821 if (isalpha(porig[0]) && porig[1] == ':')
2822 {
2823 /* copy leading drive letter */
2824 *ptrue++ = *porig++;
2825 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002826 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002827 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828
2829 while (*porig != NUL)
2830 {
2831 /* copy \ characters */
2832 while (*porig == psepc)
2833 *ptrue++ = *porig++;
2834
2835 ptruePrev = ptrue;
2836 porigPrev = porig;
2837 while (*porig != NUL && *porig != psepc)
2838 {
2839#ifdef FEAT_MBYTE
2840 int l;
2841
2842 if (enc_dbcs)
2843 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002844 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845 while (--l >= 0)
2846 *ptrue++ = *porig++;
2847 }
2848 else
2849#endif
2850 *ptrue++ = *porig++;
2851 }
2852 *ptrue = NUL;
2853
Bram Moolenaar464c9252010-10-13 20:37:41 +02002854 /* To avoid a slow failure append "\*" when searching a directory,
2855 * server or network share. */
2856 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002857 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002858 if (*porig == psepc && slen + 2 < _MAX_PATH)
2859 STRCPY(szTrueNameTemp + slen, "\\*");
2860
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861 /* Skip "", "." and "..". */
2862 if (ptrue > ptruePrev
2863 && (ptruePrev[0] != '.'
2864 || (ptruePrev[1] != NUL
2865 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002866 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867 != INVALID_HANDLE_VALUE)
2868 {
2869 c = *porig;
2870 *porig = NUL;
2871
2872 /* Only use the match when it's the same name (ignoring case) or
2873 * expansion is allowed and there is a match with the short name
2874 * and there is enough room. */
2875 if (_stricoll(porigPrev, fb.cFileName) == 0
2876 || (len > 0
2877 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2878 && (int)(ptruePrev - szTrueName)
2879 + (int)strlen(fb.cFileName) < len)))
2880 {
2881 STRCPY(ptruePrev, fb.cFileName);
2882
2883 /* Look for exact match and prefer it if found. Must be a
2884 * long name, otherwise there would be only one match. */
2885 while (FindNextFile(hFind, &fb))
2886 {
2887 if (*fb.cAlternateFileName != NUL
2888 && (strcoll(porigPrev, fb.cFileName) == 0
2889 || (len > 0
2890 && (_stricoll(porigPrev,
2891 fb.cAlternateFileName) == 0
2892 && (int)(ptruePrev - szTrueName)
2893 + (int)strlen(fb.cFileName) < len))))
2894 {
2895 STRCPY(ptruePrev, fb.cFileName);
2896 break;
2897 }
2898 }
2899 }
2900 FindClose(hFind);
2901 *porig = c;
2902 ptrue = ptruePrev + strlen(ptruePrev);
2903 }
2904 }
2905
2906 STRCPY(name, szTrueName);
2907}
2908
2909
2910/*
2911 * Insert user name in s[len].
2912 */
2913 int
2914mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002915 char_u *s,
2916 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002918 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919 DWORD cch = sizeof szUserName;
2920
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002921#ifdef FEAT_MBYTE
2922 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2923 {
2924 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2925 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2926
2927 if (GetUserNameW(wszUserName, &wcch))
2928 {
2929 char_u *p = utf16_to_enc(wszUserName, NULL);
2930
2931 if (p != NULL)
2932 {
2933 vim_strncpy(s, p, len - 1);
2934 vim_free(p);
2935 return OK;
2936 }
2937 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002938 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2939 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002940 /* Retry with non-wide function (for Windows 98). */
2941 }
2942#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 if (GetUserName(szUserName, &cch))
2944 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002945 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 return OK;
2947 }
2948 s[0] = NUL;
2949 return FAIL;
2950}
2951
2952
2953/*
2954 * Insert host name in s[len].
2955 */
2956 void
2957mch_get_host_name(
2958 char_u *s,
2959 int len)
2960{
2961 DWORD cch = len;
2962
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002963#ifdef FEAT_MBYTE
2964 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2965 {
2966 WCHAR wszHostName[256 + 1];
2967 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2968
2969 if (GetComputerNameW(wszHostName, &wcch))
2970 {
2971 char_u *p = utf16_to_enc(wszHostName, NULL);
2972
2973 if (p != NULL)
2974 {
2975 vim_strncpy(s, p, len - 1);
2976 vim_free(p);
2977 return;
2978 }
2979 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002980 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2981 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002982 /* Retry with non-wide function (for Windows 98). */
2983 }
2984#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002986 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987}
2988
2989
2990/*
2991 * return process ID
2992 */
2993 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002994mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995{
2996 return (long)GetCurrentProcessId();
2997}
2998
2999
3000/*
3001 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3002 * Return OK for success, FAIL for failure.
3003 */
3004 int
3005mch_dirname(
3006 char_u *buf,
3007 int len)
3008{
3009 /*
3010 * Originally this was:
3011 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3012 * But the Win32s known bug list says that getcwd() doesn't work
3013 * so use the Win32 system call instead. <Negri>
3014 */
3015#ifdef FEAT_MBYTE
3016 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3017 {
3018 WCHAR wbuf[_MAX_PATH + 1];
3019
3020 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3021 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003022 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023
3024 if (p != NULL)
3025 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003026 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027 vim_free(p);
3028 return OK;
3029 }
3030 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003031 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3032 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033 /* Retry with non-wide function (for Windows 98). */
3034 }
3035#endif
3036 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3037}
3038
3039/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003040 * Get file permissions for "name".
3041 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042 */
3043 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003044mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003046 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003047 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003049 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003050 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051}
3052
3053
3054/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003055 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003056 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003057 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058 */
3059 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003060mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003062 long n = -1;
3063
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064#ifdef FEAT_MBYTE
3065 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3066 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003067 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068
3069 if (p != NULL)
3070 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003071 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003073 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003074 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075 /* Retry with non-wide function (for Windows 98). */
3076 }
3077 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003078 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003080 n = _chmod(name, perm);
3081 if (n == -1)
3082 return FAIL;
3083
3084 win32_set_archive(name);
3085
3086 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087}
3088
3089/*
3090 * Set hidden flag for "name".
3091 */
3092 void
3093mch_hide(char_u *name)
3094{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003095 int attrs = win32_getattrs(name);
3096 if (attrs == -1)
3097 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003099 attrs |= FILE_ATTRIBUTE_HIDDEN;
3100 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101}
3102
3103/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003104 * Return TRUE if file "name" exists and is hidden.
3105 */
3106 int
3107mch_ishidden(char_u *name)
3108{
3109 int f = win32_getattrs(name);
3110
3111 if (f == -1)
3112 return FALSE; /* file does not exist at all */
3113
3114 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3115}
3116
3117/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118 * return TRUE if "name" is a directory
3119 * return FALSE if "name" is not a directory or upon error
3120 */
3121 int
3122mch_isdir(char_u *name)
3123{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003124 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125
3126 if (f == -1)
3127 return FALSE; /* file does not exist at all */
3128
3129 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3130}
3131
3132/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003133 * Create directory "name".
3134 * Return 0 on success, -1 on error.
3135 */
3136 int
3137mch_mkdir(char_u *name)
3138{
3139#ifdef FEAT_MBYTE
3140 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3141 {
3142 WCHAR *p;
3143 int retval;
3144
3145 p = enc_to_utf16(name, NULL);
3146 if (p == NULL)
3147 return -1;
3148 retval = _wmkdir(p);
3149 vim_free(p);
3150 return retval;
3151 }
3152#endif
3153 return _mkdir(name);
3154}
3155
3156/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003157 * Return TRUE if file "fname" has more than one link.
3158 */
3159 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003160mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003161{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003162 BY_HANDLE_FILE_INFORMATION info;
3163
3164 return win32_fileinfo(fname, &info) == FILEINFO_OK
3165 && info.nNumberOfLinks > 1;
3166}
3167
3168/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003169 * Return TRUE if file "fname" is a symbolic link.
3170 */
3171 int
3172mch_is_symbolic_link(char_u *fname)
3173{
3174 HANDLE hFind;
3175 int res = FALSE;
3176 WIN32_FIND_DATAA findDataA;
3177 DWORD fileFlags = 0, reparseTag = 0;
3178#ifdef FEAT_MBYTE
3179 WCHAR *wn = NULL;
3180 WIN32_FIND_DATAW findDataW;
3181
3182 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3183 wn = enc_to_utf16(fname, NULL);
3184 if (wn != NULL)
3185 {
3186 hFind = FindFirstFileW(wn, &findDataW);
3187 vim_free(wn);
3188 if (hFind == INVALID_HANDLE_VALUE
3189 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3190 {
3191 /* Retry with non-wide function (for Windows 98). */
3192 hFind = FindFirstFile(fname, &findDataA);
3193 if (hFind != INVALID_HANDLE_VALUE)
3194 {
3195 fileFlags = findDataA.dwFileAttributes;
3196 reparseTag = findDataA.dwReserved0;
3197 }
3198 }
3199 else
3200 {
3201 fileFlags = findDataW.dwFileAttributes;
3202 reparseTag = findDataW.dwReserved0;
3203 }
3204 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003205 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003206#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003207 {
3208 hFind = FindFirstFile(fname, &findDataA);
3209 if (hFind != INVALID_HANDLE_VALUE)
3210 {
3211 fileFlags = findDataA.dwFileAttributes;
3212 reparseTag = findDataA.dwReserved0;
3213 }
3214 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003215
3216 if (hFind != INVALID_HANDLE_VALUE)
3217 FindClose(hFind);
3218
3219 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3220 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3221 res = TRUE;
3222
3223 return res;
3224}
3225
3226/*
3227 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3228 * link.
3229 */
3230 int
3231mch_is_linked(char_u *fname)
3232{
3233 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3234 return TRUE;
3235 return FALSE;
3236}
3237
3238/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003239 * Get the by-handle-file-information for "fname".
3240 * Returns FILEINFO_OK when OK.
3241 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3242 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3243 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3244 */
3245 int
3246win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3247{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003248 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003249 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003250#ifdef FEAT_MBYTE
3251 WCHAR *wn = NULL;
3252
3253 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003254 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003255 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003256 if (wn == NULL)
3257 res = FILEINFO_ENC_FAIL;
3258 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003259 if (wn != NULL)
3260 {
3261 hFile = CreateFileW(wn, /* file name */
3262 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003263 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003264 NULL, /* security descriptor */
3265 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003266 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003267 NULL); /* handle to template file */
3268 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003269 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003270 {
3271 /* Retry with non-wide function (for Windows 98). */
3272 vim_free(wn);
3273 wn = NULL;
3274 }
3275 }
3276 if (wn == NULL)
3277#endif
3278 hFile = CreateFile(fname, /* file name */
3279 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003280 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003281 NULL, /* security descriptor */
3282 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003283 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003284 NULL); /* handle to template file */
3285
3286 if (hFile != INVALID_HANDLE_VALUE)
3287 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003288 if (GetFileInformationByHandle(hFile, info) != 0)
3289 res = FILEINFO_OK;
3290 else
3291 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003292 CloseHandle(hFile);
3293 }
3294
3295#ifdef FEAT_MBYTE
3296 vim_free(wn);
3297#endif
3298 return res;
3299}
3300
3301/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003302 * get file attributes for `name'
3303 * -1 : error
3304 * else FILE_ATTRIBUTE_* defined in winnt.h
3305 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003306 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003307win32_getattrs(char_u *name)
3308{
3309 int attr;
3310#ifdef FEAT_MBYTE
3311 WCHAR *p = NULL;
3312
3313 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3314 p = enc_to_utf16(name, NULL);
3315
3316 if (p != NULL)
3317 {
3318 attr = GetFileAttributesW(p);
3319 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3320 {
3321 /* Retry with non-wide function (for Windows 98). */
3322 vim_free(p);
3323 p = NULL;
3324 }
3325 }
3326 if (p == NULL)
3327#endif
3328 attr = GetFileAttributes((char *)name);
3329#ifdef FEAT_MBYTE
3330 vim_free(p);
3331#endif
3332 return attr;
3333}
3334
3335/*
3336 * set file attributes for `name' to `attrs'
3337 *
3338 * return -1 for failure, 0 otherwise
3339 */
3340 static
3341 int
3342win32_setattrs(char_u *name, int attrs)
3343{
3344 int res;
3345#ifdef FEAT_MBYTE
3346 WCHAR *p = NULL;
3347
3348 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3349 p = enc_to_utf16(name, NULL);
3350
3351 if (p != NULL)
3352 {
3353 res = SetFileAttributesW(p, attrs);
3354 if (res == FALSE
3355 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3356 {
3357 /* Retry with non-wide function (for Windows 98). */
3358 vim_free(p);
3359 p = NULL;
3360 }
3361 }
3362 if (p == NULL)
3363#endif
3364 res = SetFileAttributes((char *)name, attrs);
3365#ifdef FEAT_MBYTE
3366 vim_free(p);
3367#endif
3368 return res ? 0 : -1;
3369}
3370
3371/*
3372 * Set archive flag for "name".
3373 */
3374 static
3375 int
3376win32_set_archive(char_u *name)
3377{
3378 int attrs = win32_getattrs(name);
3379 if (attrs == -1)
3380 return -1;
3381
3382 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3383 return win32_setattrs(name, attrs);
3384}
3385
3386/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003387 * Return TRUE if file or directory "name" is writable (not readonly).
3388 * Strange semantics of Win32: a readonly directory is writable, but you can't
3389 * delete a file. Let's say this means it is writable.
3390 */
3391 int
3392mch_writable(char_u *name)
3393{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003394 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003396 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3397 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398}
3399
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400/*
3401 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003402 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403 * Return -1 if unknown.
3404 */
3405 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003406mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003407{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003408 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003409 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003410 char_u *p;
3411
3412 if (len >= _MAX_PATH) /* safety check */
3413 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003414 if (!use_path)
3415 {
3416 /* TODO: check if file is really executable. */
3417 return mch_getperm(name) != -1 && !mch_isdir(name);
3418 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003419
3420 /* If there already is an extension try using the name directly. Also do
3421 * this with a Unix-shell like 'shell'. */
3422 if (vim_strchr(gettail(name), '.') != NULL
3423 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003424 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003425 return TRUE;
3426
3427 /*
3428 * Loop over all extensions in $PATHEXT.
3429 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003430 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003431 p = mch_getenv("PATHEXT");
3432 if (p == NULL)
3433 p = (char_u *)".com;.exe;.bat;.cmd";
3434 while (*p)
3435 {
3436 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3437 {
3438 /* A single "." means no extension is added. */
3439 buf[len] = NUL;
3440 ++p;
3441 if (*p)
3442 ++p;
3443 }
3444 else
3445 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003446 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003447 return TRUE;
3448 }
3449 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451
3452/*
3453 * Check what "name" is:
3454 * NODE_NORMAL: file or directory (or doesn't exist)
3455 * NODE_WRITABLE: writable device, socket, fifo, etc.
3456 * NODE_OTHER: non-writable things
3457 */
3458 int
3459mch_nodetype(char_u *name)
3460{
3461 HANDLE hFile;
3462 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003463#ifdef FEAT_MBYTE
3464 WCHAR *wn = NULL;
3465#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466
Bram Moolenaar043545e2006-10-10 16:44:07 +00003467 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3468 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3469 * here. */
3470 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3471 return NODE_WRITABLE;
3472
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003473#ifdef FEAT_MBYTE
3474 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3475 {
3476 wn = enc_to_utf16(name, NULL);
3477 if (wn != NULL)
3478 {
3479 hFile = CreateFileW(wn, /* file name */
3480 GENERIC_WRITE, /* access mode */
3481 0, /* share mode */
3482 NULL, /* security descriptor */
3483 OPEN_EXISTING, /* creation disposition */
3484 0, /* file attributes */
3485 NULL); /* handle to template file */
3486 if (hFile == INVALID_HANDLE_VALUE
3487 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3488 {
3489 /* Retry with non-wide function (for Windows 98). */
3490 vim_free(wn);
3491 wn = NULL;
3492 }
3493 }
3494 }
3495 if (wn == NULL)
3496#endif
3497 hFile = CreateFile(name, /* file name */
3498 GENERIC_WRITE, /* access mode */
3499 0, /* share mode */
3500 NULL, /* security descriptor */
3501 OPEN_EXISTING, /* creation disposition */
3502 0, /* file attributes */
3503 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003505#ifdef FEAT_MBYTE
3506 vim_free(wn);
3507#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508 if (hFile == INVALID_HANDLE_VALUE)
3509 return NODE_NORMAL;
3510
3511 type = GetFileType(hFile);
3512 CloseHandle(hFile);
3513 if (type == FILE_TYPE_CHAR)
3514 return NODE_WRITABLE;
3515 if (type == FILE_TYPE_DISK)
3516 return NODE_NORMAL;
3517 return NODE_OTHER;
3518}
3519
3520#ifdef HAVE_ACL
3521struct my_acl
3522{
3523 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3524 PSID pSidOwner;
3525 PSID pSidGroup;
3526 PACL pDacl;
3527 PACL pSacl;
3528};
3529#endif
3530
3531/*
3532 * Return a pointer to the ACL of file "fname" in allocated memory.
3533 * Return NULL if the ACL is not available for whatever reason.
3534 */
3535 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003536mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537{
3538#ifndef HAVE_ACL
3539 return (vim_acl_T)NULL;
3540#else
3541 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003542 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543
3544 /* This only works on Windows NT and 2000. */
3545 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3546 {
3547 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3548 if (p != NULL)
3549 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003550# ifdef FEAT_MBYTE
3551 WCHAR *wn = NULL;
3552
3553 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3554 wn = enc_to_utf16(fname, NULL);
3555 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003556 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003557 /* Try to retrieve the entire security descriptor. */
3558 err = pGetNamedSecurityInfoW(
3559 wn, // Abstract filename
3560 SE_FILE_OBJECT, // File Object
3561 OWNER_SECURITY_INFORMATION |
3562 GROUP_SECURITY_INFORMATION |
3563 DACL_SECURITY_INFORMATION |
3564 SACL_SECURITY_INFORMATION,
3565 &p->pSidOwner, // Ownership information.
3566 &p->pSidGroup, // Group membership.
3567 &p->pDacl, // Discretionary information.
3568 &p->pSacl, // For auditing purposes.
3569 &p->pSecurityDescriptor);
3570 if (err == ERROR_ACCESS_DENIED ||
3571 err == ERROR_PRIVILEGE_NOT_HELD)
3572 {
3573 /* Retrieve only DACL. */
3574 (void)pGetNamedSecurityInfoW(
3575 wn,
3576 SE_FILE_OBJECT,
3577 DACL_SECURITY_INFORMATION,
3578 NULL,
3579 NULL,
3580 &p->pDacl,
3581 NULL,
3582 &p->pSecurityDescriptor);
3583 }
3584 if (p->pSecurityDescriptor == NULL)
3585 {
3586 mch_free_acl((vim_acl_T)p);
3587 p = NULL;
3588 }
3589 vim_free(wn);
3590 }
3591 else
3592# endif
3593 {
3594 /* Try to retrieve the entire security descriptor. */
3595 err = pGetNamedSecurityInfo(
3596 (LPSTR)fname, // Abstract filename
3597 SE_FILE_OBJECT, // File Object
3598 OWNER_SECURITY_INFORMATION |
3599 GROUP_SECURITY_INFORMATION |
3600 DACL_SECURITY_INFORMATION |
3601 SACL_SECURITY_INFORMATION,
3602 &p->pSidOwner, // Ownership information.
3603 &p->pSidGroup, // Group membership.
3604 &p->pDacl, // Discretionary information.
3605 &p->pSacl, // For auditing purposes.
3606 &p->pSecurityDescriptor);
3607 if (err == ERROR_ACCESS_DENIED ||
3608 err == ERROR_PRIVILEGE_NOT_HELD)
3609 {
3610 /* Retrieve only DACL. */
3611 (void)pGetNamedSecurityInfo(
3612 (LPSTR)fname,
3613 SE_FILE_OBJECT,
3614 DACL_SECURITY_INFORMATION,
3615 NULL,
3616 NULL,
3617 &p->pDacl,
3618 NULL,
3619 &p->pSecurityDescriptor);
3620 }
3621 if (p->pSecurityDescriptor == NULL)
3622 {
3623 mch_free_acl((vim_acl_T)p);
3624 p = NULL;
3625 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626 }
3627 }
3628 }
3629
3630 return (vim_acl_T)p;
3631#endif
3632}
3633
Bram Moolenaar27515922013-06-29 15:36:26 +02003634#ifdef HAVE_ACL
3635/*
3636 * Check if "acl" contains inherited ACE.
3637 */
3638 static BOOL
3639is_acl_inherited(PACL acl)
3640{
3641 DWORD i;
3642 ACL_SIZE_INFORMATION acl_info;
3643 PACCESS_ALLOWED_ACE ace;
3644
3645 acl_info.AceCount = 0;
3646 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3647 for (i = 0; i < acl_info.AceCount; i++)
3648 {
3649 GetAce(acl, i, (LPVOID *)&ace);
3650 if (ace->Header.AceFlags & INHERITED_ACE)
3651 return TRUE;
3652 }
3653 return FALSE;
3654}
3655#endif
3656
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657/*
3658 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3659 * Errors are ignored.
3660 * This must only be called with "acl" equal to what mch_get_acl() returned.
3661 */
3662 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003663mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664{
3665#ifdef HAVE_ACL
3666 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003667 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668
3669 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003670 {
3671# ifdef FEAT_MBYTE
3672 WCHAR *wn = NULL;
3673# endif
3674
3675 /* Set security flags */
3676 if (p->pSidOwner)
3677 sec_info |= OWNER_SECURITY_INFORMATION;
3678 if (p->pSidGroup)
3679 sec_info |= GROUP_SECURITY_INFORMATION;
3680 if (p->pDacl)
3681 {
3682 sec_info |= DACL_SECURITY_INFORMATION;
3683 /* Do not inherit its parent's DACL.
3684 * If the DACL is inherited, Cygwin permissions would be changed.
3685 */
3686 if (!is_acl_inherited(p->pDacl))
3687 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3688 }
3689 if (p->pSacl)
3690 sec_info |= SACL_SECURITY_INFORMATION;
3691
3692# ifdef FEAT_MBYTE
3693 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3694 wn = enc_to_utf16(fname, NULL);
3695 if (wn != NULL)
3696 {
3697 (void)pSetNamedSecurityInfoW(
3698 wn, // Abstract filename
3699 SE_FILE_OBJECT, // File Object
3700 sec_info,
3701 p->pSidOwner, // Ownership information.
3702 p->pSidGroup, // Group membership.
3703 p->pDacl, // Discretionary information.
3704 p->pSacl // For auditing purposes.
3705 );
3706 vim_free(wn);
3707 }
3708 else
3709# endif
3710 {
3711 (void)pSetNamedSecurityInfo(
3712 (LPSTR)fname, // Abstract filename
3713 SE_FILE_OBJECT, // File Object
3714 sec_info,
3715 p->pSidOwner, // Ownership information.
3716 p->pSidGroup, // Group membership.
3717 p->pDacl, // Discretionary information.
3718 p->pSacl // For auditing purposes.
3719 );
3720 }
3721 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722#endif
3723}
3724
3725 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003726mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727{
3728#ifdef HAVE_ACL
3729 struct my_acl *p = (struct my_acl *)acl;
3730
3731 if (p != NULL)
3732 {
3733 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3734 vim_free(p);
3735 }
3736#endif
3737}
3738
3739#ifndef FEAT_GUI_W32
3740
3741/*
3742 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3743 */
3744 static BOOL WINAPI
3745handler_routine(
3746 DWORD dwCtrlType)
3747{
3748 switch (dwCtrlType)
3749 {
3750 case CTRL_C_EVENT:
3751 if (ctrl_c_interrupts)
3752 g_fCtrlCPressed = TRUE;
3753 return TRUE;
3754
3755 case CTRL_BREAK_EVENT:
3756 g_fCBrkPressed = TRUE;
3757 return TRUE;
3758
3759 /* fatal events: shut down gracefully */
3760 case CTRL_CLOSE_EVENT:
3761 case CTRL_LOGOFF_EVENT:
3762 case CTRL_SHUTDOWN_EVENT:
3763 windgoto((int)Rows - 1, 0);
3764 g_fForceExit = TRUE;
3765
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003766 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767 (dwCtrlType == CTRL_CLOSE_EVENT
3768 ? _("close")
3769 : dwCtrlType == CTRL_LOGOFF_EVENT
3770 ? _("logoff")
3771 : _("shutdown")));
3772#ifdef DEBUG
3773 OutputDebugString(IObuff);
3774#endif
3775
3776 preserve_exit(); /* output IObuff, preserve files and exit */
3777
3778 return TRUE; /* not reached */
3779
3780 default:
3781 return FALSE;
3782 }
3783}
3784
3785
3786/*
3787 * set the tty in (raw) ? "raw" : "cooked" mode
3788 */
3789 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003790mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791{
3792 DWORD cmodein;
3793 DWORD cmodeout;
3794 BOOL bEnableHandler;
3795
3796 GetConsoleMode(g_hConIn, &cmodein);
3797 GetConsoleMode(g_hConOut, &cmodeout);
3798 if (tmode == TMODE_RAW)
3799 {
3800 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3801 ENABLE_ECHO_INPUT);
3802#ifdef FEAT_MOUSE
3803 if (g_fMouseActive)
3804 cmodein |= ENABLE_MOUSE_INPUT;
3805#endif
3806 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3807 bEnableHandler = TRUE;
3808 }
3809 else /* cooked */
3810 {
3811 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3812 ENABLE_ECHO_INPUT);
3813 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3814 bEnableHandler = FALSE;
3815 }
3816 SetConsoleMode(g_hConIn, cmodein);
3817 SetConsoleMode(g_hConOut, cmodeout);
3818 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3819
3820#ifdef MCH_WRITE_DUMP
3821 if (fdDump)
3822 {
3823 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3824 tmode == TMODE_RAW ? "raw" :
3825 tmode == TMODE_COOK ? "cooked" : "normal",
3826 cmodein, cmodeout);
3827 fflush(fdDump);
3828 }
3829#endif
3830}
3831
3832
3833/*
3834 * Get the size of the current window in `Rows' and `Columns'
3835 * Return OK when size could be determined, FAIL otherwise.
3836 */
3837 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003838mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839{
3840 CONSOLE_SCREEN_BUFFER_INFO csbi;
3841
3842 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3843 {
3844 /*
3845 * For some reason, we are trying to get the screen dimensions
3846 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3847 * variables are really intended to mean the size of Vim screen
3848 * while in termcap mode.
3849 */
3850 Rows = g_cbTermcap.Info.dwSize.Y;
3851 Columns = g_cbTermcap.Info.dwSize.X;
3852 }
3853 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3854 {
3855 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3856 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3857 }
3858 else
3859 {
3860 Rows = 25;
3861 Columns = 80;
3862 }
3863 return OK;
3864}
3865
3866/*
3867 * Set a console window to `xSize' * `ySize'
3868 */
3869 static void
3870ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003871 HANDLE hConsole,
3872 int xSize,
3873 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874{
3875 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3876 SMALL_RECT srWindowRect; /* hold the new console size */
3877 COORD coordScreen;
3878
3879#ifdef MCH_WRITE_DUMP
3880 if (fdDump)
3881 {
3882 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3883 fflush(fdDump);
3884 }
3885#endif
3886
3887 /* get the largest size we can size the console window to */
3888 coordScreen = GetLargestConsoleWindowSize(hConsole);
3889
3890 /* define the new console window size and scroll position */
3891 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3892 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3893 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3894
3895 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3896 {
3897 int sx, sy;
3898
3899 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3900 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3901 if (sy < ySize || sx < xSize)
3902 {
3903 /*
3904 * Increasing number of lines/columns, do buffer first.
3905 * Use the maximal size in x and y direction.
3906 */
3907 if (sy < ySize)
3908 coordScreen.Y = ySize;
3909 else
3910 coordScreen.Y = sy;
3911 if (sx < xSize)
3912 coordScreen.X = xSize;
3913 else
3914 coordScreen.X = sx;
3915 SetConsoleScreenBufferSize(hConsole, coordScreen);
3916 }
3917 }
3918
3919 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3920 {
3921#ifdef MCH_WRITE_DUMP
3922 if (fdDump)
3923 {
3924 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3925 GetLastError());
3926 fflush(fdDump);
3927 }
3928#endif
3929 }
3930
3931 /* define the new console buffer size */
3932 coordScreen.X = xSize;
3933 coordScreen.Y = ySize;
3934
3935 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3936 {
3937#ifdef MCH_WRITE_DUMP
3938 if (fdDump)
3939 {
3940 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3941 GetLastError());
3942 fflush(fdDump);
3943 }
3944#endif
3945 }
3946}
3947
3948
3949/*
3950 * Set the console window to `Rows' * `Columns'
3951 */
3952 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003953mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003954{
3955 COORD coordScreen;
3956
3957 /* Don't change window size while still starting up */
3958 if (suppress_winsize != 0)
3959 {
3960 suppress_winsize = 2;
3961 return;
3962 }
3963
3964 if (term_console)
3965 {
3966 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3967
3968 /* Clamp Rows and Columns to reasonable values */
3969 if (Rows > coordScreen.Y)
3970 Rows = coordScreen.Y;
3971 if (Columns > coordScreen.X)
3972 Columns = coordScreen.X;
3973
3974 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3975 }
3976}
3977
3978/*
3979 * Rows and/or Columns has changed.
3980 */
3981 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003982mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983{
3984 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3985}
3986
3987
3988/*
3989 * Called when started up, to set the winsize that was delayed.
3990 */
3991 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003992mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993{
3994 if (suppress_winsize == 2)
3995 {
3996 suppress_winsize = 0;
3997 mch_set_shellsize();
3998 shell_resized();
3999 }
4000 suppress_winsize = 0;
4001}
4002#endif /* FEAT_GUI_W32 */
4003
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004004 static BOOL
4005vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004006 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004007 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004008 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004009 STARTUPINFO *si,
4010 PROCESS_INFORMATION *pi)
4011{
4012# ifdef FEAT_MBYTE
4013 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4014 {
4015 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4016
4017 if (wcmd != NULL)
4018 {
4019 BOOL ret;
4020 ret = CreateProcessW(
4021 NULL, /* Executable name */
4022 wcmd, /* Command to execute */
4023 NULL, /* Process security attributes */
4024 NULL, /* Thread security attributes */
4025 inherit_handles, /* Inherit handles */
4026 flags, /* Creation flags */
4027 NULL, /* Environment */
4028 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004029 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004030 pi); /* Process information */
4031 vim_free(wcmd);
4032 return ret;
4033 }
4034 }
4035#endif
4036 return CreateProcess(
4037 NULL, /* Executable name */
4038 cmd, /* Command to execute */
4039 NULL, /* Process security attributes */
4040 NULL, /* Thread security attributes */
4041 inherit_handles, /* Inherit handles */
4042 flags, /* Creation flags */
4043 NULL, /* Environment */
4044 NULL, /* Current directory */
4045 si, /* Startup information */
4046 pi); /* Process information */
4047}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048
4049
4050#if defined(FEAT_GUI_W32) || defined(PROTO)
4051
4052/*
4053 * Specialised version of system() for Win32 GUI mode.
4054 * This version proceeds as follows:
4055 * 1. Create a console window for use by the subprocess
4056 * 2. Run the subprocess (it gets the allocated console by default)
4057 * 3. Wait for the subprocess to terminate and get its exit code
4058 * 4. Prompt the user to press a key to close the console window
4059 */
4060 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004061mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062{
4063 STARTUPINFO si;
4064 PROCESS_INFORMATION pi;
4065 DWORD ret = 0;
4066 HWND hwnd = GetFocus();
4067
4068 si.cb = sizeof(si);
4069 si.lpReserved = NULL;
4070 si.lpDesktop = NULL;
4071 si.lpTitle = NULL;
4072 si.dwFlags = STARTF_USESHOWWINDOW;
4073 /*
4074 * It's nicer to run a filter command in a minimized window, but in
4075 * Windows 95 this makes the command MUCH slower. We can't do it under
4076 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004077 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078 */
4079 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004080 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081 else
4082 si.wShowWindow = SW_SHOWNORMAL;
4083 si.cbReserved2 = 0;
4084 si.lpReserved2 = NULL;
4085
4086 /* There is a strange error on Windows 95 when using "c:\\command.com".
4087 * When the "c:\\" is left out it works OK...? */
4088 if (mch_windows95()
4089 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4090 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4091 cmd += 3;
4092
4093 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004094 vim_create_process(cmd, FALSE,
4095 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004096
4097 /* Wait for the command to terminate before continuing */
4098 if (g_PlatformId != VER_PLATFORM_WIN32s)
4099 {
4100#ifdef FEAT_GUI
4101 int delay = 1;
4102
4103 /* Keep updating the window while waiting for the shell to finish. */
4104 for (;;)
4105 {
4106 MSG msg;
4107
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004108 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004109 {
4110 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004111 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004112 delay = 1;
4113 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 }
4115 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4116 break;
4117
4118 /* We start waiting for a very short time and then increase it, so
4119 * that we respond quickly when the process is quick, and don't
4120 * consume too much overhead when it's slow. */
4121 if (delay < 50)
4122 delay += 10;
4123 }
4124#else
4125 WaitForSingleObject(pi.hProcess, INFINITE);
4126#endif
4127
4128 /* Get the command exit code */
4129 GetExitCodeProcess(pi.hProcess, &ret);
4130 }
4131 else
4132 {
4133 /*
4134 * This ugly code is the only quick way of performing
4135 * a synchronous spawn under Win32s. Yuk.
4136 */
4137 num_windows = 0;
4138 EnumWindows(win32ssynch_cb, 0);
4139 old_num_windows = num_windows;
4140 do
4141 {
4142 Sleep(1000);
4143 num_windows = 0;
4144 EnumWindows(win32ssynch_cb, 0);
4145 } while (num_windows == old_num_windows);
4146 ret = 0;
4147 }
4148
4149 /* Close the handles to the subprocess, so that it goes away */
4150 CloseHandle(pi.hThread);
4151 CloseHandle(pi.hProcess);
4152
4153 /* Try to get input focus back. Doesn't always work though. */
4154 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4155
4156 return ret;
4157}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004158
4159/*
4160 * Thread launched by the gui to send the current buffer data to the
4161 * process. This way avoid to hang up vim totally if the children
4162 * process take a long time to process the lines.
4163 */
4164 static DWORD WINAPI
4165sub_process_writer(LPVOID param)
4166{
4167 HANDLE g_hChildStd_IN_Wr = param;
4168 linenr_T lnum = curbuf->b_op_start.lnum;
4169 DWORD len = 0;
4170 DWORD l;
4171 char_u *lp = ml_get(lnum);
4172 char_u *s;
4173 int written = 0;
4174
4175 for (;;)
4176 {
4177 l = (DWORD)STRLEN(lp + written);
4178 if (l == 0)
4179 len = 0;
4180 else if (lp[written] == NL)
4181 {
4182 /* NL -> NUL translation */
4183 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4184 }
4185 else
4186 {
4187 s = vim_strchr(lp + written, NL);
4188 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4189 s == NULL ? l : (DWORD)(s - (lp + written)),
4190 &len, NULL);
4191 }
4192 if (len == (int)l)
4193 {
4194 /* Finished a line, add a NL, unless this line should not have
4195 * one. */
4196 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004197 || (!curbuf->b_p_bin
4198 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004199 || (lnum != curbuf->b_no_eol_lnum
4200 && (lnum != curbuf->b_ml.ml_line_count
4201 || curbuf->b_p_eol)))
4202 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004203 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004204 }
4205
4206 ++lnum;
4207 if (lnum > curbuf->b_op_end.lnum)
4208 break;
4209
4210 lp = ml_get(lnum);
4211 written = 0;
4212 }
4213 else if (len > 0)
4214 written += len;
4215 }
4216
4217 /* finished all the lines, close pipe */
4218 CloseHandle(g_hChildStd_IN_Wr);
4219 ExitThread(0);
4220}
4221
4222
4223# define BUFLEN 100 /* length for buffer, stolen from unix version */
4224
4225/*
4226 * This function read from the children's stdout and write the
4227 * data on screen or in the buffer accordingly.
4228 */
4229 static void
4230dump_pipe(int options,
4231 HANDLE g_hChildStd_OUT_Rd,
4232 garray_T *ga,
4233 char_u buffer[],
4234 DWORD *buffer_off)
4235{
4236 DWORD availableBytes = 0;
4237 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004238 int ret;
4239 DWORD len;
4240 DWORD toRead;
4241 int repeatCount;
4242
4243 /* we query the pipe to see if there is any data to read
4244 * to avoid to perform a blocking read */
4245 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4246 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004247 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004248 NULL, /* number of read bytes */
4249 &availableBytes, /* available bytes total */
4250 NULL); /* byteLeft */
4251
4252 repeatCount = 0;
4253 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004254 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004255 {
4256 repeatCount++;
4257 toRead =
4258# ifdef FEAT_MBYTE
4259 (DWORD)(BUFLEN - *buffer_off);
4260# else
4261 (DWORD)BUFLEN;
4262# endif
4263 toRead = availableBytes < toRead ? availableBytes : toRead;
4264 ReadFile(g_hChildStd_OUT_Rd, buffer
4265# ifdef FEAT_MBYTE
4266 + *buffer_off, toRead
4267# else
4268 , toRead
4269# endif
4270 , &len, NULL);
4271
4272 /* If we haven't read anything, there is a problem */
4273 if (len == 0)
4274 break;
4275
4276 availableBytes -= len;
4277
4278 if (options & SHELL_READ)
4279 {
4280 /* Do NUL -> NL translation, append NL separated
4281 * lines to the current buffer. */
4282 for (i = 0; i < len; ++i)
4283 {
4284 if (buffer[i] == NL)
4285 append_ga_line(ga);
4286 else if (buffer[i] == NUL)
4287 ga_append(ga, NL);
4288 else
4289 ga_append(ga, buffer[i]);
4290 }
4291 }
4292# ifdef FEAT_MBYTE
4293 else if (has_mbyte)
4294 {
4295 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004296 int c;
4297 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298
4299 len += *buffer_off;
4300 buffer[len] = NUL;
4301
4302 /* Check if the last character in buffer[] is
4303 * incomplete, keep these bytes for the next
4304 * round. */
4305 for (p = buffer; p < buffer + len; p += l)
4306 {
4307 l = mb_cptr2len(p);
4308 if (l == 0)
4309 l = 1; /* NUL byte? */
4310 else if (MB_BYTE2LEN(*p) != l)
4311 break;
4312 }
4313 if (p == buffer) /* no complete character */
4314 {
4315 /* avoid getting stuck at an illegal byte */
4316 if (len >= 12)
4317 ++p;
4318 else
4319 {
4320 *buffer_off = len;
4321 return;
4322 }
4323 }
4324 c = *p;
4325 *p = NUL;
4326 msg_puts(buffer);
4327 if (p < buffer + len)
4328 {
4329 *p = c;
4330 *buffer_off = (DWORD)((buffer + len) - p);
4331 mch_memmove(buffer, p, *buffer_off);
4332 return;
4333 }
4334 *buffer_off = 0;
4335 }
4336# endif /* FEAT_MBYTE */
4337 else
4338 {
4339 buffer[len] = NUL;
4340 msg_puts(buffer);
4341 }
4342
4343 windgoto(msg_row, msg_col);
4344 cursor_on();
4345 out_flush();
4346 }
4347}
4348
4349/*
4350 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4351 * for communication and doesn't open any new window.
4352 */
4353 static int
4354mch_system_piped(char *cmd, int options)
4355{
4356 STARTUPINFO si;
4357 PROCESS_INFORMATION pi;
4358 DWORD ret = 0;
4359
4360 HANDLE g_hChildStd_IN_Rd = NULL;
4361 HANDLE g_hChildStd_IN_Wr = NULL;
4362 HANDLE g_hChildStd_OUT_Rd = NULL;
4363 HANDLE g_hChildStd_OUT_Wr = NULL;
4364
4365 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4366 DWORD len;
4367
4368 /* buffer used to receive keys */
4369 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4370 int ta_len = 0; /* valid bytes in ta_buf[] */
4371
4372 DWORD i;
4373 int c;
4374 int noread_cnt = 0;
4375 garray_T ga;
4376 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004377 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004378 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004379
4380 SECURITY_ATTRIBUTES saAttr;
4381
4382 /* Set the bInheritHandle flag so pipe handles are inherited. */
4383 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4384 saAttr.bInheritHandle = TRUE;
4385 saAttr.lpSecurityDescriptor = NULL;
4386
4387 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4388 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4389 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4390 /* Create a pipe for the child process's STDIN. */
4391 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4392 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4393 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4394 {
4395 CloseHandle(g_hChildStd_IN_Rd);
4396 CloseHandle(g_hChildStd_IN_Wr);
4397 CloseHandle(g_hChildStd_OUT_Rd);
4398 CloseHandle(g_hChildStd_OUT_Wr);
4399 MSG_PUTS(_("\nCannot create pipes\n"));
4400 }
4401
4402 si.cb = sizeof(si);
4403 si.lpReserved = NULL;
4404 si.lpDesktop = NULL;
4405 si.lpTitle = NULL;
4406 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4407
4408 /* set-up our file redirection */
4409 si.hStdError = g_hChildStd_OUT_Wr;
4410 si.hStdOutput = g_hChildStd_OUT_Wr;
4411 si.hStdInput = g_hChildStd_IN_Rd;
4412 si.wShowWindow = SW_HIDE;
4413 si.cbReserved2 = 0;
4414 si.lpReserved2 = NULL;
4415
4416 if (options & SHELL_READ)
4417 ga_init2(&ga, 1, BUFLEN);
4418
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004419 if (cmd != NULL)
4420 {
4421 p = (char *)vim_strsave((char_u *)cmd);
4422 if (p != NULL)
4423 unescape_shellxquote((char_u *)p, p_sxe);
4424 else
4425 p = cmd;
4426 }
4427
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004428 /* Now, run the command.
4429 * About "Inherit handles" being TRUE: this command can be litigious,
4430 * handle inheritance was deactivated for pending temp file, but, if we
4431 * deactivate it, the pipes don't work for some reason. */
4432 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004433
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004434 if (p != cmd)
4435 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004436
4437 /* Close our unused side of the pipes */
4438 CloseHandle(g_hChildStd_IN_Rd);
4439 CloseHandle(g_hChildStd_OUT_Wr);
4440
4441 if (options & SHELL_WRITE)
4442 {
4443 HANDLE thread =
4444 CreateThread(NULL, /* security attributes */
4445 0, /* default stack size */
4446 sub_process_writer, /* function to be executed */
4447 g_hChildStd_IN_Wr, /* parameter */
4448 0, /* creation flag, start immediately */
4449 NULL); /* we don't care about thread id */
4450 CloseHandle(thread);
4451 g_hChildStd_IN_Wr = NULL;
4452 }
4453
4454 /* Keep updating the window while waiting for the shell to finish. */
4455 for (;;)
4456 {
4457 MSG msg;
4458
Bram Moolenaar175d0702013-12-11 18:36:33 +01004459 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004460 {
4461 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004462 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004463 }
4464
4465 /* write pipe information in the window */
4466 if ((options & (SHELL_READ|SHELL_WRITE))
4467# ifdef FEAT_GUI
4468 || gui.in_use
4469# endif
4470 )
4471 {
4472 len = 0;
4473 if (!(options & SHELL_EXPAND)
4474 && ((options &
4475 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4476 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4477# ifdef FEAT_GUI
4478 || gui.in_use
4479# endif
4480 )
4481 && (ta_len > 0 || noread_cnt > 4))
4482 {
4483 if (ta_len == 0)
4484 {
4485 /* Get extra characters when we don't have any. Reset the
4486 * counter and timer. */
4487 noread_cnt = 0;
4488# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4489 gettimeofday(&start_tv, NULL);
4490# endif
4491 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4492 }
4493 if (ta_len > 0 || len > 0)
4494 {
4495 /*
4496 * For pipes: Check for CTRL-C: send interrupt signal to
4497 * child. Check for CTRL-D: EOF, close pipe to child.
4498 */
4499 if (len == 1 && cmd != NULL)
4500 {
4501 if (ta_buf[ta_len] == Ctrl_C)
4502 {
4503 /* Learn what exit code is expected, for
4504 * now put 9 as SIGKILL */
4505 TerminateProcess(pi.hProcess, 9);
4506 }
4507 if (ta_buf[ta_len] == Ctrl_D)
4508 {
4509 CloseHandle(g_hChildStd_IN_Wr);
4510 g_hChildStd_IN_Wr = NULL;
4511 }
4512 }
4513
4514 /* replace K_BS by <BS> and K_DEL by <DEL> */
4515 for (i = ta_len; i < ta_len + len; ++i)
4516 {
4517 if (ta_buf[i] == CSI && len - i > 2)
4518 {
4519 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4520 if (c == K_DEL || c == K_KDEL || c == K_BS)
4521 {
4522 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4523 (size_t)(len - i - 2));
4524 if (c == K_DEL || c == K_KDEL)
4525 ta_buf[i] = DEL;
4526 else
4527 ta_buf[i] = Ctrl_H;
4528 len -= 2;
4529 }
4530 }
4531 else if (ta_buf[i] == '\r')
4532 ta_buf[i] = '\n';
4533# ifdef FEAT_MBYTE
4534 if (has_mbyte)
4535 i += (*mb_ptr2len_len)(ta_buf + i,
4536 ta_len + len - i) - 1;
4537# endif
4538 }
4539
4540 /*
4541 * For pipes: echo the typed characters. For a pty this
4542 * does not seem to work.
4543 */
4544 for (i = ta_len; i < ta_len + len; ++i)
4545 {
4546 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4547 msg_putchar(ta_buf[i]);
4548# ifdef FEAT_MBYTE
4549 else if (has_mbyte)
4550 {
4551 int l = (*mb_ptr2len)(ta_buf + i);
4552
4553 msg_outtrans_len(ta_buf + i, l);
4554 i += l - 1;
4555 }
4556# endif
4557 else
4558 msg_outtrans_len(ta_buf + i, 1);
4559 }
4560 windgoto(msg_row, msg_col);
4561 out_flush();
4562
4563 ta_len += len;
4564
4565 /*
4566 * Write the characters to the child, unless EOF has been
4567 * typed for pipes. Write one character at a time, to
4568 * avoid losing too much typeahead. When writing buffer
4569 * lines, drop the typed characters (only check for
4570 * CTRL-C).
4571 */
4572 if (options & SHELL_WRITE)
4573 ta_len = 0;
4574 else if (g_hChildStd_IN_Wr != NULL)
4575 {
4576 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4577 1, &len, NULL);
4578 // if we are typing in, we want to keep things reactive
4579 delay = 1;
4580 if (len > 0)
4581 {
4582 ta_len -= len;
4583 mch_memmove(ta_buf, ta_buf + len, ta_len);
4584 }
4585 }
4586 }
4587 }
4588 }
4589
4590 if (ta_len)
4591 ui_inchar_undo(ta_buf, ta_len);
4592
4593 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4594 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004595 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004596 break;
4597 }
4598
4599 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004600 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004601
4602 /* We start waiting for a very short time and then increase it, so
4603 * that we respond quickly when the process is quick, and don't
4604 * consume too much overhead when it's slow. */
4605 if (delay < 50)
4606 delay += 10;
4607 }
4608
4609 /* Close the pipe */
4610 CloseHandle(g_hChildStd_OUT_Rd);
4611 if (g_hChildStd_IN_Wr != NULL)
4612 CloseHandle(g_hChildStd_IN_Wr);
4613
4614 WaitForSingleObject(pi.hProcess, INFINITE);
4615
4616 /* Get the command exit code */
4617 GetExitCodeProcess(pi.hProcess, &ret);
4618
4619 if (options & SHELL_READ)
4620 {
4621 if (ga.ga_len > 0)
4622 {
4623 append_ga_line(&ga);
4624 /* remember that the NL was missing */
4625 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4626 }
4627 else
4628 curbuf->b_no_eol_lnum = 0;
4629 ga_clear(&ga);
4630 }
4631
4632 /* Close the handles to the subprocess, so that it goes away */
4633 CloseHandle(pi.hThread);
4634 CloseHandle(pi.hProcess);
4635
4636 return ret;
4637}
4638
4639 static int
4640mch_system(char *cmd, int options)
4641{
4642 /* if we can pipe and the shelltemp option is off */
4643 if (allowPiping && !p_stmp)
4644 return mch_system_piped(cmd, options);
4645 else
4646 return mch_system_classic(cmd, options);
4647}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004648#else
4649
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004650# ifdef FEAT_MBYTE
4651 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004652mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004653{
4654 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4655 {
4656 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4657 if (wcmd != NULL)
4658 {
4659 int ret = _wsystem(wcmd);
4660 vim_free(wcmd);
4661 return ret;
4662 }
4663 }
4664 return system(cmd);
4665}
4666# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004667# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004668# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004669
4670#endif
4671
4672/*
4673 * Either execute a command by calling the shell or start a new shell
4674 */
4675 int
4676mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004677 char_u *cmd,
4678 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004679{
4680 int x = 0;
4681 int tmode = cur_tmode;
4682#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004683 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004684# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004685 int did_set_title = FALSE;
4686
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004687 /* Change the title to reflect that we are in a subshell. */
4688 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4689 {
4690 WCHAR szShellTitle[512];
4691
4692 if (GetConsoleTitleW(szShellTitle,
4693 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4694 {
4695 if (cmd == NULL)
4696 wcscat(szShellTitle, L" :sh");
4697 else
4698 {
4699 WCHAR *wn = enc_to_utf16(cmd, NULL);
4700
4701 if (wn != NULL)
4702 {
4703 wcscat(szShellTitle, L" - !");
4704 if ((wcslen(szShellTitle) + wcslen(wn) <
4705 sizeof(szShellTitle)/sizeof(WCHAR)))
4706 wcscat(szShellTitle, wn);
4707 SetConsoleTitleW(szShellTitle);
4708 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004709 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004710 }
4711 }
4712 }
4713 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004714 if (!did_set_title)
4715# endif
4716 /* Change the title to reflect that we are in a subshell. */
4717 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004718 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004719 if (cmd == NULL)
4720 strcat(szShellTitle, " :sh");
4721 else
4722 {
4723 strcat(szShellTitle, " - !");
4724 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4725 strcat(szShellTitle, cmd);
4726 }
4727 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004728 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729#endif
4730
4731 out_flush();
4732
4733#ifdef MCH_WRITE_DUMP
4734 if (fdDump)
4735 {
4736 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4737 fflush(fdDump);
4738 }
4739#endif
4740
4741 /*
4742 * Catch all deadly signals while running the external command, because a
4743 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4744 */
4745 signal(SIGINT, SIG_IGN);
4746#if defined(__GNUC__) && !defined(__MINGW32__)
4747 signal(SIGKILL, SIG_IGN);
4748#else
4749 signal(SIGBREAK, SIG_IGN);
4750#endif
4751 signal(SIGILL, SIG_IGN);
4752 signal(SIGFPE, SIG_IGN);
4753 signal(SIGSEGV, SIG_IGN);
4754 signal(SIGTERM, SIG_IGN);
4755 signal(SIGABRT, SIG_IGN);
4756
4757 if (options & SHELL_COOKED)
4758 settmode(TMODE_COOK); /* set to normal mode */
4759
4760 if (cmd == NULL)
4761 {
4762 x = mch_system(p_sh, options);
4763 }
4764 else
4765 {
4766 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004767 char_u *newcmd = NULL;
4768 char_u *cmdbase = cmd;
4769 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004770
4771 /* Skip a leading ", ( and "(. */
4772 if (*cmdbase == '"' )
4773 ++cmdbase;
4774 if (*cmdbase == '(')
4775 ++cmdbase;
4776
4777 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4778 {
4779 STARTUPINFO si;
4780 PROCESS_INFORMATION pi;
4781 DWORD flags = CREATE_NEW_CONSOLE;
4782 char_u *p;
4783
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004784 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004785 si.cb = sizeof(si);
4786 si.lpReserved = NULL;
4787 si.lpDesktop = NULL;
4788 si.lpTitle = NULL;
4789 si.dwFlags = 0;
4790 si.cbReserved2 = 0;
4791 si.lpReserved2 = NULL;
4792
4793 cmdbase = skipwhite(cmdbase + 5);
4794 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4795 && vim_iswhite(cmdbase[4]))
4796 {
4797 cmdbase = skipwhite(cmdbase + 4);
4798 si.dwFlags = STARTF_USESHOWWINDOW;
4799 si.wShowWindow = SW_SHOWMINNOACTIVE;
4800 }
4801 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4802 && vim_iswhite(cmdbase[2]))
4803 {
4804 cmdbase = skipwhite(cmdbase + 2);
4805 flags = CREATE_NO_WINDOW;
4806 si.dwFlags = STARTF_USESTDHANDLES;
4807 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004808 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004809 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004810 NULL, // Security att.
4811 OPEN_EXISTING, // Open flags
4812 FILE_ATTRIBUTE_NORMAL, // File att.
4813 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004814 si.hStdOutput = si.hStdInput;
4815 si.hStdError = si.hStdInput;
4816 }
4817
4818 /* Remove a trailing ", ) and )" if they have a match
4819 * at the start of the command. */
4820 if (cmdbase > cmd)
4821 {
4822 p = cmdbase + STRLEN(cmdbase);
4823 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4824 *--p = NUL;
4825 if (p > cmdbase && p[-1] == ')'
4826 && (*cmd =='(' || cmd[1] == '('))
4827 *--p = NUL;
4828 }
4829
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004830 newcmd = cmdbase;
4831 unescape_shellxquote(cmdbase, p_sxe);
4832
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004833 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004834 * If creating new console, arguments are passed to the
4835 * 'cmd.exe' as-is. If it's not, arguments are not treated
4836 * correctly for current 'cmd.exe'. So unescape characters in
4837 * shellxescape except '|' for avoiding to be treated as
4838 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004839 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004840 if (flags != CREATE_NEW_CONSOLE)
4841 {
4842 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004843 char_u *cmd_shell = mch_getenv("COMSPEC");
4844
4845 if (cmd_shell == NULL || *cmd_shell == NUL)
4846 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004847
4848 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4849 if (subcmd != NULL)
4850 {
4851 /* make "cmd.exe /c arguments" */
4852 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004853 newcmd = lalloc(cmdlen, TRUE);
4854 if (newcmd != NULL)
4855 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004856 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004857 else
4858 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004859 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004860 }
4861 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004862
4863 /*
4864 * Now, start the command as a process, so that it doesn't
4865 * inherit our handles which causes unpleasant dangling swap
4866 * files if we exit before the spawned process
4867 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004868 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004869 x = 0;
4870 else
4871 {
4872 x = -1;
4873#ifdef FEAT_GUI_W32
4874 EMSG(_("E371: Command not found"));
4875#endif
4876 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877
4878 if (newcmd != cmdbase)
4879 vim_free(newcmd);
4880
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004881 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004882 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004883 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004884 CloseHandle(si.hStdInput);
4885 }
4886 /* Close the handles to the subprocess, so that it goes away */
4887 CloseHandle(pi.hThread);
4888 CloseHandle(pi.hProcess);
4889 }
4890 else
4891 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004892 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004894 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004896 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4897
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004898 newcmd = lalloc(cmdlen, TRUE);
4899 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900 {
4901#if defined(FEAT_GUI_W32)
4902 if (need_vimrun_warning)
4903 {
4904 MessageBox(NULL,
4905 _("VIMRUN.EXE not found in your $PATH.\n"
4906 "External commands will not pause after completion.\n"
4907 "See :help win32-vimrun for more information."),
4908 _("Vim Warning"),
4909 MB_ICONWARNING);
4910 need_vimrun_warning = FALSE;
4911 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004912 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004913 /* Use vimrun to execute the command. It opens a console
4914 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004915 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916 vimrun_path,
4917 (msg_silent != 0 || (options & SHELL_DOOUT))
4918 ? "-s " : "",
4919 p_sh, p_shcf, cmd);
4920 else
4921#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004922 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004923 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004924 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004925 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004926 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004927 }
4928 }
4929
4930 if (tmode == TMODE_RAW)
4931 settmode(TMODE_RAW); /* set to raw mode */
4932
4933 /* Print the return value, unless "vimrun" was used. */
4934 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4935#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004936 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4937 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938#endif
4939 )
4940 {
4941 smsg(_("shell returned %d"), x);
4942 msg_putchar('\n');
4943 }
4944#ifdef FEAT_TITLE
4945 resettitle();
4946#endif
4947
4948 signal(SIGINT, SIG_DFL);
4949#if defined(__GNUC__) && !defined(__MINGW32__)
4950 signal(SIGKILL, SIG_DFL);
4951#else
4952 signal(SIGBREAK, SIG_DFL);
4953#endif
4954 signal(SIGILL, SIG_DFL);
4955 signal(SIGFPE, SIG_DFL);
4956 signal(SIGSEGV, SIG_DFL);
4957 signal(SIGTERM, SIG_DFL);
4958 signal(SIGABRT, SIG_DFL);
4959
4960 return x;
4961}
4962
4963
4964#ifndef FEAT_GUI_W32
4965
4966/*
4967 * Start termcap mode
4968 */
4969 static void
4970termcap_mode_start(void)
4971{
4972 DWORD cmodein;
4973
4974 if (g_fTermcapMode)
4975 return;
4976
4977 SaveConsoleBuffer(&g_cbNonTermcap);
4978
4979 if (g_cbTermcap.IsValid)
4980 {
4981 /*
4982 * We've been in termcap mode before. Restore certain screen
4983 * characteristics, including the buffer size and the window
4984 * size. Since we will be redrawing the screen, we don't need
4985 * to restore the actual contents of the buffer.
4986 */
4987 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4988 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4989 Rows = g_cbTermcap.Info.dwSize.Y;
4990 Columns = g_cbTermcap.Info.dwSize.X;
4991 }
4992 else
4993 {
4994 /*
4995 * This is our first time entering termcap mode. Clear the console
4996 * screen buffer, and resize the buffer to match the current window
4997 * size. We will use this as the size of our editing environment.
4998 */
4999 ClearConsoleBuffer(g_attrCurrent);
5000 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5001 }
5002
5003#ifdef FEAT_TITLE
5004 resettitle();
5005#endif
5006
5007 GetConsoleMode(g_hConIn, &cmodein);
5008#ifdef FEAT_MOUSE
5009 if (g_fMouseActive)
5010 cmodein |= ENABLE_MOUSE_INPUT;
5011 else
5012 cmodein &= ~ENABLE_MOUSE_INPUT;
5013#endif
5014 cmodein |= ENABLE_WINDOW_INPUT;
5015 SetConsoleMode(g_hConIn, cmodein);
5016
5017 redraw_later_clear();
5018 g_fTermcapMode = TRUE;
5019}
5020
5021
5022/*
5023 * End termcap mode
5024 */
5025 static void
5026termcap_mode_end(void)
5027{
5028 DWORD cmodein;
5029 ConsoleBuffer *cb;
5030 COORD coord;
5031 DWORD dwDummy;
5032
5033 if (!g_fTermcapMode)
5034 return;
5035
5036 SaveConsoleBuffer(&g_cbTermcap);
5037
5038 GetConsoleMode(g_hConIn, &cmodein);
5039 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5040 SetConsoleMode(g_hConIn, cmodein);
5041
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005042#ifdef FEAT_RESTORE_ORIG_SCREEN
5043 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5044#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005046#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005047 RestoreConsoleBuffer(cb, p_rs);
5048 SetConsoleCursorInfo(g_hConOut, &g_cci);
5049
5050 if (p_rs || exiting)
5051 {
5052 /*
5053 * Clear anything that happens to be on the current line.
5054 */
5055 coord.X = 0;
5056 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5057 FillConsoleOutputCharacter(g_hConOut, ' ',
5058 cb->Info.dwSize.X, coord, &dwDummy);
5059 /*
5060 * The following is just for aesthetics. If we are exiting without
5061 * restoring the screen, then we want to have a prompt string
5062 * appear at the bottom line. However, the command interpreter
5063 * seems to always advance the cursor one line before displaying
5064 * the prompt string, which causes the screen to scroll. To
5065 * counter this, move the cursor up one line before exiting.
5066 */
5067 if (exiting && !p_rs)
5068 coord.Y--;
5069 /*
5070 * Position the cursor at the leftmost column of the desired row.
5071 */
5072 SetConsoleCursorPosition(g_hConOut, coord);
5073 }
5074
5075 g_fTermcapMode = FALSE;
5076}
5077#endif /* FEAT_GUI_W32 */
5078
5079
5080#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005081/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082 void
5083mch_write(
5084 char_u *s,
5085 int len)
5086{
5087 /* never used */
5088}
5089
5090#else
5091
5092/*
5093 * clear `n' chars, starting from `coord'
5094 */
5095 static void
5096clear_chars(
5097 COORD coord,
5098 DWORD n)
5099{
5100 DWORD dwDummy;
5101
5102 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5103 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5104}
5105
5106
5107/*
5108 * Clear the screen
5109 */
5110 static void
5111clear_screen(void)
5112{
5113 g_coord.X = g_coord.Y = 0;
5114 clear_chars(g_coord, Rows * Columns);
5115}
5116
5117
5118/*
5119 * Clear to end of display
5120 */
5121 static void
5122clear_to_end_of_display(void)
5123{
5124 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5125 * Columns + (Columns - g_coord.X));
5126}
5127
5128
5129/*
5130 * Clear to end of line
5131 */
5132 static void
5133clear_to_end_of_line(void)
5134{
5135 clear_chars(g_coord, Columns - g_coord.X);
5136}
5137
5138
5139/*
5140 * Scroll the scroll region up by `cLines' lines
5141 */
5142 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005143scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005144{
5145 COORD oldcoord = g_coord;
5146
5147 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5148 delete_lines(cLines);
5149
5150 g_coord = oldcoord;
5151}
5152
5153
5154/*
5155 * Set the scroll region
5156 */
5157 static void
5158set_scroll_region(
5159 unsigned left,
5160 unsigned top,
5161 unsigned right,
5162 unsigned bottom)
5163{
5164 if (left >= right
5165 || top >= bottom
5166 || right > (unsigned) Columns - 1
5167 || bottom > (unsigned) Rows - 1)
5168 return;
5169
5170 g_srScrollRegion.Left = left;
5171 g_srScrollRegion.Top = top;
5172 g_srScrollRegion.Right = right;
5173 g_srScrollRegion.Bottom = bottom;
5174}
5175
5176
5177/*
5178 * Insert `cLines' lines at the current cursor position
5179 */
5180 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005181insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182{
5183 SMALL_RECT source;
5184 COORD dest;
5185 CHAR_INFO fill;
5186
5187 dest.X = 0;
5188 dest.Y = g_coord.Y + cLines;
5189
5190 source.Left = 0;
5191 source.Top = g_coord.Y;
5192 source.Right = g_srScrollRegion.Right;
5193 source.Bottom = g_srScrollRegion.Bottom - cLines;
5194
5195 fill.Char.AsciiChar = ' ';
5196 fill.Attributes = g_attrCurrent;
5197
5198 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5199
5200 /* Here we have to deal with a win32 console flake: If the scroll
5201 * region looks like abc and we scroll c to a and fill with d we get
5202 * cbd... if we scroll block c one line at a time to a, we get cdd...
5203 * vim expects cdd consistently... So we have to deal with that
5204 * here... (this also occurs scrolling the same way in the other
5205 * direction). */
5206
5207 if (source.Bottom < dest.Y)
5208 {
5209 COORD coord;
5210
5211 coord.X = 0;
5212 coord.Y = source.Bottom;
5213 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5214 }
5215}
5216
5217
5218/*
5219 * Delete `cLines' lines at the current cursor position
5220 */
5221 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005222delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005223{
5224 SMALL_RECT source;
5225 COORD dest;
5226 CHAR_INFO fill;
5227 int nb;
5228
5229 dest.X = 0;
5230 dest.Y = g_coord.Y;
5231
5232 source.Left = 0;
5233 source.Top = g_coord.Y + cLines;
5234 source.Right = g_srScrollRegion.Right;
5235 source.Bottom = g_srScrollRegion.Bottom;
5236
5237 fill.Char.AsciiChar = ' ';
5238 fill.Attributes = g_attrCurrent;
5239
5240 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5241
5242 /* Here we have to deal with a win32 console flake: If the scroll
5243 * region looks like abc and we scroll c to a and fill with d we get
5244 * cbd... if we scroll block c one line at a time to a, we get cdd...
5245 * vim expects cdd consistently... So we have to deal with that
5246 * here... (this also occurs scrolling the same way in the other
5247 * direction). */
5248
5249 nb = dest.Y + (source.Bottom - source.Top) + 1;
5250
5251 if (nb < source.Top)
5252 {
5253 COORD coord;
5254
5255 coord.X = 0;
5256 coord.Y = nb;
5257 clear_chars(coord, Columns * (source.Top - nb));
5258 }
5259}
5260
5261
5262/*
5263 * Set the cursor position
5264 */
5265 static void
5266gotoxy(
5267 unsigned x,
5268 unsigned y)
5269{
5270 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5271 return;
5272
5273 /* external cursor coords are 1-based; internal are 0-based */
5274 g_coord.X = x - 1;
5275 g_coord.Y = y - 1;
5276 SetConsoleCursorPosition(g_hConOut, g_coord);
5277}
5278
5279
5280/*
5281 * Set the current text attribute = (foreground | background)
5282 * See ../doc/os_win32.txt for the numbers.
5283 */
5284 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005285textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005286{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005287 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005288
5289 SetConsoleTextAttribute(g_hConOut, wAttr);
5290}
5291
5292
5293 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005294textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005295{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005296 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005297
5298 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5299}
5300
5301
5302 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005303textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005304{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005305 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005306
5307 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5308}
5309
5310
5311/*
5312 * restore the default text attribute (whatever we started with)
5313 */
5314 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005315normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005316{
5317 textattr(g_attrDefault);
5318}
5319
5320
5321static WORD g_attrPreStandout = 0;
5322
5323/*
5324 * Make the text standout, by brightening it
5325 */
5326 static void
5327standout(void)
5328{
5329 g_attrPreStandout = g_attrCurrent;
5330 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5331}
5332
5333
5334/*
5335 * Turn off standout mode
5336 */
5337 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005338standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005339{
5340 if (g_attrPreStandout)
5341 {
5342 textattr(g_attrPreStandout);
5343 g_attrPreStandout = 0;
5344 }
5345}
5346
5347
5348/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005349 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005350 */
5351 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005352mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353{
5354 char_u *p;
5355 int n;
5356
5357 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5358 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5359 if (T_ME[0] == ESC && T_ME[1] == '|')
5360 {
5361 p = T_ME + 2;
5362 n = getdigits(&p);
5363 if (*p == 'm' && n > 0)
5364 {
5365 cterm_normal_fg_color = (n & 0xf) + 1;
5366 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5367 }
5368 }
5369}
5370
5371
5372/*
5373 * visual bell: flash the screen
5374 */
5375 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005376visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005377{
5378 COORD coordOrigin = {0, 0};
5379 WORD attrFlash = ~g_attrCurrent & 0xff;
5380
5381 DWORD dwDummy;
5382 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5383
5384 if (oldattrs == NULL)
5385 return;
5386 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5387 coordOrigin, &dwDummy);
5388 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5389 coordOrigin, &dwDummy);
5390
5391 Sleep(15); /* wait for 15 msec */
5392 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5393 coordOrigin, &dwDummy);
5394 vim_free(oldattrs);
5395}
5396
5397
5398/*
5399 * Make the cursor visible or invisible
5400 */
5401 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005402cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005403{
5404 s_cursor_visible = fVisible;
5405#ifdef MCH_CURSOR_SHAPE
5406 mch_update_cursor();
5407#endif
5408}
5409
5410
5411/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005412 * write `cbToWrite' bytes in `pchBuf' to the screen
5413 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005415 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005416write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005417 char_u *pchBuf,
5418 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005419{
5420 COORD coord = g_coord;
5421 DWORD written;
5422
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005423#ifdef FEAT_MBYTE
5424 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5425 {
5426 static WCHAR *unicodebuf = NULL;
5427 static int unibuflen = 0;
5428 int length;
5429 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005430
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005431 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5432 if (unicodebuf == NULL || length > unibuflen)
5433 {
5434 vim_free(unicodebuf);
5435 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5436 unibuflen = length;
5437 }
5438 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5439 unicodebuf, unibuflen);
5440
5441 cells = mb_string2cells(pchBuf, cbToWrite);
5442 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5443 coord, &written);
5444 /* When writing fails or didn't write a single character, pretend one
5445 * character was written, otherwise we get stuck. */
5446 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5447 coord, &cchwritten) == 0
5448 || cchwritten == 0)
5449 cchwritten = 1;
5450
5451 if (cchwritten == length)
5452 {
5453 written = cbToWrite;
5454 g_coord.X += (SHORT)cells;
5455 }
5456 else
5457 {
5458 char_u *p = pchBuf;
5459 for (n = 0; n < cchwritten; n++)
5460 mb_cptr_adv(p);
5461 written = p - pchBuf;
5462 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5463 }
5464 }
5465 else
5466#endif
5467 {
5468 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5469 coord, &written);
5470 /* When writing fails or didn't write a single character, pretend one
5471 * character was written, otherwise we get stuck. */
5472 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5473 coord, &written) == 0
5474 || written == 0)
5475 written = 1;
5476
5477 g_coord.X += (SHORT) written;
5478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005479
5480 while (g_coord.X > g_srScrollRegion.Right)
5481 {
5482 g_coord.X -= (SHORT) Columns;
5483 if (g_coord.Y < g_srScrollRegion.Bottom)
5484 g_coord.Y++;
5485 }
5486
5487 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5488
5489 return written;
5490}
5491
5492
5493/*
5494 * mch_write(): write the output buffer to the screen, translating ESC
5495 * sequences into calls to console output routines.
5496 */
5497 void
5498mch_write(
5499 char_u *s,
5500 int len)
5501{
5502 s[len] = NUL;
5503
5504 if (!term_console)
5505 {
5506 write(1, s, (unsigned)len);
5507 return;
5508 }
5509
5510 /* translate ESC | sequences into faked bios calls */
5511 while (len--)
5512 {
5513 /* optimization: use one single write_chars for runs of text,
5514 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005515 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005516
5517 if (p_wd)
5518 {
5519 WaitForChar(p_wd);
5520 if (prefix != 0)
5521 prefix = 1;
5522 }
5523
5524 if (prefix != 0)
5525 {
5526 DWORD nWritten;
5527
5528 nWritten = write_chars(s, prefix);
5529#ifdef MCH_WRITE_DUMP
5530 if (fdDump)
5531 {
5532 fputc('>', fdDump);
5533 fwrite(s, sizeof(char_u), nWritten, fdDump);
5534 fputs("<\n", fdDump);
5535 }
5536#endif
5537 len -= (nWritten - 1);
5538 s += nWritten;
5539 }
5540 else if (s[0] == '\n')
5541 {
5542 /* \n, newline: go to the beginning of the next line or scroll */
5543 if (g_coord.Y == g_srScrollRegion.Bottom)
5544 {
5545 scroll(1);
5546 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5547 }
5548 else
5549 {
5550 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5551 }
5552#ifdef MCH_WRITE_DUMP
5553 if (fdDump)
5554 fputs("\\n\n", fdDump);
5555#endif
5556 s++;
5557 }
5558 else if (s[0] == '\r')
5559 {
5560 /* \r, carriage return: go to beginning of line */
5561 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5562#ifdef MCH_WRITE_DUMP
5563 if (fdDump)
5564 fputs("\\r\n", fdDump);
5565#endif
5566 s++;
5567 }
5568 else if (s[0] == '\b')
5569 {
5570 /* \b, backspace: move cursor one position left */
5571 if (g_coord.X > g_srScrollRegion.Left)
5572 g_coord.X--;
5573 else if (g_coord.Y > g_srScrollRegion.Top)
5574 {
5575 g_coord.X = g_srScrollRegion.Right;
5576 g_coord.Y--;
5577 }
5578 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5579#ifdef MCH_WRITE_DUMP
5580 if (fdDump)
5581 fputs("\\b\n", fdDump);
5582#endif
5583 s++;
5584 }
5585 else if (s[0] == '\a')
5586 {
5587 /* \a, bell */
5588 MessageBeep(0xFFFFFFFF);
5589#ifdef MCH_WRITE_DUMP
5590 if (fdDump)
5591 fputs("\\a\n", fdDump);
5592#endif
5593 s++;
5594 }
5595 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5596 {
5597#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005598 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005599#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005600 char_u *p;
5601 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602
5603 switch (s[2])
5604 {
5605 /* one or two numeric arguments, separated by ';' */
5606
5607 case '0': case '1': case '2': case '3': case '4':
5608 case '5': case '6': case '7': case '8': case '9':
5609 p = s + 2;
5610 arg1 = getdigits(&p); /* no check for length! */
5611 if (p > s + len)
5612 break;
5613
5614 if (*p == ';')
5615 {
5616 ++p;
5617 arg2 = getdigits(&p); /* no check for length! */
5618 if (p > s + len)
5619 break;
5620
5621 if (*p == 'H')
5622 gotoxy(arg2, arg1);
5623 else if (*p == 'r')
5624 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5625 }
5626 else if (*p == 'A')
5627 {
5628 /* move cursor up arg1 lines in same column */
5629 gotoxy(g_coord.X + 1,
5630 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5631 }
5632 else if (*p == 'C')
5633 {
5634 /* move cursor right arg1 columns in same line */
5635 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5636 g_coord.Y + 1);
5637 }
5638 else if (*p == 'H')
5639 {
5640 gotoxy(1, arg1);
5641 }
5642 else if (*p == 'L')
5643 {
5644 insert_lines(arg1);
5645 }
5646 else if (*p == 'm')
5647 {
5648 if (arg1 == 0)
5649 normvideo();
5650 else
5651 textattr((WORD) arg1);
5652 }
5653 else if (*p == 'f')
5654 {
5655 textcolor((WORD) arg1);
5656 }
5657 else if (*p == 'b')
5658 {
5659 textbackground((WORD) arg1);
5660 }
5661 else if (*p == 'M')
5662 {
5663 delete_lines(arg1);
5664 }
5665
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005666 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 s = p + 1;
5668 break;
5669
5670
5671 /* Three-character escape sequences */
5672
5673 case 'A':
5674 /* move cursor up one line in same column */
5675 gotoxy(g_coord.X + 1,
5676 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5677 goto got3;
5678
5679 case 'B':
5680 visual_bell();
5681 goto got3;
5682
5683 case 'C':
5684 /* move cursor right one column in same line */
5685 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5686 g_coord.Y + 1);
5687 goto got3;
5688
5689 case 'E':
5690 termcap_mode_end();
5691 goto got3;
5692
5693 case 'F':
5694 standout();
5695 goto got3;
5696
5697 case 'f':
5698 standend();
5699 goto got3;
5700
5701 case 'H':
5702 gotoxy(1, 1);
5703 goto got3;
5704
5705 case 'j':
5706 clear_to_end_of_display();
5707 goto got3;
5708
5709 case 'J':
5710 clear_screen();
5711 goto got3;
5712
5713 case 'K':
5714 clear_to_end_of_line();
5715 goto got3;
5716
5717 case 'L':
5718 insert_lines(1);
5719 goto got3;
5720
5721 case 'M':
5722 delete_lines(1);
5723 goto got3;
5724
5725 case 'S':
5726 termcap_mode_start();
5727 goto got3;
5728
5729 case 'V':
5730 cursor_visible(TRUE);
5731 goto got3;
5732
5733 case 'v':
5734 cursor_visible(FALSE);
5735 goto got3;
5736
5737 got3:
5738 s += 3;
5739 len -= 2;
5740 }
5741
5742#ifdef MCH_WRITE_DUMP
5743 if (fdDump)
5744 {
5745 fputs("ESC | ", fdDump);
5746 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5747 fputc('\n', fdDump);
5748 }
5749#endif
5750 }
5751 else
5752 {
5753 /* Write a single character */
5754 DWORD nWritten;
5755
5756 nWritten = write_chars(s, 1);
5757#ifdef MCH_WRITE_DUMP
5758 if (fdDump)
5759 {
5760 fputc('>', fdDump);
5761 fwrite(s, sizeof(char_u), nWritten, fdDump);
5762 fputs("<\n", fdDump);
5763 }
5764#endif
5765
5766 len -= (nWritten - 1);
5767 s += nWritten;
5768 }
5769 }
5770
5771#ifdef MCH_WRITE_DUMP
5772 if (fdDump)
5773 fflush(fdDump);
5774#endif
5775}
5776
5777#endif /* FEAT_GUI_W32 */
5778
5779
5780/*
5781 * Delay for half a second.
5782 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005783/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 void
5785mch_delay(
5786 long msec,
5787 int ignoreinput)
5788{
5789#ifdef FEAT_GUI_W32
5790 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005791#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005793# ifdef FEAT_MZSCHEME
5794 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5795 {
5796 int towait = p_mzq;
5797
5798 /* if msec is large enough, wait by portions in p_mzq */
5799 while (msec > 0)
5800 {
5801 mzvim_check_threads();
5802 if (msec < towait)
5803 towait = msec;
5804 Sleep(towait);
5805 msec -= towait;
5806 }
5807 }
5808 else
5809# endif
5810 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811 else
5812 WaitForChar(msec);
5813#endif
5814}
5815
5816
5817/*
5818 * this version of remove is not scared by a readonly (backup) file
5819 * Return 0 for success, -1 for failure.
5820 */
5821 int
5822mch_remove(char_u *name)
5823{
5824#ifdef FEAT_MBYTE
5825 WCHAR *wn = NULL;
5826 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005827#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005829 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5830
5831#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5833 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005834 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005835 if (wn != NULL)
5836 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837 n = DeleteFileW(wn) ? 0 : -1;
5838 vim_free(wn);
5839 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5840 return n;
5841 /* Retry with non-wide function (for Windows 98). */
5842 }
5843 }
5844#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005845 return DeleteFile(name) ? 0 : -1;
5846}
5847
5848
5849/*
5850 * check for an "interrupt signal": CTRL-break or CTRL-C
5851 */
5852 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005853mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854{
5855#ifndef FEAT_GUI_W32 /* never used */
5856 if (g_fCtrlCPressed || g_fCBrkPressed)
5857 {
5858 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5859 got_int = TRUE;
5860 }
5861#endif
5862}
5863
Bram Moolenaaree273972016-01-02 21:11:51 +01005864/* physical RAM to leave for the OS */
5865#define WINNT_RESERVE_BYTES (256*1024*1024)
5866#define WIN95_RESERVE_BYTES (8*1024*1024)
5867
5868/*
5869 * How much main memory in KiB that can be used by VIM.
5870 */
5871/*ARGSUSED*/
5872 long_u
5873mch_total_mem(int special)
5874{
5875 PlatformId();
5876#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
5877 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5878 {
5879 MEMORYSTATUSEX ms;
5880
5881 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5882 * what fits in 32 bits. But it's not always available. */
5883 ms.dwLength = sizeof(MEMORYSTATUSEX);
5884 GlobalMemoryStatusEx(&ms);
5885 if (ms.ullAvailVirtual < ms.ullTotalPhys)
5886 {
5887 /* Process address space fits in physical RAM, use all of it. */
5888 return (long_u)(ms.ullAvailVirtual / 1024);
5889 }
5890 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
5891 {
5892 /* Catch old NT box or perverse hardware setup. */
5893 return (long_u)((ms.ullTotalPhys / 2) / 1024);
5894 }
5895 /* Use physical RAM less reserve for OS + data. */
5896 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
5897 }
5898 else
5899#endif
5900 {
5901 /* Pre-XP or 95 OS handling. */
5902 MEMORYSTATUS ms;
5903 long_u os_reserve_bytes;
5904
5905 ms.dwLength = sizeof(MEMORYSTATUS);
5906 GlobalMemoryStatus(&ms);
5907 if (ms.dwAvailVirtual < ms.dwTotalPhys)
5908 {
5909 /* Process address space fits in physical RAM, use all of it. */
5910 return (long_u)(ms.dwAvailVirtual / 1024);
5911 }
5912 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
5913 ? WINNT_RESERVE_BYTES
5914 : WIN95_RESERVE_BYTES;
5915 if (ms.dwTotalPhys <= os_reserve_bytes)
5916 {
5917 /* Catch old boxes or perverse hardware setup. */
5918 return (long_u)((ms.dwTotalPhys / 2) / 1024);
5919 }
5920 /* Use physical RAM less reserve for OS + data. */
5921 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
5922 }
5923}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924
Bram Moolenaar071d4272004-06-13 20:20:40 +00005925#ifdef FEAT_MBYTE
5926/*
5927 * Same code as below, but with wide functions and no comments.
5928 * Return 0 for success, non-zero for failure.
5929 */
5930 int
5931mch_wrename(WCHAR *wold, WCHAR *wnew)
5932{
5933 WCHAR *p;
5934 int i;
5935 WCHAR szTempFile[_MAX_PATH + 1];
5936 WCHAR szNewPath[_MAX_PATH + 1];
5937 HANDLE hf;
5938
5939 if (!mch_windows95())
5940 {
5941 p = wold;
5942 for (i = 0; wold[i] != NUL; ++i)
5943 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5944 && wold[i + 1] != 0)
5945 p = wold + i + 1;
5946 if ((int)(wold + i - p) < 8 || p[6] != '~')
5947 return (MoveFileW(wold, wnew) == 0);
5948 }
5949
5950 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5951 return -1;
5952 *p = NUL;
5953
5954 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5955 return -2;
5956
5957 if (!DeleteFileW(szTempFile))
5958 return -3;
5959
5960 if (!MoveFileW(wold, szTempFile))
5961 return -4;
5962
5963 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5964 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5965 return -5;
5966 if (!CloseHandle(hf))
5967 return -6;
5968
5969 if (!MoveFileW(szTempFile, wnew))
5970 {
5971 (void)MoveFileW(szTempFile, wold);
5972 return -7;
5973 }
5974
5975 DeleteFileW(szTempFile);
5976
5977 if (!DeleteFileW(wold))
5978 return -8;
5979
5980 return 0;
5981}
5982#endif
5983
5984
5985/*
5986 * mch_rename() works around a bug in rename (aka MoveFile) in
5987 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5988 * file whose short file name is "FOO.BAR" (its long file name will
5989 * be correct: "foo.bar~"). Because a file can be accessed by
5990 * either its SFN or its LFN, "foo.bar" has effectively been
5991 * renamed to "foo.bar", which is not at all what was wanted. This
5992 * seems to happen only when renaming files with three-character
5993 * extensions by appending a suffix that does not include ".".
5994 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5995 *
5996 * There is another problem, which isn't really a bug but isn't right either:
5997 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5998 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5999 * service pack 6. Doesn't seem to happen on Windows 98.
6000 *
6001 * Like rename(), returns 0 upon success, non-zero upon failure.
6002 * Should probably set errno appropriately when errors occur.
6003 */
6004 int
6005mch_rename(
6006 const char *pszOldFile,
6007 const char *pszNewFile)
6008{
6009 char szTempFile[_MAX_PATH+1];
6010 char szNewPath[_MAX_PATH+1];
6011 char *pszFilePart;
6012 HANDLE hf;
6013#ifdef FEAT_MBYTE
6014 WCHAR *wold = NULL;
6015 WCHAR *wnew = NULL;
6016 int retval = -1;
6017
6018 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6019 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006020 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6021 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022 if (wold != NULL && wnew != NULL)
6023 retval = mch_wrename(wold, wnew);
6024 vim_free(wold);
6025 vim_free(wnew);
6026 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6027 return retval;
6028 /* Retry with non-wide function (for Windows 98). */
6029 }
6030#endif
6031
6032 /*
6033 * No need to play tricks if not running Windows 95, unless the file name
6034 * contains a "~" as the seventh character.
6035 */
6036 if (!mch_windows95())
6037 {
6038 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6039 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6040 return rename(pszOldFile, pszNewFile);
6041 }
6042
6043 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6044 * a directory, no error is returned and pszFilePart will be NULL. */
6045 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6046 || pszFilePart == NULL)
6047 return -1;
6048 *pszFilePart = NUL;
6049
6050 /* Get (and create) a unique temporary file name in directory of new file */
6051 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6052 return -2;
6053
6054 /* blow the temp file away */
6055 if (!DeleteFile(szTempFile))
6056 return -3;
6057
6058 /* rename old file to the temp file */
6059 if (!MoveFile(pszOldFile, szTempFile))
6060 return -4;
6061
6062 /* now create an empty file called pszOldFile; this prevents the operating
6063 * system using pszOldFile as an alias (SFN) if we're renaming within the
6064 * same directory. For example, we're editing a file called
6065 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6066 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6067 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006068 * cause all sorts of problems later in buf_write(). So, we create an
6069 * empty file called filena~1.txt and the system will have to find some
6070 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071 */
6072 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6073 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6074 return -5;
6075 if (!CloseHandle(hf))
6076 return -6;
6077
6078 /* rename the temp file to the new file */
6079 if (!MoveFile(szTempFile, pszNewFile))
6080 {
6081 /* Renaming failed. Rename the file back to its old name, so that it
6082 * looks like nothing happened. */
6083 (void)MoveFile(szTempFile, pszOldFile);
6084
6085 return -7;
6086 }
6087
6088 /* Seems to be left around on Novell filesystems */
6089 DeleteFile(szTempFile);
6090
6091 /* finally, remove the empty old file */
6092 if (!DeleteFile(pszOldFile))
6093 return -8;
6094
6095 return 0; /* success */
6096}
6097
6098/*
6099 * Get the default shell for the current hardware platform
6100 */
6101 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006102default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103{
6104 char* psz = NULL;
6105
6106 PlatformId();
6107
6108 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6109 psz = "cmd.exe";
6110 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6111 psz = "command.com";
6112
6113 return psz;
6114}
6115
6116/*
6117 * mch_access() extends access() to do more detailed check on network drives.
6118 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6119 */
6120 int
6121mch_access(char *n, int p)
6122{
6123 HANDLE hFile;
6124 DWORD am;
6125 int retval = -1; /* default: fail */
6126#ifdef FEAT_MBYTE
6127 WCHAR *wn = NULL;
6128
6129 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006130 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131#endif
6132
6133 if (mch_isdir(n))
6134 {
6135 char TempName[_MAX_PATH + 16] = "";
6136#ifdef FEAT_MBYTE
6137 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6138#endif
6139
6140 if (p & R_OK)
6141 {
6142 /* Read check is performed by seeing if we can do a find file on
6143 * the directory for any file. */
6144#ifdef FEAT_MBYTE
6145 if (wn != NULL)
6146 {
6147 int i;
6148 WIN32_FIND_DATAW d;
6149
6150 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6151 TempNameW[i] = wn[i];
6152 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6153 TempNameW[i++] = '\\';
6154 TempNameW[i++] = '*';
6155 TempNameW[i++] = 0;
6156
6157 hFile = FindFirstFileW(TempNameW, &d);
6158 if (hFile == INVALID_HANDLE_VALUE)
6159 {
6160 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6161 goto getout;
6162
6163 /* Retry with non-wide function (for Windows 98). */
6164 vim_free(wn);
6165 wn = NULL;
6166 }
6167 else
6168 (void)FindClose(hFile);
6169 }
6170 if (wn == NULL)
6171#endif
6172 {
6173 char *pch;
6174 WIN32_FIND_DATA d;
6175
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006176 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177 pch = TempName + STRLEN(TempName) - 1;
6178 if (*pch != '\\' && *pch != '/')
6179 *++pch = '\\';
6180 *++pch = '*';
6181 *++pch = NUL;
6182
6183 hFile = FindFirstFile(TempName, &d);
6184 if (hFile == INVALID_HANDLE_VALUE)
6185 goto getout;
6186 (void)FindClose(hFile);
6187 }
6188 }
6189
6190 if (p & W_OK)
6191 {
6192 /* Trying to create a temporary file in the directory should catch
6193 * directories on read-only network shares. However, in
6194 * directories whose ACL allows writes but denies deletes will end
6195 * up keeping the temporary file :-(. */
6196#ifdef FEAT_MBYTE
6197 if (wn != NULL)
6198 {
6199 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6200 {
6201 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6202 goto getout;
6203
6204 /* Retry with non-wide function (for Windows 98). */
6205 vim_free(wn);
6206 wn = NULL;
6207 }
6208 else
6209 DeleteFileW(TempNameW);
6210 }
6211 if (wn == NULL)
6212#endif
6213 {
6214 if (!GetTempFileName(n, "VIM", 0, TempName))
6215 goto getout;
6216 mch_remove((char_u *)TempName);
6217 }
6218 }
6219 }
6220 else
6221 {
6222 /* Trying to open the file for the required access does ACL, read-only
6223 * network share, and file attribute checks. */
6224 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6225 | ((p & R_OK) ? GENERIC_READ : 0);
6226#ifdef FEAT_MBYTE
6227 if (wn != NULL)
6228 {
6229 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6230 if (hFile == INVALID_HANDLE_VALUE
6231 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6232 {
6233 /* Retry with non-wide function (for Windows 98). */
6234 vim_free(wn);
6235 wn = NULL;
6236 }
6237 }
6238 if (wn == NULL)
6239#endif
6240 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6241 if (hFile == INVALID_HANDLE_VALUE)
6242 goto getout;
6243 CloseHandle(hFile);
6244 }
6245
6246 retval = 0; /* success */
6247getout:
6248#ifdef FEAT_MBYTE
6249 vim_free(wn);
6250#endif
6251 return retval;
6252}
6253
6254#if defined(FEAT_MBYTE) || defined(PROTO)
6255/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006256 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 */
6258 int
6259mch_open(char *name, int flags, int mode)
6260{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006261 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6262# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263 WCHAR *wn;
6264 int f;
6265
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006266 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006268 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269 if (wn != NULL)
6270 {
6271 f = _wopen(wn, flags, mode);
6272 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006273 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274 return f;
6275 /* Retry with non-wide function (for Windows 98). Can't use
6276 * GetLastError() here and it's unclear what errno gets set to if
6277 * the _wopen() fails for missing wide functions. */
6278 }
6279 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006280# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006282 /* open() can open a file which name is longer than _MAX_PATH bytes
6283 * and shorter than _MAX_PATH characters successfully, but sometimes it
6284 * causes unexpected error in another part. We make it an error explicitly
6285 * here. */
6286 if (strlen(name) >= _MAX_PATH)
6287 return -1;
6288
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 return open(name, flags, mode);
6290}
6291
6292/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006293 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 */
6295 FILE *
6296mch_fopen(char *name, char *mode)
6297{
6298 WCHAR *wn, *wm;
6299 FILE *f = NULL;
6300
6301 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6302# ifdef __BORLANDC__
6303 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6304 && g_PlatformId == VER_PLATFORM_WIN32_NT
6305# endif
6306 )
6307 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006308# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006309 /* Work around an annoying assertion in the Microsoft debug CRT
6310 * when mode's text/binary setting doesn't match _get_fmode(). */
6311 char newMode = mode[strlen(mode) - 1];
6312 int oldMode = 0;
6313
6314 _get_fmode(&oldMode);
6315 if (newMode == 't')
6316 _set_fmode(_O_TEXT);
6317 else if (newMode == 'b')
6318 _set_fmode(_O_BINARY);
6319# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006320 wn = enc_to_utf16(name, NULL);
6321 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 if (wn != NULL && wm != NULL)
6323 f = _wfopen(wn, wm);
6324 vim_free(wn);
6325 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006326
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006327# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006328 _set_fmode(oldMode);
6329# endif
6330
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006331 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 return f;
6333 /* Retry with non-wide function (for Windows 98). Can't use
6334 * GetLastError() here and it's unclear what errno gets set to if
6335 * the _wfopen() fails for missing wide functions. */
6336 }
6337
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006338 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6339 * and shorter than _MAX_PATH characters successfully, but sometimes it
6340 * causes unexpected error in another part. We make it an error explicitly
6341 * here. */
6342 if (strlen(name) >= _MAX_PATH)
6343 return NULL;
6344
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 return fopen(name, mode);
6346}
6347#endif
6348
6349#ifdef FEAT_MBYTE
6350/*
6351 * SUB STREAM (aka info stream) handling:
6352 *
6353 * NTFS can have sub streams for each file. Normal contents of file is
6354 * stored in the main stream, and extra contents (author information and
6355 * title and so on) can be stored in sub stream. After Windows 2000, user
6356 * can access and store those informations in sub streams via explorer's
6357 * property menuitem in right click menu. Those informations in sub streams
6358 * were lost when copying only the main stream. So we have to copy sub
6359 * streams.
6360 *
6361 * Incomplete explanation:
6362 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6363 * More useful info and an example:
6364 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6365 */
6366
6367/*
6368 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6369 * and write to stream "substream" of file "to".
6370 * Errors are ignored.
6371 */
6372 static void
6373copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6374{
6375 HANDLE hTo;
6376 WCHAR *to_name;
6377
6378 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6379 wcscpy(to_name, to);
6380 wcscat(to_name, substream);
6381
6382 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6383 FILE_ATTRIBUTE_NORMAL, NULL);
6384 if (hTo != INVALID_HANDLE_VALUE)
6385 {
6386 long done;
6387 DWORD todo;
6388 DWORD readcnt, written;
6389 char buf[4096];
6390
6391 /* Copy block of bytes at a time. Abort when something goes wrong. */
6392 for (done = 0; done < len; done += written)
6393 {
6394 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006395 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6396 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6398 FALSE, FALSE, context)
6399 || readcnt != todo
6400 || !WriteFile(hTo, buf, todo, &written, NULL)
6401 || written != todo)
6402 break;
6403 }
6404 CloseHandle(hTo);
6405 }
6406
6407 free(to_name);
6408}
6409
6410/*
6411 * Copy info streams from file "from" to file "to".
6412 */
6413 static void
6414copy_infostreams(char_u *from, char_u *to)
6415{
6416 WCHAR *fromw;
6417 WCHAR *tow;
6418 HANDLE sh;
6419 WIN32_STREAM_ID sid;
6420 int headersize;
6421 WCHAR streamname[_MAX_PATH];
6422 DWORD readcount;
6423 void *context = NULL;
6424 DWORD lo, hi;
6425 int len;
6426
6427 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006428 fromw = enc_to_utf16(from, NULL);
6429 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006430 if (fromw != NULL && tow != NULL)
6431 {
6432 /* Open the file for reading. */
6433 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6434 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6435 if (sh != INVALID_HANDLE_VALUE)
6436 {
6437 /* Use BackupRead() to find the info streams. Repeat until we
6438 * have done them all.*/
6439 for (;;)
6440 {
6441 /* Get the header to find the length of the stream name. If
6442 * the "readcount" is zero we have done all info streams. */
6443 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006444 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006445 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6446 &readcount, FALSE, FALSE, &context)
6447 || readcount == 0)
6448 break;
6449
6450 /* We only deal with streams that have a name. The normal
6451 * file data appears to be without a name, even though docs
6452 * suggest it is called "::$DATA". */
6453 if (sid.dwStreamNameSize > 0)
6454 {
6455 /* Read the stream name. */
6456 if (!BackupRead(sh, (LPBYTE)streamname,
6457 sid.dwStreamNameSize,
6458 &readcount, FALSE, FALSE, &context))
6459 break;
6460
6461 /* Copy an info stream with a name ":anything:$DATA".
6462 * Skip "::$DATA", it has no stream name (examples suggest
6463 * it might be used for the normal file contents).
6464 * Note that BackupRead() counts bytes, but the name is in
6465 * wide characters. */
6466 len = readcount / sizeof(WCHAR);
6467 streamname[len] = 0;
6468 if (len > 7 && wcsicmp(streamname + len - 6,
6469 L":$DATA") == 0)
6470 {
6471 streamname[len - 6] = 0;
6472 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006473 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006474 }
6475 }
6476
6477 /* Advance to the next stream. We might try seeking too far,
6478 * but BackupSeek() doesn't skip over stream borders, thus
6479 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006480 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481 &lo, &hi, &context);
6482 }
6483
6484 /* Clear the context. */
6485 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6486
6487 CloseHandle(sh);
6488 }
6489 }
6490 vim_free(fromw);
6491 vim_free(tow);
6492}
6493#endif
6494
6495/*
6496 * Copy file attributes from file "from" to file "to".
6497 * For Windows NT and later we copy info streams.
6498 * Always returns zero, errors are ignored.
6499 */
6500 int
6501mch_copy_file_attribute(char_u *from, char_u *to)
6502{
6503#ifdef FEAT_MBYTE
6504 /* File streams only work on Windows NT and later. */
6505 PlatformId();
6506 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6507 copy_infostreams(from, to);
6508#endif
6509 return 0;
6510}
6511
6512#if defined(MYRESETSTKOFLW) || defined(PROTO)
6513/*
6514 * Recreate a destroyed stack guard page in win32.
6515 * Written by Benjamin Peterson.
6516 */
6517
6518/* These magic numbers are from the MS header files */
6519#define MIN_STACK_WIN9X 17
6520#define MIN_STACK_WINNT 2
6521
6522/*
6523 * This function does the same thing as _resetstkoflw(), which is only
6524 * available in DevStudio .net and later.
6525 * Returns 0 for failure, 1 for success.
6526 */
6527 int
6528myresetstkoflw(void)
6529{
6530 BYTE *pStackPtr;
6531 BYTE *pGuardPage;
6532 BYTE *pStackBase;
6533 BYTE *pLowestPossiblePage;
6534 MEMORY_BASIC_INFORMATION mbi;
6535 SYSTEM_INFO si;
6536 DWORD nPageSize;
6537 DWORD dummy;
6538
6539 /* This code will not work on win32s. */
6540 PlatformId();
6541 if (g_PlatformId == VER_PLATFORM_WIN32s)
6542 return 0;
6543
6544 /* We need to know the system page size. */
6545 GetSystemInfo(&si);
6546 nPageSize = si.dwPageSize;
6547
6548 /* ...and the current stack pointer */
6549 pStackPtr = (BYTE*)_alloca(1);
6550
6551 /* ...and the base of the stack. */
6552 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6553 return 0;
6554 pStackBase = (BYTE*)mbi.AllocationBase;
6555
6556 /* ...and the page thats min_stack_req pages away from stack base; this is
6557 * the lowest page we could use. */
6558 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6559 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6560
6561 /* On Win95, we want the next page down from the end of the stack. */
6562 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6563 {
6564 /* Find the page that's only 1 page down from the page that the stack
6565 * ptr is in. */
6566 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6567 / (DWORD)nPageSize) - 1));
6568 if (pGuardPage < pLowestPossiblePage)
6569 return 0;
6570
6571 /* Apply the noaccess attribute to the page -- there's no guard
6572 * attribute in win95-type OSes. */
6573 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6574 return 0;
6575 }
6576 else
6577 {
6578 /* On NT, however, we want the first committed page in the stack Start
6579 * at the stack base and move forward through memory until we find a
6580 * committed block. */
6581 BYTE *pBlock = pStackBase;
6582
Bram Moolenaara466c992005-07-09 21:03:22 +00006583 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584 {
6585 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6586 return 0;
6587
6588 pBlock += mbi.RegionSize;
6589
6590 if (mbi.State & MEM_COMMIT)
6591 break;
6592 }
6593
6594 /* mbi now describes the first committed block in the stack. */
6595 if (mbi.Protect & PAGE_GUARD)
6596 return 1;
6597
6598 /* decide where the guard page should start */
6599 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6600 pGuardPage = pLowestPossiblePage;
6601 else
6602 pGuardPage = (BYTE*)mbi.BaseAddress;
6603
6604 /* allocate the guard page */
6605 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6606 return 0;
6607
6608 /* apply the guard attribute to the page */
6609 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6610 &dummy))
6611 return 0;
6612 }
6613
6614 return 1;
6615}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006616#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006618
6619#if defined(FEAT_MBYTE) || defined(PROTO)
6620/*
6621 * The command line arguments in UCS2
6622 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006623static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006624static LPWSTR *ArglistW = NULL;
6625static int global_argc = 0;
6626static char **global_argv;
6627
6628static int used_file_argc = 0; /* last argument in global_argv[] used
6629 for the argument list. */
6630static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6631 command line arguments added to
6632 the argument list */
6633static int used_file_count = 0; /* nr of entries in used_file_indexes */
6634static int used_file_literal = FALSE; /* take file names literally */
6635static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006636static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006637static int used_alist_count = 0;
6638
6639
6640/*
6641 * Get the command line arguments. Unicode version.
6642 * Returns argc. Zero when something fails.
6643 */
6644 int
6645get_cmd_argsW(char ***argvp)
6646{
6647 char **argv = NULL;
6648 int argc = 0;
6649 int i;
6650
Bram Moolenaar14993322014-09-09 12:25:33 +02006651 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006652 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6653 if (ArglistW != NULL)
6654 {
6655 argv = malloc((nArgsW + 1) * sizeof(char *));
6656 if (argv != NULL)
6657 {
6658 argc = nArgsW;
6659 argv[argc] = NULL;
6660 for (i = 0; i < argc; ++i)
6661 {
6662 int len;
6663
6664 /* Convert each Unicode argument to the current codepage. */
6665 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006666 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006667 (LPSTR *)&argv[i], &len, 0, 0);
6668 if (argv[i] == NULL)
6669 {
6670 /* Out of memory, clear everything. */
6671 while (i > 0)
6672 free(argv[--i]);
6673 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006674 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006675 argc = 0;
6676 }
6677 }
6678 }
6679 }
6680
6681 global_argc = argc;
6682 global_argv = argv;
6683 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006684 {
6685 if (used_file_indexes != NULL)
6686 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006687 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006688 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006689
6690 if (argvp != NULL)
6691 *argvp = argv;
6692 return argc;
6693}
6694
6695 void
6696free_cmd_argsW(void)
6697{
6698 if (ArglistW != NULL)
6699 {
6700 GlobalFree(ArglistW);
6701 ArglistW = NULL;
6702 }
6703}
6704
6705/*
6706 * Remember "name" is an argument that was added to the argument list.
6707 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6708 * is called.
6709 */
6710 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006711used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006712{
6713 int i;
6714
6715 if (used_file_indexes == NULL)
6716 return;
6717 for (i = used_file_argc + 1; i < global_argc; ++i)
6718 if (STRCMP(global_argv[i], name) == 0)
6719 {
6720 used_file_argc = i;
6721 used_file_indexes[used_file_count++] = i;
6722 break;
6723 }
6724 used_file_literal = literal;
6725 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006726 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006727}
6728
6729/*
6730 * Remember the length of the argument list as it was. If it changes then we
6731 * leave it alone when 'encoding' is set.
6732 */
6733 void
6734set_alist_count(void)
6735{
6736 used_alist_count = GARGCOUNT;
6737}
6738
6739/*
6740 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6741 * has been changed while starting up. Use the UCS-2 command line arguments
6742 * and convert them to 'encoding'.
6743 */
6744 void
6745fix_arg_enc(void)
6746{
6747 int i;
6748 int idx;
6749 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006750 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006751
6752 /* Safety checks:
6753 * - if argument count differs between the wide and non-wide argument
6754 * list, something must be wrong.
6755 * - the file name arguments must have been located.
6756 * - the length of the argument list wasn't changed by the user.
6757 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006758 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006759 || ArglistW == NULL
6760 || used_file_indexes == NULL
6761 || used_file_count == 0
6762 || used_alist_count != GARGCOUNT)
6763 return;
6764
Bram Moolenaar86b68352004-12-27 21:59:20 +00006765 /* Remember the buffer numbers for the arguments. */
6766 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6767 if (fnum_list == NULL)
6768 return; /* out of memory */
6769 for (i = 0; i < GARGCOUNT; ++i)
6770 fnum_list[i] = GARGLIST[i].ae_fnum;
6771
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006772 /* Clear the argument list. Make room for the new arguments. */
6773 alist_clear(&global_alist);
6774 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006775 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006776
6777 for (i = 0; i < used_file_count; ++i)
6778 {
6779 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006780 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006781 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006782 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006783#ifdef FEAT_DIFF
6784 /* When using diff mode may need to concatenate file name to
6785 * directory name. Just like it's done in main(). */
6786 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6787 && !mch_isdir(alist_name(&GARGLIST[0])))
6788 {
6789 char_u *r;
6790
6791 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6792 if (r != NULL)
6793 {
6794 vim_free(str);
6795 str = r;
6796 }
6797 }
6798#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006799 /* Re-use the old buffer by renaming it. When not using literal
6800 * names it's done by alist_expand() below. */
6801 if (used_file_literal)
6802 buf_set_name(fnum_list[i], str);
6803
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006804 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006805 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006806 }
6807
6808 if (!used_file_literal)
6809 {
6810 /* Now expand wildcards in the arguments. */
6811 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6812 * filename characters but are excluded from 'isfname' to make
6813 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6814 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006815 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006816 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6817 }
6818
6819 /* If wildcard expansion failed, we are editing the first file of the
6820 * arglist and there is no file name: Edit the first argument now. */
6821 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6822 {
6823 do_cmdline_cmd((char_u *)":rewind");
6824 if (GARGCOUNT == 1 && used_file_full_path)
6825 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6826 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006827
6828 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006829}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006830#endif