blob: a47ffaf18a04d652c254aba8d664afca3c4cbbf6 [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 Moolenaar4cf76792016-01-16 22:02:57 +01003157 * Delete directory "name".
3158 * Return 0 on success, -1 on error.
3159 */
3160 int
3161mch_rmdir(char_u *name)
3162{
3163#ifdef FEAT_MBYTE
3164 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3165 {
3166 WCHAR *p;
3167 int retval;
3168
3169 p = enc_to_utf16(name, NULL);
3170 if (p == NULL)
3171 return -1;
3172 retval = _wrmdir(p);
3173 vim_free(p);
3174 return retval;
3175 }
3176#endif
3177 return _rmdir(name);
3178}
3179
3180/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003181 * Return TRUE if file "fname" has more than one link.
3182 */
3183 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003184mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003185{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003186 BY_HANDLE_FILE_INFORMATION info;
3187
3188 return win32_fileinfo(fname, &info) == FILEINFO_OK
3189 && info.nNumberOfLinks > 1;
3190}
3191
3192/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003193 * Return TRUE if file "fname" is a symbolic link.
3194 */
3195 int
3196mch_is_symbolic_link(char_u *fname)
3197{
3198 HANDLE hFind;
3199 int res = FALSE;
3200 WIN32_FIND_DATAA findDataA;
3201 DWORD fileFlags = 0, reparseTag = 0;
3202#ifdef FEAT_MBYTE
3203 WCHAR *wn = NULL;
3204 WIN32_FIND_DATAW findDataW;
3205
3206 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3207 wn = enc_to_utf16(fname, NULL);
3208 if (wn != NULL)
3209 {
3210 hFind = FindFirstFileW(wn, &findDataW);
3211 vim_free(wn);
3212 if (hFind == INVALID_HANDLE_VALUE
3213 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3214 {
3215 /* Retry with non-wide function (for Windows 98). */
3216 hFind = FindFirstFile(fname, &findDataA);
3217 if (hFind != INVALID_HANDLE_VALUE)
3218 {
3219 fileFlags = findDataA.dwFileAttributes;
3220 reparseTag = findDataA.dwReserved0;
3221 }
3222 }
3223 else
3224 {
3225 fileFlags = findDataW.dwFileAttributes;
3226 reparseTag = findDataW.dwReserved0;
3227 }
3228 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003229 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003230#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003231 {
3232 hFind = FindFirstFile(fname, &findDataA);
3233 if (hFind != INVALID_HANDLE_VALUE)
3234 {
3235 fileFlags = findDataA.dwFileAttributes;
3236 reparseTag = findDataA.dwReserved0;
3237 }
3238 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003239
3240 if (hFind != INVALID_HANDLE_VALUE)
3241 FindClose(hFind);
3242
3243 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3244 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3245 res = TRUE;
3246
3247 return res;
3248}
3249
3250/*
3251 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3252 * link.
3253 */
3254 int
3255mch_is_linked(char_u *fname)
3256{
3257 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3258 return TRUE;
3259 return FALSE;
3260}
3261
3262/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003263 * Get the by-handle-file-information for "fname".
3264 * Returns FILEINFO_OK when OK.
3265 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3266 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3267 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3268 */
3269 int
3270win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3271{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003272 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003273 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003274#ifdef FEAT_MBYTE
3275 WCHAR *wn = NULL;
3276
3277 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003278 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003279 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003280 if (wn == NULL)
3281 res = FILEINFO_ENC_FAIL;
3282 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003283 if (wn != NULL)
3284 {
3285 hFile = CreateFileW(wn, /* file name */
3286 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003287 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003288 NULL, /* security descriptor */
3289 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003290 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003291 NULL); /* handle to template file */
3292 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003293 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003294 {
3295 /* Retry with non-wide function (for Windows 98). */
3296 vim_free(wn);
3297 wn = NULL;
3298 }
3299 }
3300 if (wn == NULL)
3301#endif
3302 hFile = CreateFile(fname, /* file name */
3303 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003304 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003305 NULL, /* security descriptor */
3306 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003307 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003308 NULL); /* handle to template file */
3309
3310 if (hFile != INVALID_HANDLE_VALUE)
3311 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003312 if (GetFileInformationByHandle(hFile, info) != 0)
3313 res = FILEINFO_OK;
3314 else
3315 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003316 CloseHandle(hFile);
3317 }
3318
3319#ifdef FEAT_MBYTE
3320 vim_free(wn);
3321#endif
3322 return res;
3323}
3324
3325/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003326 * get file attributes for `name'
3327 * -1 : error
3328 * else FILE_ATTRIBUTE_* defined in winnt.h
3329 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003330 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003331win32_getattrs(char_u *name)
3332{
3333 int attr;
3334#ifdef FEAT_MBYTE
3335 WCHAR *p = NULL;
3336
3337 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3338 p = enc_to_utf16(name, NULL);
3339
3340 if (p != NULL)
3341 {
3342 attr = GetFileAttributesW(p);
3343 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3344 {
3345 /* Retry with non-wide function (for Windows 98). */
3346 vim_free(p);
3347 p = NULL;
3348 }
3349 }
3350 if (p == NULL)
3351#endif
3352 attr = GetFileAttributes((char *)name);
3353#ifdef FEAT_MBYTE
3354 vim_free(p);
3355#endif
3356 return attr;
3357}
3358
3359/*
3360 * set file attributes for `name' to `attrs'
3361 *
3362 * return -1 for failure, 0 otherwise
3363 */
3364 static
3365 int
3366win32_setattrs(char_u *name, int attrs)
3367{
3368 int res;
3369#ifdef FEAT_MBYTE
3370 WCHAR *p = NULL;
3371
3372 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3373 p = enc_to_utf16(name, NULL);
3374
3375 if (p != NULL)
3376 {
3377 res = SetFileAttributesW(p, attrs);
3378 if (res == FALSE
3379 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3380 {
3381 /* Retry with non-wide function (for Windows 98). */
3382 vim_free(p);
3383 p = NULL;
3384 }
3385 }
3386 if (p == NULL)
3387#endif
3388 res = SetFileAttributes((char *)name, attrs);
3389#ifdef FEAT_MBYTE
3390 vim_free(p);
3391#endif
3392 return res ? 0 : -1;
3393}
3394
3395/*
3396 * Set archive flag for "name".
3397 */
3398 static
3399 int
3400win32_set_archive(char_u *name)
3401{
3402 int attrs = win32_getattrs(name);
3403 if (attrs == -1)
3404 return -1;
3405
3406 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3407 return win32_setattrs(name, attrs);
3408}
3409
3410/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411 * Return TRUE if file or directory "name" is writable (not readonly).
3412 * Strange semantics of Win32: a readonly directory is writable, but you can't
3413 * delete a file. Let's say this means it is writable.
3414 */
3415 int
3416mch_writable(char_u *name)
3417{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003418 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003419
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003420 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3421 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003422}
3423
Bram Moolenaar071d4272004-06-13 20:20:40 +00003424/*
3425 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003426 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427 * Return -1 if unknown.
3428 */
3429 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003430mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003432 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003433 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003434 char_u *p;
3435
3436 if (len >= _MAX_PATH) /* safety check */
3437 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003438 if (!use_path)
3439 {
3440 /* TODO: check if file is really executable. */
3441 return mch_getperm(name) != -1 && !mch_isdir(name);
3442 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003443
3444 /* If there already is an extension try using the name directly. Also do
3445 * this with a Unix-shell like 'shell'. */
3446 if (vim_strchr(gettail(name), '.') != NULL
3447 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003448 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003449 return TRUE;
3450
3451 /*
3452 * Loop over all extensions in $PATHEXT.
3453 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003454 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003455 p = mch_getenv("PATHEXT");
3456 if (p == NULL)
3457 p = (char_u *)".com;.exe;.bat;.cmd";
3458 while (*p)
3459 {
3460 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3461 {
3462 /* A single "." means no extension is added. */
3463 buf[len] = NUL;
3464 ++p;
3465 if (*p)
3466 ++p;
3467 }
3468 else
3469 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003470 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003471 return TRUE;
3472 }
3473 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475
3476/*
3477 * Check what "name" is:
3478 * NODE_NORMAL: file or directory (or doesn't exist)
3479 * NODE_WRITABLE: writable device, socket, fifo, etc.
3480 * NODE_OTHER: non-writable things
3481 */
3482 int
3483mch_nodetype(char_u *name)
3484{
3485 HANDLE hFile;
3486 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003487#ifdef FEAT_MBYTE
3488 WCHAR *wn = NULL;
3489#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490
Bram Moolenaar043545e2006-10-10 16:44:07 +00003491 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3492 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3493 * here. */
3494 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3495 return NODE_WRITABLE;
3496
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003497#ifdef FEAT_MBYTE
3498 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3499 {
3500 wn = enc_to_utf16(name, NULL);
3501 if (wn != NULL)
3502 {
3503 hFile = CreateFileW(wn, /* file name */
3504 GENERIC_WRITE, /* access mode */
3505 0, /* share mode */
3506 NULL, /* security descriptor */
3507 OPEN_EXISTING, /* creation disposition */
3508 0, /* file attributes */
3509 NULL); /* handle to template file */
3510 if (hFile == INVALID_HANDLE_VALUE
3511 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3512 {
3513 /* Retry with non-wide function (for Windows 98). */
3514 vim_free(wn);
3515 wn = NULL;
3516 }
3517 }
3518 }
3519 if (wn == NULL)
3520#endif
3521 hFile = CreateFile(name, /* file name */
3522 GENERIC_WRITE, /* access mode */
3523 0, /* share mode */
3524 NULL, /* security descriptor */
3525 OPEN_EXISTING, /* creation disposition */
3526 0, /* file attributes */
3527 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003529#ifdef FEAT_MBYTE
3530 vim_free(wn);
3531#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 if (hFile == INVALID_HANDLE_VALUE)
3533 return NODE_NORMAL;
3534
3535 type = GetFileType(hFile);
3536 CloseHandle(hFile);
3537 if (type == FILE_TYPE_CHAR)
3538 return NODE_WRITABLE;
3539 if (type == FILE_TYPE_DISK)
3540 return NODE_NORMAL;
3541 return NODE_OTHER;
3542}
3543
3544#ifdef HAVE_ACL
3545struct my_acl
3546{
3547 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3548 PSID pSidOwner;
3549 PSID pSidGroup;
3550 PACL pDacl;
3551 PACL pSacl;
3552};
3553#endif
3554
3555/*
3556 * Return a pointer to the ACL of file "fname" in allocated memory.
3557 * Return NULL if the ACL is not available for whatever reason.
3558 */
3559 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003560mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003561{
3562#ifndef HAVE_ACL
3563 return (vim_acl_T)NULL;
3564#else
3565 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003566 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003567
3568 /* This only works on Windows NT and 2000. */
3569 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3570 {
3571 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3572 if (p != NULL)
3573 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003574# ifdef FEAT_MBYTE
3575 WCHAR *wn = NULL;
3576
3577 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3578 wn = enc_to_utf16(fname, NULL);
3579 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003581 /* Try to retrieve the entire security descriptor. */
3582 err = pGetNamedSecurityInfoW(
3583 wn, // Abstract filename
3584 SE_FILE_OBJECT, // File Object
3585 OWNER_SECURITY_INFORMATION |
3586 GROUP_SECURITY_INFORMATION |
3587 DACL_SECURITY_INFORMATION |
3588 SACL_SECURITY_INFORMATION,
3589 &p->pSidOwner, // Ownership information.
3590 &p->pSidGroup, // Group membership.
3591 &p->pDacl, // Discretionary information.
3592 &p->pSacl, // For auditing purposes.
3593 &p->pSecurityDescriptor);
3594 if (err == ERROR_ACCESS_DENIED ||
3595 err == ERROR_PRIVILEGE_NOT_HELD)
3596 {
3597 /* Retrieve only DACL. */
3598 (void)pGetNamedSecurityInfoW(
3599 wn,
3600 SE_FILE_OBJECT,
3601 DACL_SECURITY_INFORMATION,
3602 NULL,
3603 NULL,
3604 &p->pDacl,
3605 NULL,
3606 &p->pSecurityDescriptor);
3607 }
3608 if (p->pSecurityDescriptor == NULL)
3609 {
3610 mch_free_acl((vim_acl_T)p);
3611 p = NULL;
3612 }
3613 vim_free(wn);
3614 }
3615 else
3616# endif
3617 {
3618 /* Try to retrieve the entire security descriptor. */
3619 err = pGetNamedSecurityInfo(
3620 (LPSTR)fname, // Abstract filename
3621 SE_FILE_OBJECT, // File Object
3622 OWNER_SECURITY_INFORMATION |
3623 GROUP_SECURITY_INFORMATION |
3624 DACL_SECURITY_INFORMATION |
3625 SACL_SECURITY_INFORMATION,
3626 &p->pSidOwner, // Ownership information.
3627 &p->pSidGroup, // Group membership.
3628 &p->pDacl, // Discretionary information.
3629 &p->pSacl, // For auditing purposes.
3630 &p->pSecurityDescriptor);
3631 if (err == ERROR_ACCESS_DENIED ||
3632 err == ERROR_PRIVILEGE_NOT_HELD)
3633 {
3634 /* Retrieve only DACL. */
3635 (void)pGetNamedSecurityInfo(
3636 (LPSTR)fname,
3637 SE_FILE_OBJECT,
3638 DACL_SECURITY_INFORMATION,
3639 NULL,
3640 NULL,
3641 &p->pDacl,
3642 NULL,
3643 &p->pSecurityDescriptor);
3644 }
3645 if (p->pSecurityDescriptor == NULL)
3646 {
3647 mch_free_acl((vim_acl_T)p);
3648 p = NULL;
3649 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650 }
3651 }
3652 }
3653
3654 return (vim_acl_T)p;
3655#endif
3656}
3657
Bram Moolenaar27515922013-06-29 15:36:26 +02003658#ifdef HAVE_ACL
3659/*
3660 * Check if "acl" contains inherited ACE.
3661 */
3662 static BOOL
3663is_acl_inherited(PACL acl)
3664{
3665 DWORD i;
3666 ACL_SIZE_INFORMATION acl_info;
3667 PACCESS_ALLOWED_ACE ace;
3668
3669 acl_info.AceCount = 0;
3670 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3671 for (i = 0; i < acl_info.AceCount; i++)
3672 {
3673 GetAce(acl, i, (LPVOID *)&ace);
3674 if (ace->Header.AceFlags & INHERITED_ACE)
3675 return TRUE;
3676 }
3677 return FALSE;
3678}
3679#endif
3680
Bram Moolenaar071d4272004-06-13 20:20:40 +00003681/*
3682 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3683 * Errors are ignored.
3684 * This must only be called with "acl" equal to what mch_get_acl() returned.
3685 */
3686 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003687mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688{
3689#ifdef HAVE_ACL
3690 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003691 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692
3693 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003694 {
3695# ifdef FEAT_MBYTE
3696 WCHAR *wn = NULL;
3697# endif
3698
3699 /* Set security flags */
3700 if (p->pSidOwner)
3701 sec_info |= OWNER_SECURITY_INFORMATION;
3702 if (p->pSidGroup)
3703 sec_info |= GROUP_SECURITY_INFORMATION;
3704 if (p->pDacl)
3705 {
3706 sec_info |= DACL_SECURITY_INFORMATION;
3707 /* Do not inherit its parent's DACL.
3708 * If the DACL is inherited, Cygwin permissions would be changed.
3709 */
3710 if (!is_acl_inherited(p->pDacl))
3711 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3712 }
3713 if (p->pSacl)
3714 sec_info |= SACL_SECURITY_INFORMATION;
3715
3716# ifdef FEAT_MBYTE
3717 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3718 wn = enc_to_utf16(fname, NULL);
3719 if (wn != NULL)
3720 {
3721 (void)pSetNamedSecurityInfoW(
3722 wn, // Abstract filename
3723 SE_FILE_OBJECT, // File Object
3724 sec_info,
3725 p->pSidOwner, // Ownership information.
3726 p->pSidGroup, // Group membership.
3727 p->pDacl, // Discretionary information.
3728 p->pSacl // For auditing purposes.
3729 );
3730 vim_free(wn);
3731 }
3732 else
3733# endif
3734 {
3735 (void)pSetNamedSecurityInfo(
3736 (LPSTR)fname, // Abstract filename
3737 SE_FILE_OBJECT, // File Object
3738 sec_info,
3739 p->pSidOwner, // Ownership information.
3740 p->pSidGroup, // Group membership.
3741 p->pDacl, // Discretionary information.
3742 p->pSacl // For auditing purposes.
3743 );
3744 }
3745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746#endif
3747}
3748
3749 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003750mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751{
3752#ifdef HAVE_ACL
3753 struct my_acl *p = (struct my_acl *)acl;
3754
3755 if (p != NULL)
3756 {
3757 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3758 vim_free(p);
3759 }
3760#endif
3761}
3762
3763#ifndef FEAT_GUI_W32
3764
3765/*
3766 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3767 */
3768 static BOOL WINAPI
3769handler_routine(
3770 DWORD dwCtrlType)
3771{
3772 switch (dwCtrlType)
3773 {
3774 case CTRL_C_EVENT:
3775 if (ctrl_c_interrupts)
3776 g_fCtrlCPressed = TRUE;
3777 return TRUE;
3778
3779 case CTRL_BREAK_EVENT:
3780 g_fCBrkPressed = TRUE;
3781 return TRUE;
3782
3783 /* fatal events: shut down gracefully */
3784 case CTRL_CLOSE_EVENT:
3785 case CTRL_LOGOFF_EVENT:
3786 case CTRL_SHUTDOWN_EVENT:
3787 windgoto((int)Rows - 1, 0);
3788 g_fForceExit = TRUE;
3789
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003790 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791 (dwCtrlType == CTRL_CLOSE_EVENT
3792 ? _("close")
3793 : dwCtrlType == CTRL_LOGOFF_EVENT
3794 ? _("logoff")
3795 : _("shutdown")));
3796#ifdef DEBUG
3797 OutputDebugString(IObuff);
3798#endif
3799
3800 preserve_exit(); /* output IObuff, preserve files and exit */
3801
3802 return TRUE; /* not reached */
3803
3804 default:
3805 return FALSE;
3806 }
3807}
3808
3809
3810/*
3811 * set the tty in (raw) ? "raw" : "cooked" mode
3812 */
3813 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003814mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815{
3816 DWORD cmodein;
3817 DWORD cmodeout;
3818 BOOL bEnableHandler;
3819
3820 GetConsoleMode(g_hConIn, &cmodein);
3821 GetConsoleMode(g_hConOut, &cmodeout);
3822 if (tmode == TMODE_RAW)
3823 {
3824 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3825 ENABLE_ECHO_INPUT);
3826#ifdef FEAT_MOUSE
3827 if (g_fMouseActive)
3828 cmodein |= ENABLE_MOUSE_INPUT;
3829#endif
3830 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3831 bEnableHandler = TRUE;
3832 }
3833 else /* cooked */
3834 {
3835 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3836 ENABLE_ECHO_INPUT);
3837 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3838 bEnableHandler = FALSE;
3839 }
3840 SetConsoleMode(g_hConIn, cmodein);
3841 SetConsoleMode(g_hConOut, cmodeout);
3842 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3843
3844#ifdef MCH_WRITE_DUMP
3845 if (fdDump)
3846 {
3847 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3848 tmode == TMODE_RAW ? "raw" :
3849 tmode == TMODE_COOK ? "cooked" : "normal",
3850 cmodein, cmodeout);
3851 fflush(fdDump);
3852 }
3853#endif
3854}
3855
3856
3857/*
3858 * Get the size of the current window in `Rows' and `Columns'
3859 * Return OK when size could be determined, FAIL otherwise.
3860 */
3861 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003862mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863{
3864 CONSOLE_SCREEN_BUFFER_INFO csbi;
3865
3866 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3867 {
3868 /*
3869 * For some reason, we are trying to get the screen dimensions
3870 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3871 * variables are really intended to mean the size of Vim screen
3872 * while in termcap mode.
3873 */
3874 Rows = g_cbTermcap.Info.dwSize.Y;
3875 Columns = g_cbTermcap.Info.dwSize.X;
3876 }
3877 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3878 {
3879 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3880 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3881 }
3882 else
3883 {
3884 Rows = 25;
3885 Columns = 80;
3886 }
3887 return OK;
3888}
3889
3890/*
3891 * Set a console window to `xSize' * `ySize'
3892 */
3893 static void
3894ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003895 HANDLE hConsole,
3896 int xSize,
3897 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003898{
3899 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3900 SMALL_RECT srWindowRect; /* hold the new console size */
3901 COORD coordScreen;
3902
3903#ifdef MCH_WRITE_DUMP
3904 if (fdDump)
3905 {
3906 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3907 fflush(fdDump);
3908 }
3909#endif
3910
3911 /* get the largest size we can size the console window to */
3912 coordScreen = GetLargestConsoleWindowSize(hConsole);
3913
3914 /* define the new console window size and scroll position */
3915 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3916 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3917 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3918
3919 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3920 {
3921 int sx, sy;
3922
3923 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3924 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3925 if (sy < ySize || sx < xSize)
3926 {
3927 /*
3928 * Increasing number of lines/columns, do buffer first.
3929 * Use the maximal size in x and y direction.
3930 */
3931 if (sy < ySize)
3932 coordScreen.Y = ySize;
3933 else
3934 coordScreen.Y = sy;
3935 if (sx < xSize)
3936 coordScreen.X = xSize;
3937 else
3938 coordScreen.X = sx;
3939 SetConsoleScreenBufferSize(hConsole, coordScreen);
3940 }
3941 }
3942
3943 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3944 {
3945#ifdef MCH_WRITE_DUMP
3946 if (fdDump)
3947 {
3948 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3949 GetLastError());
3950 fflush(fdDump);
3951 }
3952#endif
3953 }
3954
3955 /* define the new console buffer size */
3956 coordScreen.X = xSize;
3957 coordScreen.Y = ySize;
3958
3959 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3960 {
3961#ifdef MCH_WRITE_DUMP
3962 if (fdDump)
3963 {
3964 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3965 GetLastError());
3966 fflush(fdDump);
3967 }
3968#endif
3969 }
3970}
3971
3972
3973/*
3974 * Set the console window to `Rows' * `Columns'
3975 */
3976 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003977mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978{
3979 COORD coordScreen;
3980
3981 /* Don't change window size while still starting up */
3982 if (suppress_winsize != 0)
3983 {
3984 suppress_winsize = 2;
3985 return;
3986 }
3987
3988 if (term_console)
3989 {
3990 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3991
3992 /* Clamp Rows and Columns to reasonable values */
3993 if (Rows > coordScreen.Y)
3994 Rows = coordScreen.Y;
3995 if (Columns > coordScreen.X)
3996 Columns = coordScreen.X;
3997
3998 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3999 }
4000}
4001
4002/*
4003 * Rows and/or Columns has changed.
4004 */
4005 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004006mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004007{
4008 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4009}
4010
4011
4012/*
4013 * Called when started up, to set the winsize that was delayed.
4014 */
4015 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004016mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017{
4018 if (suppress_winsize == 2)
4019 {
4020 suppress_winsize = 0;
4021 mch_set_shellsize();
4022 shell_resized();
4023 }
4024 suppress_winsize = 0;
4025}
4026#endif /* FEAT_GUI_W32 */
4027
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004028 static BOOL
4029vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004030 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004031 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004032 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004033 STARTUPINFO *si,
4034 PROCESS_INFORMATION *pi)
4035{
4036# ifdef FEAT_MBYTE
4037 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4038 {
4039 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4040
4041 if (wcmd != NULL)
4042 {
4043 BOOL ret;
4044 ret = CreateProcessW(
4045 NULL, /* Executable name */
4046 wcmd, /* Command to execute */
4047 NULL, /* Process security attributes */
4048 NULL, /* Thread security attributes */
4049 inherit_handles, /* Inherit handles */
4050 flags, /* Creation flags */
4051 NULL, /* Environment */
4052 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004053 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004054 pi); /* Process information */
4055 vim_free(wcmd);
4056 return ret;
4057 }
4058 }
4059#endif
4060 return CreateProcess(
4061 NULL, /* Executable name */
4062 cmd, /* Command to execute */
4063 NULL, /* Process security attributes */
4064 NULL, /* Thread security attributes */
4065 inherit_handles, /* Inherit handles */
4066 flags, /* Creation flags */
4067 NULL, /* Environment */
4068 NULL, /* Current directory */
4069 si, /* Startup information */
4070 pi); /* Process information */
4071}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004072
4073
4074#if defined(FEAT_GUI_W32) || defined(PROTO)
4075
4076/*
4077 * Specialised version of system() for Win32 GUI mode.
4078 * This version proceeds as follows:
4079 * 1. Create a console window for use by the subprocess
4080 * 2. Run the subprocess (it gets the allocated console by default)
4081 * 3. Wait for the subprocess to terminate and get its exit code
4082 * 4. Prompt the user to press a key to close the console window
4083 */
4084 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004085mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086{
4087 STARTUPINFO si;
4088 PROCESS_INFORMATION pi;
4089 DWORD ret = 0;
4090 HWND hwnd = GetFocus();
4091
4092 si.cb = sizeof(si);
4093 si.lpReserved = NULL;
4094 si.lpDesktop = NULL;
4095 si.lpTitle = NULL;
4096 si.dwFlags = STARTF_USESHOWWINDOW;
4097 /*
4098 * It's nicer to run a filter command in a minimized window, but in
4099 * Windows 95 this makes the command MUCH slower. We can't do it under
4100 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004101 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 */
4103 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004104 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105 else
4106 si.wShowWindow = SW_SHOWNORMAL;
4107 si.cbReserved2 = 0;
4108 si.lpReserved2 = NULL;
4109
4110 /* There is a strange error on Windows 95 when using "c:\\command.com".
4111 * When the "c:\\" is left out it works OK...? */
4112 if (mch_windows95()
4113 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4114 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4115 cmd += 3;
4116
4117 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004118 vim_create_process(cmd, FALSE,
4119 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120
4121 /* Wait for the command to terminate before continuing */
4122 if (g_PlatformId != VER_PLATFORM_WIN32s)
4123 {
4124#ifdef FEAT_GUI
4125 int delay = 1;
4126
4127 /* Keep updating the window while waiting for the shell to finish. */
4128 for (;;)
4129 {
4130 MSG msg;
4131
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004132 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 {
4134 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004135 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004136 delay = 1;
4137 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 }
4139 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4140 break;
4141
4142 /* We start waiting for a very short time and then increase it, so
4143 * that we respond quickly when the process is quick, and don't
4144 * consume too much overhead when it's slow. */
4145 if (delay < 50)
4146 delay += 10;
4147 }
4148#else
4149 WaitForSingleObject(pi.hProcess, INFINITE);
4150#endif
4151
4152 /* Get the command exit code */
4153 GetExitCodeProcess(pi.hProcess, &ret);
4154 }
4155 else
4156 {
4157 /*
4158 * This ugly code is the only quick way of performing
4159 * a synchronous spawn under Win32s. Yuk.
4160 */
4161 num_windows = 0;
4162 EnumWindows(win32ssynch_cb, 0);
4163 old_num_windows = num_windows;
4164 do
4165 {
4166 Sleep(1000);
4167 num_windows = 0;
4168 EnumWindows(win32ssynch_cb, 0);
4169 } while (num_windows == old_num_windows);
4170 ret = 0;
4171 }
4172
4173 /* Close the handles to the subprocess, so that it goes away */
4174 CloseHandle(pi.hThread);
4175 CloseHandle(pi.hProcess);
4176
4177 /* Try to get input focus back. Doesn't always work though. */
4178 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4179
4180 return ret;
4181}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004182
4183/*
4184 * Thread launched by the gui to send the current buffer data to the
4185 * process. This way avoid to hang up vim totally if the children
4186 * process take a long time to process the lines.
4187 */
4188 static DWORD WINAPI
4189sub_process_writer(LPVOID param)
4190{
4191 HANDLE g_hChildStd_IN_Wr = param;
4192 linenr_T lnum = curbuf->b_op_start.lnum;
4193 DWORD len = 0;
4194 DWORD l;
4195 char_u *lp = ml_get(lnum);
4196 char_u *s;
4197 int written = 0;
4198
4199 for (;;)
4200 {
4201 l = (DWORD)STRLEN(lp + written);
4202 if (l == 0)
4203 len = 0;
4204 else if (lp[written] == NL)
4205 {
4206 /* NL -> NUL translation */
4207 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4208 }
4209 else
4210 {
4211 s = vim_strchr(lp + written, NL);
4212 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4213 s == NULL ? l : (DWORD)(s - (lp + written)),
4214 &len, NULL);
4215 }
4216 if (len == (int)l)
4217 {
4218 /* Finished a line, add a NL, unless this line should not have
4219 * one. */
4220 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004221 || (!curbuf->b_p_bin
4222 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004223 || (lnum != curbuf->b_no_eol_lnum
4224 && (lnum != curbuf->b_ml.ml_line_count
4225 || curbuf->b_p_eol)))
4226 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004227 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004228 }
4229
4230 ++lnum;
4231 if (lnum > curbuf->b_op_end.lnum)
4232 break;
4233
4234 lp = ml_get(lnum);
4235 written = 0;
4236 }
4237 else if (len > 0)
4238 written += len;
4239 }
4240
4241 /* finished all the lines, close pipe */
4242 CloseHandle(g_hChildStd_IN_Wr);
4243 ExitThread(0);
4244}
4245
4246
4247# define BUFLEN 100 /* length for buffer, stolen from unix version */
4248
4249/*
4250 * This function read from the children's stdout and write the
4251 * data on screen or in the buffer accordingly.
4252 */
4253 static void
4254dump_pipe(int options,
4255 HANDLE g_hChildStd_OUT_Rd,
4256 garray_T *ga,
4257 char_u buffer[],
4258 DWORD *buffer_off)
4259{
4260 DWORD availableBytes = 0;
4261 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004262 int ret;
4263 DWORD len;
4264 DWORD toRead;
4265 int repeatCount;
4266
4267 /* we query the pipe to see if there is any data to read
4268 * to avoid to perform a blocking read */
4269 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4270 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004271 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004272 NULL, /* number of read bytes */
4273 &availableBytes, /* available bytes total */
4274 NULL); /* byteLeft */
4275
4276 repeatCount = 0;
4277 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004278 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004279 {
4280 repeatCount++;
4281 toRead =
4282# ifdef FEAT_MBYTE
4283 (DWORD)(BUFLEN - *buffer_off);
4284# else
4285 (DWORD)BUFLEN;
4286# endif
4287 toRead = availableBytes < toRead ? availableBytes : toRead;
4288 ReadFile(g_hChildStd_OUT_Rd, buffer
4289# ifdef FEAT_MBYTE
4290 + *buffer_off, toRead
4291# else
4292 , toRead
4293# endif
4294 , &len, NULL);
4295
4296 /* If we haven't read anything, there is a problem */
4297 if (len == 0)
4298 break;
4299
4300 availableBytes -= len;
4301
4302 if (options & SHELL_READ)
4303 {
4304 /* Do NUL -> NL translation, append NL separated
4305 * lines to the current buffer. */
4306 for (i = 0; i < len; ++i)
4307 {
4308 if (buffer[i] == NL)
4309 append_ga_line(ga);
4310 else if (buffer[i] == NUL)
4311 ga_append(ga, NL);
4312 else
4313 ga_append(ga, buffer[i]);
4314 }
4315 }
4316# ifdef FEAT_MBYTE
4317 else if (has_mbyte)
4318 {
4319 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004320 int c;
4321 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004322
4323 len += *buffer_off;
4324 buffer[len] = NUL;
4325
4326 /* Check if the last character in buffer[] is
4327 * incomplete, keep these bytes for the next
4328 * round. */
4329 for (p = buffer; p < buffer + len; p += l)
4330 {
4331 l = mb_cptr2len(p);
4332 if (l == 0)
4333 l = 1; /* NUL byte? */
4334 else if (MB_BYTE2LEN(*p) != l)
4335 break;
4336 }
4337 if (p == buffer) /* no complete character */
4338 {
4339 /* avoid getting stuck at an illegal byte */
4340 if (len >= 12)
4341 ++p;
4342 else
4343 {
4344 *buffer_off = len;
4345 return;
4346 }
4347 }
4348 c = *p;
4349 *p = NUL;
4350 msg_puts(buffer);
4351 if (p < buffer + len)
4352 {
4353 *p = c;
4354 *buffer_off = (DWORD)((buffer + len) - p);
4355 mch_memmove(buffer, p, *buffer_off);
4356 return;
4357 }
4358 *buffer_off = 0;
4359 }
4360# endif /* FEAT_MBYTE */
4361 else
4362 {
4363 buffer[len] = NUL;
4364 msg_puts(buffer);
4365 }
4366
4367 windgoto(msg_row, msg_col);
4368 cursor_on();
4369 out_flush();
4370 }
4371}
4372
4373/*
4374 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4375 * for communication and doesn't open any new window.
4376 */
4377 static int
4378mch_system_piped(char *cmd, int options)
4379{
4380 STARTUPINFO si;
4381 PROCESS_INFORMATION pi;
4382 DWORD ret = 0;
4383
4384 HANDLE g_hChildStd_IN_Rd = NULL;
4385 HANDLE g_hChildStd_IN_Wr = NULL;
4386 HANDLE g_hChildStd_OUT_Rd = NULL;
4387 HANDLE g_hChildStd_OUT_Wr = NULL;
4388
4389 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4390 DWORD len;
4391
4392 /* buffer used to receive keys */
4393 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4394 int ta_len = 0; /* valid bytes in ta_buf[] */
4395
4396 DWORD i;
4397 int c;
4398 int noread_cnt = 0;
4399 garray_T ga;
4400 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004401 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004402 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004403
4404 SECURITY_ATTRIBUTES saAttr;
4405
4406 /* Set the bInheritHandle flag so pipe handles are inherited. */
4407 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4408 saAttr.bInheritHandle = TRUE;
4409 saAttr.lpSecurityDescriptor = NULL;
4410
4411 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4412 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4413 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4414 /* Create a pipe for the child process's STDIN. */
4415 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4416 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4417 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4418 {
4419 CloseHandle(g_hChildStd_IN_Rd);
4420 CloseHandle(g_hChildStd_IN_Wr);
4421 CloseHandle(g_hChildStd_OUT_Rd);
4422 CloseHandle(g_hChildStd_OUT_Wr);
4423 MSG_PUTS(_("\nCannot create pipes\n"));
4424 }
4425
4426 si.cb = sizeof(si);
4427 si.lpReserved = NULL;
4428 si.lpDesktop = NULL;
4429 si.lpTitle = NULL;
4430 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4431
4432 /* set-up our file redirection */
4433 si.hStdError = g_hChildStd_OUT_Wr;
4434 si.hStdOutput = g_hChildStd_OUT_Wr;
4435 si.hStdInput = g_hChildStd_IN_Rd;
4436 si.wShowWindow = SW_HIDE;
4437 si.cbReserved2 = 0;
4438 si.lpReserved2 = NULL;
4439
4440 if (options & SHELL_READ)
4441 ga_init2(&ga, 1, BUFLEN);
4442
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004443 if (cmd != NULL)
4444 {
4445 p = (char *)vim_strsave((char_u *)cmd);
4446 if (p != NULL)
4447 unescape_shellxquote((char_u *)p, p_sxe);
4448 else
4449 p = cmd;
4450 }
4451
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004452 /* Now, run the command.
4453 * About "Inherit handles" being TRUE: this command can be litigious,
4454 * handle inheritance was deactivated for pending temp file, but, if we
4455 * deactivate it, the pipes don't work for some reason. */
4456 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004457
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004458 if (p != cmd)
4459 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004460
4461 /* Close our unused side of the pipes */
4462 CloseHandle(g_hChildStd_IN_Rd);
4463 CloseHandle(g_hChildStd_OUT_Wr);
4464
4465 if (options & SHELL_WRITE)
4466 {
4467 HANDLE thread =
4468 CreateThread(NULL, /* security attributes */
4469 0, /* default stack size */
4470 sub_process_writer, /* function to be executed */
4471 g_hChildStd_IN_Wr, /* parameter */
4472 0, /* creation flag, start immediately */
4473 NULL); /* we don't care about thread id */
4474 CloseHandle(thread);
4475 g_hChildStd_IN_Wr = NULL;
4476 }
4477
4478 /* Keep updating the window while waiting for the shell to finish. */
4479 for (;;)
4480 {
4481 MSG msg;
4482
Bram Moolenaar175d0702013-12-11 18:36:33 +01004483 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004484 {
4485 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004486 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004487 }
4488
4489 /* write pipe information in the window */
4490 if ((options & (SHELL_READ|SHELL_WRITE))
4491# ifdef FEAT_GUI
4492 || gui.in_use
4493# endif
4494 )
4495 {
4496 len = 0;
4497 if (!(options & SHELL_EXPAND)
4498 && ((options &
4499 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4500 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4501# ifdef FEAT_GUI
4502 || gui.in_use
4503# endif
4504 )
4505 && (ta_len > 0 || noread_cnt > 4))
4506 {
4507 if (ta_len == 0)
4508 {
4509 /* Get extra characters when we don't have any. Reset the
4510 * counter and timer. */
4511 noread_cnt = 0;
4512# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4513 gettimeofday(&start_tv, NULL);
4514# endif
4515 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4516 }
4517 if (ta_len > 0 || len > 0)
4518 {
4519 /*
4520 * For pipes: Check for CTRL-C: send interrupt signal to
4521 * child. Check for CTRL-D: EOF, close pipe to child.
4522 */
4523 if (len == 1 && cmd != NULL)
4524 {
4525 if (ta_buf[ta_len] == Ctrl_C)
4526 {
4527 /* Learn what exit code is expected, for
4528 * now put 9 as SIGKILL */
4529 TerminateProcess(pi.hProcess, 9);
4530 }
4531 if (ta_buf[ta_len] == Ctrl_D)
4532 {
4533 CloseHandle(g_hChildStd_IN_Wr);
4534 g_hChildStd_IN_Wr = NULL;
4535 }
4536 }
4537
4538 /* replace K_BS by <BS> and K_DEL by <DEL> */
4539 for (i = ta_len; i < ta_len + len; ++i)
4540 {
4541 if (ta_buf[i] == CSI && len - i > 2)
4542 {
4543 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4544 if (c == K_DEL || c == K_KDEL || c == K_BS)
4545 {
4546 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4547 (size_t)(len - i - 2));
4548 if (c == K_DEL || c == K_KDEL)
4549 ta_buf[i] = DEL;
4550 else
4551 ta_buf[i] = Ctrl_H;
4552 len -= 2;
4553 }
4554 }
4555 else if (ta_buf[i] == '\r')
4556 ta_buf[i] = '\n';
4557# ifdef FEAT_MBYTE
4558 if (has_mbyte)
4559 i += (*mb_ptr2len_len)(ta_buf + i,
4560 ta_len + len - i) - 1;
4561# endif
4562 }
4563
4564 /*
4565 * For pipes: echo the typed characters. For a pty this
4566 * does not seem to work.
4567 */
4568 for (i = ta_len; i < ta_len + len; ++i)
4569 {
4570 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4571 msg_putchar(ta_buf[i]);
4572# ifdef FEAT_MBYTE
4573 else if (has_mbyte)
4574 {
4575 int l = (*mb_ptr2len)(ta_buf + i);
4576
4577 msg_outtrans_len(ta_buf + i, l);
4578 i += l - 1;
4579 }
4580# endif
4581 else
4582 msg_outtrans_len(ta_buf + i, 1);
4583 }
4584 windgoto(msg_row, msg_col);
4585 out_flush();
4586
4587 ta_len += len;
4588
4589 /*
4590 * Write the characters to the child, unless EOF has been
4591 * typed for pipes. Write one character at a time, to
4592 * avoid losing too much typeahead. When writing buffer
4593 * lines, drop the typed characters (only check for
4594 * CTRL-C).
4595 */
4596 if (options & SHELL_WRITE)
4597 ta_len = 0;
4598 else if (g_hChildStd_IN_Wr != NULL)
4599 {
4600 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4601 1, &len, NULL);
4602 // if we are typing in, we want to keep things reactive
4603 delay = 1;
4604 if (len > 0)
4605 {
4606 ta_len -= len;
4607 mch_memmove(ta_buf, ta_buf + len, ta_len);
4608 }
4609 }
4610 }
4611 }
4612 }
4613
4614 if (ta_len)
4615 ui_inchar_undo(ta_buf, ta_len);
4616
4617 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4618 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004619 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004620 break;
4621 }
4622
4623 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004624 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004625
4626 /* We start waiting for a very short time and then increase it, so
4627 * that we respond quickly when the process is quick, and don't
4628 * consume too much overhead when it's slow. */
4629 if (delay < 50)
4630 delay += 10;
4631 }
4632
4633 /* Close the pipe */
4634 CloseHandle(g_hChildStd_OUT_Rd);
4635 if (g_hChildStd_IN_Wr != NULL)
4636 CloseHandle(g_hChildStd_IN_Wr);
4637
4638 WaitForSingleObject(pi.hProcess, INFINITE);
4639
4640 /* Get the command exit code */
4641 GetExitCodeProcess(pi.hProcess, &ret);
4642
4643 if (options & SHELL_READ)
4644 {
4645 if (ga.ga_len > 0)
4646 {
4647 append_ga_line(&ga);
4648 /* remember that the NL was missing */
4649 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4650 }
4651 else
4652 curbuf->b_no_eol_lnum = 0;
4653 ga_clear(&ga);
4654 }
4655
4656 /* Close the handles to the subprocess, so that it goes away */
4657 CloseHandle(pi.hThread);
4658 CloseHandle(pi.hProcess);
4659
4660 return ret;
4661}
4662
4663 static int
4664mch_system(char *cmd, int options)
4665{
4666 /* if we can pipe and the shelltemp option is off */
4667 if (allowPiping && !p_stmp)
4668 return mch_system_piped(cmd, options);
4669 else
4670 return mch_system_classic(cmd, options);
4671}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672#else
4673
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004674# ifdef FEAT_MBYTE
4675 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004676mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004677{
4678 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4679 {
4680 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4681 if (wcmd != NULL)
4682 {
4683 int ret = _wsystem(wcmd);
4684 vim_free(wcmd);
4685 return ret;
4686 }
4687 }
4688 return system(cmd);
4689}
4690# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004691# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004692# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004693
4694#endif
4695
4696/*
4697 * Either execute a command by calling the shell or start a new shell
4698 */
4699 int
4700mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004701 char_u *cmd,
4702 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004703{
4704 int x = 0;
4705 int tmode = cur_tmode;
4706#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004707 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004708# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004709 int did_set_title = FALSE;
4710
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004711 /* Change the title to reflect that we are in a subshell. */
4712 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4713 {
4714 WCHAR szShellTitle[512];
4715
4716 if (GetConsoleTitleW(szShellTitle,
4717 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4718 {
4719 if (cmd == NULL)
4720 wcscat(szShellTitle, L" :sh");
4721 else
4722 {
4723 WCHAR *wn = enc_to_utf16(cmd, NULL);
4724
4725 if (wn != NULL)
4726 {
4727 wcscat(szShellTitle, L" - !");
4728 if ((wcslen(szShellTitle) + wcslen(wn) <
4729 sizeof(szShellTitle)/sizeof(WCHAR)))
4730 wcscat(szShellTitle, wn);
4731 SetConsoleTitleW(szShellTitle);
4732 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004733 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004734 }
4735 }
4736 }
4737 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004738 if (!did_set_title)
4739# endif
4740 /* Change the title to reflect that we are in a subshell. */
4741 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004743 if (cmd == NULL)
4744 strcat(szShellTitle, " :sh");
4745 else
4746 {
4747 strcat(szShellTitle, " - !");
4748 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4749 strcat(szShellTitle, cmd);
4750 }
4751 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004752 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753#endif
4754
4755 out_flush();
4756
4757#ifdef MCH_WRITE_DUMP
4758 if (fdDump)
4759 {
4760 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4761 fflush(fdDump);
4762 }
4763#endif
4764
4765 /*
4766 * Catch all deadly signals while running the external command, because a
4767 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4768 */
4769 signal(SIGINT, SIG_IGN);
4770#if defined(__GNUC__) && !defined(__MINGW32__)
4771 signal(SIGKILL, SIG_IGN);
4772#else
4773 signal(SIGBREAK, SIG_IGN);
4774#endif
4775 signal(SIGILL, SIG_IGN);
4776 signal(SIGFPE, SIG_IGN);
4777 signal(SIGSEGV, SIG_IGN);
4778 signal(SIGTERM, SIG_IGN);
4779 signal(SIGABRT, SIG_IGN);
4780
4781 if (options & SHELL_COOKED)
4782 settmode(TMODE_COOK); /* set to normal mode */
4783
4784 if (cmd == NULL)
4785 {
4786 x = mch_system(p_sh, options);
4787 }
4788 else
4789 {
4790 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004791 char_u *newcmd = NULL;
4792 char_u *cmdbase = cmd;
4793 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004794
4795 /* Skip a leading ", ( and "(. */
4796 if (*cmdbase == '"' )
4797 ++cmdbase;
4798 if (*cmdbase == '(')
4799 ++cmdbase;
4800
4801 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4802 {
4803 STARTUPINFO si;
4804 PROCESS_INFORMATION pi;
4805 DWORD flags = CREATE_NEW_CONSOLE;
4806 char_u *p;
4807
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004808 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004809 si.cb = sizeof(si);
4810 si.lpReserved = NULL;
4811 si.lpDesktop = NULL;
4812 si.lpTitle = NULL;
4813 si.dwFlags = 0;
4814 si.cbReserved2 = 0;
4815 si.lpReserved2 = NULL;
4816
4817 cmdbase = skipwhite(cmdbase + 5);
4818 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4819 && vim_iswhite(cmdbase[4]))
4820 {
4821 cmdbase = skipwhite(cmdbase + 4);
4822 si.dwFlags = STARTF_USESHOWWINDOW;
4823 si.wShowWindow = SW_SHOWMINNOACTIVE;
4824 }
4825 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4826 && vim_iswhite(cmdbase[2]))
4827 {
4828 cmdbase = skipwhite(cmdbase + 2);
4829 flags = CREATE_NO_WINDOW;
4830 si.dwFlags = STARTF_USESTDHANDLES;
4831 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004832 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004833 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004834 NULL, // Security att.
4835 OPEN_EXISTING, // Open flags
4836 FILE_ATTRIBUTE_NORMAL, // File att.
4837 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004838 si.hStdOutput = si.hStdInput;
4839 si.hStdError = si.hStdInput;
4840 }
4841
4842 /* Remove a trailing ", ) and )" if they have a match
4843 * at the start of the command. */
4844 if (cmdbase > cmd)
4845 {
4846 p = cmdbase + STRLEN(cmdbase);
4847 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4848 *--p = NUL;
4849 if (p > cmdbase && p[-1] == ')'
4850 && (*cmd =='(' || cmd[1] == '('))
4851 *--p = NUL;
4852 }
4853
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004854 newcmd = cmdbase;
4855 unescape_shellxquote(cmdbase, p_sxe);
4856
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004857 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004858 * If creating new console, arguments are passed to the
4859 * 'cmd.exe' as-is. If it's not, arguments are not treated
4860 * correctly for current 'cmd.exe'. So unescape characters in
4861 * shellxescape except '|' for avoiding to be treated as
4862 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004863 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004864 if (flags != CREATE_NEW_CONSOLE)
4865 {
4866 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004867 char_u *cmd_shell = mch_getenv("COMSPEC");
4868
4869 if (cmd_shell == NULL || *cmd_shell == NUL)
4870 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004871
4872 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4873 if (subcmd != NULL)
4874 {
4875 /* make "cmd.exe /c arguments" */
4876 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877 newcmd = lalloc(cmdlen, TRUE);
4878 if (newcmd != NULL)
4879 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004880 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004881 else
4882 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004883 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004884 }
4885 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004886
4887 /*
4888 * Now, start the command as a process, so that it doesn't
4889 * inherit our handles which causes unpleasant dangling swap
4890 * files if we exit before the spawned process
4891 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004892 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004893 x = 0;
4894 else
4895 {
4896 x = -1;
4897#ifdef FEAT_GUI_W32
4898 EMSG(_("E371: Command not found"));
4899#endif
4900 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004901
4902 if (newcmd != cmdbase)
4903 vim_free(newcmd);
4904
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004905 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004906 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004907 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004908 CloseHandle(si.hStdInput);
4909 }
4910 /* Close the handles to the subprocess, so that it goes away */
4911 CloseHandle(pi.hThread);
4912 CloseHandle(pi.hProcess);
4913 }
4914 else
4915 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004916 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004917#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004918 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004919#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004920 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4921
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004922 newcmd = lalloc(cmdlen, TRUE);
4923 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004924 {
4925#if defined(FEAT_GUI_W32)
4926 if (need_vimrun_warning)
4927 {
4928 MessageBox(NULL,
4929 _("VIMRUN.EXE not found in your $PATH.\n"
4930 "External commands will not pause after completion.\n"
4931 "See :help win32-vimrun for more information."),
4932 _("Vim Warning"),
4933 MB_ICONWARNING);
4934 need_vimrun_warning = FALSE;
4935 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004936 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004937 /* Use vimrun to execute the command. It opens a console
4938 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004939 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940 vimrun_path,
4941 (msg_silent != 0 || (options & SHELL_DOOUT))
4942 ? "-s " : "",
4943 p_sh, p_shcf, cmd);
4944 else
4945#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004946 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004947 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004948 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004949 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004950 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004951 }
4952 }
4953
4954 if (tmode == TMODE_RAW)
4955 settmode(TMODE_RAW); /* set to raw mode */
4956
4957 /* Print the return value, unless "vimrun" was used. */
4958 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4959#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004960 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4961 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962#endif
4963 )
4964 {
4965 smsg(_("shell returned %d"), x);
4966 msg_putchar('\n');
4967 }
4968#ifdef FEAT_TITLE
4969 resettitle();
4970#endif
4971
4972 signal(SIGINT, SIG_DFL);
4973#if defined(__GNUC__) && !defined(__MINGW32__)
4974 signal(SIGKILL, SIG_DFL);
4975#else
4976 signal(SIGBREAK, SIG_DFL);
4977#endif
4978 signal(SIGILL, SIG_DFL);
4979 signal(SIGFPE, SIG_DFL);
4980 signal(SIGSEGV, SIG_DFL);
4981 signal(SIGTERM, SIG_DFL);
4982 signal(SIGABRT, SIG_DFL);
4983
4984 return x;
4985}
4986
4987
4988#ifndef FEAT_GUI_W32
4989
4990/*
4991 * Start termcap mode
4992 */
4993 static void
4994termcap_mode_start(void)
4995{
4996 DWORD cmodein;
4997
4998 if (g_fTermcapMode)
4999 return;
5000
5001 SaveConsoleBuffer(&g_cbNonTermcap);
5002
5003 if (g_cbTermcap.IsValid)
5004 {
5005 /*
5006 * We've been in termcap mode before. Restore certain screen
5007 * characteristics, including the buffer size and the window
5008 * size. Since we will be redrawing the screen, we don't need
5009 * to restore the actual contents of the buffer.
5010 */
5011 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5012 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5013 Rows = g_cbTermcap.Info.dwSize.Y;
5014 Columns = g_cbTermcap.Info.dwSize.X;
5015 }
5016 else
5017 {
5018 /*
5019 * This is our first time entering termcap mode. Clear the console
5020 * screen buffer, and resize the buffer to match the current window
5021 * size. We will use this as the size of our editing environment.
5022 */
5023 ClearConsoleBuffer(g_attrCurrent);
5024 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5025 }
5026
5027#ifdef FEAT_TITLE
5028 resettitle();
5029#endif
5030
5031 GetConsoleMode(g_hConIn, &cmodein);
5032#ifdef FEAT_MOUSE
5033 if (g_fMouseActive)
5034 cmodein |= ENABLE_MOUSE_INPUT;
5035 else
5036 cmodein &= ~ENABLE_MOUSE_INPUT;
5037#endif
5038 cmodein |= ENABLE_WINDOW_INPUT;
5039 SetConsoleMode(g_hConIn, cmodein);
5040
5041 redraw_later_clear();
5042 g_fTermcapMode = TRUE;
5043}
5044
5045
5046/*
5047 * End termcap mode
5048 */
5049 static void
5050termcap_mode_end(void)
5051{
5052 DWORD cmodein;
5053 ConsoleBuffer *cb;
5054 COORD coord;
5055 DWORD dwDummy;
5056
5057 if (!g_fTermcapMode)
5058 return;
5059
5060 SaveConsoleBuffer(&g_cbTermcap);
5061
5062 GetConsoleMode(g_hConIn, &cmodein);
5063 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5064 SetConsoleMode(g_hConIn, cmodein);
5065
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005066#ifdef FEAT_RESTORE_ORIG_SCREEN
5067 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5068#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005069 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005070#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005071 RestoreConsoleBuffer(cb, p_rs);
5072 SetConsoleCursorInfo(g_hConOut, &g_cci);
5073
5074 if (p_rs || exiting)
5075 {
5076 /*
5077 * Clear anything that happens to be on the current line.
5078 */
5079 coord.X = 0;
5080 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5081 FillConsoleOutputCharacter(g_hConOut, ' ',
5082 cb->Info.dwSize.X, coord, &dwDummy);
5083 /*
5084 * The following is just for aesthetics. If we are exiting without
5085 * restoring the screen, then we want to have a prompt string
5086 * appear at the bottom line. However, the command interpreter
5087 * seems to always advance the cursor one line before displaying
5088 * the prompt string, which causes the screen to scroll. To
5089 * counter this, move the cursor up one line before exiting.
5090 */
5091 if (exiting && !p_rs)
5092 coord.Y--;
5093 /*
5094 * Position the cursor at the leftmost column of the desired row.
5095 */
5096 SetConsoleCursorPosition(g_hConOut, coord);
5097 }
5098
5099 g_fTermcapMode = FALSE;
5100}
5101#endif /* FEAT_GUI_W32 */
5102
5103
5104#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005105/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106 void
5107mch_write(
5108 char_u *s,
5109 int len)
5110{
5111 /* never used */
5112}
5113
5114#else
5115
5116/*
5117 * clear `n' chars, starting from `coord'
5118 */
5119 static void
5120clear_chars(
5121 COORD coord,
5122 DWORD n)
5123{
5124 DWORD dwDummy;
5125
5126 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5127 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5128}
5129
5130
5131/*
5132 * Clear the screen
5133 */
5134 static void
5135clear_screen(void)
5136{
5137 g_coord.X = g_coord.Y = 0;
5138 clear_chars(g_coord, Rows * Columns);
5139}
5140
5141
5142/*
5143 * Clear to end of display
5144 */
5145 static void
5146clear_to_end_of_display(void)
5147{
5148 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5149 * Columns + (Columns - g_coord.X));
5150}
5151
5152
5153/*
5154 * Clear to end of line
5155 */
5156 static void
5157clear_to_end_of_line(void)
5158{
5159 clear_chars(g_coord, Columns - g_coord.X);
5160}
5161
5162
5163/*
5164 * Scroll the scroll region up by `cLines' lines
5165 */
5166 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005167scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005168{
5169 COORD oldcoord = g_coord;
5170
5171 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5172 delete_lines(cLines);
5173
5174 g_coord = oldcoord;
5175}
5176
5177
5178/*
5179 * Set the scroll region
5180 */
5181 static void
5182set_scroll_region(
5183 unsigned left,
5184 unsigned top,
5185 unsigned right,
5186 unsigned bottom)
5187{
5188 if (left >= right
5189 || top >= bottom
5190 || right > (unsigned) Columns - 1
5191 || bottom > (unsigned) Rows - 1)
5192 return;
5193
5194 g_srScrollRegion.Left = left;
5195 g_srScrollRegion.Top = top;
5196 g_srScrollRegion.Right = right;
5197 g_srScrollRegion.Bottom = bottom;
5198}
5199
5200
5201/*
5202 * Insert `cLines' lines at the current cursor position
5203 */
5204 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005205insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206{
5207 SMALL_RECT source;
5208 COORD dest;
5209 CHAR_INFO fill;
5210
5211 dest.X = 0;
5212 dest.Y = g_coord.Y + cLines;
5213
5214 source.Left = 0;
5215 source.Top = g_coord.Y;
5216 source.Right = g_srScrollRegion.Right;
5217 source.Bottom = g_srScrollRegion.Bottom - cLines;
5218
5219 fill.Char.AsciiChar = ' ';
5220 fill.Attributes = g_attrCurrent;
5221
5222 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5223
5224 /* Here we have to deal with a win32 console flake: If the scroll
5225 * region looks like abc and we scroll c to a and fill with d we get
5226 * cbd... if we scroll block c one line at a time to a, we get cdd...
5227 * vim expects cdd consistently... So we have to deal with that
5228 * here... (this also occurs scrolling the same way in the other
5229 * direction). */
5230
5231 if (source.Bottom < dest.Y)
5232 {
5233 COORD coord;
5234
5235 coord.X = 0;
5236 coord.Y = source.Bottom;
5237 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5238 }
5239}
5240
5241
5242/*
5243 * Delete `cLines' lines at the current cursor position
5244 */
5245 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005246delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005247{
5248 SMALL_RECT source;
5249 COORD dest;
5250 CHAR_INFO fill;
5251 int nb;
5252
5253 dest.X = 0;
5254 dest.Y = g_coord.Y;
5255
5256 source.Left = 0;
5257 source.Top = g_coord.Y + cLines;
5258 source.Right = g_srScrollRegion.Right;
5259 source.Bottom = g_srScrollRegion.Bottom;
5260
5261 fill.Char.AsciiChar = ' ';
5262 fill.Attributes = g_attrCurrent;
5263
5264 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5265
5266 /* Here we have to deal with a win32 console flake: If the scroll
5267 * region looks like abc and we scroll c to a and fill with d we get
5268 * cbd... if we scroll block c one line at a time to a, we get cdd...
5269 * vim expects cdd consistently... So we have to deal with that
5270 * here... (this also occurs scrolling the same way in the other
5271 * direction). */
5272
5273 nb = dest.Y + (source.Bottom - source.Top) + 1;
5274
5275 if (nb < source.Top)
5276 {
5277 COORD coord;
5278
5279 coord.X = 0;
5280 coord.Y = nb;
5281 clear_chars(coord, Columns * (source.Top - nb));
5282 }
5283}
5284
5285
5286/*
5287 * Set the cursor position
5288 */
5289 static void
5290gotoxy(
5291 unsigned x,
5292 unsigned y)
5293{
5294 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5295 return;
5296
5297 /* external cursor coords are 1-based; internal are 0-based */
5298 g_coord.X = x - 1;
5299 g_coord.Y = y - 1;
5300 SetConsoleCursorPosition(g_hConOut, g_coord);
5301}
5302
5303
5304/*
5305 * Set the current text attribute = (foreground | background)
5306 * See ../doc/os_win32.txt for the numbers.
5307 */
5308 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005309textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005311 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005312
5313 SetConsoleTextAttribute(g_hConOut, wAttr);
5314}
5315
5316
5317 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005318textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005319{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005320 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005321
5322 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5323}
5324
5325
5326 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005327textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005329 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005330
5331 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5332}
5333
5334
5335/*
5336 * restore the default text attribute (whatever we started with)
5337 */
5338 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005339normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005340{
5341 textattr(g_attrDefault);
5342}
5343
5344
5345static WORD g_attrPreStandout = 0;
5346
5347/*
5348 * Make the text standout, by brightening it
5349 */
5350 static void
5351standout(void)
5352{
5353 g_attrPreStandout = g_attrCurrent;
5354 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5355}
5356
5357
5358/*
5359 * Turn off standout mode
5360 */
5361 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005362standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005363{
5364 if (g_attrPreStandout)
5365 {
5366 textattr(g_attrPreStandout);
5367 g_attrPreStandout = 0;
5368 }
5369}
5370
5371
5372/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005373 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005374 */
5375 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005376mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005377{
5378 char_u *p;
5379 int n;
5380
5381 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5382 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5383 if (T_ME[0] == ESC && T_ME[1] == '|')
5384 {
5385 p = T_ME + 2;
5386 n = getdigits(&p);
5387 if (*p == 'm' && n > 0)
5388 {
5389 cterm_normal_fg_color = (n & 0xf) + 1;
5390 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5391 }
5392 }
5393}
5394
5395
5396/*
5397 * visual bell: flash the screen
5398 */
5399 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005400visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005401{
5402 COORD coordOrigin = {0, 0};
5403 WORD attrFlash = ~g_attrCurrent & 0xff;
5404
5405 DWORD dwDummy;
5406 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5407
5408 if (oldattrs == NULL)
5409 return;
5410 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5411 coordOrigin, &dwDummy);
5412 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5413 coordOrigin, &dwDummy);
5414
5415 Sleep(15); /* wait for 15 msec */
5416 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5417 coordOrigin, &dwDummy);
5418 vim_free(oldattrs);
5419}
5420
5421
5422/*
5423 * Make the cursor visible or invisible
5424 */
5425 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005426cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005427{
5428 s_cursor_visible = fVisible;
5429#ifdef MCH_CURSOR_SHAPE
5430 mch_update_cursor();
5431#endif
5432}
5433
5434
5435/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005436 * write `cbToWrite' bytes in `pchBuf' to the screen
5437 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005438 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005439 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005441 char_u *pchBuf,
5442 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005443{
5444 COORD coord = g_coord;
5445 DWORD written;
5446
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005447#ifdef FEAT_MBYTE
5448 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5449 {
5450 static WCHAR *unicodebuf = NULL;
5451 static int unibuflen = 0;
5452 int length;
5453 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005455 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5456 if (unicodebuf == NULL || length > unibuflen)
5457 {
5458 vim_free(unicodebuf);
5459 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5460 unibuflen = length;
5461 }
5462 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5463 unicodebuf, unibuflen);
5464
5465 cells = mb_string2cells(pchBuf, cbToWrite);
5466 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5467 coord, &written);
5468 /* When writing fails or didn't write a single character, pretend one
5469 * character was written, otherwise we get stuck. */
5470 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5471 coord, &cchwritten) == 0
5472 || cchwritten == 0)
5473 cchwritten = 1;
5474
5475 if (cchwritten == length)
5476 {
5477 written = cbToWrite;
5478 g_coord.X += (SHORT)cells;
5479 }
5480 else
5481 {
5482 char_u *p = pchBuf;
5483 for (n = 0; n < cchwritten; n++)
5484 mb_cptr_adv(p);
5485 written = p - pchBuf;
5486 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5487 }
5488 }
5489 else
5490#endif
5491 {
5492 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5493 coord, &written);
5494 /* When writing fails or didn't write a single character, pretend one
5495 * character was written, otherwise we get stuck. */
5496 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5497 coord, &written) == 0
5498 || written == 0)
5499 written = 1;
5500
5501 g_coord.X += (SHORT) written;
5502 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503
5504 while (g_coord.X > g_srScrollRegion.Right)
5505 {
5506 g_coord.X -= (SHORT) Columns;
5507 if (g_coord.Y < g_srScrollRegion.Bottom)
5508 g_coord.Y++;
5509 }
5510
5511 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5512
5513 return written;
5514}
5515
5516
5517/*
5518 * mch_write(): write the output buffer to the screen, translating ESC
5519 * sequences into calls to console output routines.
5520 */
5521 void
5522mch_write(
5523 char_u *s,
5524 int len)
5525{
5526 s[len] = NUL;
5527
5528 if (!term_console)
5529 {
5530 write(1, s, (unsigned)len);
5531 return;
5532 }
5533
5534 /* translate ESC | sequences into faked bios calls */
5535 while (len--)
5536 {
5537 /* optimization: use one single write_chars for runs of text,
5538 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005539 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540
5541 if (p_wd)
5542 {
5543 WaitForChar(p_wd);
5544 if (prefix != 0)
5545 prefix = 1;
5546 }
5547
5548 if (prefix != 0)
5549 {
5550 DWORD nWritten;
5551
5552 nWritten = write_chars(s, prefix);
5553#ifdef MCH_WRITE_DUMP
5554 if (fdDump)
5555 {
5556 fputc('>', fdDump);
5557 fwrite(s, sizeof(char_u), nWritten, fdDump);
5558 fputs("<\n", fdDump);
5559 }
5560#endif
5561 len -= (nWritten - 1);
5562 s += nWritten;
5563 }
5564 else if (s[0] == '\n')
5565 {
5566 /* \n, newline: go to the beginning of the next line or scroll */
5567 if (g_coord.Y == g_srScrollRegion.Bottom)
5568 {
5569 scroll(1);
5570 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5571 }
5572 else
5573 {
5574 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5575 }
5576#ifdef MCH_WRITE_DUMP
5577 if (fdDump)
5578 fputs("\\n\n", fdDump);
5579#endif
5580 s++;
5581 }
5582 else if (s[0] == '\r')
5583 {
5584 /* \r, carriage return: go to beginning of line */
5585 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5586#ifdef MCH_WRITE_DUMP
5587 if (fdDump)
5588 fputs("\\r\n", fdDump);
5589#endif
5590 s++;
5591 }
5592 else if (s[0] == '\b')
5593 {
5594 /* \b, backspace: move cursor one position left */
5595 if (g_coord.X > g_srScrollRegion.Left)
5596 g_coord.X--;
5597 else if (g_coord.Y > g_srScrollRegion.Top)
5598 {
5599 g_coord.X = g_srScrollRegion.Right;
5600 g_coord.Y--;
5601 }
5602 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5603#ifdef MCH_WRITE_DUMP
5604 if (fdDump)
5605 fputs("\\b\n", fdDump);
5606#endif
5607 s++;
5608 }
5609 else if (s[0] == '\a')
5610 {
5611 /* \a, bell */
5612 MessageBeep(0xFFFFFFFF);
5613#ifdef MCH_WRITE_DUMP
5614 if (fdDump)
5615 fputs("\\a\n", fdDump);
5616#endif
5617 s++;
5618 }
5619 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5620 {
5621#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005622 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005624 char_u *p;
5625 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626
5627 switch (s[2])
5628 {
5629 /* one or two numeric arguments, separated by ';' */
5630
5631 case '0': case '1': case '2': case '3': case '4':
5632 case '5': case '6': case '7': case '8': case '9':
5633 p = s + 2;
5634 arg1 = getdigits(&p); /* no check for length! */
5635 if (p > s + len)
5636 break;
5637
5638 if (*p == ';')
5639 {
5640 ++p;
5641 arg2 = getdigits(&p); /* no check for length! */
5642 if (p > s + len)
5643 break;
5644
5645 if (*p == 'H')
5646 gotoxy(arg2, arg1);
5647 else if (*p == 'r')
5648 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5649 }
5650 else if (*p == 'A')
5651 {
5652 /* move cursor up arg1 lines in same column */
5653 gotoxy(g_coord.X + 1,
5654 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5655 }
5656 else if (*p == 'C')
5657 {
5658 /* move cursor right arg1 columns in same line */
5659 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5660 g_coord.Y + 1);
5661 }
5662 else if (*p == 'H')
5663 {
5664 gotoxy(1, arg1);
5665 }
5666 else if (*p == 'L')
5667 {
5668 insert_lines(arg1);
5669 }
5670 else if (*p == 'm')
5671 {
5672 if (arg1 == 0)
5673 normvideo();
5674 else
5675 textattr((WORD) arg1);
5676 }
5677 else if (*p == 'f')
5678 {
5679 textcolor((WORD) arg1);
5680 }
5681 else if (*p == 'b')
5682 {
5683 textbackground((WORD) arg1);
5684 }
5685 else if (*p == 'M')
5686 {
5687 delete_lines(arg1);
5688 }
5689
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005690 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691 s = p + 1;
5692 break;
5693
5694
5695 /* Three-character escape sequences */
5696
5697 case 'A':
5698 /* move cursor up one line in same column */
5699 gotoxy(g_coord.X + 1,
5700 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5701 goto got3;
5702
5703 case 'B':
5704 visual_bell();
5705 goto got3;
5706
5707 case 'C':
5708 /* move cursor right one column in same line */
5709 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5710 g_coord.Y + 1);
5711 goto got3;
5712
5713 case 'E':
5714 termcap_mode_end();
5715 goto got3;
5716
5717 case 'F':
5718 standout();
5719 goto got3;
5720
5721 case 'f':
5722 standend();
5723 goto got3;
5724
5725 case 'H':
5726 gotoxy(1, 1);
5727 goto got3;
5728
5729 case 'j':
5730 clear_to_end_of_display();
5731 goto got3;
5732
5733 case 'J':
5734 clear_screen();
5735 goto got3;
5736
5737 case 'K':
5738 clear_to_end_of_line();
5739 goto got3;
5740
5741 case 'L':
5742 insert_lines(1);
5743 goto got3;
5744
5745 case 'M':
5746 delete_lines(1);
5747 goto got3;
5748
5749 case 'S':
5750 termcap_mode_start();
5751 goto got3;
5752
5753 case 'V':
5754 cursor_visible(TRUE);
5755 goto got3;
5756
5757 case 'v':
5758 cursor_visible(FALSE);
5759 goto got3;
5760
5761 got3:
5762 s += 3;
5763 len -= 2;
5764 }
5765
5766#ifdef MCH_WRITE_DUMP
5767 if (fdDump)
5768 {
5769 fputs("ESC | ", fdDump);
5770 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5771 fputc('\n', fdDump);
5772 }
5773#endif
5774 }
5775 else
5776 {
5777 /* Write a single character */
5778 DWORD nWritten;
5779
5780 nWritten = write_chars(s, 1);
5781#ifdef MCH_WRITE_DUMP
5782 if (fdDump)
5783 {
5784 fputc('>', fdDump);
5785 fwrite(s, sizeof(char_u), nWritten, fdDump);
5786 fputs("<\n", fdDump);
5787 }
5788#endif
5789
5790 len -= (nWritten - 1);
5791 s += nWritten;
5792 }
5793 }
5794
5795#ifdef MCH_WRITE_DUMP
5796 if (fdDump)
5797 fflush(fdDump);
5798#endif
5799}
5800
5801#endif /* FEAT_GUI_W32 */
5802
5803
5804/*
5805 * Delay for half a second.
5806 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005807/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808 void
5809mch_delay(
5810 long msec,
5811 int ignoreinput)
5812{
5813#ifdef FEAT_GUI_W32
5814 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005815#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005816 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005817# ifdef FEAT_MZSCHEME
5818 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5819 {
5820 int towait = p_mzq;
5821
5822 /* if msec is large enough, wait by portions in p_mzq */
5823 while (msec > 0)
5824 {
5825 mzvim_check_threads();
5826 if (msec < towait)
5827 towait = msec;
5828 Sleep(towait);
5829 msec -= towait;
5830 }
5831 }
5832 else
5833# endif
5834 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005835 else
5836 WaitForChar(msec);
5837#endif
5838}
5839
5840
5841/*
5842 * this version of remove is not scared by a readonly (backup) file
5843 * Return 0 for success, -1 for failure.
5844 */
5845 int
5846mch_remove(char_u *name)
5847{
5848#ifdef FEAT_MBYTE
5849 WCHAR *wn = NULL;
5850 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005851#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005852
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005853 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5854
5855#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5857 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005858 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005859 if (wn != NULL)
5860 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861 n = DeleteFileW(wn) ? 0 : -1;
5862 vim_free(wn);
5863 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5864 return n;
5865 /* Retry with non-wide function (for Windows 98). */
5866 }
5867 }
5868#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869 return DeleteFile(name) ? 0 : -1;
5870}
5871
5872
5873/*
5874 * check for an "interrupt signal": CTRL-break or CTRL-C
5875 */
5876 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005877mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878{
5879#ifndef FEAT_GUI_W32 /* never used */
5880 if (g_fCtrlCPressed || g_fCBrkPressed)
5881 {
5882 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5883 got_int = TRUE;
5884 }
5885#endif
5886}
5887
Bram Moolenaaree273972016-01-02 21:11:51 +01005888/* physical RAM to leave for the OS */
5889#define WINNT_RESERVE_BYTES (256*1024*1024)
5890#define WIN95_RESERVE_BYTES (8*1024*1024)
5891
5892/*
5893 * How much main memory in KiB that can be used by VIM.
5894 */
5895/*ARGSUSED*/
5896 long_u
5897mch_total_mem(int special)
5898{
5899 PlatformId();
5900#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
5901 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5902 {
5903 MEMORYSTATUSEX ms;
5904
5905 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5906 * what fits in 32 bits. But it's not always available. */
5907 ms.dwLength = sizeof(MEMORYSTATUSEX);
5908 GlobalMemoryStatusEx(&ms);
5909 if (ms.ullAvailVirtual < ms.ullTotalPhys)
5910 {
5911 /* Process address space fits in physical RAM, use all of it. */
5912 return (long_u)(ms.ullAvailVirtual / 1024);
5913 }
5914 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
5915 {
5916 /* Catch old NT box or perverse hardware setup. */
5917 return (long_u)((ms.ullTotalPhys / 2) / 1024);
5918 }
5919 /* Use physical RAM less reserve for OS + data. */
5920 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
5921 }
5922 else
5923#endif
5924 {
5925 /* Pre-XP or 95 OS handling. */
5926 MEMORYSTATUS ms;
5927 long_u os_reserve_bytes;
5928
5929 ms.dwLength = sizeof(MEMORYSTATUS);
5930 GlobalMemoryStatus(&ms);
5931 if (ms.dwAvailVirtual < ms.dwTotalPhys)
5932 {
5933 /* Process address space fits in physical RAM, use all of it. */
5934 return (long_u)(ms.dwAvailVirtual / 1024);
5935 }
5936 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
5937 ? WINNT_RESERVE_BYTES
5938 : WIN95_RESERVE_BYTES;
5939 if (ms.dwTotalPhys <= os_reserve_bytes)
5940 {
5941 /* Catch old boxes or perverse hardware setup. */
5942 return (long_u)((ms.dwTotalPhys / 2) / 1024);
5943 }
5944 /* Use physical RAM less reserve for OS + data. */
5945 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
5946 }
5947}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949#ifdef FEAT_MBYTE
5950/*
5951 * Same code as below, but with wide functions and no comments.
5952 * Return 0 for success, non-zero for failure.
5953 */
5954 int
5955mch_wrename(WCHAR *wold, WCHAR *wnew)
5956{
5957 WCHAR *p;
5958 int i;
5959 WCHAR szTempFile[_MAX_PATH + 1];
5960 WCHAR szNewPath[_MAX_PATH + 1];
5961 HANDLE hf;
5962
5963 if (!mch_windows95())
5964 {
5965 p = wold;
5966 for (i = 0; wold[i] != NUL; ++i)
5967 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5968 && wold[i + 1] != 0)
5969 p = wold + i + 1;
5970 if ((int)(wold + i - p) < 8 || p[6] != '~')
5971 return (MoveFileW(wold, wnew) == 0);
5972 }
5973
5974 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5975 return -1;
5976 *p = NUL;
5977
5978 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5979 return -2;
5980
5981 if (!DeleteFileW(szTempFile))
5982 return -3;
5983
5984 if (!MoveFileW(wold, szTempFile))
5985 return -4;
5986
5987 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5988 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5989 return -5;
5990 if (!CloseHandle(hf))
5991 return -6;
5992
5993 if (!MoveFileW(szTempFile, wnew))
5994 {
5995 (void)MoveFileW(szTempFile, wold);
5996 return -7;
5997 }
5998
5999 DeleteFileW(szTempFile);
6000
6001 if (!DeleteFileW(wold))
6002 return -8;
6003
6004 return 0;
6005}
6006#endif
6007
6008
6009/*
6010 * mch_rename() works around a bug in rename (aka MoveFile) in
6011 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6012 * file whose short file name is "FOO.BAR" (its long file name will
6013 * be correct: "foo.bar~"). Because a file can be accessed by
6014 * either its SFN or its LFN, "foo.bar" has effectively been
6015 * renamed to "foo.bar", which is not at all what was wanted. This
6016 * seems to happen only when renaming files with three-character
6017 * extensions by appending a suffix that does not include ".".
6018 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6019 *
6020 * There is another problem, which isn't really a bug but isn't right either:
6021 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6022 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6023 * service pack 6. Doesn't seem to happen on Windows 98.
6024 *
6025 * Like rename(), returns 0 upon success, non-zero upon failure.
6026 * Should probably set errno appropriately when errors occur.
6027 */
6028 int
6029mch_rename(
6030 const char *pszOldFile,
6031 const char *pszNewFile)
6032{
6033 char szTempFile[_MAX_PATH+1];
6034 char szNewPath[_MAX_PATH+1];
6035 char *pszFilePart;
6036 HANDLE hf;
6037#ifdef FEAT_MBYTE
6038 WCHAR *wold = NULL;
6039 WCHAR *wnew = NULL;
6040 int retval = -1;
6041
6042 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6043 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006044 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6045 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046 if (wold != NULL && wnew != NULL)
6047 retval = mch_wrename(wold, wnew);
6048 vim_free(wold);
6049 vim_free(wnew);
6050 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6051 return retval;
6052 /* Retry with non-wide function (for Windows 98). */
6053 }
6054#endif
6055
6056 /*
6057 * No need to play tricks if not running Windows 95, unless the file name
6058 * contains a "~" as the seventh character.
6059 */
6060 if (!mch_windows95())
6061 {
6062 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6063 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6064 return rename(pszOldFile, pszNewFile);
6065 }
6066
6067 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6068 * a directory, no error is returned and pszFilePart will be NULL. */
6069 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6070 || pszFilePart == NULL)
6071 return -1;
6072 *pszFilePart = NUL;
6073
6074 /* Get (and create) a unique temporary file name in directory of new file */
6075 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6076 return -2;
6077
6078 /* blow the temp file away */
6079 if (!DeleteFile(szTempFile))
6080 return -3;
6081
6082 /* rename old file to the temp file */
6083 if (!MoveFile(pszOldFile, szTempFile))
6084 return -4;
6085
6086 /* now create an empty file called pszOldFile; this prevents the operating
6087 * system using pszOldFile as an alias (SFN) if we're renaming within the
6088 * same directory. For example, we're editing a file called
6089 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6090 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6091 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006092 * cause all sorts of problems later in buf_write(). So, we create an
6093 * empty file called filena~1.txt and the system will have to find some
6094 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095 */
6096 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6097 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6098 return -5;
6099 if (!CloseHandle(hf))
6100 return -6;
6101
6102 /* rename the temp file to the new file */
6103 if (!MoveFile(szTempFile, pszNewFile))
6104 {
6105 /* Renaming failed. Rename the file back to its old name, so that it
6106 * looks like nothing happened. */
6107 (void)MoveFile(szTempFile, pszOldFile);
6108
6109 return -7;
6110 }
6111
6112 /* Seems to be left around on Novell filesystems */
6113 DeleteFile(szTempFile);
6114
6115 /* finally, remove the empty old file */
6116 if (!DeleteFile(pszOldFile))
6117 return -8;
6118
6119 return 0; /* success */
6120}
6121
6122/*
6123 * Get the default shell for the current hardware platform
6124 */
6125 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006126default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127{
6128 char* psz = NULL;
6129
6130 PlatformId();
6131
6132 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6133 psz = "cmd.exe";
6134 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6135 psz = "command.com";
6136
6137 return psz;
6138}
6139
6140/*
6141 * mch_access() extends access() to do more detailed check on network drives.
6142 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6143 */
6144 int
6145mch_access(char *n, int p)
6146{
6147 HANDLE hFile;
6148 DWORD am;
6149 int retval = -1; /* default: fail */
6150#ifdef FEAT_MBYTE
6151 WCHAR *wn = NULL;
6152
6153 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006154 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155#endif
6156
6157 if (mch_isdir(n))
6158 {
6159 char TempName[_MAX_PATH + 16] = "";
6160#ifdef FEAT_MBYTE
6161 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6162#endif
6163
6164 if (p & R_OK)
6165 {
6166 /* Read check is performed by seeing if we can do a find file on
6167 * the directory for any file. */
6168#ifdef FEAT_MBYTE
6169 if (wn != NULL)
6170 {
6171 int i;
6172 WIN32_FIND_DATAW d;
6173
6174 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6175 TempNameW[i] = wn[i];
6176 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6177 TempNameW[i++] = '\\';
6178 TempNameW[i++] = '*';
6179 TempNameW[i++] = 0;
6180
6181 hFile = FindFirstFileW(TempNameW, &d);
6182 if (hFile == INVALID_HANDLE_VALUE)
6183 {
6184 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6185 goto getout;
6186
6187 /* Retry with non-wide function (for Windows 98). */
6188 vim_free(wn);
6189 wn = NULL;
6190 }
6191 else
6192 (void)FindClose(hFile);
6193 }
6194 if (wn == NULL)
6195#endif
6196 {
6197 char *pch;
6198 WIN32_FIND_DATA d;
6199
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006200 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006201 pch = TempName + STRLEN(TempName) - 1;
6202 if (*pch != '\\' && *pch != '/')
6203 *++pch = '\\';
6204 *++pch = '*';
6205 *++pch = NUL;
6206
6207 hFile = FindFirstFile(TempName, &d);
6208 if (hFile == INVALID_HANDLE_VALUE)
6209 goto getout;
6210 (void)FindClose(hFile);
6211 }
6212 }
6213
6214 if (p & W_OK)
6215 {
6216 /* Trying to create a temporary file in the directory should catch
6217 * directories on read-only network shares. However, in
6218 * directories whose ACL allows writes but denies deletes will end
6219 * up keeping the temporary file :-(. */
6220#ifdef FEAT_MBYTE
6221 if (wn != NULL)
6222 {
6223 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6224 {
6225 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6226 goto getout;
6227
6228 /* Retry with non-wide function (for Windows 98). */
6229 vim_free(wn);
6230 wn = NULL;
6231 }
6232 else
6233 DeleteFileW(TempNameW);
6234 }
6235 if (wn == NULL)
6236#endif
6237 {
6238 if (!GetTempFileName(n, "VIM", 0, TempName))
6239 goto getout;
6240 mch_remove((char_u *)TempName);
6241 }
6242 }
6243 }
6244 else
6245 {
6246 /* Trying to open the file for the required access does ACL, read-only
6247 * network share, and file attribute checks. */
6248 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6249 | ((p & R_OK) ? GENERIC_READ : 0);
6250#ifdef FEAT_MBYTE
6251 if (wn != NULL)
6252 {
6253 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6254 if (hFile == INVALID_HANDLE_VALUE
6255 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6256 {
6257 /* Retry with non-wide function (for Windows 98). */
6258 vim_free(wn);
6259 wn = NULL;
6260 }
6261 }
6262 if (wn == NULL)
6263#endif
6264 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6265 if (hFile == INVALID_HANDLE_VALUE)
6266 goto getout;
6267 CloseHandle(hFile);
6268 }
6269
6270 retval = 0; /* success */
6271getout:
6272#ifdef FEAT_MBYTE
6273 vim_free(wn);
6274#endif
6275 return retval;
6276}
6277
6278#if defined(FEAT_MBYTE) || defined(PROTO)
6279/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006280 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 */
6282 int
6283mch_open(char *name, int flags, int mode)
6284{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006285 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6286# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287 WCHAR *wn;
6288 int f;
6289
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006290 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006292 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293 if (wn != NULL)
6294 {
6295 f = _wopen(wn, flags, mode);
6296 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006297 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006298 return f;
6299 /* Retry with non-wide function (for Windows 98). Can't use
6300 * GetLastError() here and it's unclear what errno gets set to if
6301 * the _wopen() fails for missing wide functions. */
6302 }
6303 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006304# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006306 /* open() can open a file which name is longer than _MAX_PATH bytes
6307 * and shorter than _MAX_PATH characters successfully, but sometimes it
6308 * causes unexpected error in another part. We make it an error explicitly
6309 * here. */
6310 if (strlen(name) >= _MAX_PATH)
6311 return -1;
6312
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 return open(name, flags, mode);
6314}
6315
6316/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006317 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318 */
6319 FILE *
6320mch_fopen(char *name, char *mode)
6321{
6322 WCHAR *wn, *wm;
6323 FILE *f = NULL;
6324
6325 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6326# ifdef __BORLANDC__
6327 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6328 && g_PlatformId == VER_PLATFORM_WIN32_NT
6329# endif
6330 )
6331 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006332# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006333 /* Work around an annoying assertion in the Microsoft debug CRT
6334 * when mode's text/binary setting doesn't match _get_fmode(). */
6335 char newMode = mode[strlen(mode) - 1];
6336 int oldMode = 0;
6337
6338 _get_fmode(&oldMode);
6339 if (newMode == 't')
6340 _set_fmode(_O_TEXT);
6341 else if (newMode == 'b')
6342 _set_fmode(_O_BINARY);
6343# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006344 wn = enc_to_utf16(name, NULL);
6345 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 if (wn != NULL && wm != NULL)
6347 f = _wfopen(wn, wm);
6348 vim_free(wn);
6349 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006350
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006351# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006352 _set_fmode(oldMode);
6353# endif
6354
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006355 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006356 return f;
6357 /* Retry with non-wide function (for Windows 98). Can't use
6358 * GetLastError() here and it's unclear what errno gets set to if
6359 * the _wfopen() fails for missing wide functions. */
6360 }
6361
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006362 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6363 * and shorter than _MAX_PATH characters successfully, but sometimes it
6364 * causes unexpected error in another part. We make it an error explicitly
6365 * here. */
6366 if (strlen(name) >= _MAX_PATH)
6367 return NULL;
6368
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369 return fopen(name, mode);
6370}
6371#endif
6372
6373#ifdef FEAT_MBYTE
6374/*
6375 * SUB STREAM (aka info stream) handling:
6376 *
6377 * NTFS can have sub streams for each file. Normal contents of file is
6378 * stored in the main stream, and extra contents (author information and
6379 * title and so on) can be stored in sub stream. After Windows 2000, user
6380 * can access and store those informations in sub streams via explorer's
6381 * property menuitem in right click menu. Those informations in sub streams
6382 * were lost when copying only the main stream. So we have to copy sub
6383 * streams.
6384 *
6385 * Incomplete explanation:
6386 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6387 * More useful info and an example:
6388 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6389 */
6390
6391/*
6392 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6393 * and write to stream "substream" of file "to".
6394 * Errors are ignored.
6395 */
6396 static void
6397copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6398{
6399 HANDLE hTo;
6400 WCHAR *to_name;
6401
6402 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6403 wcscpy(to_name, to);
6404 wcscat(to_name, substream);
6405
6406 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6407 FILE_ATTRIBUTE_NORMAL, NULL);
6408 if (hTo != INVALID_HANDLE_VALUE)
6409 {
6410 long done;
6411 DWORD todo;
6412 DWORD readcnt, written;
6413 char buf[4096];
6414
6415 /* Copy block of bytes at a time. Abort when something goes wrong. */
6416 for (done = 0; done < len; done += written)
6417 {
6418 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006419 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6420 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6422 FALSE, FALSE, context)
6423 || readcnt != todo
6424 || !WriteFile(hTo, buf, todo, &written, NULL)
6425 || written != todo)
6426 break;
6427 }
6428 CloseHandle(hTo);
6429 }
6430
6431 free(to_name);
6432}
6433
6434/*
6435 * Copy info streams from file "from" to file "to".
6436 */
6437 static void
6438copy_infostreams(char_u *from, char_u *to)
6439{
6440 WCHAR *fromw;
6441 WCHAR *tow;
6442 HANDLE sh;
6443 WIN32_STREAM_ID sid;
6444 int headersize;
6445 WCHAR streamname[_MAX_PATH];
6446 DWORD readcount;
6447 void *context = NULL;
6448 DWORD lo, hi;
6449 int len;
6450
6451 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006452 fromw = enc_to_utf16(from, NULL);
6453 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454 if (fromw != NULL && tow != NULL)
6455 {
6456 /* Open the file for reading. */
6457 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6458 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6459 if (sh != INVALID_HANDLE_VALUE)
6460 {
6461 /* Use BackupRead() to find the info streams. Repeat until we
6462 * have done them all.*/
6463 for (;;)
6464 {
6465 /* Get the header to find the length of the stream name. If
6466 * the "readcount" is zero we have done all info streams. */
6467 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006468 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6470 &readcount, FALSE, FALSE, &context)
6471 || readcount == 0)
6472 break;
6473
6474 /* We only deal with streams that have a name. The normal
6475 * file data appears to be without a name, even though docs
6476 * suggest it is called "::$DATA". */
6477 if (sid.dwStreamNameSize > 0)
6478 {
6479 /* Read the stream name. */
6480 if (!BackupRead(sh, (LPBYTE)streamname,
6481 sid.dwStreamNameSize,
6482 &readcount, FALSE, FALSE, &context))
6483 break;
6484
6485 /* Copy an info stream with a name ":anything:$DATA".
6486 * Skip "::$DATA", it has no stream name (examples suggest
6487 * it might be used for the normal file contents).
6488 * Note that BackupRead() counts bytes, but the name is in
6489 * wide characters. */
6490 len = readcount / sizeof(WCHAR);
6491 streamname[len] = 0;
6492 if (len > 7 && wcsicmp(streamname + len - 6,
6493 L":$DATA") == 0)
6494 {
6495 streamname[len - 6] = 0;
6496 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006497 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 }
6499 }
6500
6501 /* Advance to the next stream. We might try seeking too far,
6502 * but BackupSeek() doesn't skip over stream borders, thus
6503 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006504 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006505 &lo, &hi, &context);
6506 }
6507
6508 /* Clear the context. */
6509 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6510
6511 CloseHandle(sh);
6512 }
6513 }
6514 vim_free(fromw);
6515 vim_free(tow);
6516}
6517#endif
6518
6519/*
6520 * Copy file attributes from file "from" to file "to".
6521 * For Windows NT and later we copy info streams.
6522 * Always returns zero, errors are ignored.
6523 */
6524 int
6525mch_copy_file_attribute(char_u *from, char_u *to)
6526{
6527#ifdef FEAT_MBYTE
6528 /* File streams only work on Windows NT and later. */
6529 PlatformId();
6530 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6531 copy_infostreams(from, to);
6532#endif
6533 return 0;
6534}
6535
6536#if defined(MYRESETSTKOFLW) || defined(PROTO)
6537/*
6538 * Recreate a destroyed stack guard page in win32.
6539 * Written by Benjamin Peterson.
6540 */
6541
6542/* These magic numbers are from the MS header files */
6543#define MIN_STACK_WIN9X 17
6544#define MIN_STACK_WINNT 2
6545
6546/*
6547 * This function does the same thing as _resetstkoflw(), which is only
6548 * available in DevStudio .net and later.
6549 * Returns 0 for failure, 1 for success.
6550 */
6551 int
6552myresetstkoflw(void)
6553{
6554 BYTE *pStackPtr;
6555 BYTE *pGuardPage;
6556 BYTE *pStackBase;
6557 BYTE *pLowestPossiblePage;
6558 MEMORY_BASIC_INFORMATION mbi;
6559 SYSTEM_INFO si;
6560 DWORD nPageSize;
6561 DWORD dummy;
6562
6563 /* This code will not work on win32s. */
6564 PlatformId();
6565 if (g_PlatformId == VER_PLATFORM_WIN32s)
6566 return 0;
6567
6568 /* We need to know the system page size. */
6569 GetSystemInfo(&si);
6570 nPageSize = si.dwPageSize;
6571
6572 /* ...and the current stack pointer */
6573 pStackPtr = (BYTE*)_alloca(1);
6574
6575 /* ...and the base of the stack. */
6576 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6577 return 0;
6578 pStackBase = (BYTE*)mbi.AllocationBase;
6579
6580 /* ...and the page thats min_stack_req pages away from stack base; this is
6581 * the lowest page we could use. */
6582 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6583 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6584
6585 /* On Win95, we want the next page down from the end of the stack. */
6586 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6587 {
6588 /* Find the page that's only 1 page down from the page that the stack
6589 * ptr is in. */
6590 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6591 / (DWORD)nPageSize) - 1));
6592 if (pGuardPage < pLowestPossiblePage)
6593 return 0;
6594
6595 /* Apply the noaccess attribute to the page -- there's no guard
6596 * attribute in win95-type OSes. */
6597 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6598 return 0;
6599 }
6600 else
6601 {
6602 /* On NT, however, we want the first committed page in the stack Start
6603 * at the stack base and move forward through memory until we find a
6604 * committed block. */
6605 BYTE *pBlock = pStackBase;
6606
Bram Moolenaara466c992005-07-09 21:03:22 +00006607 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608 {
6609 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6610 return 0;
6611
6612 pBlock += mbi.RegionSize;
6613
6614 if (mbi.State & MEM_COMMIT)
6615 break;
6616 }
6617
6618 /* mbi now describes the first committed block in the stack. */
6619 if (mbi.Protect & PAGE_GUARD)
6620 return 1;
6621
6622 /* decide where the guard page should start */
6623 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6624 pGuardPage = pLowestPossiblePage;
6625 else
6626 pGuardPage = (BYTE*)mbi.BaseAddress;
6627
6628 /* allocate the guard page */
6629 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6630 return 0;
6631
6632 /* apply the guard attribute to the page */
6633 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6634 &dummy))
6635 return 0;
6636 }
6637
6638 return 1;
6639}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006640#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006642
6643#if defined(FEAT_MBYTE) || defined(PROTO)
6644/*
6645 * The command line arguments in UCS2
6646 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006647static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006648static LPWSTR *ArglistW = NULL;
6649static int global_argc = 0;
6650static char **global_argv;
6651
6652static int used_file_argc = 0; /* last argument in global_argv[] used
6653 for the argument list. */
6654static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6655 command line arguments added to
6656 the argument list */
6657static int used_file_count = 0; /* nr of entries in used_file_indexes */
6658static int used_file_literal = FALSE; /* take file names literally */
6659static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006660static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006661static int used_alist_count = 0;
6662
6663
6664/*
6665 * Get the command line arguments. Unicode version.
6666 * Returns argc. Zero when something fails.
6667 */
6668 int
6669get_cmd_argsW(char ***argvp)
6670{
6671 char **argv = NULL;
6672 int argc = 0;
6673 int i;
6674
Bram Moolenaar14993322014-09-09 12:25:33 +02006675 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006676 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6677 if (ArglistW != NULL)
6678 {
6679 argv = malloc((nArgsW + 1) * sizeof(char *));
6680 if (argv != NULL)
6681 {
6682 argc = nArgsW;
6683 argv[argc] = NULL;
6684 for (i = 0; i < argc; ++i)
6685 {
6686 int len;
6687
6688 /* Convert each Unicode argument to the current codepage. */
6689 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006690 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006691 (LPSTR *)&argv[i], &len, 0, 0);
6692 if (argv[i] == NULL)
6693 {
6694 /* Out of memory, clear everything. */
6695 while (i > 0)
6696 free(argv[--i]);
6697 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006698 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006699 argc = 0;
6700 }
6701 }
6702 }
6703 }
6704
6705 global_argc = argc;
6706 global_argv = argv;
6707 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006708 {
6709 if (used_file_indexes != NULL)
6710 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006711 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006712 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006713
6714 if (argvp != NULL)
6715 *argvp = argv;
6716 return argc;
6717}
6718
6719 void
6720free_cmd_argsW(void)
6721{
6722 if (ArglistW != NULL)
6723 {
6724 GlobalFree(ArglistW);
6725 ArglistW = NULL;
6726 }
6727}
6728
6729/*
6730 * Remember "name" is an argument that was added to the argument list.
6731 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6732 * is called.
6733 */
6734 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006735used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006736{
6737 int i;
6738
6739 if (used_file_indexes == NULL)
6740 return;
6741 for (i = used_file_argc + 1; i < global_argc; ++i)
6742 if (STRCMP(global_argv[i], name) == 0)
6743 {
6744 used_file_argc = i;
6745 used_file_indexes[used_file_count++] = i;
6746 break;
6747 }
6748 used_file_literal = literal;
6749 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006750 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006751}
6752
6753/*
6754 * Remember the length of the argument list as it was. If it changes then we
6755 * leave it alone when 'encoding' is set.
6756 */
6757 void
6758set_alist_count(void)
6759{
6760 used_alist_count = GARGCOUNT;
6761}
6762
6763/*
6764 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6765 * has been changed while starting up. Use the UCS-2 command line arguments
6766 * and convert them to 'encoding'.
6767 */
6768 void
6769fix_arg_enc(void)
6770{
6771 int i;
6772 int idx;
6773 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006774 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006775
6776 /* Safety checks:
6777 * - if argument count differs between the wide and non-wide argument
6778 * list, something must be wrong.
6779 * - the file name arguments must have been located.
6780 * - the length of the argument list wasn't changed by the user.
6781 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006782 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006783 || ArglistW == NULL
6784 || used_file_indexes == NULL
6785 || used_file_count == 0
6786 || used_alist_count != GARGCOUNT)
6787 return;
6788
Bram Moolenaar86b68352004-12-27 21:59:20 +00006789 /* Remember the buffer numbers for the arguments. */
6790 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6791 if (fnum_list == NULL)
6792 return; /* out of memory */
6793 for (i = 0; i < GARGCOUNT; ++i)
6794 fnum_list[i] = GARGLIST[i].ae_fnum;
6795
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006796 /* Clear the argument list. Make room for the new arguments. */
6797 alist_clear(&global_alist);
6798 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006799 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006800
6801 for (i = 0; i < used_file_count; ++i)
6802 {
6803 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006804 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006805 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006806 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006807#ifdef FEAT_DIFF
6808 /* When using diff mode may need to concatenate file name to
6809 * directory name. Just like it's done in main(). */
6810 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6811 && !mch_isdir(alist_name(&GARGLIST[0])))
6812 {
6813 char_u *r;
6814
6815 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6816 if (r != NULL)
6817 {
6818 vim_free(str);
6819 str = r;
6820 }
6821 }
6822#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006823 /* Re-use the old buffer by renaming it. When not using literal
6824 * names it's done by alist_expand() below. */
6825 if (used_file_literal)
6826 buf_set_name(fnum_list[i], str);
6827
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006828 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006829 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006830 }
6831
6832 if (!used_file_literal)
6833 {
6834 /* Now expand wildcards in the arguments. */
6835 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6836 * filename characters but are excluded from 'isfname' to make
6837 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6838 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006839 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006840 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6841 }
6842
6843 /* If wildcard expansion failed, we are editing the first file of the
6844 * arglist and there is no file name: Edit the first argument now. */
6845 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6846 {
6847 do_cmdline_cmd((char_u *)":rewind");
6848 if (GARGCOUNT == 1 && used_file_full_path)
6849 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6850 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006851
6852 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006853}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854#endif