blob: b4f5fa466646de3e770c249aa6ae9107c9d83c7c [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 Moolenaar203258c2016-01-17 22:15:16 +01003133 * return TRUE if "name" is a directory, NOT a symlink to a directory
3134 * return FALSE if "name" is not a directory
3135 * return FALSE for error
3136 */
3137 int
3138mch_isrealdir(char_u *name)
3139{
3140 return mch_isdir(name) && !mch_is_symbolic_link(name);
3141}
3142
3143/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003144 * Create directory "name".
3145 * Return 0 on success, -1 on error.
3146 */
3147 int
3148mch_mkdir(char_u *name)
3149{
3150#ifdef FEAT_MBYTE
3151 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3152 {
3153 WCHAR *p;
3154 int retval;
3155
3156 p = enc_to_utf16(name, NULL);
3157 if (p == NULL)
3158 return -1;
3159 retval = _wmkdir(p);
3160 vim_free(p);
3161 return retval;
3162 }
3163#endif
3164 return _mkdir(name);
3165}
3166
3167/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003168 * Delete directory "name".
3169 * Return 0 on success, -1 on error.
3170 */
3171 int
3172mch_rmdir(char_u *name)
3173{
3174#ifdef FEAT_MBYTE
3175 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3176 {
3177 WCHAR *p;
3178 int retval;
3179
3180 p = enc_to_utf16(name, NULL);
3181 if (p == NULL)
3182 return -1;
3183 retval = _wrmdir(p);
3184 vim_free(p);
3185 return retval;
3186 }
3187#endif
3188 return _rmdir(name);
3189}
3190
3191/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003192 * Return TRUE if file "fname" has more than one link.
3193 */
3194 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003195mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003196{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003197 BY_HANDLE_FILE_INFORMATION info;
3198
3199 return win32_fileinfo(fname, &info) == FILEINFO_OK
3200 && info.nNumberOfLinks > 1;
3201}
3202
3203/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003204 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003205 */
3206 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003207mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003208{
3209 HANDLE hFind;
3210 int res = FALSE;
3211 WIN32_FIND_DATAA findDataA;
3212 DWORD fileFlags = 0, reparseTag = 0;
3213#ifdef FEAT_MBYTE
3214 WCHAR *wn = NULL;
3215 WIN32_FIND_DATAW findDataW;
3216
3217 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003218 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003219 if (wn != NULL)
3220 {
3221 hFind = FindFirstFileW(wn, &findDataW);
3222 vim_free(wn);
3223 if (hFind == INVALID_HANDLE_VALUE
3224 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3225 {
3226 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar203258c2016-01-17 22:15:16 +01003227 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003228 if (hFind != INVALID_HANDLE_VALUE)
3229 {
3230 fileFlags = findDataA.dwFileAttributes;
3231 reparseTag = findDataA.dwReserved0;
3232 }
3233 }
3234 else
3235 {
3236 fileFlags = findDataW.dwFileAttributes;
3237 reparseTag = findDataW.dwReserved0;
3238 }
3239 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003240 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003242 {
Bram Moolenaar203258c2016-01-17 22:15:16 +01003243 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003244 if (hFind != INVALID_HANDLE_VALUE)
3245 {
3246 fileFlags = findDataA.dwFileAttributes;
3247 reparseTag = findDataA.dwReserved0;
3248 }
3249 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003250
3251 if (hFind != INVALID_HANDLE_VALUE)
3252 FindClose(hFind);
3253
3254 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003255 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3256 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003257 res = TRUE;
3258
3259 return res;
3260}
3261
3262/*
3263 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3264 * link.
3265 */
3266 int
3267mch_is_linked(char_u *fname)
3268{
3269 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3270 return TRUE;
3271 return FALSE;
3272}
3273
3274/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003275 * Get the by-handle-file-information for "fname".
3276 * Returns FILEINFO_OK when OK.
3277 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3278 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3279 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3280 */
3281 int
3282win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3283{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003284 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003285 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003286#ifdef FEAT_MBYTE
3287 WCHAR *wn = NULL;
3288
3289 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003290 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003291 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003292 if (wn == NULL)
3293 res = FILEINFO_ENC_FAIL;
3294 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003295 if (wn != NULL)
3296 {
3297 hFile = CreateFileW(wn, /* file name */
3298 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003299 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003300 NULL, /* security descriptor */
3301 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003302 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003303 NULL); /* handle to template file */
3304 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003305 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003306 {
3307 /* Retry with non-wide function (for Windows 98). */
3308 vim_free(wn);
3309 wn = NULL;
3310 }
3311 }
3312 if (wn == NULL)
3313#endif
3314 hFile = CreateFile(fname, /* file name */
3315 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003316 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003317 NULL, /* security descriptor */
3318 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003319 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003320 NULL); /* handle to template file */
3321
3322 if (hFile != INVALID_HANDLE_VALUE)
3323 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003324 if (GetFileInformationByHandle(hFile, info) != 0)
3325 res = FILEINFO_OK;
3326 else
3327 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003328 CloseHandle(hFile);
3329 }
3330
3331#ifdef FEAT_MBYTE
3332 vim_free(wn);
3333#endif
3334 return res;
3335}
3336
3337/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003338 * get file attributes for `name'
3339 * -1 : error
3340 * else FILE_ATTRIBUTE_* defined in winnt.h
3341 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003342 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003343win32_getattrs(char_u *name)
3344{
3345 int attr;
3346#ifdef FEAT_MBYTE
3347 WCHAR *p = NULL;
3348
3349 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3350 p = enc_to_utf16(name, NULL);
3351
3352 if (p != NULL)
3353 {
3354 attr = GetFileAttributesW(p);
3355 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3356 {
3357 /* Retry with non-wide function (for Windows 98). */
3358 vim_free(p);
3359 p = NULL;
3360 }
3361 }
3362 if (p == NULL)
3363#endif
3364 attr = GetFileAttributes((char *)name);
3365#ifdef FEAT_MBYTE
3366 vim_free(p);
3367#endif
3368 return attr;
3369}
3370
3371/*
3372 * set file attributes for `name' to `attrs'
3373 *
3374 * return -1 for failure, 0 otherwise
3375 */
3376 static
3377 int
3378win32_setattrs(char_u *name, int attrs)
3379{
3380 int res;
3381#ifdef FEAT_MBYTE
3382 WCHAR *p = NULL;
3383
3384 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3385 p = enc_to_utf16(name, NULL);
3386
3387 if (p != NULL)
3388 {
3389 res = SetFileAttributesW(p, attrs);
3390 if (res == FALSE
3391 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3392 {
3393 /* Retry with non-wide function (for Windows 98). */
3394 vim_free(p);
3395 p = NULL;
3396 }
3397 }
3398 if (p == NULL)
3399#endif
3400 res = SetFileAttributes((char *)name, attrs);
3401#ifdef FEAT_MBYTE
3402 vim_free(p);
3403#endif
3404 return res ? 0 : -1;
3405}
3406
3407/*
3408 * Set archive flag for "name".
3409 */
3410 static
3411 int
3412win32_set_archive(char_u *name)
3413{
3414 int attrs = win32_getattrs(name);
3415 if (attrs == -1)
3416 return -1;
3417
3418 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3419 return win32_setattrs(name, attrs);
3420}
3421
3422/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423 * Return TRUE if file or directory "name" is writable (not readonly).
3424 * Strange semantics of Win32: a readonly directory is writable, but you can't
3425 * delete a file. Let's say this means it is writable.
3426 */
3427 int
3428mch_writable(char_u *name)
3429{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003430 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003432 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3433 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434}
3435
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436/*
3437 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003438 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 * Return -1 if unknown.
3440 */
3441 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003442mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003443{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003444 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003445 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003446 char_u *p;
3447
3448 if (len >= _MAX_PATH) /* safety check */
3449 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003450 if (!use_path)
3451 {
3452 /* TODO: check if file is really executable. */
3453 return mch_getperm(name) != -1 && !mch_isdir(name);
3454 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003455
3456 /* If there already is an extension try using the name directly. Also do
3457 * this with a Unix-shell like 'shell'. */
3458 if (vim_strchr(gettail(name), '.') != NULL
3459 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003460 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003461 return TRUE;
3462
3463 /*
3464 * Loop over all extensions in $PATHEXT.
3465 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003466 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003467 p = mch_getenv("PATHEXT");
3468 if (p == NULL)
3469 p = (char_u *)".com;.exe;.bat;.cmd";
3470 while (*p)
3471 {
3472 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3473 {
3474 /* A single "." means no extension is added. */
3475 buf[len] = NUL;
3476 ++p;
3477 if (*p)
3478 ++p;
3479 }
3480 else
3481 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003482 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003483 return TRUE;
3484 }
3485 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487
3488/*
3489 * Check what "name" is:
3490 * NODE_NORMAL: file or directory (or doesn't exist)
3491 * NODE_WRITABLE: writable device, socket, fifo, etc.
3492 * NODE_OTHER: non-writable things
3493 */
3494 int
3495mch_nodetype(char_u *name)
3496{
3497 HANDLE hFile;
3498 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003499#ifdef FEAT_MBYTE
3500 WCHAR *wn = NULL;
3501#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502
Bram Moolenaar043545e2006-10-10 16:44:07 +00003503 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3504 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3505 * here. */
3506 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3507 return NODE_WRITABLE;
3508
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003509#ifdef FEAT_MBYTE
3510 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3511 {
3512 wn = enc_to_utf16(name, NULL);
3513 if (wn != NULL)
3514 {
3515 hFile = CreateFileW(wn, /* file name */
3516 GENERIC_WRITE, /* access mode */
3517 0, /* share mode */
3518 NULL, /* security descriptor */
3519 OPEN_EXISTING, /* creation disposition */
3520 0, /* file attributes */
3521 NULL); /* handle to template file */
3522 if (hFile == INVALID_HANDLE_VALUE
3523 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3524 {
3525 /* Retry with non-wide function (for Windows 98). */
3526 vim_free(wn);
3527 wn = NULL;
3528 }
3529 }
3530 }
3531 if (wn == NULL)
3532#endif
3533 hFile = CreateFile(name, /* file name */
3534 GENERIC_WRITE, /* access mode */
3535 0, /* share mode */
3536 NULL, /* security descriptor */
3537 OPEN_EXISTING, /* creation disposition */
3538 0, /* file attributes */
3539 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003541#ifdef FEAT_MBYTE
3542 vim_free(wn);
3543#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544 if (hFile == INVALID_HANDLE_VALUE)
3545 return NODE_NORMAL;
3546
3547 type = GetFileType(hFile);
3548 CloseHandle(hFile);
3549 if (type == FILE_TYPE_CHAR)
3550 return NODE_WRITABLE;
3551 if (type == FILE_TYPE_DISK)
3552 return NODE_NORMAL;
3553 return NODE_OTHER;
3554}
3555
3556#ifdef HAVE_ACL
3557struct my_acl
3558{
3559 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3560 PSID pSidOwner;
3561 PSID pSidGroup;
3562 PACL pDacl;
3563 PACL pSacl;
3564};
3565#endif
3566
3567/*
3568 * Return a pointer to the ACL of file "fname" in allocated memory.
3569 * Return NULL if the ACL is not available for whatever reason.
3570 */
3571 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003572mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003573{
3574#ifndef HAVE_ACL
3575 return (vim_acl_T)NULL;
3576#else
3577 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003578 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003579
3580 /* This only works on Windows NT and 2000. */
3581 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3582 {
3583 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3584 if (p != NULL)
3585 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003586# ifdef FEAT_MBYTE
3587 WCHAR *wn = NULL;
3588
3589 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3590 wn = enc_to_utf16(fname, NULL);
3591 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003592 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003593 /* Try to retrieve the entire security descriptor. */
3594 err = pGetNamedSecurityInfoW(
3595 wn, // Abstract filename
3596 SE_FILE_OBJECT, // File Object
3597 OWNER_SECURITY_INFORMATION |
3598 GROUP_SECURITY_INFORMATION |
3599 DACL_SECURITY_INFORMATION |
3600 SACL_SECURITY_INFORMATION,
3601 &p->pSidOwner, // Ownership information.
3602 &p->pSidGroup, // Group membership.
3603 &p->pDacl, // Discretionary information.
3604 &p->pSacl, // For auditing purposes.
3605 &p->pSecurityDescriptor);
3606 if (err == ERROR_ACCESS_DENIED ||
3607 err == ERROR_PRIVILEGE_NOT_HELD)
3608 {
3609 /* Retrieve only DACL. */
3610 (void)pGetNamedSecurityInfoW(
3611 wn,
3612 SE_FILE_OBJECT,
3613 DACL_SECURITY_INFORMATION,
3614 NULL,
3615 NULL,
3616 &p->pDacl,
3617 NULL,
3618 &p->pSecurityDescriptor);
3619 }
3620 if (p->pSecurityDescriptor == NULL)
3621 {
3622 mch_free_acl((vim_acl_T)p);
3623 p = NULL;
3624 }
3625 vim_free(wn);
3626 }
3627 else
3628# endif
3629 {
3630 /* Try to retrieve the entire security descriptor. */
3631 err = pGetNamedSecurityInfo(
3632 (LPSTR)fname, // Abstract filename
3633 SE_FILE_OBJECT, // File Object
3634 OWNER_SECURITY_INFORMATION |
3635 GROUP_SECURITY_INFORMATION |
3636 DACL_SECURITY_INFORMATION |
3637 SACL_SECURITY_INFORMATION,
3638 &p->pSidOwner, // Ownership information.
3639 &p->pSidGroup, // Group membership.
3640 &p->pDacl, // Discretionary information.
3641 &p->pSacl, // For auditing purposes.
3642 &p->pSecurityDescriptor);
3643 if (err == ERROR_ACCESS_DENIED ||
3644 err == ERROR_PRIVILEGE_NOT_HELD)
3645 {
3646 /* Retrieve only DACL. */
3647 (void)pGetNamedSecurityInfo(
3648 (LPSTR)fname,
3649 SE_FILE_OBJECT,
3650 DACL_SECURITY_INFORMATION,
3651 NULL,
3652 NULL,
3653 &p->pDacl,
3654 NULL,
3655 &p->pSecurityDescriptor);
3656 }
3657 if (p->pSecurityDescriptor == NULL)
3658 {
3659 mch_free_acl((vim_acl_T)p);
3660 p = NULL;
3661 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003662 }
3663 }
3664 }
3665
3666 return (vim_acl_T)p;
3667#endif
3668}
3669
Bram Moolenaar27515922013-06-29 15:36:26 +02003670#ifdef HAVE_ACL
3671/*
3672 * Check if "acl" contains inherited ACE.
3673 */
3674 static BOOL
3675is_acl_inherited(PACL acl)
3676{
3677 DWORD i;
3678 ACL_SIZE_INFORMATION acl_info;
3679 PACCESS_ALLOWED_ACE ace;
3680
3681 acl_info.AceCount = 0;
3682 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3683 for (i = 0; i < acl_info.AceCount; i++)
3684 {
3685 GetAce(acl, i, (LPVOID *)&ace);
3686 if (ace->Header.AceFlags & INHERITED_ACE)
3687 return TRUE;
3688 }
3689 return FALSE;
3690}
3691#endif
3692
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693/*
3694 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3695 * Errors are ignored.
3696 * This must only be called with "acl" equal to what mch_get_acl() returned.
3697 */
3698 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003699mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700{
3701#ifdef HAVE_ACL
3702 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003703 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704
3705 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003706 {
3707# ifdef FEAT_MBYTE
3708 WCHAR *wn = NULL;
3709# endif
3710
3711 /* Set security flags */
3712 if (p->pSidOwner)
3713 sec_info |= OWNER_SECURITY_INFORMATION;
3714 if (p->pSidGroup)
3715 sec_info |= GROUP_SECURITY_INFORMATION;
3716 if (p->pDacl)
3717 {
3718 sec_info |= DACL_SECURITY_INFORMATION;
3719 /* Do not inherit its parent's DACL.
3720 * If the DACL is inherited, Cygwin permissions would be changed.
3721 */
3722 if (!is_acl_inherited(p->pDacl))
3723 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3724 }
3725 if (p->pSacl)
3726 sec_info |= SACL_SECURITY_INFORMATION;
3727
3728# ifdef FEAT_MBYTE
3729 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3730 wn = enc_to_utf16(fname, NULL);
3731 if (wn != NULL)
3732 {
3733 (void)pSetNamedSecurityInfoW(
3734 wn, // Abstract filename
3735 SE_FILE_OBJECT, // File Object
3736 sec_info,
3737 p->pSidOwner, // Ownership information.
3738 p->pSidGroup, // Group membership.
3739 p->pDacl, // Discretionary information.
3740 p->pSacl // For auditing purposes.
3741 );
3742 vim_free(wn);
3743 }
3744 else
3745# endif
3746 {
3747 (void)pSetNamedSecurityInfo(
3748 (LPSTR)fname, // Abstract filename
3749 SE_FILE_OBJECT, // File Object
3750 sec_info,
3751 p->pSidOwner, // Ownership information.
3752 p->pSidGroup, // Group membership.
3753 p->pDacl, // Discretionary information.
3754 p->pSacl // For auditing purposes.
3755 );
3756 }
3757 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758#endif
3759}
3760
3761 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003762mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003763{
3764#ifdef HAVE_ACL
3765 struct my_acl *p = (struct my_acl *)acl;
3766
3767 if (p != NULL)
3768 {
3769 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3770 vim_free(p);
3771 }
3772#endif
3773}
3774
3775#ifndef FEAT_GUI_W32
3776
3777/*
3778 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3779 */
3780 static BOOL WINAPI
3781handler_routine(
3782 DWORD dwCtrlType)
3783{
3784 switch (dwCtrlType)
3785 {
3786 case CTRL_C_EVENT:
3787 if (ctrl_c_interrupts)
3788 g_fCtrlCPressed = TRUE;
3789 return TRUE;
3790
3791 case CTRL_BREAK_EVENT:
3792 g_fCBrkPressed = TRUE;
3793 return TRUE;
3794
3795 /* fatal events: shut down gracefully */
3796 case CTRL_CLOSE_EVENT:
3797 case CTRL_LOGOFF_EVENT:
3798 case CTRL_SHUTDOWN_EVENT:
3799 windgoto((int)Rows - 1, 0);
3800 g_fForceExit = TRUE;
3801
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003802 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803 (dwCtrlType == CTRL_CLOSE_EVENT
3804 ? _("close")
3805 : dwCtrlType == CTRL_LOGOFF_EVENT
3806 ? _("logoff")
3807 : _("shutdown")));
3808#ifdef DEBUG
3809 OutputDebugString(IObuff);
3810#endif
3811
3812 preserve_exit(); /* output IObuff, preserve files and exit */
3813
3814 return TRUE; /* not reached */
3815
3816 default:
3817 return FALSE;
3818 }
3819}
3820
3821
3822/*
3823 * set the tty in (raw) ? "raw" : "cooked" mode
3824 */
3825 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003826mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827{
3828 DWORD cmodein;
3829 DWORD cmodeout;
3830 BOOL bEnableHandler;
3831
3832 GetConsoleMode(g_hConIn, &cmodein);
3833 GetConsoleMode(g_hConOut, &cmodeout);
3834 if (tmode == TMODE_RAW)
3835 {
3836 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3837 ENABLE_ECHO_INPUT);
3838#ifdef FEAT_MOUSE
3839 if (g_fMouseActive)
3840 cmodein |= ENABLE_MOUSE_INPUT;
3841#endif
3842 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3843 bEnableHandler = TRUE;
3844 }
3845 else /* cooked */
3846 {
3847 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3848 ENABLE_ECHO_INPUT);
3849 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3850 bEnableHandler = FALSE;
3851 }
3852 SetConsoleMode(g_hConIn, cmodein);
3853 SetConsoleMode(g_hConOut, cmodeout);
3854 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3855
3856#ifdef MCH_WRITE_DUMP
3857 if (fdDump)
3858 {
3859 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3860 tmode == TMODE_RAW ? "raw" :
3861 tmode == TMODE_COOK ? "cooked" : "normal",
3862 cmodein, cmodeout);
3863 fflush(fdDump);
3864 }
3865#endif
3866}
3867
3868
3869/*
3870 * Get the size of the current window in `Rows' and `Columns'
3871 * Return OK when size could be determined, FAIL otherwise.
3872 */
3873 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003874mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003875{
3876 CONSOLE_SCREEN_BUFFER_INFO csbi;
3877
3878 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3879 {
3880 /*
3881 * For some reason, we are trying to get the screen dimensions
3882 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3883 * variables are really intended to mean the size of Vim screen
3884 * while in termcap mode.
3885 */
3886 Rows = g_cbTermcap.Info.dwSize.Y;
3887 Columns = g_cbTermcap.Info.dwSize.X;
3888 }
3889 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3890 {
3891 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3892 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3893 }
3894 else
3895 {
3896 Rows = 25;
3897 Columns = 80;
3898 }
3899 return OK;
3900}
3901
3902/*
3903 * Set a console window to `xSize' * `ySize'
3904 */
3905 static void
3906ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003907 HANDLE hConsole,
3908 int xSize,
3909 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003910{
3911 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3912 SMALL_RECT srWindowRect; /* hold the new console size */
3913 COORD coordScreen;
3914
3915#ifdef MCH_WRITE_DUMP
3916 if (fdDump)
3917 {
3918 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3919 fflush(fdDump);
3920 }
3921#endif
3922
3923 /* get the largest size we can size the console window to */
3924 coordScreen = GetLargestConsoleWindowSize(hConsole);
3925
3926 /* define the new console window size and scroll position */
3927 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3928 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3929 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3930
3931 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3932 {
3933 int sx, sy;
3934
3935 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3936 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3937 if (sy < ySize || sx < xSize)
3938 {
3939 /*
3940 * Increasing number of lines/columns, do buffer first.
3941 * Use the maximal size in x and y direction.
3942 */
3943 if (sy < ySize)
3944 coordScreen.Y = ySize;
3945 else
3946 coordScreen.Y = sy;
3947 if (sx < xSize)
3948 coordScreen.X = xSize;
3949 else
3950 coordScreen.X = sx;
3951 SetConsoleScreenBufferSize(hConsole, coordScreen);
3952 }
3953 }
3954
3955 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3956 {
3957#ifdef MCH_WRITE_DUMP
3958 if (fdDump)
3959 {
3960 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3961 GetLastError());
3962 fflush(fdDump);
3963 }
3964#endif
3965 }
3966
3967 /* define the new console buffer size */
3968 coordScreen.X = xSize;
3969 coordScreen.Y = ySize;
3970
3971 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3972 {
3973#ifdef MCH_WRITE_DUMP
3974 if (fdDump)
3975 {
3976 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3977 GetLastError());
3978 fflush(fdDump);
3979 }
3980#endif
3981 }
3982}
3983
3984
3985/*
3986 * Set the console window to `Rows' * `Columns'
3987 */
3988 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003989mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003990{
3991 COORD coordScreen;
3992
3993 /* Don't change window size while still starting up */
3994 if (suppress_winsize != 0)
3995 {
3996 suppress_winsize = 2;
3997 return;
3998 }
3999
4000 if (term_console)
4001 {
4002 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4003
4004 /* Clamp Rows and Columns to reasonable values */
4005 if (Rows > coordScreen.Y)
4006 Rows = coordScreen.Y;
4007 if (Columns > coordScreen.X)
4008 Columns = coordScreen.X;
4009
4010 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4011 }
4012}
4013
4014/*
4015 * Rows and/or Columns has changed.
4016 */
4017 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004018mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004019{
4020 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4021}
4022
4023
4024/*
4025 * Called when started up, to set the winsize that was delayed.
4026 */
4027 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004028mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004029{
4030 if (suppress_winsize == 2)
4031 {
4032 suppress_winsize = 0;
4033 mch_set_shellsize();
4034 shell_resized();
4035 }
4036 suppress_winsize = 0;
4037}
4038#endif /* FEAT_GUI_W32 */
4039
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004040 static BOOL
4041vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004042 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004043 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004044 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004045 STARTUPINFO *si,
4046 PROCESS_INFORMATION *pi)
4047{
4048# ifdef FEAT_MBYTE
4049 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4050 {
4051 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4052
4053 if (wcmd != NULL)
4054 {
4055 BOOL ret;
4056 ret = CreateProcessW(
4057 NULL, /* Executable name */
4058 wcmd, /* Command to execute */
4059 NULL, /* Process security attributes */
4060 NULL, /* Thread security attributes */
4061 inherit_handles, /* Inherit handles */
4062 flags, /* Creation flags */
4063 NULL, /* Environment */
4064 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004065 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004066 pi); /* Process information */
4067 vim_free(wcmd);
4068 return ret;
4069 }
4070 }
4071#endif
4072 return CreateProcess(
4073 NULL, /* Executable name */
4074 cmd, /* Command to execute */
4075 NULL, /* Process security attributes */
4076 NULL, /* Thread security attributes */
4077 inherit_handles, /* Inherit handles */
4078 flags, /* Creation flags */
4079 NULL, /* Environment */
4080 NULL, /* Current directory */
4081 si, /* Startup information */
4082 pi); /* Process information */
4083}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084
4085
4086#if defined(FEAT_GUI_W32) || defined(PROTO)
4087
4088/*
4089 * Specialised version of system() for Win32 GUI mode.
4090 * This version proceeds as follows:
4091 * 1. Create a console window for use by the subprocess
4092 * 2. Run the subprocess (it gets the allocated console by default)
4093 * 3. Wait for the subprocess to terminate and get its exit code
4094 * 4. Prompt the user to press a key to close the console window
4095 */
4096 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004097mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004098{
4099 STARTUPINFO si;
4100 PROCESS_INFORMATION pi;
4101 DWORD ret = 0;
4102 HWND hwnd = GetFocus();
4103
4104 si.cb = sizeof(si);
4105 si.lpReserved = NULL;
4106 si.lpDesktop = NULL;
4107 si.lpTitle = NULL;
4108 si.dwFlags = STARTF_USESHOWWINDOW;
4109 /*
4110 * It's nicer to run a filter command in a minimized window, but in
4111 * Windows 95 this makes the command MUCH slower. We can't do it under
4112 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004113 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 */
4115 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004116 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117 else
4118 si.wShowWindow = SW_SHOWNORMAL;
4119 si.cbReserved2 = 0;
4120 si.lpReserved2 = NULL;
4121
4122 /* There is a strange error on Windows 95 when using "c:\\command.com".
4123 * When the "c:\\" is left out it works OK...? */
4124 if (mch_windows95()
4125 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4126 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4127 cmd += 3;
4128
4129 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004130 vim_create_process(cmd, FALSE,
4131 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132
4133 /* Wait for the command to terminate before continuing */
4134 if (g_PlatformId != VER_PLATFORM_WIN32s)
4135 {
4136#ifdef FEAT_GUI
4137 int delay = 1;
4138
4139 /* Keep updating the window while waiting for the shell to finish. */
4140 for (;;)
4141 {
4142 MSG msg;
4143
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004144 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145 {
4146 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004147 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004148 delay = 1;
4149 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150 }
4151 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4152 break;
4153
4154 /* We start waiting for a very short time and then increase it, so
4155 * that we respond quickly when the process is quick, and don't
4156 * consume too much overhead when it's slow. */
4157 if (delay < 50)
4158 delay += 10;
4159 }
4160#else
4161 WaitForSingleObject(pi.hProcess, INFINITE);
4162#endif
4163
4164 /* Get the command exit code */
4165 GetExitCodeProcess(pi.hProcess, &ret);
4166 }
4167 else
4168 {
4169 /*
4170 * This ugly code is the only quick way of performing
4171 * a synchronous spawn under Win32s. Yuk.
4172 */
4173 num_windows = 0;
4174 EnumWindows(win32ssynch_cb, 0);
4175 old_num_windows = num_windows;
4176 do
4177 {
4178 Sleep(1000);
4179 num_windows = 0;
4180 EnumWindows(win32ssynch_cb, 0);
4181 } while (num_windows == old_num_windows);
4182 ret = 0;
4183 }
4184
4185 /* Close the handles to the subprocess, so that it goes away */
4186 CloseHandle(pi.hThread);
4187 CloseHandle(pi.hProcess);
4188
4189 /* Try to get input focus back. Doesn't always work though. */
4190 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4191
4192 return ret;
4193}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004194
4195/*
4196 * Thread launched by the gui to send the current buffer data to the
4197 * process. This way avoid to hang up vim totally if the children
4198 * process take a long time to process the lines.
4199 */
4200 static DWORD WINAPI
4201sub_process_writer(LPVOID param)
4202{
4203 HANDLE g_hChildStd_IN_Wr = param;
4204 linenr_T lnum = curbuf->b_op_start.lnum;
4205 DWORD len = 0;
4206 DWORD l;
4207 char_u *lp = ml_get(lnum);
4208 char_u *s;
4209 int written = 0;
4210
4211 for (;;)
4212 {
4213 l = (DWORD)STRLEN(lp + written);
4214 if (l == 0)
4215 len = 0;
4216 else if (lp[written] == NL)
4217 {
4218 /* NL -> NUL translation */
4219 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4220 }
4221 else
4222 {
4223 s = vim_strchr(lp + written, NL);
4224 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4225 s == NULL ? l : (DWORD)(s - (lp + written)),
4226 &len, NULL);
4227 }
4228 if (len == (int)l)
4229 {
4230 /* Finished a line, add a NL, unless this line should not have
4231 * one. */
4232 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004233 || (!curbuf->b_p_bin
4234 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004235 || (lnum != curbuf->b_no_eol_lnum
4236 && (lnum != curbuf->b_ml.ml_line_count
4237 || curbuf->b_p_eol)))
4238 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004239 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004240 }
4241
4242 ++lnum;
4243 if (lnum > curbuf->b_op_end.lnum)
4244 break;
4245
4246 lp = ml_get(lnum);
4247 written = 0;
4248 }
4249 else if (len > 0)
4250 written += len;
4251 }
4252
4253 /* finished all the lines, close pipe */
4254 CloseHandle(g_hChildStd_IN_Wr);
4255 ExitThread(0);
4256}
4257
4258
4259# define BUFLEN 100 /* length for buffer, stolen from unix version */
4260
4261/*
4262 * This function read from the children's stdout and write the
4263 * data on screen or in the buffer accordingly.
4264 */
4265 static void
4266dump_pipe(int options,
4267 HANDLE g_hChildStd_OUT_Rd,
4268 garray_T *ga,
4269 char_u buffer[],
4270 DWORD *buffer_off)
4271{
4272 DWORD availableBytes = 0;
4273 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004274 int ret;
4275 DWORD len;
4276 DWORD toRead;
4277 int repeatCount;
4278
4279 /* we query the pipe to see if there is any data to read
4280 * to avoid to perform a blocking read */
4281 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4282 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004283 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004284 NULL, /* number of read bytes */
4285 &availableBytes, /* available bytes total */
4286 NULL); /* byteLeft */
4287
4288 repeatCount = 0;
4289 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004290 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004291 {
4292 repeatCount++;
4293 toRead =
4294# ifdef FEAT_MBYTE
4295 (DWORD)(BUFLEN - *buffer_off);
4296# else
4297 (DWORD)BUFLEN;
4298# endif
4299 toRead = availableBytes < toRead ? availableBytes : toRead;
4300 ReadFile(g_hChildStd_OUT_Rd, buffer
4301# ifdef FEAT_MBYTE
4302 + *buffer_off, toRead
4303# else
4304 , toRead
4305# endif
4306 , &len, NULL);
4307
4308 /* If we haven't read anything, there is a problem */
4309 if (len == 0)
4310 break;
4311
4312 availableBytes -= len;
4313
4314 if (options & SHELL_READ)
4315 {
4316 /* Do NUL -> NL translation, append NL separated
4317 * lines to the current buffer. */
4318 for (i = 0; i < len; ++i)
4319 {
4320 if (buffer[i] == NL)
4321 append_ga_line(ga);
4322 else if (buffer[i] == NUL)
4323 ga_append(ga, NL);
4324 else
4325 ga_append(ga, buffer[i]);
4326 }
4327 }
4328# ifdef FEAT_MBYTE
4329 else if (has_mbyte)
4330 {
4331 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004332 int c;
4333 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004334
4335 len += *buffer_off;
4336 buffer[len] = NUL;
4337
4338 /* Check if the last character in buffer[] is
4339 * incomplete, keep these bytes for the next
4340 * round. */
4341 for (p = buffer; p < buffer + len; p += l)
4342 {
4343 l = mb_cptr2len(p);
4344 if (l == 0)
4345 l = 1; /* NUL byte? */
4346 else if (MB_BYTE2LEN(*p) != l)
4347 break;
4348 }
4349 if (p == buffer) /* no complete character */
4350 {
4351 /* avoid getting stuck at an illegal byte */
4352 if (len >= 12)
4353 ++p;
4354 else
4355 {
4356 *buffer_off = len;
4357 return;
4358 }
4359 }
4360 c = *p;
4361 *p = NUL;
4362 msg_puts(buffer);
4363 if (p < buffer + len)
4364 {
4365 *p = c;
4366 *buffer_off = (DWORD)((buffer + len) - p);
4367 mch_memmove(buffer, p, *buffer_off);
4368 return;
4369 }
4370 *buffer_off = 0;
4371 }
4372# endif /* FEAT_MBYTE */
4373 else
4374 {
4375 buffer[len] = NUL;
4376 msg_puts(buffer);
4377 }
4378
4379 windgoto(msg_row, msg_col);
4380 cursor_on();
4381 out_flush();
4382 }
4383}
4384
4385/*
4386 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4387 * for communication and doesn't open any new window.
4388 */
4389 static int
4390mch_system_piped(char *cmd, int options)
4391{
4392 STARTUPINFO si;
4393 PROCESS_INFORMATION pi;
4394 DWORD ret = 0;
4395
4396 HANDLE g_hChildStd_IN_Rd = NULL;
4397 HANDLE g_hChildStd_IN_Wr = NULL;
4398 HANDLE g_hChildStd_OUT_Rd = NULL;
4399 HANDLE g_hChildStd_OUT_Wr = NULL;
4400
4401 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4402 DWORD len;
4403
4404 /* buffer used to receive keys */
4405 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4406 int ta_len = 0; /* valid bytes in ta_buf[] */
4407
4408 DWORD i;
4409 int c;
4410 int noread_cnt = 0;
4411 garray_T ga;
4412 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004413 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004414 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004415
4416 SECURITY_ATTRIBUTES saAttr;
4417
4418 /* Set the bInheritHandle flag so pipe handles are inherited. */
4419 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4420 saAttr.bInheritHandle = TRUE;
4421 saAttr.lpSecurityDescriptor = NULL;
4422
4423 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4424 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4425 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4426 /* Create a pipe for the child process's STDIN. */
4427 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4428 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4429 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4430 {
4431 CloseHandle(g_hChildStd_IN_Rd);
4432 CloseHandle(g_hChildStd_IN_Wr);
4433 CloseHandle(g_hChildStd_OUT_Rd);
4434 CloseHandle(g_hChildStd_OUT_Wr);
4435 MSG_PUTS(_("\nCannot create pipes\n"));
4436 }
4437
4438 si.cb = sizeof(si);
4439 si.lpReserved = NULL;
4440 si.lpDesktop = NULL;
4441 si.lpTitle = NULL;
4442 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4443
4444 /* set-up our file redirection */
4445 si.hStdError = g_hChildStd_OUT_Wr;
4446 si.hStdOutput = g_hChildStd_OUT_Wr;
4447 si.hStdInput = g_hChildStd_IN_Rd;
4448 si.wShowWindow = SW_HIDE;
4449 si.cbReserved2 = 0;
4450 si.lpReserved2 = NULL;
4451
4452 if (options & SHELL_READ)
4453 ga_init2(&ga, 1, BUFLEN);
4454
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004455 if (cmd != NULL)
4456 {
4457 p = (char *)vim_strsave((char_u *)cmd);
4458 if (p != NULL)
4459 unescape_shellxquote((char_u *)p, p_sxe);
4460 else
4461 p = cmd;
4462 }
4463
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004464 /* Now, run the command.
4465 * About "Inherit handles" being TRUE: this command can be litigious,
4466 * handle inheritance was deactivated for pending temp file, but, if we
4467 * deactivate it, the pipes don't work for some reason. */
4468 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004469
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004470 if (p != cmd)
4471 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004472
4473 /* Close our unused side of the pipes */
4474 CloseHandle(g_hChildStd_IN_Rd);
4475 CloseHandle(g_hChildStd_OUT_Wr);
4476
4477 if (options & SHELL_WRITE)
4478 {
4479 HANDLE thread =
4480 CreateThread(NULL, /* security attributes */
4481 0, /* default stack size */
4482 sub_process_writer, /* function to be executed */
4483 g_hChildStd_IN_Wr, /* parameter */
4484 0, /* creation flag, start immediately */
4485 NULL); /* we don't care about thread id */
4486 CloseHandle(thread);
4487 g_hChildStd_IN_Wr = NULL;
4488 }
4489
4490 /* Keep updating the window while waiting for the shell to finish. */
4491 for (;;)
4492 {
4493 MSG msg;
4494
Bram Moolenaar175d0702013-12-11 18:36:33 +01004495 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004496 {
4497 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004498 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004499 }
4500
4501 /* write pipe information in the window */
4502 if ((options & (SHELL_READ|SHELL_WRITE))
4503# ifdef FEAT_GUI
4504 || gui.in_use
4505# endif
4506 )
4507 {
4508 len = 0;
4509 if (!(options & SHELL_EXPAND)
4510 && ((options &
4511 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4512 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4513# ifdef FEAT_GUI
4514 || gui.in_use
4515# endif
4516 )
4517 && (ta_len > 0 || noread_cnt > 4))
4518 {
4519 if (ta_len == 0)
4520 {
4521 /* Get extra characters when we don't have any. Reset the
4522 * counter and timer. */
4523 noread_cnt = 0;
4524# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4525 gettimeofday(&start_tv, NULL);
4526# endif
4527 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4528 }
4529 if (ta_len > 0 || len > 0)
4530 {
4531 /*
4532 * For pipes: Check for CTRL-C: send interrupt signal to
4533 * child. Check for CTRL-D: EOF, close pipe to child.
4534 */
4535 if (len == 1 && cmd != NULL)
4536 {
4537 if (ta_buf[ta_len] == Ctrl_C)
4538 {
4539 /* Learn what exit code is expected, for
4540 * now put 9 as SIGKILL */
4541 TerminateProcess(pi.hProcess, 9);
4542 }
4543 if (ta_buf[ta_len] == Ctrl_D)
4544 {
4545 CloseHandle(g_hChildStd_IN_Wr);
4546 g_hChildStd_IN_Wr = NULL;
4547 }
4548 }
4549
4550 /* replace K_BS by <BS> and K_DEL by <DEL> */
4551 for (i = ta_len; i < ta_len + len; ++i)
4552 {
4553 if (ta_buf[i] == CSI && len - i > 2)
4554 {
4555 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4556 if (c == K_DEL || c == K_KDEL || c == K_BS)
4557 {
4558 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4559 (size_t)(len - i - 2));
4560 if (c == K_DEL || c == K_KDEL)
4561 ta_buf[i] = DEL;
4562 else
4563 ta_buf[i] = Ctrl_H;
4564 len -= 2;
4565 }
4566 }
4567 else if (ta_buf[i] == '\r')
4568 ta_buf[i] = '\n';
4569# ifdef FEAT_MBYTE
4570 if (has_mbyte)
4571 i += (*mb_ptr2len_len)(ta_buf + i,
4572 ta_len + len - i) - 1;
4573# endif
4574 }
4575
4576 /*
4577 * For pipes: echo the typed characters. For a pty this
4578 * does not seem to work.
4579 */
4580 for (i = ta_len; i < ta_len + len; ++i)
4581 {
4582 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4583 msg_putchar(ta_buf[i]);
4584# ifdef FEAT_MBYTE
4585 else if (has_mbyte)
4586 {
4587 int l = (*mb_ptr2len)(ta_buf + i);
4588
4589 msg_outtrans_len(ta_buf + i, l);
4590 i += l - 1;
4591 }
4592# endif
4593 else
4594 msg_outtrans_len(ta_buf + i, 1);
4595 }
4596 windgoto(msg_row, msg_col);
4597 out_flush();
4598
4599 ta_len += len;
4600
4601 /*
4602 * Write the characters to the child, unless EOF has been
4603 * typed for pipes. Write one character at a time, to
4604 * avoid losing too much typeahead. When writing buffer
4605 * lines, drop the typed characters (only check for
4606 * CTRL-C).
4607 */
4608 if (options & SHELL_WRITE)
4609 ta_len = 0;
4610 else if (g_hChildStd_IN_Wr != NULL)
4611 {
4612 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4613 1, &len, NULL);
4614 // if we are typing in, we want to keep things reactive
4615 delay = 1;
4616 if (len > 0)
4617 {
4618 ta_len -= len;
4619 mch_memmove(ta_buf, ta_buf + len, ta_len);
4620 }
4621 }
4622 }
4623 }
4624 }
4625
4626 if (ta_len)
4627 ui_inchar_undo(ta_buf, ta_len);
4628
4629 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4630 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004631 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004632 break;
4633 }
4634
4635 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004636 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004637
4638 /* We start waiting for a very short time and then increase it, so
4639 * that we respond quickly when the process is quick, and don't
4640 * consume too much overhead when it's slow. */
4641 if (delay < 50)
4642 delay += 10;
4643 }
4644
4645 /* Close the pipe */
4646 CloseHandle(g_hChildStd_OUT_Rd);
4647 if (g_hChildStd_IN_Wr != NULL)
4648 CloseHandle(g_hChildStd_IN_Wr);
4649
4650 WaitForSingleObject(pi.hProcess, INFINITE);
4651
4652 /* Get the command exit code */
4653 GetExitCodeProcess(pi.hProcess, &ret);
4654
4655 if (options & SHELL_READ)
4656 {
4657 if (ga.ga_len > 0)
4658 {
4659 append_ga_line(&ga);
4660 /* remember that the NL was missing */
4661 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4662 }
4663 else
4664 curbuf->b_no_eol_lnum = 0;
4665 ga_clear(&ga);
4666 }
4667
4668 /* Close the handles to the subprocess, so that it goes away */
4669 CloseHandle(pi.hThread);
4670 CloseHandle(pi.hProcess);
4671
4672 return ret;
4673}
4674
4675 static int
4676mch_system(char *cmd, int options)
4677{
4678 /* if we can pipe and the shelltemp option is off */
4679 if (allowPiping && !p_stmp)
4680 return mch_system_piped(cmd, options);
4681 else
4682 return mch_system_classic(cmd, options);
4683}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004684#else
4685
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004686# ifdef FEAT_MBYTE
4687 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004688mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004689{
4690 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4691 {
4692 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4693 if (wcmd != NULL)
4694 {
4695 int ret = _wsystem(wcmd);
4696 vim_free(wcmd);
4697 return ret;
4698 }
4699 }
4700 return system(cmd);
4701}
4702# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004703# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004704# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004705
4706#endif
4707
4708/*
4709 * Either execute a command by calling the shell or start a new shell
4710 */
4711 int
4712mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004713 char_u *cmd,
4714 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004715{
4716 int x = 0;
4717 int tmode = cur_tmode;
4718#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004719 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004720# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004721 int did_set_title = FALSE;
4722
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004723 /* Change the title to reflect that we are in a subshell. */
4724 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4725 {
4726 WCHAR szShellTitle[512];
4727
4728 if (GetConsoleTitleW(szShellTitle,
4729 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4730 {
4731 if (cmd == NULL)
4732 wcscat(szShellTitle, L" :sh");
4733 else
4734 {
4735 WCHAR *wn = enc_to_utf16(cmd, NULL);
4736
4737 if (wn != NULL)
4738 {
4739 wcscat(szShellTitle, L" - !");
4740 if ((wcslen(szShellTitle) + wcslen(wn) <
4741 sizeof(szShellTitle)/sizeof(WCHAR)))
4742 wcscat(szShellTitle, wn);
4743 SetConsoleTitleW(szShellTitle);
4744 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004745 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004746 }
4747 }
4748 }
4749 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004750 if (!did_set_title)
4751# endif
4752 /* Change the title to reflect that we are in a subshell. */
4753 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004755 if (cmd == NULL)
4756 strcat(szShellTitle, " :sh");
4757 else
4758 {
4759 strcat(szShellTitle, " - !");
4760 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4761 strcat(szShellTitle, cmd);
4762 }
4763 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004764 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765#endif
4766
4767 out_flush();
4768
4769#ifdef MCH_WRITE_DUMP
4770 if (fdDump)
4771 {
4772 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4773 fflush(fdDump);
4774 }
4775#endif
4776
4777 /*
4778 * Catch all deadly signals while running the external command, because a
4779 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4780 */
4781 signal(SIGINT, SIG_IGN);
4782#if defined(__GNUC__) && !defined(__MINGW32__)
4783 signal(SIGKILL, SIG_IGN);
4784#else
4785 signal(SIGBREAK, SIG_IGN);
4786#endif
4787 signal(SIGILL, SIG_IGN);
4788 signal(SIGFPE, SIG_IGN);
4789 signal(SIGSEGV, SIG_IGN);
4790 signal(SIGTERM, SIG_IGN);
4791 signal(SIGABRT, SIG_IGN);
4792
4793 if (options & SHELL_COOKED)
4794 settmode(TMODE_COOK); /* set to normal mode */
4795
4796 if (cmd == NULL)
4797 {
4798 x = mch_system(p_sh, options);
4799 }
4800 else
4801 {
4802 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004803 char_u *newcmd = NULL;
4804 char_u *cmdbase = cmd;
4805 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004806
4807 /* Skip a leading ", ( and "(. */
4808 if (*cmdbase == '"' )
4809 ++cmdbase;
4810 if (*cmdbase == '(')
4811 ++cmdbase;
4812
4813 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4814 {
4815 STARTUPINFO si;
4816 PROCESS_INFORMATION pi;
4817 DWORD flags = CREATE_NEW_CONSOLE;
4818 char_u *p;
4819
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004820 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004821 si.cb = sizeof(si);
4822 si.lpReserved = NULL;
4823 si.lpDesktop = NULL;
4824 si.lpTitle = NULL;
4825 si.dwFlags = 0;
4826 si.cbReserved2 = 0;
4827 si.lpReserved2 = NULL;
4828
4829 cmdbase = skipwhite(cmdbase + 5);
4830 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4831 && vim_iswhite(cmdbase[4]))
4832 {
4833 cmdbase = skipwhite(cmdbase + 4);
4834 si.dwFlags = STARTF_USESHOWWINDOW;
4835 si.wShowWindow = SW_SHOWMINNOACTIVE;
4836 }
4837 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4838 && vim_iswhite(cmdbase[2]))
4839 {
4840 cmdbase = skipwhite(cmdbase + 2);
4841 flags = CREATE_NO_WINDOW;
4842 si.dwFlags = STARTF_USESTDHANDLES;
4843 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004844 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004845 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004846 NULL, // Security att.
4847 OPEN_EXISTING, // Open flags
4848 FILE_ATTRIBUTE_NORMAL, // File att.
4849 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004850 si.hStdOutput = si.hStdInput;
4851 si.hStdError = si.hStdInput;
4852 }
4853
4854 /* Remove a trailing ", ) and )" if they have a match
4855 * at the start of the command. */
4856 if (cmdbase > cmd)
4857 {
4858 p = cmdbase + STRLEN(cmdbase);
4859 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4860 *--p = NUL;
4861 if (p > cmdbase && p[-1] == ')'
4862 && (*cmd =='(' || cmd[1] == '('))
4863 *--p = NUL;
4864 }
4865
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004866 newcmd = cmdbase;
4867 unescape_shellxquote(cmdbase, p_sxe);
4868
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004869 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004870 * If creating new console, arguments are passed to the
4871 * 'cmd.exe' as-is. If it's not, arguments are not treated
4872 * correctly for current 'cmd.exe'. So unescape characters in
4873 * shellxescape except '|' for avoiding to be treated as
4874 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004875 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004876 if (flags != CREATE_NEW_CONSOLE)
4877 {
4878 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004879 char_u *cmd_shell = mch_getenv("COMSPEC");
4880
4881 if (cmd_shell == NULL || *cmd_shell == NUL)
4882 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004883
4884 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4885 if (subcmd != NULL)
4886 {
4887 /* make "cmd.exe /c arguments" */
4888 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004889 newcmd = lalloc(cmdlen, TRUE);
4890 if (newcmd != NULL)
4891 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004892 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004893 else
4894 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004895 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004896 }
4897 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004898
4899 /*
4900 * Now, start the command as a process, so that it doesn't
4901 * inherit our handles which causes unpleasant dangling swap
4902 * files if we exit before the spawned process
4903 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004904 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004905 x = 0;
4906 else
4907 {
4908 x = -1;
4909#ifdef FEAT_GUI_W32
4910 EMSG(_("E371: Command not found"));
4911#endif
4912 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004913
4914 if (newcmd != cmdbase)
4915 vim_free(newcmd);
4916
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004917 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004918 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004919 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004920 CloseHandle(si.hStdInput);
4921 }
4922 /* Close the handles to the subprocess, so that it goes away */
4923 CloseHandle(pi.hThread);
4924 CloseHandle(pi.hProcess);
4925 }
4926 else
4927 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004928 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004929#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004930 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004931#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004932 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4933
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004934 newcmd = lalloc(cmdlen, TRUE);
4935 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 {
4937#if defined(FEAT_GUI_W32)
4938 if (need_vimrun_warning)
4939 {
4940 MessageBox(NULL,
4941 _("VIMRUN.EXE not found in your $PATH.\n"
4942 "External commands will not pause after completion.\n"
4943 "See :help win32-vimrun for more information."),
4944 _("Vim Warning"),
4945 MB_ICONWARNING);
4946 need_vimrun_warning = FALSE;
4947 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004948 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004949 /* Use vimrun to execute the command. It opens a console
4950 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004951 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952 vimrun_path,
4953 (msg_silent != 0 || (options & SHELL_DOOUT))
4954 ? "-s " : "",
4955 p_sh, p_shcf, cmd);
4956 else
4957#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004958 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004959 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004960 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004961 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963 }
4964 }
4965
4966 if (tmode == TMODE_RAW)
4967 settmode(TMODE_RAW); /* set to raw mode */
4968
4969 /* Print the return value, unless "vimrun" was used. */
4970 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4971#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004972 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4973 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974#endif
4975 )
4976 {
4977 smsg(_("shell returned %d"), x);
4978 msg_putchar('\n');
4979 }
4980#ifdef FEAT_TITLE
4981 resettitle();
4982#endif
4983
4984 signal(SIGINT, SIG_DFL);
4985#if defined(__GNUC__) && !defined(__MINGW32__)
4986 signal(SIGKILL, SIG_DFL);
4987#else
4988 signal(SIGBREAK, SIG_DFL);
4989#endif
4990 signal(SIGILL, SIG_DFL);
4991 signal(SIGFPE, SIG_DFL);
4992 signal(SIGSEGV, SIG_DFL);
4993 signal(SIGTERM, SIG_DFL);
4994 signal(SIGABRT, SIG_DFL);
4995
4996 return x;
4997}
4998
4999
5000#ifndef FEAT_GUI_W32
5001
5002/*
5003 * Start termcap mode
5004 */
5005 static void
5006termcap_mode_start(void)
5007{
5008 DWORD cmodein;
5009
5010 if (g_fTermcapMode)
5011 return;
5012
5013 SaveConsoleBuffer(&g_cbNonTermcap);
5014
5015 if (g_cbTermcap.IsValid)
5016 {
5017 /*
5018 * We've been in termcap mode before. Restore certain screen
5019 * characteristics, including the buffer size and the window
5020 * size. Since we will be redrawing the screen, we don't need
5021 * to restore the actual contents of the buffer.
5022 */
5023 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5024 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5025 Rows = g_cbTermcap.Info.dwSize.Y;
5026 Columns = g_cbTermcap.Info.dwSize.X;
5027 }
5028 else
5029 {
5030 /*
5031 * This is our first time entering termcap mode. Clear the console
5032 * screen buffer, and resize the buffer to match the current window
5033 * size. We will use this as the size of our editing environment.
5034 */
5035 ClearConsoleBuffer(g_attrCurrent);
5036 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5037 }
5038
5039#ifdef FEAT_TITLE
5040 resettitle();
5041#endif
5042
5043 GetConsoleMode(g_hConIn, &cmodein);
5044#ifdef FEAT_MOUSE
5045 if (g_fMouseActive)
5046 cmodein |= ENABLE_MOUSE_INPUT;
5047 else
5048 cmodein &= ~ENABLE_MOUSE_INPUT;
5049#endif
5050 cmodein |= ENABLE_WINDOW_INPUT;
5051 SetConsoleMode(g_hConIn, cmodein);
5052
5053 redraw_later_clear();
5054 g_fTermcapMode = TRUE;
5055}
5056
5057
5058/*
5059 * End termcap mode
5060 */
5061 static void
5062termcap_mode_end(void)
5063{
5064 DWORD cmodein;
5065 ConsoleBuffer *cb;
5066 COORD coord;
5067 DWORD dwDummy;
5068
5069 if (!g_fTermcapMode)
5070 return;
5071
5072 SaveConsoleBuffer(&g_cbTermcap);
5073
5074 GetConsoleMode(g_hConIn, &cmodein);
5075 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5076 SetConsoleMode(g_hConIn, cmodein);
5077
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005078#ifdef FEAT_RESTORE_ORIG_SCREEN
5079 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5080#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005081 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005082#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005083 RestoreConsoleBuffer(cb, p_rs);
5084 SetConsoleCursorInfo(g_hConOut, &g_cci);
5085
5086 if (p_rs || exiting)
5087 {
5088 /*
5089 * Clear anything that happens to be on the current line.
5090 */
5091 coord.X = 0;
5092 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5093 FillConsoleOutputCharacter(g_hConOut, ' ',
5094 cb->Info.dwSize.X, coord, &dwDummy);
5095 /*
5096 * The following is just for aesthetics. If we are exiting without
5097 * restoring the screen, then we want to have a prompt string
5098 * appear at the bottom line. However, the command interpreter
5099 * seems to always advance the cursor one line before displaying
5100 * the prompt string, which causes the screen to scroll. To
5101 * counter this, move the cursor up one line before exiting.
5102 */
5103 if (exiting && !p_rs)
5104 coord.Y--;
5105 /*
5106 * Position the cursor at the leftmost column of the desired row.
5107 */
5108 SetConsoleCursorPosition(g_hConOut, coord);
5109 }
5110
5111 g_fTermcapMode = FALSE;
5112}
5113#endif /* FEAT_GUI_W32 */
5114
5115
5116#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005117/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005118 void
5119mch_write(
5120 char_u *s,
5121 int len)
5122{
5123 /* never used */
5124}
5125
5126#else
5127
5128/*
5129 * clear `n' chars, starting from `coord'
5130 */
5131 static void
5132clear_chars(
5133 COORD coord,
5134 DWORD n)
5135{
5136 DWORD dwDummy;
5137
5138 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5139 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5140}
5141
5142
5143/*
5144 * Clear the screen
5145 */
5146 static void
5147clear_screen(void)
5148{
5149 g_coord.X = g_coord.Y = 0;
5150 clear_chars(g_coord, Rows * Columns);
5151}
5152
5153
5154/*
5155 * Clear to end of display
5156 */
5157 static void
5158clear_to_end_of_display(void)
5159{
5160 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5161 * Columns + (Columns - g_coord.X));
5162}
5163
5164
5165/*
5166 * Clear to end of line
5167 */
5168 static void
5169clear_to_end_of_line(void)
5170{
5171 clear_chars(g_coord, Columns - g_coord.X);
5172}
5173
5174
5175/*
5176 * Scroll the scroll region up by `cLines' lines
5177 */
5178 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005179scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005180{
5181 COORD oldcoord = g_coord;
5182
5183 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5184 delete_lines(cLines);
5185
5186 g_coord = oldcoord;
5187}
5188
5189
5190/*
5191 * Set the scroll region
5192 */
5193 static void
5194set_scroll_region(
5195 unsigned left,
5196 unsigned top,
5197 unsigned right,
5198 unsigned bottom)
5199{
5200 if (left >= right
5201 || top >= bottom
5202 || right > (unsigned) Columns - 1
5203 || bottom > (unsigned) Rows - 1)
5204 return;
5205
5206 g_srScrollRegion.Left = left;
5207 g_srScrollRegion.Top = top;
5208 g_srScrollRegion.Right = right;
5209 g_srScrollRegion.Bottom = bottom;
5210}
5211
5212
5213/*
5214 * Insert `cLines' lines at the current cursor position
5215 */
5216 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005217insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218{
5219 SMALL_RECT source;
5220 COORD dest;
5221 CHAR_INFO fill;
5222
5223 dest.X = 0;
5224 dest.Y = g_coord.Y + cLines;
5225
5226 source.Left = 0;
5227 source.Top = g_coord.Y;
5228 source.Right = g_srScrollRegion.Right;
5229 source.Bottom = g_srScrollRegion.Bottom - cLines;
5230
5231 fill.Char.AsciiChar = ' ';
5232 fill.Attributes = g_attrCurrent;
5233
5234 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5235
5236 /* Here we have to deal with a win32 console flake: If the scroll
5237 * region looks like abc and we scroll c to a and fill with d we get
5238 * cbd... if we scroll block c one line at a time to a, we get cdd...
5239 * vim expects cdd consistently... So we have to deal with that
5240 * here... (this also occurs scrolling the same way in the other
5241 * direction). */
5242
5243 if (source.Bottom < dest.Y)
5244 {
5245 COORD coord;
5246
5247 coord.X = 0;
5248 coord.Y = source.Bottom;
5249 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5250 }
5251}
5252
5253
5254/*
5255 * Delete `cLines' lines at the current cursor position
5256 */
5257 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005258delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005259{
5260 SMALL_RECT source;
5261 COORD dest;
5262 CHAR_INFO fill;
5263 int nb;
5264
5265 dest.X = 0;
5266 dest.Y = g_coord.Y;
5267
5268 source.Left = 0;
5269 source.Top = g_coord.Y + cLines;
5270 source.Right = g_srScrollRegion.Right;
5271 source.Bottom = g_srScrollRegion.Bottom;
5272
5273 fill.Char.AsciiChar = ' ';
5274 fill.Attributes = g_attrCurrent;
5275
5276 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5277
5278 /* Here we have to deal with a win32 console flake: If the scroll
5279 * region looks like abc and we scroll c to a and fill with d we get
5280 * cbd... if we scroll block c one line at a time to a, we get cdd...
5281 * vim expects cdd consistently... So we have to deal with that
5282 * here... (this also occurs scrolling the same way in the other
5283 * direction). */
5284
5285 nb = dest.Y + (source.Bottom - source.Top) + 1;
5286
5287 if (nb < source.Top)
5288 {
5289 COORD coord;
5290
5291 coord.X = 0;
5292 coord.Y = nb;
5293 clear_chars(coord, Columns * (source.Top - nb));
5294 }
5295}
5296
5297
5298/*
5299 * Set the cursor position
5300 */
5301 static void
5302gotoxy(
5303 unsigned x,
5304 unsigned y)
5305{
5306 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5307 return;
5308
5309 /* external cursor coords are 1-based; internal are 0-based */
5310 g_coord.X = x - 1;
5311 g_coord.Y = y - 1;
5312 SetConsoleCursorPosition(g_hConOut, g_coord);
5313}
5314
5315
5316/*
5317 * Set the current text attribute = (foreground | background)
5318 * See ../doc/os_win32.txt for the numbers.
5319 */
5320 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005321textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005323 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005324
5325 SetConsoleTextAttribute(g_hConOut, wAttr);
5326}
5327
5328
5329 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005330textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005331{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005332 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005333
5334 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5335}
5336
5337
5338 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005339textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005340{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005341 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342
5343 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5344}
5345
5346
5347/*
5348 * restore the default text attribute (whatever we started with)
5349 */
5350 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005351normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005352{
5353 textattr(g_attrDefault);
5354}
5355
5356
5357static WORD g_attrPreStandout = 0;
5358
5359/*
5360 * Make the text standout, by brightening it
5361 */
5362 static void
5363standout(void)
5364{
5365 g_attrPreStandout = g_attrCurrent;
5366 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5367}
5368
5369
5370/*
5371 * Turn off standout mode
5372 */
5373 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005374standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375{
5376 if (g_attrPreStandout)
5377 {
5378 textattr(g_attrPreStandout);
5379 g_attrPreStandout = 0;
5380 }
5381}
5382
5383
5384/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005385 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386 */
5387 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005388mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005389{
5390 char_u *p;
5391 int n;
5392
5393 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5394 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5395 if (T_ME[0] == ESC && T_ME[1] == '|')
5396 {
5397 p = T_ME + 2;
5398 n = getdigits(&p);
5399 if (*p == 'm' && n > 0)
5400 {
5401 cterm_normal_fg_color = (n & 0xf) + 1;
5402 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5403 }
5404 }
5405}
5406
5407
5408/*
5409 * visual bell: flash the screen
5410 */
5411 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005412visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413{
5414 COORD coordOrigin = {0, 0};
5415 WORD attrFlash = ~g_attrCurrent & 0xff;
5416
5417 DWORD dwDummy;
5418 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5419
5420 if (oldattrs == NULL)
5421 return;
5422 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5423 coordOrigin, &dwDummy);
5424 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5425 coordOrigin, &dwDummy);
5426
5427 Sleep(15); /* wait for 15 msec */
5428 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5429 coordOrigin, &dwDummy);
5430 vim_free(oldattrs);
5431}
5432
5433
5434/*
5435 * Make the cursor visible or invisible
5436 */
5437 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005438cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005439{
5440 s_cursor_visible = fVisible;
5441#ifdef MCH_CURSOR_SHAPE
5442 mch_update_cursor();
5443#endif
5444}
5445
5446
5447/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005448 * write `cbToWrite' bytes in `pchBuf' to the screen
5449 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005450 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005451 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005452write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005453 char_u *pchBuf,
5454 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005455{
5456 COORD coord = g_coord;
5457 DWORD written;
5458
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005459#ifdef FEAT_MBYTE
5460 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5461 {
5462 static WCHAR *unicodebuf = NULL;
5463 static int unibuflen = 0;
5464 int length;
5465 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005466
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005467 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5468 if (unicodebuf == NULL || length > unibuflen)
5469 {
5470 vim_free(unicodebuf);
5471 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5472 unibuflen = length;
5473 }
5474 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5475 unicodebuf, unibuflen);
5476
5477 cells = mb_string2cells(pchBuf, cbToWrite);
5478 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5479 coord, &written);
5480 /* When writing fails or didn't write a single character, pretend one
5481 * character was written, otherwise we get stuck. */
5482 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5483 coord, &cchwritten) == 0
5484 || cchwritten == 0)
5485 cchwritten = 1;
5486
5487 if (cchwritten == length)
5488 {
5489 written = cbToWrite;
5490 g_coord.X += (SHORT)cells;
5491 }
5492 else
5493 {
5494 char_u *p = pchBuf;
5495 for (n = 0; n < cchwritten; n++)
5496 mb_cptr_adv(p);
5497 written = p - pchBuf;
5498 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5499 }
5500 }
5501 else
5502#endif
5503 {
5504 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5505 coord, &written);
5506 /* When writing fails or didn't write a single character, pretend one
5507 * character was written, otherwise we get stuck. */
5508 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5509 coord, &written) == 0
5510 || written == 0)
5511 written = 1;
5512
5513 g_coord.X += (SHORT) written;
5514 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515
5516 while (g_coord.X > g_srScrollRegion.Right)
5517 {
5518 g_coord.X -= (SHORT) Columns;
5519 if (g_coord.Y < g_srScrollRegion.Bottom)
5520 g_coord.Y++;
5521 }
5522
5523 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5524
5525 return written;
5526}
5527
5528
5529/*
5530 * mch_write(): write the output buffer to the screen, translating ESC
5531 * sequences into calls to console output routines.
5532 */
5533 void
5534mch_write(
5535 char_u *s,
5536 int len)
5537{
5538 s[len] = NUL;
5539
5540 if (!term_console)
5541 {
5542 write(1, s, (unsigned)len);
5543 return;
5544 }
5545
5546 /* translate ESC | sequences into faked bios calls */
5547 while (len--)
5548 {
5549 /* optimization: use one single write_chars for runs of text,
5550 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005551 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005552
5553 if (p_wd)
5554 {
5555 WaitForChar(p_wd);
5556 if (prefix != 0)
5557 prefix = 1;
5558 }
5559
5560 if (prefix != 0)
5561 {
5562 DWORD nWritten;
5563
5564 nWritten = write_chars(s, prefix);
5565#ifdef MCH_WRITE_DUMP
5566 if (fdDump)
5567 {
5568 fputc('>', fdDump);
5569 fwrite(s, sizeof(char_u), nWritten, fdDump);
5570 fputs("<\n", fdDump);
5571 }
5572#endif
5573 len -= (nWritten - 1);
5574 s += nWritten;
5575 }
5576 else if (s[0] == '\n')
5577 {
5578 /* \n, newline: go to the beginning of the next line or scroll */
5579 if (g_coord.Y == g_srScrollRegion.Bottom)
5580 {
5581 scroll(1);
5582 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5583 }
5584 else
5585 {
5586 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5587 }
5588#ifdef MCH_WRITE_DUMP
5589 if (fdDump)
5590 fputs("\\n\n", fdDump);
5591#endif
5592 s++;
5593 }
5594 else if (s[0] == '\r')
5595 {
5596 /* \r, carriage return: go to beginning of line */
5597 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5598#ifdef MCH_WRITE_DUMP
5599 if (fdDump)
5600 fputs("\\r\n", fdDump);
5601#endif
5602 s++;
5603 }
5604 else if (s[0] == '\b')
5605 {
5606 /* \b, backspace: move cursor one position left */
5607 if (g_coord.X > g_srScrollRegion.Left)
5608 g_coord.X--;
5609 else if (g_coord.Y > g_srScrollRegion.Top)
5610 {
5611 g_coord.X = g_srScrollRegion.Right;
5612 g_coord.Y--;
5613 }
5614 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5615#ifdef MCH_WRITE_DUMP
5616 if (fdDump)
5617 fputs("\\b\n", fdDump);
5618#endif
5619 s++;
5620 }
5621 else if (s[0] == '\a')
5622 {
5623 /* \a, bell */
5624 MessageBeep(0xFFFFFFFF);
5625#ifdef MCH_WRITE_DUMP
5626 if (fdDump)
5627 fputs("\\a\n", fdDump);
5628#endif
5629 s++;
5630 }
5631 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5632 {
5633#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005634 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005636 char_u *p;
5637 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638
5639 switch (s[2])
5640 {
5641 /* one or two numeric arguments, separated by ';' */
5642
5643 case '0': case '1': case '2': case '3': case '4':
5644 case '5': case '6': case '7': case '8': case '9':
5645 p = s + 2;
5646 arg1 = getdigits(&p); /* no check for length! */
5647 if (p > s + len)
5648 break;
5649
5650 if (*p == ';')
5651 {
5652 ++p;
5653 arg2 = getdigits(&p); /* no check for length! */
5654 if (p > s + len)
5655 break;
5656
5657 if (*p == 'H')
5658 gotoxy(arg2, arg1);
5659 else if (*p == 'r')
5660 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5661 }
5662 else if (*p == 'A')
5663 {
5664 /* move cursor up arg1 lines in same column */
5665 gotoxy(g_coord.X + 1,
5666 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5667 }
5668 else if (*p == 'C')
5669 {
5670 /* move cursor right arg1 columns in same line */
5671 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5672 g_coord.Y + 1);
5673 }
5674 else if (*p == 'H')
5675 {
5676 gotoxy(1, arg1);
5677 }
5678 else if (*p == 'L')
5679 {
5680 insert_lines(arg1);
5681 }
5682 else if (*p == 'm')
5683 {
5684 if (arg1 == 0)
5685 normvideo();
5686 else
5687 textattr((WORD) arg1);
5688 }
5689 else if (*p == 'f')
5690 {
5691 textcolor((WORD) arg1);
5692 }
5693 else if (*p == 'b')
5694 {
5695 textbackground((WORD) arg1);
5696 }
5697 else if (*p == 'M')
5698 {
5699 delete_lines(arg1);
5700 }
5701
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005702 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703 s = p + 1;
5704 break;
5705
5706
5707 /* Three-character escape sequences */
5708
5709 case 'A':
5710 /* move cursor up one line in same column */
5711 gotoxy(g_coord.X + 1,
5712 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5713 goto got3;
5714
5715 case 'B':
5716 visual_bell();
5717 goto got3;
5718
5719 case 'C':
5720 /* move cursor right one column in same line */
5721 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5722 g_coord.Y + 1);
5723 goto got3;
5724
5725 case 'E':
5726 termcap_mode_end();
5727 goto got3;
5728
5729 case 'F':
5730 standout();
5731 goto got3;
5732
5733 case 'f':
5734 standend();
5735 goto got3;
5736
5737 case 'H':
5738 gotoxy(1, 1);
5739 goto got3;
5740
5741 case 'j':
5742 clear_to_end_of_display();
5743 goto got3;
5744
5745 case 'J':
5746 clear_screen();
5747 goto got3;
5748
5749 case 'K':
5750 clear_to_end_of_line();
5751 goto got3;
5752
5753 case 'L':
5754 insert_lines(1);
5755 goto got3;
5756
5757 case 'M':
5758 delete_lines(1);
5759 goto got3;
5760
5761 case 'S':
5762 termcap_mode_start();
5763 goto got3;
5764
5765 case 'V':
5766 cursor_visible(TRUE);
5767 goto got3;
5768
5769 case 'v':
5770 cursor_visible(FALSE);
5771 goto got3;
5772
5773 got3:
5774 s += 3;
5775 len -= 2;
5776 }
5777
5778#ifdef MCH_WRITE_DUMP
5779 if (fdDump)
5780 {
5781 fputs("ESC | ", fdDump);
5782 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5783 fputc('\n', fdDump);
5784 }
5785#endif
5786 }
5787 else
5788 {
5789 /* Write a single character */
5790 DWORD nWritten;
5791
5792 nWritten = write_chars(s, 1);
5793#ifdef MCH_WRITE_DUMP
5794 if (fdDump)
5795 {
5796 fputc('>', fdDump);
5797 fwrite(s, sizeof(char_u), nWritten, fdDump);
5798 fputs("<\n", fdDump);
5799 }
5800#endif
5801
5802 len -= (nWritten - 1);
5803 s += nWritten;
5804 }
5805 }
5806
5807#ifdef MCH_WRITE_DUMP
5808 if (fdDump)
5809 fflush(fdDump);
5810#endif
5811}
5812
5813#endif /* FEAT_GUI_W32 */
5814
5815
5816/*
5817 * Delay for half a second.
5818 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005819/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820 void
5821mch_delay(
5822 long msec,
5823 int ignoreinput)
5824{
5825#ifdef FEAT_GUI_W32
5826 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005827#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005829# ifdef FEAT_MZSCHEME
5830 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5831 {
5832 int towait = p_mzq;
5833
5834 /* if msec is large enough, wait by portions in p_mzq */
5835 while (msec > 0)
5836 {
5837 mzvim_check_threads();
5838 if (msec < towait)
5839 towait = msec;
5840 Sleep(towait);
5841 msec -= towait;
5842 }
5843 }
5844 else
5845# endif
5846 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847 else
5848 WaitForChar(msec);
5849#endif
5850}
5851
5852
5853/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01005854 * This version of remove is not scared by a readonly (backup) file.
5855 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856 * Return 0 for success, -1 for failure.
5857 */
5858 int
5859mch_remove(char_u *name)
5860{
5861#ifdef FEAT_MBYTE
5862 WCHAR *wn = NULL;
5863 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005864#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005865
Bram Moolenaar203258c2016-01-17 22:15:16 +01005866 /*
5867 * On Windows, deleting a directory's symbolic link is done by
5868 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
5869 */
5870 if (mch_isdir(name) && mch_is_symbolic_link(name))
5871 return mch_rmdir(name);
5872
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005873 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5874
5875#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005876 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5877 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005878 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879 if (wn != NULL)
5880 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881 n = DeleteFileW(wn) ? 0 : -1;
5882 vim_free(wn);
5883 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5884 return n;
5885 /* Retry with non-wide function (for Windows 98). */
5886 }
5887 }
5888#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005889 return DeleteFile(name) ? 0 : -1;
5890}
5891
5892
5893/*
5894 * check for an "interrupt signal": CTRL-break or CTRL-C
5895 */
5896 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005897mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898{
5899#ifndef FEAT_GUI_W32 /* never used */
5900 if (g_fCtrlCPressed || g_fCBrkPressed)
5901 {
5902 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5903 got_int = TRUE;
5904 }
5905#endif
5906}
5907
Bram Moolenaaree273972016-01-02 21:11:51 +01005908/* physical RAM to leave for the OS */
5909#define WINNT_RESERVE_BYTES (256*1024*1024)
5910#define WIN95_RESERVE_BYTES (8*1024*1024)
5911
5912/*
5913 * How much main memory in KiB that can be used by VIM.
5914 */
5915/*ARGSUSED*/
5916 long_u
5917mch_total_mem(int special)
5918{
5919 PlatformId();
5920#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
5921 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5922 {
5923 MEMORYSTATUSEX ms;
5924
5925 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5926 * what fits in 32 bits. But it's not always available. */
5927 ms.dwLength = sizeof(MEMORYSTATUSEX);
5928 GlobalMemoryStatusEx(&ms);
5929 if (ms.ullAvailVirtual < ms.ullTotalPhys)
5930 {
5931 /* Process address space fits in physical RAM, use all of it. */
5932 return (long_u)(ms.ullAvailVirtual / 1024);
5933 }
5934 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
5935 {
5936 /* Catch old NT box or perverse hardware setup. */
5937 return (long_u)((ms.ullTotalPhys / 2) / 1024);
5938 }
5939 /* Use physical RAM less reserve for OS + data. */
5940 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
5941 }
5942 else
5943#endif
5944 {
5945 /* Pre-XP or 95 OS handling. */
5946 MEMORYSTATUS ms;
5947 long_u os_reserve_bytes;
5948
5949 ms.dwLength = sizeof(MEMORYSTATUS);
5950 GlobalMemoryStatus(&ms);
5951 if (ms.dwAvailVirtual < ms.dwTotalPhys)
5952 {
5953 /* Process address space fits in physical RAM, use all of it. */
5954 return (long_u)(ms.dwAvailVirtual / 1024);
5955 }
5956 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
5957 ? WINNT_RESERVE_BYTES
5958 : WIN95_RESERVE_BYTES;
5959 if (ms.dwTotalPhys <= os_reserve_bytes)
5960 {
5961 /* Catch old boxes or perverse hardware setup. */
5962 return (long_u)((ms.dwTotalPhys / 2) / 1024);
5963 }
5964 /* Use physical RAM less reserve for OS + data. */
5965 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
5966 }
5967}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005968
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969#ifdef FEAT_MBYTE
5970/*
5971 * Same code as below, but with wide functions and no comments.
5972 * Return 0 for success, non-zero for failure.
5973 */
5974 int
5975mch_wrename(WCHAR *wold, WCHAR *wnew)
5976{
5977 WCHAR *p;
5978 int i;
5979 WCHAR szTempFile[_MAX_PATH + 1];
5980 WCHAR szNewPath[_MAX_PATH + 1];
5981 HANDLE hf;
5982
5983 if (!mch_windows95())
5984 {
5985 p = wold;
5986 for (i = 0; wold[i] != NUL; ++i)
5987 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5988 && wold[i + 1] != 0)
5989 p = wold + i + 1;
5990 if ((int)(wold + i - p) < 8 || p[6] != '~')
5991 return (MoveFileW(wold, wnew) == 0);
5992 }
5993
5994 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5995 return -1;
5996 *p = NUL;
5997
5998 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5999 return -2;
6000
6001 if (!DeleteFileW(szTempFile))
6002 return -3;
6003
6004 if (!MoveFileW(wold, szTempFile))
6005 return -4;
6006
6007 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6008 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6009 return -5;
6010 if (!CloseHandle(hf))
6011 return -6;
6012
6013 if (!MoveFileW(szTempFile, wnew))
6014 {
6015 (void)MoveFileW(szTempFile, wold);
6016 return -7;
6017 }
6018
6019 DeleteFileW(szTempFile);
6020
6021 if (!DeleteFileW(wold))
6022 return -8;
6023
6024 return 0;
6025}
6026#endif
6027
6028
6029/*
6030 * mch_rename() works around a bug in rename (aka MoveFile) in
6031 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6032 * file whose short file name is "FOO.BAR" (its long file name will
6033 * be correct: "foo.bar~"). Because a file can be accessed by
6034 * either its SFN or its LFN, "foo.bar" has effectively been
6035 * renamed to "foo.bar", which is not at all what was wanted. This
6036 * seems to happen only when renaming files with three-character
6037 * extensions by appending a suffix that does not include ".".
6038 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6039 *
6040 * There is another problem, which isn't really a bug but isn't right either:
6041 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6042 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6043 * service pack 6. Doesn't seem to happen on Windows 98.
6044 *
6045 * Like rename(), returns 0 upon success, non-zero upon failure.
6046 * Should probably set errno appropriately when errors occur.
6047 */
6048 int
6049mch_rename(
6050 const char *pszOldFile,
6051 const char *pszNewFile)
6052{
6053 char szTempFile[_MAX_PATH+1];
6054 char szNewPath[_MAX_PATH+1];
6055 char *pszFilePart;
6056 HANDLE hf;
6057#ifdef FEAT_MBYTE
6058 WCHAR *wold = NULL;
6059 WCHAR *wnew = NULL;
6060 int retval = -1;
6061
6062 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6063 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006064 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6065 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066 if (wold != NULL && wnew != NULL)
6067 retval = mch_wrename(wold, wnew);
6068 vim_free(wold);
6069 vim_free(wnew);
6070 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6071 return retval;
6072 /* Retry with non-wide function (for Windows 98). */
6073 }
6074#endif
6075
6076 /*
6077 * No need to play tricks if not running Windows 95, unless the file name
6078 * contains a "~" as the seventh character.
6079 */
6080 if (!mch_windows95())
6081 {
6082 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6083 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6084 return rename(pszOldFile, pszNewFile);
6085 }
6086
6087 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6088 * a directory, no error is returned and pszFilePart will be NULL. */
6089 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6090 || pszFilePart == NULL)
6091 return -1;
6092 *pszFilePart = NUL;
6093
6094 /* Get (and create) a unique temporary file name in directory of new file */
6095 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6096 return -2;
6097
6098 /* blow the temp file away */
6099 if (!DeleteFile(szTempFile))
6100 return -3;
6101
6102 /* rename old file to the temp file */
6103 if (!MoveFile(pszOldFile, szTempFile))
6104 return -4;
6105
6106 /* now create an empty file called pszOldFile; this prevents the operating
6107 * system using pszOldFile as an alias (SFN) if we're renaming within the
6108 * same directory. For example, we're editing a file called
6109 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6110 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6111 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006112 * cause all sorts of problems later in buf_write(). So, we create an
6113 * empty file called filena~1.txt and the system will have to find some
6114 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115 */
6116 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6117 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6118 return -5;
6119 if (!CloseHandle(hf))
6120 return -6;
6121
6122 /* rename the temp file to the new file */
6123 if (!MoveFile(szTempFile, pszNewFile))
6124 {
6125 /* Renaming failed. Rename the file back to its old name, so that it
6126 * looks like nothing happened. */
6127 (void)MoveFile(szTempFile, pszOldFile);
6128
6129 return -7;
6130 }
6131
6132 /* Seems to be left around on Novell filesystems */
6133 DeleteFile(szTempFile);
6134
6135 /* finally, remove the empty old file */
6136 if (!DeleteFile(pszOldFile))
6137 return -8;
6138
6139 return 0; /* success */
6140}
6141
6142/*
6143 * Get the default shell for the current hardware platform
6144 */
6145 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006146default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147{
6148 char* psz = NULL;
6149
6150 PlatformId();
6151
6152 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6153 psz = "cmd.exe";
6154 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6155 psz = "command.com";
6156
6157 return psz;
6158}
6159
6160/*
6161 * mch_access() extends access() to do more detailed check on network drives.
6162 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6163 */
6164 int
6165mch_access(char *n, int p)
6166{
6167 HANDLE hFile;
6168 DWORD am;
6169 int retval = -1; /* default: fail */
6170#ifdef FEAT_MBYTE
6171 WCHAR *wn = NULL;
6172
6173 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006174 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175#endif
6176
6177 if (mch_isdir(n))
6178 {
6179 char TempName[_MAX_PATH + 16] = "";
6180#ifdef FEAT_MBYTE
6181 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6182#endif
6183
6184 if (p & R_OK)
6185 {
6186 /* Read check is performed by seeing if we can do a find file on
6187 * the directory for any file. */
6188#ifdef FEAT_MBYTE
6189 if (wn != NULL)
6190 {
6191 int i;
6192 WIN32_FIND_DATAW d;
6193
6194 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6195 TempNameW[i] = wn[i];
6196 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6197 TempNameW[i++] = '\\';
6198 TempNameW[i++] = '*';
6199 TempNameW[i++] = 0;
6200
6201 hFile = FindFirstFileW(TempNameW, &d);
6202 if (hFile == INVALID_HANDLE_VALUE)
6203 {
6204 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6205 goto getout;
6206
6207 /* Retry with non-wide function (for Windows 98). */
6208 vim_free(wn);
6209 wn = NULL;
6210 }
6211 else
6212 (void)FindClose(hFile);
6213 }
6214 if (wn == NULL)
6215#endif
6216 {
6217 char *pch;
6218 WIN32_FIND_DATA d;
6219
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006220 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 pch = TempName + STRLEN(TempName) - 1;
6222 if (*pch != '\\' && *pch != '/')
6223 *++pch = '\\';
6224 *++pch = '*';
6225 *++pch = NUL;
6226
6227 hFile = FindFirstFile(TempName, &d);
6228 if (hFile == INVALID_HANDLE_VALUE)
6229 goto getout;
6230 (void)FindClose(hFile);
6231 }
6232 }
6233
6234 if (p & W_OK)
6235 {
6236 /* Trying to create a temporary file in the directory should catch
6237 * directories on read-only network shares. However, in
6238 * directories whose ACL allows writes but denies deletes will end
6239 * up keeping the temporary file :-(. */
6240#ifdef FEAT_MBYTE
6241 if (wn != NULL)
6242 {
6243 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6244 {
6245 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6246 goto getout;
6247
6248 /* Retry with non-wide function (for Windows 98). */
6249 vim_free(wn);
6250 wn = NULL;
6251 }
6252 else
6253 DeleteFileW(TempNameW);
6254 }
6255 if (wn == NULL)
6256#endif
6257 {
6258 if (!GetTempFileName(n, "VIM", 0, TempName))
6259 goto getout;
6260 mch_remove((char_u *)TempName);
6261 }
6262 }
6263 }
6264 else
6265 {
6266 /* Trying to open the file for the required access does ACL, read-only
6267 * network share, and file attribute checks. */
6268 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6269 | ((p & R_OK) ? GENERIC_READ : 0);
6270#ifdef FEAT_MBYTE
6271 if (wn != NULL)
6272 {
6273 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6274 if (hFile == INVALID_HANDLE_VALUE
6275 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6276 {
6277 /* Retry with non-wide function (for Windows 98). */
6278 vim_free(wn);
6279 wn = NULL;
6280 }
6281 }
6282 if (wn == NULL)
6283#endif
6284 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6285 if (hFile == INVALID_HANDLE_VALUE)
6286 goto getout;
6287 CloseHandle(hFile);
6288 }
6289
6290 retval = 0; /* success */
6291getout:
6292#ifdef FEAT_MBYTE
6293 vim_free(wn);
6294#endif
6295 return retval;
6296}
6297
6298#if defined(FEAT_MBYTE) || defined(PROTO)
6299/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006300 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 */
6302 int
6303mch_open(char *name, int flags, int mode)
6304{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006305 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6306# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 WCHAR *wn;
6308 int f;
6309
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006310 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006312 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 if (wn != NULL)
6314 {
6315 f = _wopen(wn, flags, mode);
6316 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006317 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318 return f;
6319 /* Retry with non-wide function (for Windows 98). Can't use
6320 * GetLastError() here and it's unclear what errno gets set to if
6321 * the _wopen() fails for missing wide functions. */
6322 }
6323 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006324# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006325
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006326 /* open() can open a file which name is longer than _MAX_PATH bytes
6327 * and shorter than _MAX_PATH characters successfully, but sometimes it
6328 * causes unexpected error in another part. We make it an error explicitly
6329 * here. */
6330 if (strlen(name) >= _MAX_PATH)
6331 return -1;
6332
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333 return open(name, flags, mode);
6334}
6335
6336/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006337 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338 */
6339 FILE *
6340mch_fopen(char *name, char *mode)
6341{
6342 WCHAR *wn, *wm;
6343 FILE *f = NULL;
6344
6345 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6346# ifdef __BORLANDC__
6347 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6348 && g_PlatformId == VER_PLATFORM_WIN32_NT
6349# endif
6350 )
6351 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006352# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006353 /* Work around an annoying assertion in the Microsoft debug CRT
6354 * when mode's text/binary setting doesn't match _get_fmode(). */
6355 char newMode = mode[strlen(mode) - 1];
6356 int oldMode = 0;
6357
6358 _get_fmode(&oldMode);
6359 if (newMode == 't')
6360 _set_fmode(_O_TEXT);
6361 else if (newMode == 'b')
6362 _set_fmode(_O_BINARY);
6363# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006364 wn = enc_to_utf16(name, NULL);
6365 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 if (wn != NULL && wm != NULL)
6367 f = _wfopen(wn, wm);
6368 vim_free(wn);
6369 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006370
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006371# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006372 _set_fmode(oldMode);
6373# endif
6374
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006375 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 return f;
6377 /* Retry with non-wide function (for Windows 98). Can't use
6378 * GetLastError() here and it's unclear what errno gets set to if
6379 * the _wfopen() fails for missing wide functions. */
6380 }
6381
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006382 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6383 * and shorter than _MAX_PATH characters successfully, but sometimes it
6384 * causes unexpected error in another part. We make it an error explicitly
6385 * here. */
6386 if (strlen(name) >= _MAX_PATH)
6387 return NULL;
6388
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389 return fopen(name, mode);
6390}
6391#endif
6392
6393#ifdef FEAT_MBYTE
6394/*
6395 * SUB STREAM (aka info stream) handling:
6396 *
6397 * NTFS can have sub streams for each file. Normal contents of file is
6398 * stored in the main stream, and extra contents (author information and
6399 * title and so on) can be stored in sub stream. After Windows 2000, user
6400 * can access and store those informations in sub streams via explorer's
6401 * property menuitem in right click menu. Those informations in sub streams
6402 * were lost when copying only the main stream. So we have to copy sub
6403 * streams.
6404 *
6405 * Incomplete explanation:
6406 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6407 * More useful info and an example:
6408 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6409 */
6410
6411/*
6412 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6413 * and write to stream "substream" of file "to".
6414 * Errors are ignored.
6415 */
6416 static void
6417copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6418{
6419 HANDLE hTo;
6420 WCHAR *to_name;
6421
6422 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6423 wcscpy(to_name, to);
6424 wcscat(to_name, substream);
6425
6426 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6427 FILE_ATTRIBUTE_NORMAL, NULL);
6428 if (hTo != INVALID_HANDLE_VALUE)
6429 {
6430 long done;
6431 DWORD todo;
6432 DWORD readcnt, written;
6433 char buf[4096];
6434
6435 /* Copy block of bytes at a time. Abort when something goes wrong. */
6436 for (done = 0; done < len; done += written)
6437 {
6438 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006439 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6440 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006441 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6442 FALSE, FALSE, context)
6443 || readcnt != todo
6444 || !WriteFile(hTo, buf, todo, &written, NULL)
6445 || written != todo)
6446 break;
6447 }
6448 CloseHandle(hTo);
6449 }
6450
6451 free(to_name);
6452}
6453
6454/*
6455 * Copy info streams from file "from" to file "to".
6456 */
6457 static void
6458copy_infostreams(char_u *from, char_u *to)
6459{
6460 WCHAR *fromw;
6461 WCHAR *tow;
6462 HANDLE sh;
6463 WIN32_STREAM_ID sid;
6464 int headersize;
6465 WCHAR streamname[_MAX_PATH];
6466 DWORD readcount;
6467 void *context = NULL;
6468 DWORD lo, hi;
6469 int len;
6470
6471 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006472 fromw = enc_to_utf16(from, NULL);
6473 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006474 if (fromw != NULL && tow != NULL)
6475 {
6476 /* Open the file for reading. */
6477 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6478 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6479 if (sh != INVALID_HANDLE_VALUE)
6480 {
6481 /* Use BackupRead() to find the info streams. Repeat until we
6482 * have done them all.*/
6483 for (;;)
6484 {
6485 /* Get the header to find the length of the stream name. If
6486 * the "readcount" is zero we have done all info streams. */
6487 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006488 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6490 &readcount, FALSE, FALSE, &context)
6491 || readcount == 0)
6492 break;
6493
6494 /* We only deal with streams that have a name. The normal
6495 * file data appears to be without a name, even though docs
6496 * suggest it is called "::$DATA". */
6497 if (sid.dwStreamNameSize > 0)
6498 {
6499 /* Read the stream name. */
6500 if (!BackupRead(sh, (LPBYTE)streamname,
6501 sid.dwStreamNameSize,
6502 &readcount, FALSE, FALSE, &context))
6503 break;
6504
6505 /* Copy an info stream with a name ":anything:$DATA".
6506 * Skip "::$DATA", it has no stream name (examples suggest
6507 * it might be used for the normal file contents).
6508 * Note that BackupRead() counts bytes, but the name is in
6509 * wide characters. */
6510 len = readcount / sizeof(WCHAR);
6511 streamname[len] = 0;
6512 if (len > 7 && wcsicmp(streamname + len - 6,
6513 L":$DATA") == 0)
6514 {
6515 streamname[len - 6] = 0;
6516 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006517 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518 }
6519 }
6520
6521 /* Advance to the next stream. We might try seeking too far,
6522 * but BackupSeek() doesn't skip over stream borders, thus
6523 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006524 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525 &lo, &hi, &context);
6526 }
6527
6528 /* Clear the context. */
6529 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6530
6531 CloseHandle(sh);
6532 }
6533 }
6534 vim_free(fromw);
6535 vim_free(tow);
6536}
6537#endif
6538
6539/*
6540 * Copy file attributes from file "from" to file "to".
6541 * For Windows NT and later we copy info streams.
6542 * Always returns zero, errors are ignored.
6543 */
6544 int
6545mch_copy_file_attribute(char_u *from, char_u *to)
6546{
6547#ifdef FEAT_MBYTE
6548 /* File streams only work on Windows NT and later. */
6549 PlatformId();
6550 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6551 copy_infostreams(from, to);
6552#endif
6553 return 0;
6554}
6555
6556#if defined(MYRESETSTKOFLW) || defined(PROTO)
6557/*
6558 * Recreate a destroyed stack guard page in win32.
6559 * Written by Benjamin Peterson.
6560 */
6561
6562/* These magic numbers are from the MS header files */
6563#define MIN_STACK_WIN9X 17
6564#define MIN_STACK_WINNT 2
6565
6566/*
6567 * This function does the same thing as _resetstkoflw(), which is only
6568 * available in DevStudio .net and later.
6569 * Returns 0 for failure, 1 for success.
6570 */
6571 int
6572myresetstkoflw(void)
6573{
6574 BYTE *pStackPtr;
6575 BYTE *pGuardPage;
6576 BYTE *pStackBase;
6577 BYTE *pLowestPossiblePage;
6578 MEMORY_BASIC_INFORMATION mbi;
6579 SYSTEM_INFO si;
6580 DWORD nPageSize;
6581 DWORD dummy;
6582
6583 /* This code will not work on win32s. */
6584 PlatformId();
6585 if (g_PlatformId == VER_PLATFORM_WIN32s)
6586 return 0;
6587
6588 /* We need to know the system page size. */
6589 GetSystemInfo(&si);
6590 nPageSize = si.dwPageSize;
6591
6592 /* ...and the current stack pointer */
6593 pStackPtr = (BYTE*)_alloca(1);
6594
6595 /* ...and the base of the stack. */
6596 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6597 return 0;
6598 pStackBase = (BYTE*)mbi.AllocationBase;
6599
6600 /* ...and the page thats min_stack_req pages away from stack base; this is
6601 * the lowest page we could use. */
6602 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6603 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6604
6605 /* On Win95, we want the next page down from the end of the stack. */
6606 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6607 {
6608 /* Find the page that's only 1 page down from the page that the stack
6609 * ptr is in. */
6610 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6611 / (DWORD)nPageSize) - 1));
6612 if (pGuardPage < pLowestPossiblePage)
6613 return 0;
6614
6615 /* Apply the noaccess attribute to the page -- there's no guard
6616 * attribute in win95-type OSes. */
6617 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6618 return 0;
6619 }
6620 else
6621 {
6622 /* On NT, however, we want the first committed page in the stack Start
6623 * at the stack base and move forward through memory until we find a
6624 * committed block. */
6625 BYTE *pBlock = pStackBase;
6626
Bram Moolenaara466c992005-07-09 21:03:22 +00006627 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006628 {
6629 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6630 return 0;
6631
6632 pBlock += mbi.RegionSize;
6633
6634 if (mbi.State & MEM_COMMIT)
6635 break;
6636 }
6637
6638 /* mbi now describes the first committed block in the stack. */
6639 if (mbi.Protect & PAGE_GUARD)
6640 return 1;
6641
6642 /* decide where the guard page should start */
6643 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6644 pGuardPage = pLowestPossiblePage;
6645 else
6646 pGuardPage = (BYTE*)mbi.BaseAddress;
6647
6648 /* allocate the guard page */
6649 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6650 return 0;
6651
6652 /* apply the guard attribute to the page */
6653 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6654 &dummy))
6655 return 0;
6656 }
6657
6658 return 1;
6659}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006660#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006662
6663#if defined(FEAT_MBYTE) || defined(PROTO)
6664/*
6665 * The command line arguments in UCS2
6666 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006667static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006668static LPWSTR *ArglistW = NULL;
6669static int global_argc = 0;
6670static char **global_argv;
6671
6672static int used_file_argc = 0; /* last argument in global_argv[] used
6673 for the argument list. */
6674static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6675 command line arguments added to
6676 the argument list */
6677static int used_file_count = 0; /* nr of entries in used_file_indexes */
6678static int used_file_literal = FALSE; /* take file names literally */
6679static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006680static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006681static int used_alist_count = 0;
6682
6683
6684/*
6685 * Get the command line arguments. Unicode version.
6686 * Returns argc. Zero when something fails.
6687 */
6688 int
6689get_cmd_argsW(char ***argvp)
6690{
6691 char **argv = NULL;
6692 int argc = 0;
6693 int i;
6694
Bram Moolenaar14993322014-09-09 12:25:33 +02006695 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006696 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6697 if (ArglistW != NULL)
6698 {
6699 argv = malloc((nArgsW + 1) * sizeof(char *));
6700 if (argv != NULL)
6701 {
6702 argc = nArgsW;
6703 argv[argc] = NULL;
6704 for (i = 0; i < argc; ++i)
6705 {
6706 int len;
6707
6708 /* Convert each Unicode argument to the current codepage. */
6709 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006710 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006711 (LPSTR *)&argv[i], &len, 0, 0);
6712 if (argv[i] == NULL)
6713 {
6714 /* Out of memory, clear everything. */
6715 while (i > 0)
6716 free(argv[--i]);
6717 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006718 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006719 argc = 0;
6720 }
6721 }
6722 }
6723 }
6724
6725 global_argc = argc;
6726 global_argv = argv;
6727 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006728 {
6729 if (used_file_indexes != NULL)
6730 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006731 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006732 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006733
6734 if (argvp != NULL)
6735 *argvp = argv;
6736 return argc;
6737}
6738
6739 void
6740free_cmd_argsW(void)
6741{
6742 if (ArglistW != NULL)
6743 {
6744 GlobalFree(ArglistW);
6745 ArglistW = NULL;
6746 }
6747}
6748
6749/*
6750 * Remember "name" is an argument that was added to the argument list.
6751 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6752 * is called.
6753 */
6754 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006755used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006756{
6757 int i;
6758
6759 if (used_file_indexes == NULL)
6760 return;
6761 for (i = used_file_argc + 1; i < global_argc; ++i)
6762 if (STRCMP(global_argv[i], name) == 0)
6763 {
6764 used_file_argc = i;
6765 used_file_indexes[used_file_count++] = i;
6766 break;
6767 }
6768 used_file_literal = literal;
6769 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006770 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006771}
6772
6773/*
6774 * Remember the length of the argument list as it was. If it changes then we
6775 * leave it alone when 'encoding' is set.
6776 */
6777 void
6778set_alist_count(void)
6779{
6780 used_alist_count = GARGCOUNT;
6781}
6782
6783/*
6784 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6785 * has been changed while starting up. Use the UCS-2 command line arguments
6786 * and convert them to 'encoding'.
6787 */
6788 void
6789fix_arg_enc(void)
6790{
6791 int i;
6792 int idx;
6793 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006794 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006795
6796 /* Safety checks:
6797 * - if argument count differs between the wide and non-wide argument
6798 * list, something must be wrong.
6799 * - the file name arguments must have been located.
6800 * - the length of the argument list wasn't changed by the user.
6801 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006802 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006803 || ArglistW == NULL
6804 || used_file_indexes == NULL
6805 || used_file_count == 0
6806 || used_alist_count != GARGCOUNT)
6807 return;
6808
Bram Moolenaar86b68352004-12-27 21:59:20 +00006809 /* Remember the buffer numbers for the arguments. */
6810 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6811 if (fnum_list == NULL)
6812 return; /* out of memory */
6813 for (i = 0; i < GARGCOUNT; ++i)
6814 fnum_list[i] = GARGLIST[i].ae_fnum;
6815
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006816 /* Clear the argument list. Make room for the new arguments. */
6817 alist_clear(&global_alist);
6818 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006819 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006820
6821 for (i = 0; i < used_file_count; ++i)
6822 {
6823 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006824 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006825 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006826 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006827#ifdef FEAT_DIFF
6828 /* When using diff mode may need to concatenate file name to
6829 * directory name. Just like it's done in main(). */
6830 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6831 && !mch_isdir(alist_name(&GARGLIST[0])))
6832 {
6833 char_u *r;
6834
6835 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6836 if (r != NULL)
6837 {
6838 vim_free(str);
6839 str = r;
6840 }
6841 }
6842#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006843 /* Re-use the old buffer by renaming it. When not using literal
6844 * names it's done by alist_expand() below. */
6845 if (used_file_literal)
6846 buf_set_name(fnum_list[i], str);
6847
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006848 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006849 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006850 }
6851
6852 if (!used_file_literal)
6853 {
6854 /* Now expand wildcards in the arguments. */
6855 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6856 * filename characters but are excluded from 'isfname' to make
6857 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6858 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006859 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006860 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6861 }
6862
6863 /* If wildcard expansion failed, we are editing the first file of the
6864 * arglist and there is no file name: Edit the first argument now. */
6865 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6866 {
6867 do_cmdline_cmd((char_u *)":rewind");
6868 if (GARGCOUNT == 1 && used_file_full_path)
6869 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6870 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006871
6872 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006873}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874#endif