blob: bfd5f4a2edafd4e1ffc9ec509de00b0b72d9e79c [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 Moolenaar071d4272004-06-13 20:20:40 +0000138#endif
139
140#ifndef FEAT_GUI_W32
141/* Undocumented API in kernel32.dll needed to work around dead key bug in
142 * console-mode applications in NT 4.0. If you switch keyboard layouts
143 * in a console app to a layout that includes dead keys and then hit a
144 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
145 * and Michael Dietrich for helping me figure out this workaround.
146 */
147
148/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
149#ifndef WINBASEAPI
150# define WINBASEAPI __stdcall
151#endif
152#if defined(__BORLANDC__)
153typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
154#else
155typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
156#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000157static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158#endif
159
160#if defined(__BORLANDC__)
161/* Strangely Borland uses a non-standard name. */
162# define wcsicmp(a, b) wcscmpi((a), (b))
163#endif
164
Bram Moolenaar82881492012-11-20 16:53:39 +0100165#ifndef PROTO
166
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200167/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200168#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100169LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200170BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
171BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
172BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
173#endif
174
Bram Moolenaar82881492012-11-20 16:53:39 +0100175#endif /* PROTO */
176
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177#ifndef FEAT_GUI_W32
178/* Win32 Console handles for input and output */
179static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
180static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
181
182/* Win32 Screen buffer,coordinate,console I/O information */
183static SMALL_RECT g_srScrollRegion;
184static COORD g_coord; /* 0-based, but external coords are 1-based */
185
186/* The attribute of the screen when the editor was started */
187static WORD g_attrDefault = 7; /* lightgray text on black background */
188static WORD g_attrCurrent;
189
190static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
191static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
192static int g_fForceExit = FALSE; /* set when forcefully exiting */
193
194static void termcap_mode_start(void);
195static void termcap_mode_end(void);
196static void clear_chars(COORD coord, DWORD n);
197static void clear_screen(void);
198static void clear_to_end_of_display(void);
199static void clear_to_end_of_line(void);
200static void scroll(unsigned cLines);
201static void set_scroll_region(unsigned left, unsigned top,
202 unsigned right, unsigned bottom);
203static void insert_lines(unsigned cLines);
204static void delete_lines(unsigned cLines);
205static void gotoxy(unsigned x, unsigned y);
206static void normvideo(void);
207static void textattr(WORD wAttr);
208static void textcolor(WORD wAttr);
209static void textbackground(WORD wAttr);
210static void standout(void);
211static void standend(void);
212static void visual_bell(void);
213static void cursor_visible(BOOL fVisible);
214static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
215static char_u tgetch(int *pmodifiers, char_u *pch2);
216static void create_conin(void);
217static int s_cursor_visible = TRUE;
218static int did_create_conin = FALSE;
219#else
220static int s_dont_use_vimrun = TRUE;
221static int need_vimrun_warning = FALSE;
222static char *vimrun_path = "vimrun ";
223#endif
224
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200225static int win32_getattrs(char_u *name);
226static int win32_setattrs(char_u *name, int attrs);
227static int win32_set_archive(char_u *name);
228
Bram Moolenaar071d4272004-06-13 20:20:40 +0000229#ifndef FEAT_GUI_W32
230static int suppress_winsize = 1; /* don't fiddle with console */
231#endif
232
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200233static char_u *exe_path = NULL;
234
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100235static BOOL win8_or_later = FALSE;
236
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100237/*
238 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100239 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100240 */
241 static BOOL
242read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100243 HANDLE hInput,
244 INPUT_RECORD *lpBuffer,
245 DWORD nLength,
246 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100247{
248 enum
249 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100250 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100251 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100252 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100253 static DWORD s_dwIndex = 0;
254 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100255 DWORD dwEvents;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100256
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100257 if (!win8_or_later)
258 {
259 if (nLength == -1)
260 return PeekConsoleInput(hInput, lpBuffer, 1, lpEvents);
261 return ReadConsoleInput(hInput, lpBuffer, 1, &dwEvents);
262 }
263
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100264 if (s_dwMax == 0)
265 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100266 if (nLength == -1)
267 return PeekConsoleInput(hInput, lpBuffer, 1, lpEvents);
268 if (!ReadConsoleInput(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100269 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100270 s_dwIndex = 0;
271 s_dwMax = dwEvents;
272 if (dwEvents == 0)
273 {
274 *lpEvents = 0;
275 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100276 }
277 }
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100278 *lpBuffer = s_irCache[s_dwIndex];
279 if (nLength != -1 && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100281 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100282 return TRUE;
283}
284
285/*
286 * Version of PeekConsoleInput() that works with IME.
287 */
288 static BOOL
289peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 HANDLE hInput,
291 INPUT_RECORD *lpBuffer,
292 DWORD nLength,
293 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100294{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100296}
297
Bram Moolenaar071d4272004-06-13 20:20:40 +0000298 static void
299get_exe_name(void)
300{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100301 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
302 * as the maximum length that works (plus a NUL byte). */
303#define MAX_ENV_PATH_LEN 8192
304 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200305 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000306
307 if (exe_name == NULL)
308 {
309 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100310 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000311 if (*temp != NUL)
312 exe_name = FullName_save((char_u *)temp, FALSE);
313 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000314
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200315 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000316 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200317 exe_path = vim_strnsave(exe_name,
318 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200319 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000320 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200321 /* Append our starting directory to $PATH, so that when doing
322 * "!xxd" it's found in our starting directory. Needed because
323 * SearchPath() also looks there. */
324 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100325 if (p == NULL
326 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200327 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100328 if (p == NULL || *p == NUL)
329 temp[0] = NUL;
330 else
331 {
332 STRCPY(temp, p);
333 STRCAT(temp, ";");
334 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200335 STRCAT(temp, exe_path);
336 vim_setenv((char_u *)"PATH", temp);
337 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000338 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340}
341
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200342/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100343 * Unescape characters in "p" that appear in "escaped".
344 */
345 static void
346unescape_shellxquote(char_u *p, char_u *escaped)
347{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100348 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100349 int n;
350
351 while (*p != NUL)
352 {
353 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
354 mch_memmove(p, p + 1, l--);
355#ifdef FEAT_MBYTE
356 n = (*mb_ptr2len)(p);
357#else
358 n = 1;
359#endif
360 p += n;
361 l -= n;
362 }
363}
364
365/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200366 * Load library "name".
367 */
368 HINSTANCE
369vimLoadLib(char *name)
370{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200371 HINSTANCE dll = NULL;
372 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200373
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200374 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
375 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200376 if (exe_path == NULL)
377 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200378 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200379 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200380#ifdef FEAT_MBYTE
381 WCHAR old_dirw[MAXPATHL];
382
383 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
384 {
385 /* Change directory to where the executable is, both to make
386 * sure we find a .dll there and to avoid looking for a .dll
387 * in the current directory. */
388 SetCurrentDirectory(exe_path);
389 dll = LoadLibrary(name);
390 SetCurrentDirectoryW(old_dirw);
391 return dll;
392 }
393 /* Retry with non-wide function (for Windows 98). */
394 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
395#endif
396 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
397 {
398 /* Change directory to where the executable is, both to make
399 * sure we find a .dll there and to avoid looking for a .dll
400 * in the current directory. */
401 SetCurrentDirectory(exe_path);
402 dll = LoadLibrary(name);
403 SetCurrentDirectory(old_dir);
404 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200405 }
406 return dll;
407}
408
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
410# ifndef GETTEXT_DLL
411# define GETTEXT_DLL "libintl.dll"
412# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200413/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000414static char *null_libintl_gettext(const char *);
415static char *null_libintl_textdomain(const char *);
416static char *null_libintl_bindtextdomain(const char *, const char *);
417static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200419static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000420char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
421char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
422char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000423 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000424char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
425 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000426
427 int
428dyn_libintl_init(char *libname)
429{
430 int i;
431 static struct
432 {
433 char *name;
434 FARPROC *ptr;
435 } libintl_entry[] =
436 {
437 {"gettext", (FARPROC*)&dyn_libintl_gettext},
438 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
439 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
440 {NULL, NULL}
441 };
442
443 /* No need to initialize twice. */
444 if (hLibintlDLL)
445 return 1;
446 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200447 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448 if (!hLibintlDLL)
449 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200450 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000451 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200452 verbose_enter();
453 EMSG2(_(e_loadlib), GETTEXT_DLL);
454 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000455 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200456 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457 }
458 for (i = 0; libintl_entry[i].name != NULL
459 && libintl_entry[i].ptr != NULL; ++i)
460 {
461 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
462 libintl_entry[i].name)) == NULL)
463 {
464 dyn_libintl_end();
465 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000466 {
467 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000469 verbose_leave();
470 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471 return 0;
472 }
473 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000474
475 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000476 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000477 "bind_textdomain_codeset");
478 if (dyn_libintl_bind_textdomain_codeset == NULL)
479 dyn_libintl_bind_textdomain_codeset =
480 null_libintl_bind_textdomain_codeset;
481
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482 return 1;
483}
484
485 void
486dyn_libintl_end()
487{
488 if (hLibintlDLL)
489 FreeLibrary(hLibintlDLL);
490 hLibintlDLL = NULL;
491 dyn_libintl_gettext = null_libintl_gettext;
492 dyn_libintl_textdomain = null_libintl_textdomain;
493 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000494 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495}
496
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000497/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000499null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000500{
501 return (char*)msgid;
502}
503
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000504/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000506null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507{
508 return NULL;
509}
510
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000511/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000513null_libintl_bind_textdomain_codeset(const char *domainname,
514 const char *codeset)
515{
516 return NULL;
517}
518
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000519/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000520 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000521null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522{
523 return NULL;
524}
525
526#endif /* DYNAMIC_GETTEXT */
527
528/* This symbol is not defined in older versions of the SDK or Visual C++ */
529
530#ifndef VER_PLATFORM_WIN32_WINDOWS
531# define VER_PLATFORM_WIN32_WINDOWS 1
532#endif
533
534DWORD g_PlatformId;
535
536#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100537# ifndef PROTO
538# include <aclapi.h>
539# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200540# ifndef PROTECTED_DACL_SECURITY_INFORMATION
541# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
542# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100543
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544/*
545 * These are needed to dynamically load the ADVAPI DLL, which is not
546 * implemented under Windows 95 (and causes VIM to crash)
547 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200548typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200550typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000551 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
552 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200553# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200554typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200555 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200556typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200557 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
558 PSECURITY_DESCRIPTOR *);
559# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560
561static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
562static PSNSECINFO pSetNamedSecurityInfo;
563static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200564# ifdef FEAT_MBYTE
565static PSNSECINFOW pSetNamedSecurityInfoW;
566static PGNSECINFOW pGetNamedSecurityInfoW;
567# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000568#endif
569
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200570typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
571
572static BOOL allowPiping = FALSE;
573static PSETHANDLEINFORMATION pSetHandleInformation;
574
Bram Moolenaar27515922013-06-29 15:36:26 +0200575#ifdef HAVE_ACL
576/*
577 * Enables or disables the specified privilege.
578 */
579 static BOOL
580win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
581{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100582 BOOL bResult;
583 LUID luid;
584 HANDLE hToken;
585 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200586
587 if (!OpenProcessToken(GetCurrentProcess(),
588 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
589 return FALSE;
590
591 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
592 {
593 CloseHandle(hToken);
594 return FALSE;
595 }
596
597 tokenPrivileges.PrivilegeCount = 1;
598 tokenPrivileges.Privileges[0].Luid = luid;
599 tokenPrivileges.Privileges[0].Attributes = bEnable ?
600 SE_PRIVILEGE_ENABLED : 0;
601
602 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
603 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
604
605 CloseHandle(hToken);
606
607 return bResult && GetLastError() == ERROR_SUCCESS;
608}
609#endif
610
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611/*
612 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
613 * VER_PLATFORM_WIN32_WINDOWS (Win95).
614 */
615 void
616PlatformId(void)
617{
618 static int done = FALSE;
619
620 if (!done)
621 {
622 OSVERSIONINFO ovi;
623
624 ovi.dwOSVersionInfoSize = sizeof(ovi);
625 GetVersionEx(&ovi);
626
627 g_PlatformId = ovi.dwPlatformId;
628
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100629 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
630 || ovi.dwMajorVersion > 6)
631 win8_or_later = TRUE;
632
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633#ifdef HAVE_ACL
634 /*
635 * Load the ADVAPI runtime if we are on anything
636 * other than Windows 95
637 */
638 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
639 {
640 /*
641 * do this load. Problems: Doesn't unload at end of run (this is
642 * theoretically okay, since Windows should unload it when VIM
643 * terminates). Should we be using the 'mch_libcall' routines?
644 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
645 * time we verify security...
646 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200647 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000648 if (advapi_lib != NULL)
649 {
650 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
651 "SetNamedSecurityInfoA");
652 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
653 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200654# ifdef FEAT_MBYTE
655 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
656 "SetNamedSecurityInfoW");
657 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
658 "GetNamedSecurityInfoW");
659# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000660 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200661 || pGetNamedSecurityInfo == NULL
662# ifdef FEAT_MBYTE
663 || pSetNamedSecurityInfoW == NULL
664 || pGetNamedSecurityInfoW == NULL
665# endif
666 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000667 {
668 /* If we can't get the function addresses, set advapi_lib
669 * to NULL so that we don't use them. */
670 FreeLibrary(advapi_lib);
671 advapi_lib = NULL;
672 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200673 /* Enable privilege for getting or setting SACLs. */
674 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675 }
676 }
677#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200678 /*
679 * If we are on windows NT, try to load the pipe functions, only
680 * available from Win2K.
681 */
682 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
683 {
684 HANDLE kernel32 = GetModuleHandle("kernel32");
685 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
686 kernel32, "SetHandleInformation");
687
688 allowPiping = pSetHandleInformation != NULL;
689 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690 done = TRUE;
691 }
692}
693
694/*
695 * Return TRUE when running on Windows 95 (or 98 or ME).
696 * Only to be used after mch_init().
697 */
698 int
699mch_windows95(void)
700{
701 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
702}
703
704#ifdef FEAT_GUI_W32
705/*
706 * Used to work around the "can't do synchronous spawn"
707 * problem on Win32s, without resorting to Universal Thunk.
708 */
709static int old_num_windows;
710static int num_windows;
711
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000712/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713 static BOOL CALLBACK
714win32ssynch_cb(HWND hwnd, LPARAM lparam)
715{
716 num_windows++;
717 return TRUE;
718}
719#endif
720
721#ifndef FEAT_GUI_W32
722
723#define SHIFT (SHIFT_PRESSED)
724#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
725#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
726#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
727
728
729/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
730 * We map function keys to their ANSI terminal equivalents, as produced
731 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
732 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
733 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
734 * combinations of function/arrow/etc keys.
735 */
736
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000737static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738{
739 WORD wVirtKey;
740 BOOL fAnsiKey;
741 int chAlone;
742 int chShift;
743 int chCtrl;
744 int chAlt;
745} VirtKeyMap[] =
746{
747
748/* Key ANSI alone shift ctrl alt */
749 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
750
751 { VK_F1, TRUE, ';', 'T', '^', 'h', },
752 { VK_F2, TRUE, '<', 'U', '_', 'i', },
753 { VK_F3, TRUE, '=', 'V', '`', 'j', },
754 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
755 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
756 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
757 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
758 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
759 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
760 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
761 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
762 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
763
764 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
765 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
766 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
767 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
768 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
769 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
770 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
771 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
772 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
773 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
774
775 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
776
777#if 0
778 /* Most people don't have F13-F20, but what the hell... */
779 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
780 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
781 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
782 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
783 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
784 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
785 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
786 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
787#endif
788 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
789 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
790 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
791 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
792
793 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
794 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
795 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
796 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
797 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
798 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
799 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
800 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
801 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
802 /* Sorry, out of number space! <negri>*/
803 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
804
805};
806
807
808#ifdef _MSC_VER
809// The ToAscii bug destroys several registers. Need to turn off optimization
810// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000811# pragma warning(push)
812# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813# pragma optimize("", off)
814#endif
815
816#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
817# define AChar AsciiChar
818#else
819# define AChar uChar.AsciiChar
820#endif
821
822/* The return code indicates key code size. */
823 static int
824#ifdef __BORLANDC__
825 __stdcall
826#endif
827win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000828 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829{
830 UINT uMods = pker->dwControlKeyState;
831 static int s_iIsDead = 0;
832 static WORD awAnsiCode[2];
833 static BYTE abKeystate[256];
834
835
836 if (s_iIsDead == 2)
837 {
838 pker->AChar = (CHAR) awAnsiCode[1];
839 s_iIsDead = 0;
840 return 1;
841 }
842
843 if (pker->AChar != 0)
844 return 1;
845
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200846 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847
848 // Should only be non-NULL on NT 4.0
849 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
850 {
851 CHAR szKLID[KL_NAMELENGTH];
852
853 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
854 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
855 }
856
857 /* Clear any pending dead keys */
858 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
859
860 if (uMods & SHIFT_PRESSED)
861 abKeystate[VK_SHIFT] = 0x80;
862 if (uMods & CAPSLOCK_ON)
863 abKeystate[VK_CAPITAL] = 1;
864
865 if ((uMods & ALT_GR) == ALT_GR)
866 {
867 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
868 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
869 }
870
871 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
872 abKeystate, awAnsiCode, 0);
873
874 if (s_iIsDead > 0)
875 pker->AChar = (CHAR) awAnsiCode[0];
876
877 return s_iIsDead;
878}
879
880#ifdef _MSC_VER
881/* MUST switch optimization on again here, otherwise a call to
882 * decode_key_event() may crash (e.g. when hitting caps-lock) */
883# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000884# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885
886# if (_MSC_VER < 1100)
887/* MUST turn off global optimisation for this next function, or
888 * pressing ctrl-minus in insert mode crashes Vim when built with
889 * VC4.1. -- negri. */
890# pragma optimize("g", off)
891# endif
892#endif
893
894static BOOL g_fJustGotFocus = FALSE;
895
896/*
897 * Decode a KEY_EVENT into one or two keystrokes
898 */
899 static BOOL
900decode_key_event(
901 KEY_EVENT_RECORD *pker,
902 char_u *pch,
903 char_u *pch2,
904 int *pmodifiers,
905 BOOL fDoPost)
906{
907 int i;
908 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
909
910 *pch = *pch2 = NUL;
911 g_fJustGotFocus = FALSE;
912
913 /* ignore key up events */
914 if (!pker->bKeyDown)
915 return FALSE;
916
917 /* ignore some keystrokes */
918 switch (pker->wVirtualKeyCode)
919 {
920 /* modifiers */
921 case VK_SHIFT:
922 case VK_CONTROL:
923 case VK_MENU: /* Alt key */
924 return FALSE;
925
926 default:
927 break;
928 }
929
930 /* special cases */
931 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
932 {
933 /* Ctrl-6 is Ctrl-^ */
934 if (pker->wVirtualKeyCode == '6')
935 {
936 *pch = Ctrl_HAT;
937 return TRUE;
938 }
939 /* Ctrl-2 is Ctrl-@ */
940 else if (pker->wVirtualKeyCode == '2')
941 {
942 *pch = NUL;
943 return TRUE;
944 }
945 /* Ctrl-- is Ctrl-_ */
946 else if (pker->wVirtualKeyCode == 0xBD)
947 {
948 *pch = Ctrl__;
949 return TRUE;
950 }
951 }
952
953 /* Shift-TAB */
954 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
955 {
956 *pch = K_NUL;
957 *pch2 = '\017';
958 return TRUE;
959 }
960
961 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
962 {
963 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
964 {
965 if (nModifs == 0)
966 *pch = VirtKeyMap[i].chAlone;
967 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
968 *pch = VirtKeyMap[i].chShift;
969 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
970 *pch = VirtKeyMap[i].chCtrl;
971 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
972 *pch = VirtKeyMap[i].chAlt;
973
974 if (*pch != 0)
975 {
976 if (VirtKeyMap[i].fAnsiKey)
977 {
978 *pch2 = *pch;
979 *pch = K_NUL;
980 }
981
982 return TRUE;
983 }
984 }
985 }
986
987 i = win32_kbd_patch_key(pker);
988
989 if (i < 0)
990 *pch = NUL;
991 else
992 {
993 *pch = (i > 0) ? pker->AChar : NUL;
994
995 if (pmodifiers != NULL)
996 {
997 /* Pass on the ALT key as a modifier, but only when not combined
998 * with CTRL (which is ALTGR). */
999 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1000 *pmodifiers |= MOD_MASK_ALT;
1001
1002 /* Pass on SHIFT only for special keys, because we don't know when
1003 * it's already included with the character. */
1004 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1005 *pmodifiers |= MOD_MASK_SHIFT;
1006
1007 /* Pass on CTRL only for non-special keys, because we don't know
1008 * when it's already included with the character. And not when
1009 * combined with ALT (which is ALTGR). */
1010 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1011 && *pch >= 0x20 && *pch < 0x80)
1012 *pmodifiers |= MOD_MASK_CTRL;
1013 }
1014 }
1015
1016 return (*pch != NUL);
1017}
1018
1019#ifdef _MSC_VER
1020# pragma optimize("", on)
1021#endif
1022
1023#endif /* FEAT_GUI_W32 */
1024
1025
1026#ifdef FEAT_MOUSE
1027
1028/*
1029 * For the GUI the mouse handling is in gui_w32.c.
1030 */
1031# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001032/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001034mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035{
1036}
1037# else
1038static int g_fMouseAvail = FALSE; /* mouse present */
1039static int g_fMouseActive = FALSE; /* mouse enabled */
1040static int g_nMouseClick = -1; /* mouse status */
1041static int g_xMouse; /* mouse x coordinate */
1042static int g_yMouse; /* mouse y coordinate */
1043
1044/*
1045 * Enable or disable mouse input
1046 */
1047 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001048mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049{
1050 DWORD cmodein;
1051
1052 if (!g_fMouseAvail)
1053 return;
1054
1055 g_fMouseActive = on;
1056 GetConsoleMode(g_hConIn, &cmodein);
1057
1058 if (g_fMouseActive)
1059 cmodein |= ENABLE_MOUSE_INPUT;
1060 else
1061 cmodein &= ~ENABLE_MOUSE_INPUT;
1062
1063 SetConsoleMode(g_hConIn, cmodein);
1064}
1065
1066
1067/*
1068 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1069 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1070 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1071 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1072 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1073 * and we return the mouse position in g_xMouse and g_yMouse.
1074 *
1075 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1076 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1077 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1078 *
1079 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1080 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1081 *
1082 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1083 * moves, even if it stays within the same character cell. We ignore
1084 * all MOUSE_MOVED messages if the position hasn't really changed, and
1085 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1086 * we're only interested in MOUSE_DRAG).
1087 *
1088 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1089 * 2-button mouses by pressing the left & right buttons simultaneously.
1090 * In practice, it's almost impossible to click both at the same time,
1091 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1092 * in such cases, if the user is clicking quickly.
1093 */
1094 static BOOL
1095decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001096 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097{
1098 static int s_nOldButton = -1;
1099 static int s_nOldMouseClick = -1;
1100 static int s_xOldMouse = -1;
1101 static int s_yOldMouse = -1;
1102 static linenr_T s_old_topline = 0;
1103#ifdef FEAT_DIFF
1104 static int s_old_topfill = 0;
1105#endif
1106 static int s_cClicks = 1;
1107 static BOOL s_fReleased = TRUE;
1108 static DWORD s_dwLastClickTime = 0;
1109 static BOOL s_fNextIsMiddle = FALSE;
1110
1111 static DWORD cButtons = 0; /* number of buttons supported */
1112
1113 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1114 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1115 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1116 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1117
1118 int nButton;
1119
1120 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1121 cButtons = 2;
1122
1123 if (!g_fMouseAvail || !g_fMouseActive)
1124 {
1125 g_nMouseClick = -1;
1126 return FALSE;
1127 }
1128
1129 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1130 if (g_fJustGotFocus)
1131 {
1132 g_fJustGotFocus = FALSE;
1133 return FALSE;
1134 }
1135
1136 /* unprocessed mouse click? */
1137 if (g_nMouseClick != -1)
1138 return TRUE;
1139
1140 nButton = -1;
1141 g_xMouse = pmer->dwMousePosition.X;
1142 g_yMouse = pmer->dwMousePosition.Y;
1143
1144 if (pmer->dwEventFlags == MOUSE_MOVED)
1145 {
1146 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1147 * events even when the mouse moves only within a char cell.) */
1148 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1149 return FALSE;
1150 }
1151
1152 /* If no buttons are pressed... */
1153 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1154 {
1155 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1156 if (s_fReleased)
1157 return FALSE;
1158
1159 nButton = MOUSE_RELEASE;
1160 s_fReleased = TRUE;
1161 }
1162 else /* one or more buttons pressed */
1163 {
1164 /* on a 2-button mouse, hold down left and right buttons
1165 * simultaneously to get MIDDLE. */
1166
1167 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1168 {
1169 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1170
1171 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001172 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173 if (dwLR == LEFT || dwLR == RIGHT)
1174 {
1175 for (;;)
1176 {
1177 /* wait a short time for next input event */
1178 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1179 != WAIT_OBJECT_0)
1180 break;
1181 else
1182 {
1183 DWORD cRecords = 0;
1184 INPUT_RECORD ir;
1185 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1186
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001187 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188
1189 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1190 || !(pmer2->dwButtonState & LEFT_RIGHT))
1191 break;
1192 else
1193 {
1194 if (pmer2->dwEventFlags != MOUSE_MOVED)
1195 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001196 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001197
1198 return decode_mouse_event(pmer2);
1199 }
1200 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1201 s_yOldMouse == pmer2->dwMousePosition.Y)
1202 {
1203 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001204 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001205
1206 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001207 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001208
1209 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1210 break;
1211 }
1212 else
1213 break;
1214 }
1215 }
1216 }
1217 }
1218 }
1219
1220 if (s_fNextIsMiddle)
1221 {
1222 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1223 ? MOUSE_DRAG : MOUSE_MIDDLE;
1224 s_fNextIsMiddle = FALSE;
1225 }
1226 else if (cButtons == 2 &&
1227 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1228 {
1229 nButton = MOUSE_MIDDLE;
1230
1231 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1232 {
1233 s_fNextIsMiddle = TRUE;
1234 nButton = MOUSE_RELEASE;
1235 }
1236 }
1237 else if ((pmer->dwButtonState & LEFT) == LEFT)
1238 nButton = MOUSE_LEFT;
1239 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1240 nButton = MOUSE_MIDDLE;
1241 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1242 nButton = MOUSE_RIGHT;
1243
1244 if (! s_fReleased && ! s_fNextIsMiddle
1245 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1246 return FALSE;
1247
1248 s_fReleased = s_fNextIsMiddle;
1249 }
1250
1251 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1252 {
1253 /* button pressed or released, without mouse moving */
1254 if (nButton != -1 && nButton != MOUSE_RELEASE)
1255 {
1256 DWORD dwCurrentTime = GetTickCount();
1257
1258 if (s_xOldMouse != g_xMouse
1259 || s_yOldMouse != g_yMouse
1260 || s_nOldButton != nButton
1261 || s_old_topline != curwin->w_topline
1262#ifdef FEAT_DIFF
1263 || s_old_topfill != curwin->w_topfill
1264#endif
1265 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1266 {
1267 s_cClicks = 1;
1268 }
1269 else if (++s_cClicks > 4)
1270 {
1271 s_cClicks = 1;
1272 }
1273
1274 s_dwLastClickTime = dwCurrentTime;
1275 }
1276 }
1277 else if (pmer->dwEventFlags == MOUSE_MOVED)
1278 {
1279 if (nButton != -1 && nButton != MOUSE_RELEASE)
1280 nButton = MOUSE_DRAG;
1281
1282 s_cClicks = 1;
1283 }
1284
1285 if (nButton == -1)
1286 return FALSE;
1287
1288 if (nButton != MOUSE_RELEASE)
1289 s_nOldButton = nButton;
1290
1291 g_nMouseClick = nButton;
1292
1293 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1294 g_nMouseClick |= MOUSE_SHIFT;
1295 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1296 g_nMouseClick |= MOUSE_CTRL;
1297 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1298 g_nMouseClick |= MOUSE_ALT;
1299
1300 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1301 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1302
1303 /* only pass on interesting (i.e., different) mouse events */
1304 if (s_xOldMouse == g_xMouse
1305 && s_yOldMouse == g_yMouse
1306 && s_nOldMouseClick == g_nMouseClick)
1307 {
1308 g_nMouseClick = -1;
1309 return FALSE;
1310 }
1311
1312 s_xOldMouse = g_xMouse;
1313 s_yOldMouse = g_yMouse;
1314 s_old_topline = curwin->w_topline;
1315#ifdef FEAT_DIFF
1316 s_old_topfill = curwin->w_topfill;
1317#endif
1318 s_nOldMouseClick = g_nMouseClick;
1319
1320 return TRUE;
1321}
1322
1323# endif /* FEAT_GUI_W32 */
1324#endif /* FEAT_MOUSE */
1325
1326
1327#ifdef MCH_CURSOR_SHAPE
1328/*
1329 * Set the shape of the cursor.
1330 * 'thickness' can be from 1 (thin) to 99 (block)
1331 */
1332 static void
1333mch_set_cursor_shape(int thickness)
1334{
1335 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1336 ConsoleCursorInfo.dwSize = thickness;
1337 ConsoleCursorInfo.bVisible = s_cursor_visible;
1338
1339 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1340 if (s_cursor_visible)
1341 SetConsoleCursorPosition(g_hConOut, g_coord);
1342}
1343
1344 void
1345mch_update_cursor(void)
1346{
1347 int idx;
1348 int thickness;
1349
1350 /*
1351 * How the cursor is drawn depends on the current mode.
1352 */
1353 idx = get_shape_idx(FALSE);
1354
1355 if (shape_table[idx].shape == SHAPE_BLOCK)
1356 thickness = 99; /* 100 doesn't work on W95 */
1357 else
1358 thickness = shape_table[idx].percentage;
1359 mch_set_cursor_shape(thickness);
1360}
1361#endif
1362
1363#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1364/*
1365 * Handle FOCUS_EVENT.
1366 */
1367 static void
1368handle_focus_event(INPUT_RECORD ir)
1369{
1370 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1371 ui_focus_change((int)g_fJustGotFocus);
1372}
1373
1374/*
1375 * Wait until console input from keyboard or mouse is available,
1376 * or the time is up.
1377 * Return TRUE if something is available FALSE if not.
1378 */
1379 static int
1380WaitForChar(long msec)
1381{
1382 DWORD dwNow = 0, dwEndTime = 0;
1383 INPUT_RECORD ir;
1384 DWORD cRecords;
1385 char_u ch, ch2;
1386
1387 if (msec > 0)
1388 /* Wait until the specified time has elapsed. */
1389 dwEndTime = GetTickCount() + msec;
1390 else if (msec < 0)
1391 /* Wait forever. */
1392 dwEndTime = INFINITE;
1393
1394 /* We need to loop until the end of the time period, because
1395 * we might get multiple unusable mouse events in that time.
1396 */
1397 for (;;)
1398 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001399#ifdef FEAT_MZSCHEME
1400 mzvim_check_threads();
1401#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402#ifdef FEAT_CLIENTSERVER
1403 serverProcessPendingMessages();
1404#endif
1405 if (0
1406#ifdef FEAT_MOUSE
1407 || g_nMouseClick != -1
1408#endif
1409#ifdef FEAT_CLIENTSERVER
1410 || input_available()
1411#endif
1412 )
1413 return TRUE;
1414
1415 if (msec > 0)
1416 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001417 /* If the specified wait time has passed, return. Beware that
1418 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001419 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001420 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001421 break;
1422 }
1423 if (msec != 0)
1424 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001425 DWORD dwWaitTime = dwEndTime - dwNow;
1426
1427#ifdef FEAT_MZSCHEME
1428 if (mzthreads_allowed() && p_mzq > 0
1429 && (msec < 0 || (long)dwWaitTime > p_mzq))
1430 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1431#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432#ifdef FEAT_CLIENTSERVER
1433 /* Wait for either an event on the console input or a message in
1434 * the client-server window. */
1435 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001436 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001438 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001439#endif
1440 continue;
1441 }
1442
1443 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001444 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001445
1446#ifdef FEAT_MBYTE_IME
1447 if (State & CMDLINE && msg_row == Rows - 1)
1448 {
1449 CONSOLE_SCREEN_BUFFER_INFO csbi;
1450
1451 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1452 {
1453 if (csbi.dwCursorPosition.Y != msg_row)
1454 {
1455 /* The screen is now messed up, must redraw the
1456 * command line and later all the windows. */
1457 redraw_all_later(CLEAR);
1458 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1459 redrawcmd();
1460 }
1461 }
1462 }
1463#endif
1464
1465 if (cRecords > 0)
1466 {
1467 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1468 {
1469#ifdef FEAT_MBYTE_IME
1470 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1471 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1472 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1473 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1474 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001475 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001476 continue;
1477 }
1478#endif
1479 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1480 NULL, FALSE))
1481 return TRUE;
1482 }
1483
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001484 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485
1486 if (ir.EventType == FOCUS_EVENT)
1487 handle_focus_event(ir);
1488 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1489 shell_resized();
1490#ifdef FEAT_MOUSE
1491 else if (ir.EventType == MOUSE_EVENT
1492 && decode_mouse_event(&ir.Event.MouseEvent))
1493 return TRUE;
1494#endif
1495 }
1496 else if (msec == 0)
1497 break;
1498 }
1499
1500#ifdef FEAT_CLIENTSERVER
1501 /* Something might have been received while we were waiting. */
1502 if (input_available())
1503 return TRUE;
1504#endif
1505 return FALSE;
1506}
1507
1508#ifndef FEAT_GUI_MSWIN
1509/*
1510 * return non-zero if a character is available
1511 */
1512 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001513mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514{
1515 return WaitForChar(0L);
1516}
1517#endif
1518
1519/*
1520 * Create the console input. Used when reading stdin doesn't work.
1521 */
1522 static void
1523create_conin(void)
1524{
1525 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1526 FILE_SHARE_READ|FILE_SHARE_WRITE,
1527 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001528 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529 did_create_conin = TRUE;
1530}
1531
1532/*
1533 * Get a keystroke or a mouse event
1534 */
1535 static char_u
1536tgetch(int *pmodifiers, char_u *pch2)
1537{
1538 char_u ch;
1539
1540 for (;;)
1541 {
1542 INPUT_RECORD ir;
1543 DWORD cRecords = 0;
1544
1545#ifdef FEAT_CLIENTSERVER
1546 (void)WaitForChar(-1L);
1547 if (input_available())
1548 return 0;
1549# ifdef FEAT_MOUSE
1550 if (g_nMouseClick != -1)
1551 return 0;
1552# endif
1553#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001554 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555 {
1556 if (did_create_conin)
1557 read_error_exit();
1558 create_conin();
1559 continue;
1560 }
1561
1562 if (ir.EventType == KEY_EVENT)
1563 {
1564 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1565 pmodifiers, TRUE))
1566 return ch;
1567 }
1568 else if (ir.EventType == FOCUS_EVENT)
1569 handle_focus_event(ir);
1570 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1571 shell_resized();
1572#ifdef FEAT_MOUSE
1573 else if (ir.EventType == MOUSE_EVENT)
1574 {
1575 if (decode_mouse_event(&ir.Event.MouseEvent))
1576 return 0;
1577 }
1578#endif
1579 }
1580}
1581#endif /* !FEAT_GUI_W32 */
1582
1583
1584/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001585 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586 * Get one or more characters from the keyboard or the mouse.
1587 * If time == 0, do not wait for characters.
1588 * If time == n, wait a short time for characters.
1589 * If time == -1, wait forever for characters.
1590 * Returns the number of characters read into buf.
1591 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001592/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593 int
1594mch_inchar(
1595 char_u *buf,
1596 int maxlen,
1597 long time,
1598 int tb_change_cnt)
1599{
1600#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1601
1602 int len;
1603 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604#define TYPEAHEADLEN 20
1605 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1606 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001607#ifdef FEAT_MBYTE
1608 static char_u *rest = NULL; /* unconverted rest of previous read */
1609 static int restlen = 0;
1610 int unconverted;
1611#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612
1613 /* First use any typeahead that was kept because "buf" was too small. */
1614 if (typeaheadlen > 0)
1615 goto theend;
1616
1617#ifdef FEAT_SNIFF
1618 if (want_sniff_request)
1619 {
1620 if (sniff_request_waiting)
1621 {
1622 /* return K_SNIFF */
1623 typeahead[typeaheadlen++] = CSI;
1624 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1625 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1626 sniff_request_waiting = 0;
1627 want_sniff_request = 0;
1628 goto theend;
1629 }
1630 else if (time < 0 || time > 250)
1631 {
1632 /* don't wait too long, a request might be pending */
1633 time = 250;
1634 }
1635 }
1636#endif
1637
1638 if (time >= 0)
1639 {
1640 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 }
1643 else /* time == -1, wait forever */
1644 {
1645 mch_set_winsize_now(); /* Allow winsize changes from now on */
1646
Bram Moolenaar3918c952005-03-15 22:34:55 +00001647 /*
1648 * If there is no character available within 2 seconds (default)
1649 * write the autoscript file to disk. Or cause the CursorHold event
1650 * to be triggered.
1651 */
1652 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 {
1654#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001655 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001657 buf[0] = K_SPECIAL;
1658 buf[1] = KS_EXTRA;
1659 buf[2] = (int)KE_CURSORHOLD;
1660 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661 }
1662#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001663 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001664 }
1665 }
1666
1667 /*
1668 * Try to read as many characters as there are, until the buffer is full.
1669 */
1670
1671 /* we will get at least one key. Get more if they are available. */
1672 g_fCBrkPressed = FALSE;
1673
1674#ifdef MCH_WRITE_DUMP
1675 if (fdDump)
1676 fputc('[', fdDump);
1677#endif
1678
1679 /* Keep looping until there is something in the typeahead buffer and more
1680 * to get and still room in the buffer (up to two bytes for a char and
1681 * three bytes for a modifier). */
1682 while ((typeaheadlen == 0 || WaitForChar(0L))
1683 && typeaheadlen + 5 <= TYPEAHEADLEN)
1684 {
1685 if (typebuf_changed(tb_change_cnt))
1686 {
1687 /* "buf" may be invalid now if a client put something in the
1688 * typeahead buffer and "buf" is in the typeahead buffer. */
1689 typeaheadlen = 0;
1690 break;
1691 }
1692#ifdef FEAT_MOUSE
1693 if (g_nMouseClick != -1)
1694 {
1695# ifdef MCH_WRITE_DUMP
1696 if (fdDump)
1697 fprintf(fdDump, "{%02x @ %d, %d}",
1698 g_nMouseClick, g_xMouse, g_yMouse);
1699# endif
1700 typeahead[typeaheadlen++] = ESC + 128;
1701 typeahead[typeaheadlen++] = 'M';
1702 typeahead[typeaheadlen++] = g_nMouseClick;
1703 typeahead[typeaheadlen++] = g_xMouse + '!';
1704 typeahead[typeaheadlen++] = g_yMouse + '!';
1705 g_nMouseClick = -1;
1706 }
1707 else
1708#endif
1709 {
1710 char_u ch2 = NUL;
1711 int modifiers = 0;
1712
1713 c = tgetch(&modifiers, &ch2);
1714
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001715#ifdef FEAT_MBYTE
1716 /* stolen from fill_input_buf() in ui.c */
1717 if (rest != NULL)
1718 {
1719 /* Use remainder of previous call, starts with an invalid
1720 * character that may become valid when reading more. */
1721 if (restlen > TYPEAHEADLEN - typeaheadlen)
1722 unconverted = TYPEAHEADLEN - typeaheadlen;
1723 else
1724 unconverted = restlen;
1725 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1726 if (unconverted == restlen)
1727 {
1728 vim_free(rest);
1729 rest = NULL;
1730 }
1731 else
1732 {
1733 restlen -= unconverted;
1734 mch_memmove(rest, rest + unconverted, restlen);
1735 }
1736 typeaheadlen += unconverted;
1737 }
1738 else
1739 unconverted = 0;
1740#endif
1741
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742 if (typebuf_changed(tb_change_cnt))
1743 {
1744 /* "buf" may be invalid now if a client put something in the
1745 * typeahead buffer and "buf" is in the typeahead buffer. */
1746 typeaheadlen = 0;
1747 break;
1748 }
1749
1750 if (c == Ctrl_C && ctrl_c_interrupts)
1751 {
1752#if defined(FEAT_CLIENTSERVER)
1753 trash_input_buf();
1754#endif
1755 got_int = TRUE;
1756 }
1757
1758#ifdef FEAT_MOUSE
1759 if (g_nMouseClick == -1)
1760#endif
1761 {
1762 int n = 1;
1763
1764 /* A key may have one or two bytes. */
1765 typeahead[typeaheadlen] = c;
1766 if (ch2 != NUL)
1767 {
1768 typeahead[typeaheadlen + 1] = ch2;
1769 ++n;
1770 }
1771#ifdef FEAT_MBYTE
1772 /* Only convert normal characters, not special keys. Need to
1773 * convert before applying ALT, otherwise mapping <M-x> breaks
1774 * when 'tenc' is set. */
1775 if (input_conv.vc_type != CONV_NONE
1776 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001777 {
1778 typeaheadlen -= unconverted;
1779 n = convert_input_safe(typeahead + typeaheadlen,
1780 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1781 rest == NULL ? &rest : NULL, &restlen);
1782 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783#endif
1784
1785 /* Use the ALT key to set the 8th bit of the character
1786 * when it's one byte, the 8th bit isn't set yet and not
1787 * using a double-byte encoding (would become a lead
1788 * byte). */
1789 if ((modifiers & MOD_MASK_ALT)
1790 && n == 1
1791 && (typeahead[typeaheadlen] & 0x80) == 0
1792#ifdef FEAT_MBYTE
1793 && !enc_dbcs
1794#endif
1795 )
1796 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001797#ifdef FEAT_MBYTE
1798 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1799 typeahead + typeaheadlen);
1800#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001802#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 modifiers &= ~MOD_MASK_ALT;
1804 }
1805
1806 if (modifiers != 0)
1807 {
1808 /* Prepend modifiers to the character. */
1809 mch_memmove(typeahead + typeaheadlen + 3,
1810 typeahead + typeaheadlen, n);
1811 typeahead[typeaheadlen++] = K_SPECIAL;
1812 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1813 typeahead[typeaheadlen++] = modifiers;
1814 }
1815
1816 typeaheadlen += n;
1817
1818#ifdef MCH_WRITE_DUMP
1819 if (fdDump)
1820 fputc(c, fdDump);
1821#endif
1822 }
1823 }
1824 }
1825
1826#ifdef MCH_WRITE_DUMP
1827 if (fdDump)
1828 {
1829 fputs("]\n", fdDump);
1830 fflush(fdDump);
1831 }
1832#endif
1833
Bram Moolenaar071d4272004-06-13 20:20:40 +00001834theend:
1835 /* Move typeahead to "buf", as much as fits. */
1836 len = 0;
1837 while (len < maxlen && typeaheadlen > 0)
1838 {
1839 buf[len++] = typeahead[0];
1840 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1841 }
1842 return len;
1843
1844#else /* FEAT_GUI_W32 */
1845 return 0;
1846#endif /* FEAT_GUI_W32 */
1847}
1848
Bram Moolenaar82881492012-11-20 16:53:39 +01001849#ifndef PROTO
1850# ifndef __MINGW32__
1851# include <shellapi.h> /* required for FindExecutable() */
1852# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001853#endif
1854
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001855/*
1856 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001857 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001858 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859 static int
1860executable_exists(char *name)
1861{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001862 char *dum;
1863 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001865#ifdef FEAT_MBYTE
1866 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001868 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001869 WCHAR fnamew[_MAX_PATH];
1870 WCHAR *dumw;
1871 long n;
1872
1873 if (p != NULL)
1874 {
1875 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1876 vim_free(p);
1877 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1878 {
1879 if (n == 0)
1880 return FALSE;
1881 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1882 return FALSE;
1883 return TRUE;
1884 }
1885 /* Retry with non-wide function (for Windows 98). */
1886 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001888#endif
1889 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1890 return FALSE;
1891 if (mch_isdir(fname))
1892 return FALSE;
1893 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894}
1895
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001896#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001897 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001898/*
1899 * Bad parameter handler.
1900 *
1901 * Certain MS CRT functions will intentionally crash when passed invalid
1902 * parameters to highlight possible security holes. Setting this function as
1903 * the bad parameter handler will prevent the crash.
1904 *
1905 * In debug builds the parameters contain CRT information that might help track
1906 * down the source of a problem, but in non-debug builds the arguments are all
1907 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1908 * worth allowing these to make debugging of issues easier.
1909 */
1910 static void
1911bad_param_handler(const wchar_t *expression,
1912 const wchar_t *function,
1913 const wchar_t *file,
1914 unsigned int line,
1915 uintptr_t pReserved)
1916{
1917}
1918
1919# define SET_INVALID_PARAM_HANDLER \
1920 ((void)_set_invalid_parameter_handler(bad_param_handler))
1921#else
1922# define SET_INVALID_PARAM_HANDLER
1923#endif
1924
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925#ifdef FEAT_GUI_W32
1926
1927/*
1928 * GUI version of mch_init().
1929 */
1930 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001931mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932{
1933#ifndef __MINGW32__
1934 extern int _fmode;
1935#endif
1936
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001937 /* Silently handle invalid parameters to CRT functions */
1938 SET_INVALID_PARAM_HANDLER;
1939
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940 /* Let critical errors result in a failure, not in a dialog box. Required
1941 * for the timestamp test to work on removed floppies. */
1942 SetErrorMode(SEM_FAILCRITICALERRORS);
1943
1944 _fmode = O_BINARY; /* we do our own CR-LF translation */
1945
1946 /* Specify window size. Is there a place to get the default from? */
1947 Rows = 25;
1948 Columns = 80;
1949
1950 /* Look for 'vimrun' */
1951 if (!gui_is_win32s())
1952 {
1953 char_u vimrun_location[_MAX_PATH + 4];
1954
1955 /* First try in same directory as gvim.exe */
1956 STRCPY(vimrun_location, exe_name);
1957 STRCPY(gettail(vimrun_location), "vimrun.exe");
1958 if (mch_getperm(vimrun_location) >= 0)
1959 {
1960 if (*skiptowhite(vimrun_location) != NUL)
1961 {
1962 /* Enclose path with white space in double quotes. */
1963 mch_memmove(vimrun_location + 1, vimrun_location,
1964 STRLEN(vimrun_location) + 1);
1965 *vimrun_location = '"';
1966 STRCPY(gettail(vimrun_location), "vimrun\" ");
1967 }
1968 else
1969 STRCPY(gettail(vimrun_location), "vimrun ");
1970
1971 vimrun_path = (char *)vim_strsave(vimrun_location);
1972 s_dont_use_vimrun = FALSE;
1973 }
1974 else if (executable_exists("vimrun.exe"))
1975 s_dont_use_vimrun = FALSE;
1976
1977 /* Don't give the warning for a missing vimrun.exe right now, but only
1978 * when vimrun was supposed to be used. Don't bother people that do
1979 * not need vimrun.exe. */
1980 if (s_dont_use_vimrun)
1981 need_vimrun_warning = TRUE;
1982 }
1983
1984 /*
1985 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1986 * Otherwise the default "findstr /n" is used.
1987 */
1988 if (!executable_exists("findstr.exe"))
1989 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1990
1991#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001992 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993#endif
1994}
1995
1996
1997#else /* FEAT_GUI_W32 */
1998
1999#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2000#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2001
2002/*
2003 * ClearConsoleBuffer()
2004 * Description:
2005 * Clears the entire contents of the console screen buffer, using the
2006 * specified attribute.
2007 * Returns:
2008 * TRUE on success
2009 */
2010 static BOOL
2011ClearConsoleBuffer(WORD wAttribute)
2012{
2013 CONSOLE_SCREEN_BUFFER_INFO csbi;
2014 COORD coord;
2015 DWORD NumCells, dummy;
2016
2017 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2018 return FALSE;
2019
2020 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2021 coord.X = 0;
2022 coord.Y = 0;
2023 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2024 coord, &dummy))
2025 {
2026 return FALSE;
2027 }
2028 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2029 coord, &dummy))
2030 {
2031 return FALSE;
2032 }
2033
2034 return TRUE;
2035}
2036
2037/*
2038 * FitConsoleWindow()
2039 * Description:
2040 * Checks if the console window will fit within given buffer dimensions.
2041 * Also, if requested, will shrink the window to fit.
2042 * Returns:
2043 * TRUE on success
2044 */
2045 static BOOL
2046FitConsoleWindow(
2047 COORD dwBufferSize,
2048 BOOL WantAdjust)
2049{
2050 CONSOLE_SCREEN_BUFFER_INFO csbi;
2051 COORD dwWindowSize;
2052 BOOL NeedAdjust = FALSE;
2053
2054 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2055 {
2056 /*
2057 * A buffer resize will fail if the current console window does
2058 * not lie completely within that buffer. To avoid this, we might
2059 * have to move and possibly shrink the window.
2060 */
2061 if (csbi.srWindow.Right >= dwBufferSize.X)
2062 {
2063 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2064 if (dwWindowSize.X > dwBufferSize.X)
2065 dwWindowSize.X = dwBufferSize.X;
2066 csbi.srWindow.Right = dwBufferSize.X - 1;
2067 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2068 NeedAdjust = TRUE;
2069 }
2070 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2071 {
2072 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2073 if (dwWindowSize.Y > dwBufferSize.Y)
2074 dwWindowSize.Y = dwBufferSize.Y;
2075 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2076 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2077 NeedAdjust = TRUE;
2078 }
2079 if (NeedAdjust && WantAdjust)
2080 {
2081 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2082 return FALSE;
2083 }
2084 return TRUE;
2085 }
2086
2087 return FALSE;
2088}
2089
2090typedef struct ConsoleBufferStruct
2091{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002092 BOOL IsValid;
2093 CONSOLE_SCREEN_BUFFER_INFO Info;
2094 PCHAR_INFO Buffer;
2095 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096} ConsoleBuffer;
2097
2098/*
2099 * SaveConsoleBuffer()
2100 * Description:
2101 * Saves important information about the console buffer, including the
2102 * actual buffer contents. The saved information is suitable for later
2103 * restoration by RestoreConsoleBuffer().
2104 * Returns:
2105 * TRUE if all information was saved; FALSE otherwise
2106 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2107 */
2108 static BOOL
2109SaveConsoleBuffer(
2110 ConsoleBuffer *cb)
2111{
2112 DWORD NumCells;
2113 COORD BufferCoord;
2114 SMALL_RECT ReadRegion;
2115 WORD Y, Y_incr;
2116
2117 if (cb == NULL)
2118 return FALSE;
2119
2120 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2121 {
2122 cb->IsValid = FALSE;
2123 return FALSE;
2124 }
2125 cb->IsValid = TRUE;
2126
2127 /*
2128 * Allocate a buffer large enough to hold the entire console screen
2129 * buffer. If this ConsoleBuffer structure has already been initialized
2130 * with a buffer of the correct size, then just use that one.
2131 */
2132 if (!cb->IsValid || cb->Buffer == NULL ||
2133 cb->BufferSize.X != cb->Info.dwSize.X ||
2134 cb->BufferSize.Y != cb->Info.dwSize.Y)
2135 {
2136 cb->BufferSize.X = cb->Info.dwSize.X;
2137 cb->BufferSize.Y = cb->Info.dwSize.Y;
2138 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002139 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2141 if (cb->Buffer == NULL)
2142 return FALSE;
2143 }
2144
2145 /*
2146 * We will now copy the console screen buffer into our buffer.
2147 * ReadConsoleOutput() seems to be limited as far as how much you
2148 * can read at a time. Empirically, this number seems to be about
2149 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2150 * in chunks until it is all copied. The chunks will all have the
2151 * same horizontal characteristics, so initialize them now. The
2152 * height of each chunk will be (12000 / width).
2153 */
2154 BufferCoord.X = 0;
2155 ReadRegion.Left = 0;
2156 ReadRegion.Right = cb->Info.dwSize.X - 1;
2157 Y_incr = 12000 / cb->Info.dwSize.X;
2158 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2159 {
2160 /*
2161 * Read into position (0, Y) in our buffer.
2162 */
2163 BufferCoord.Y = Y;
2164 /*
2165 * Read the region whose top left corner is (0, Y) and whose bottom
2166 * right corner is (width - 1, Y + Y_incr - 1). This should define
2167 * a region of size width by Y_incr. Don't worry if this region is
2168 * too large for the remaining buffer; it will be cropped.
2169 */
2170 ReadRegion.Top = Y;
2171 ReadRegion.Bottom = Y + Y_incr - 1;
2172 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2173 cb->Buffer, /* our buffer */
2174 cb->BufferSize, /* dimensions of our buffer */
2175 BufferCoord, /* offset in our buffer */
2176 &ReadRegion)) /* region to save */
2177 {
2178 vim_free(cb->Buffer);
2179 cb->Buffer = NULL;
2180 return FALSE;
2181 }
2182 }
2183
2184 return TRUE;
2185}
2186
2187/*
2188 * RestoreConsoleBuffer()
2189 * Description:
2190 * Restores important information about the console buffer, including the
2191 * actual buffer contents, if desired. The information to restore is in
2192 * the same format used by SaveConsoleBuffer().
2193 * Returns:
2194 * TRUE on success
2195 */
2196 static BOOL
2197RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002198 ConsoleBuffer *cb,
2199 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200{
2201 COORD BufferCoord;
2202 SMALL_RECT WriteRegion;
2203
2204 if (cb == NULL || !cb->IsValid)
2205 return FALSE;
2206
2207 /*
2208 * Before restoring the buffer contents, clear the current buffer, and
2209 * restore the cursor position and window information. Doing this now
2210 * prevents old buffer contents from "flashing" onto the screen.
2211 */
2212 if (RestoreScreen)
2213 ClearConsoleBuffer(cb->Info.wAttributes);
2214
2215 FitConsoleWindow(cb->Info.dwSize, TRUE);
2216 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2217 return FALSE;
2218 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2219 return FALSE;
2220
2221 if (!RestoreScreen)
2222 {
2223 /*
2224 * No need to restore the screen buffer contents, so we're done.
2225 */
2226 return TRUE;
2227 }
2228
2229 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2230 return FALSE;
2231 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2232 return FALSE;
2233
2234 /*
2235 * Restore the screen buffer contents.
2236 */
2237 if (cb->Buffer != NULL)
2238 {
2239 BufferCoord.X = 0;
2240 BufferCoord.Y = 0;
2241 WriteRegion.Left = 0;
2242 WriteRegion.Top = 0;
2243 WriteRegion.Right = cb->Info.dwSize.X - 1;
2244 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2245 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2246 cb->Buffer, /* our buffer */
2247 cb->BufferSize, /* dimensions of our buffer */
2248 BufferCoord, /* offset in our buffer */
2249 &WriteRegion)) /* region to restore */
2250 {
2251 return FALSE;
2252 }
2253 }
2254
2255 return TRUE;
2256}
2257
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002258#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259#ifdef FEAT_RESTORE_ORIG_SCREEN
2260static ConsoleBuffer g_cbOrig = { 0 };
2261#endif
2262static ConsoleBuffer g_cbNonTermcap = { 0 };
2263static ConsoleBuffer g_cbTermcap = { 0 };
2264
2265#ifdef FEAT_TITLE
2266#ifdef __BORLANDC__
2267typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2268#else
2269typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2270#endif
2271char g_szOrigTitle[256] = { 0 };
2272HWND g_hWnd = NULL; /* also used in os_mswin.c */
2273static HICON g_hOrigIconSmall = NULL;
2274static HICON g_hOrigIcon = NULL;
2275static HICON g_hVimIcon = NULL;
2276static BOOL g_fCanChangeIcon = FALSE;
2277
2278/* ICON* are not defined in VC++ 4.0 */
2279#ifndef ICON_SMALL
2280#define ICON_SMALL 0
2281#endif
2282#ifndef ICON_BIG
2283#define ICON_BIG 1
2284#endif
2285/*
2286 * GetConsoleIcon()
2287 * Description:
2288 * Attempts to retrieve the small icon and/or the big icon currently in
2289 * use by a given window.
2290 * Returns:
2291 * TRUE on success
2292 */
2293 static BOOL
2294GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002295 HWND hWnd,
2296 HICON *phIconSmall,
2297 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002298{
2299 if (hWnd == NULL)
2300 return FALSE;
2301
2302 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002303 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2304 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002305 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002306 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2307 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 return TRUE;
2309}
2310
2311/*
2312 * SetConsoleIcon()
2313 * Description:
2314 * Attempts to change the small icon and/or the big icon currently in
2315 * use by a given window.
2316 * Returns:
2317 * TRUE on success
2318 */
2319 static BOOL
2320SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002321 HWND hWnd,
2322 HICON hIconSmall,
2323 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002325 HICON hPrevIconSmall;
2326 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327
2328 if (hWnd == NULL)
2329 return FALSE;
2330
2331 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002332 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2333 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002334 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002335 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2336 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 return TRUE;
2338}
2339
2340/*
2341 * SaveConsoleTitleAndIcon()
2342 * Description:
2343 * Saves the current console window title in g_szOrigTitle, for later
2344 * restoration. Also, attempts to obtain a handle to the console window,
2345 * and use it to save the small and big icons currently in use by the
2346 * console window. This is not always possible on some versions of Windows;
2347 * nor is it possible when running Vim remotely using Telnet (since the
2348 * console window the user sees is owned by a remote process).
2349 */
2350 static void
2351SaveConsoleTitleAndIcon(void)
2352{
2353 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2354
2355 /* Save the original title. */
2356 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2357 return;
2358
2359 /*
2360 * Obtain a handle to the console window using GetConsoleWindow() from
2361 * KERNEL32.DLL; we need to handle in order to change the window icon.
2362 * This function only exists on NT-based Windows, starting with Windows
2363 * 2000. On older operating systems, we can't change the window icon
2364 * anyway.
2365 */
2366 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2367 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2368 "GetConsoleWindow")) != NULL)
2369 {
2370 g_hWnd = (*GetConsoleWindowProc)();
2371 }
2372 if (g_hWnd == NULL)
2373 return;
2374
2375 /* Save the original console window icon. */
2376 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2377 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2378 return;
2379
2380 /* Extract the first icon contained in the Vim executable. */
2381 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2382 if (g_hVimIcon != NULL)
2383 g_fCanChangeIcon = TRUE;
2384}
2385#endif
2386
2387static int g_fWindInitCalled = FALSE;
2388static int g_fTermcapMode = FALSE;
2389static CONSOLE_CURSOR_INFO g_cci;
2390static DWORD g_cmodein = 0;
2391static DWORD g_cmodeout = 0;
2392
2393/*
2394 * non-GUI version of mch_init().
2395 */
2396 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002397mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398{
2399#ifndef FEAT_RESTORE_ORIG_SCREEN
2400 CONSOLE_SCREEN_BUFFER_INFO csbi;
2401#endif
2402#ifndef __MINGW32__
2403 extern int _fmode;
2404#endif
2405
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002406 /* Silently handle invalid parameters to CRT functions */
2407 SET_INVALID_PARAM_HANDLER;
2408
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 /* Let critical errors result in a failure, not in a dialog box. Required
2410 * for the timestamp test to work on removed floppies. */
2411 SetErrorMode(SEM_FAILCRITICALERRORS);
2412
2413 _fmode = O_BINARY; /* we do our own CR-LF translation */
2414 out_flush();
2415
2416 /* Obtain handles for the standard Console I/O devices */
2417 if (read_cmd_fd == 0)
2418 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2419 else
2420 create_conin();
2421 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2422
2423#ifdef FEAT_RESTORE_ORIG_SCREEN
2424 /* Save the initial console buffer for later restoration */
2425 SaveConsoleBuffer(&g_cbOrig);
2426 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2427#else
2428 /* Get current text attributes */
2429 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2430 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2431#endif
2432 if (cterm_normal_fg_color == 0)
2433 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2434 if (cterm_normal_bg_color == 0)
2435 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2436
2437 /* set termcap codes to current text attributes */
2438 update_tcap(g_attrCurrent);
2439
2440 GetConsoleCursorInfo(g_hConOut, &g_cci);
2441 GetConsoleMode(g_hConIn, &g_cmodein);
2442 GetConsoleMode(g_hConOut, &g_cmodeout);
2443
2444#ifdef FEAT_TITLE
2445 SaveConsoleTitleAndIcon();
2446 /*
2447 * Set both the small and big icons of the console window to Vim's icon.
2448 * Note that Vim presently only has one size of icon (32x32), but it
2449 * automatically gets scaled down to 16x16 when setting the small icon.
2450 */
2451 if (g_fCanChangeIcon)
2452 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2453#endif
2454
2455 ui_get_shellsize();
2456
2457#ifdef MCH_WRITE_DUMP
2458 fdDump = fopen("dump", "wt");
2459
2460 if (fdDump)
2461 {
2462 time_t t;
2463
2464 time(&t);
2465 fputs(ctime(&t), fdDump);
2466 fflush(fdDump);
2467 }
2468#endif
2469
2470 g_fWindInitCalled = TRUE;
2471
2472#ifdef FEAT_MOUSE
2473 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2474#endif
2475
2476#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002477 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478#endif
2479
2480 /* This will be NULL on anything but NT 4.0 */
2481 s_pfnGetConsoleKeyboardLayoutName =
2482 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2483 "GetConsoleKeyboardLayoutNameA");
2484}
2485
2486/*
2487 * non-GUI version of mch_exit().
2488 * Shut down and exit with status `r'
2489 * Careful: mch_exit() may be called before mch_init()!
2490 */
2491 void
2492mch_exit(int r)
2493{
2494 stoptermcap();
2495
2496 if (g_fWindInitCalled)
2497 settmode(TMODE_COOK);
2498
2499 ml_close_all(TRUE); /* remove all memfiles */
2500
2501 if (g_fWindInitCalled)
2502 {
2503#ifdef FEAT_TITLE
2504 mch_restore_title(3);
2505 /*
2506 * Restore both the small and big icons of the console window to
2507 * what they were at startup. Don't do this when the window is
2508 * closed, Vim would hang here.
2509 */
2510 if (g_fCanChangeIcon && !g_fForceExit)
2511 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2512#endif
2513
2514#ifdef MCH_WRITE_DUMP
2515 if (fdDump)
2516 {
2517 time_t t;
2518
2519 time(&t);
2520 fputs(ctime(&t), fdDump);
2521 fclose(fdDump);
2522 }
2523 fdDump = NULL;
2524#endif
2525 }
2526
2527 SetConsoleCursorInfo(g_hConOut, &g_cci);
2528 SetConsoleMode(g_hConIn, g_cmodein);
2529 SetConsoleMode(g_hConOut, g_cmodeout);
2530
2531#ifdef DYNAMIC_GETTEXT
2532 dyn_libintl_end();
2533#endif
2534
2535 exit(r);
2536}
2537#endif /* !FEAT_GUI_W32 */
2538
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539/*
2540 * Do we have an interactive window?
2541 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002542/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 int
2544mch_check_win(
2545 int argc,
2546 char **argv)
2547{
2548 get_exe_name();
2549
2550#ifdef FEAT_GUI_W32
2551 return OK; /* GUI always has a tty */
2552#else
2553 if (isatty(1))
2554 return OK;
2555 return FAIL;
2556#endif
2557}
2558
2559
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002560#ifdef FEAT_MBYTE
2561/*
2562 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2563 * if it already exists. When "len" is > 0, also expand short to long
2564 * filenames.
2565 * Return FAIL if wide functions are not available, OK otherwise.
2566 * NOTE: much of this is identical to fname_case(), keep in sync!
2567 */
2568 static int
2569fname_casew(
2570 WCHAR *name,
2571 int len)
2572{
2573 WCHAR szTrueName[_MAX_PATH + 2];
2574 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2575 WCHAR *ptrue, *ptruePrev;
2576 WCHAR *porig, *porigPrev;
2577 int flen;
2578 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002579 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002580 int c;
2581 int slen;
2582
2583 flen = (int)wcslen(name);
2584 if (flen > _MAX_PATH)
2585 return OK;
2586
2587 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2588
2589 /* Build the new name in szTrueName[] one component at a time. */
2590 porig = name;
2591 ptrue = szTrueName;
2592
2593 if (iswalpha(porig[0]) && porig[1] == L':')
2594 {
2595 /* copy leading drive letter */
2596 *ptrue++ = *porig++;
2597 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002598 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002599 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002600
2601 while (*porig != NUL)
2602 {
2603 /* copy \ characters */
2604 while (*porig == psepc)
2605 *ptrue++ = *porig++;
2606
2607 ptruePrev = ptrue;
2608 porigPrev = porig;
2609 while (*porig != NUL && *porig != psepc)
2610 {
2611 *ptrue++ = *porig++;
2612 }
2613 *ptrue = NUL;
2614
2615 /* To avoid a slow failure append "\*" when searching a directory,
2616 * server or network share. */
2617 wcscpy(szTrueNameTemp, szTrueName);
2618 slen = (int)wcslen(szTrueNameTemp);
2619 if (*porig == psepc && slen + 2 < _MAX_PATH)
2620 wcscpy(szTrueNameTemp + slen, L"\\*");
2621
2622 /* Skip "", "." and "..". */
2623 if (ptrue > ptruePrev
2624 && (ptruePrev[0] != L'.'
2625 || (ptruePrev[1] != NUL
2626 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2627 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2628 != INVALID_HANDLE_VALUE)
2629 {
2630 c = *porig;
2631 *porig = NUL;
2632
2633 /* Only use the match when it's the same name (ignoring case) or
2634 * expansion is allowed and there is a match with the short name
2635 * and there is enough room. */
2636 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2637 || (len > 0
2638 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2639 && (int)(ptruePrev - szTrueName)
2640 + (int)wcslen(fb.cFileName) < len)))
2641 {
2642 wcscpy(ptruePrev, fb.cFileName);
2643
2644 /* Look for exact match and prefer it if found. Must be a
2645 * long name, otherwise there would be only one match. */
2646 while (FindNextFileW(hFind, &fb))
2647 {
2648 if (*fb.cAlternateFileName != NUL
2649 && (wcscoll(porigPrev, fb.cFileName) == 0
2650 || (len > 0
2651 && (_wcsicoll(porigPrev,
2652 fb.cAlternateFileName) == 0
2653 && (int)(ptruePrev - szTrueName)
2654 + (int)wcslen(fb.cFileName) < len))))
2655 {
2656 wcscpy(ptruePrev, fb.cFileName);
2657 break;
2658 }
2659 }
2660 }
2661 FindClose(hFind);
2662 *porig = c;
2663 ptrue = ptruePrev + wcslen(ptruePrev);
2664 }
2665 else if (hFind == INVALID_HANDLE_VALUE
2666 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2667 return FAIL;
2668 }
2669
2670 wcscpy(name, szTrueName);
2671 return OK;
2672}
2673#endif
2674
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675/*
2676 * fname_case(): Set the case of the file name, if it already exists.
2677 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002678 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002679 */
2680 void
2681fname_case(
2682 char_u *name,
2683 int len)
2684{
2685 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002686 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687 char *ptrue, *ptruePrev;
2688 char *porig, *porigPrev;
2689 int flen;
2690 WIN32_FIND_DATA fb;
2691 HANDLE hFind;
2692 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002693 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002695 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002696 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002697 return;
2698
2699 slash_adjust(name);
2700
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002701#ifdef FEAT_MBYTE
2702 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2703 {
2704 WCHAR *p = enc_to_utf16(name, NULL);
2705
2706 if (p != NULL)
2707 {
2708 char_u *q;
2709 WCHAR buf[_MAX_PATH + 2];
2710
2711 wcscpy(buf, p);
2712 vim_free(p);
2713
2714 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2715 {
2716 q = utf16_to_enc(buf, NULL);
2717 if (q != NULL)
2718 {
2719 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2720 vim_free(q);
2721 return;
2722 }
2723 }
2724 }
2725 /* Retry with non-wide function (for Windows 98). */
2726 }
2727#endif
2728
2729 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2730 * So we should check this after calling wide function. */
2731 if (flen > _MAX_PATH)
2732 return;
2733
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734 /* Build the new name in szTrueName[] one component at a time. */
2735 porig = name;
2736 ptrue = szTrueName;
2737
2738 if (isalpha(porig[0]) && porig[1] == ':')
2739 {
2740 /* copy leading drive letter */
2741 *ptrue++ = *porig++;
2742 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002744 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745
2746 while (*porig != NUL)
2747 {
2748 /* copy \ characters */
2749 while (*porig == psepc)
2750 *ptrue++ = *porig++;
2751
2752 ptruePrev = ptrue;
2753 porigPrev = porig;
2754 while (*porig != NUL && *porig != psepc)
2755 {
2756#ifdef FEAT_MBYTE
2757 int l;
2758
2759 if (enc_dbcs)
2760 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002761 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002762 while (--l >= 0)
2763 *ptrue++ = *porig++;
2764 }
2765 else
2766#endif
2767 *ptrue++ = *porig++;
2768 }
2769 *ptrue = NUL;
2770
Bram Moolenaar464c9252010-10-13 20:37:41 +02002771 /* To avoid a slow failure append "\*" when searching a directory,
2772 * server or network share. */
2773 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002774 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002775 if (*porig == psepc && slen + 2 < _MAX_PATH)
2776 STRCPY(szTrueNameTemp + slen, "\\*");
2777
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778 /* Skip "", "." and "..". */
2779 if (ptrue > ptruePrev
2780 && (ptruePrev[0] != '.'
2781 || (ptruePrev[1] != NUL
2782 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002783 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002784 != INVALID_HANDLE_VALUE)
2785 {
2786 c = *porig;
2787 *porig = NUL;
2788
2789 /* Only use the match when it's the same name (ignoring case) or
2790 * expansion is allowed and there is a match with the short name
2791 * and there is enough room. */
2792 if (_stricoll(porigPrev, fb.cFileName) == 0
2793 || (len > 0
2794 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2795 && (int)(ptruePrev - szTrueName)
2796 + (int)strlen(fb.cFileName) < len)))
2797 {
2798 STRCPY(ptruePrev, fb.cFileName);
2799
2800 /* Look for exact match and prefer it if found. Must be a
2801 * long name, otherwise there would be only one match. */
2802 while (FindNextFile(hFind, &fb))
2803 {
2804 if (*fb.cAlternateFileName != NUL
2805 && (strcoll(porigPrev, fb.cFileName) == 0
2806 || (len > 0
2807 && (_stricoll(porigPrev,
2808 fb.cAlternateFileName) == 0
2809 && (int)(ptruePrev - szTrueName)
2810 + (int)strlen(fb.cFileName) < len))))
2811 {
2812 STRCPY(ptruePrev, fb.cFileName);
2813 break;
2814 }
2815 }
2816 }
2817 FindClose(hFind);
2818 *porig = c;
2819 ptrue = ptruePrev + strlen(ptruePrev);
2820 }
2821 }
2822
2823 STRCPY(name, szTrueName);
2824}
2825
2826
2827/*
2828 * Insert user name in s[len].
2829 */
2830 int
2831mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002832 char_u *s,
2833 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002835 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002836 DWORD cch = sizeof szUserName;
2837
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002838#ifdef FEAT_MBYTE
2839 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2840 {
2841 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2842 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2843
2844 if (GetUserNameW(wszUserName, &wcch))
2845 {
2846 char_u *p = utf16_to_enc(wszUserName, NULL);
2847
2848 if (p != NULL)
2849 {
2850 vim_strncpy(s, p, len - 1);
2851 vim_free(p);
2852 return OK;
2853 }
2854 }
2855 /* Retry with non-wide function (for Windows 98). */
2856 }
2857#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858 if (GetUserName(szUserName, &cch))
2859 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002860 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861 return OK;
2862 }
2863 s[0] = NUL;
2864 return FAIL;
2865}
2866
2867
2868/*
2869 * Insert host name in s[len].
2870 */
2871 void
2872mch_get_host_name(
2873 char_u *s,
2874 int len)
2875{
2876 DWORD cch = len;
2877
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002878#ifdef FEAT_MBYTE
2879 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2880 {
2881 WCHAR wszHostName[256 + 1];
2882 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2883
2884 if (GetComputerNameW(wszHostName, &wcch))
2885 {
2886 char_u *p = utf16_to_enc(wszHostName, NULL);
2887
2888 if (p != NULL)
2889 {
2890 vim_strncpy(s, p, len - 1);
2891 vim_free(p);
2892 return;
2893 }
2894 }
2895 /* Retry with non-wide function (for Windows 98). */
2896 }
2897#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002899 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900}
2901
2902
2903/*
2904 * return process ID
2905 */
2906 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002907mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908{
2909 return (long)GetCurrentProcessId();
2910}
2911
2912
2913/*
2914 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2915 * Return OK for success, FAIL for failure.
2916 */
2917 int
2918mch_dirname(
2919 char_u *buf,
2920 int len)
2921{
2922 /*
2923 * Originally this was:
2924 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2925 * But the Win32s known bug list says that getcwd() doesn't work
2926 * so use the Win32 system call instead. <Negri>
2927 */
2928#ifdef FEAT_MBYTE
2929 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2930 {
2931 WCHAR wbuf[_MAX_PATH + 1];
2932
2933 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2934 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002935 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936
2937 if (p != NULL)
2938 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002939 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940 vim_free(p);
2941 return OK;
2942 }
2943 }
2944 /* Retry with non-wide function (for Windows 98). */
2945 }
2946#endif
2947 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2948}
2949
2950/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002951 * Get file permissions for "name".
2952 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953 */
2954 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002955mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002957 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002958 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002960 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002961 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962}
2963
2964
2965/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002966 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002967 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002968 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 */
2970 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002971mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002973 long n = -1;
2974
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975#ifdef FEAT_MBYTE
2976 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2977 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002978 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979
2980 if (p != NULL)
2981 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002982 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002984 if (n == -1 && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2985 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 /* Retry with non-wide function (for Windows 98). */
2987 }
2988 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002989 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002991 n = _chmod(name, perm);
2992 if (n == -1)
2993 return FAIL;
2994
2995 win32_set_archive(name);
2996
2997 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998}
2999
3000/*
3001 * Set hidden flag for "name".
3002 */
3003 void
3004mch_hide(char_u *name)
3005{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003006 int attrs = win32_getattrs(name);
3007 if (attrs == -1)
3008 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003010 attrs |= FILE_ATTRIBUTE_HIDDEN;
3011 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012}
3013
3014/*
3015 * return TRUE if "name" is a directory
3016 * return FALSE if "name" is not a directory or upon error
3017 */
3018 int
3019mch_isdir(char_u *name)
3020{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003021 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022
3023 if (f == -1)
3024 return FALSE; /* file does not exist at all */
3025
3026 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3027}
3028
3029/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003030 * Create directory "name".
3031 * Return 0 on success, -1 on error.
3032 */
3033 int
3034mch_mkdir(char_u *name)
3035{
3036#ifdef FEAT_MBYTE
3037 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3038 {
3039 WCHAR *p;
3040 int retval;
3041
3042 p = enc_to_utf16(name, NULL);
3043 if (p == NULL)
3044 return -1;
3045 retval = _wmkdir(p);
3046 vim_free(p);
3047 return retval;
3048 }
3049#endif
3050 return _mkdir(name);
3051}
3052
3053/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003054 * Return TRUE if file "fname" has more than one link.
3055 */
3056 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003057mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003058{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003059 BY_HANDLE_FILE_INFORMATION info;
3060
3061 return win32_fileinfo(fname, &info) == FILEINFO_OK
3062 && info.nNumberOfLinks > 1;
3063}
3064
3065/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003066 * Return TRUE if file "fname" is a symbolic link.
3067 */
3068 int
3069mch_is_symbolic_link(char_u *fname)
3070{
3071 HANDLE hFind;
3072 int res = FALSE;
3073 WIN32_FIND_DATAA findDataA;
3074 DWORD fileFlags = 0, reparseTag = 0;
3075#ifdef FEAT_MBYTE
3076 WCHAR *wn = NULL;
3077 WIN32_FIND_DATAW findDataW;
3078
3079 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3080 wn = enc_to_utf16(fname, NULL);
3081 if (wn != NULL)
3082 {
3083 hFind = FindFirstFileW(wn, &findDataW);
3084 vim_free(wn);
3085 if (hFind == INVALID_HANDLE_VALUE
3086 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3087 {
3088 /* Retry with non-wide function (for Windows 98). */
3089 hFind = FindFirstFile(fname, &findDataA);
3090 if (hFind != INVALID_HANDLE_VALUE)
3091 {
3092 fileFlags = findDataA.dwFileAttributes;
3093 reparseTag = findDataA.dwReserved0;
3094 }
3095 }
3096 else
3097 {
3098 fileFlags = findDataW.dwFileAttributes;
3099 reparseTag = findDataW.dwReserved0;
3100 }
3101 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003102 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003103#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003104 {
3105 hFind = FindFirstFile(fname, &findDataA);
3106 if (hFind != INVALID_HANDLE_VALUE)
3107 {
3108 fileFlags = findDataA.dwFileAttributes;
3109 reparseTag = findDataA.dwReserved0;
3110 }
3111 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003112
3113 if (hFind != INVALID_HANDLE_VALUE)
3114 FindClose(hFind);
3115
3116 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3117 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3118 res = TRUE;
3119
3120 return res;
3121}
3122
3123/*
3124 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3125 * link.
3126 */
3127 int
3128mch_is_linked(char_u *fname)
3129{
3130 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3131 return TRUE;
3132 return FALSE;
3133}
3134
3135/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003136 * Get the by-handle-file-information for "fname".
3137 * Returns FILEINFO_OK when OK.
3138 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3139 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3140 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3141 */
3142 int
3143win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3144{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003145 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003146 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003147#ifdef FEAT_MBYTE
3148 WCHAR *wn = NULL;
3149
3150 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003151 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003152 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003153 if (wn == NULL)
3154 res = FILEINFO_ENC_FAIL;
3155 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003156 if (wn != NULL)
3157 {
3158 hFile = CreateFileW(wn, /* file name */
3159 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003160 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003161 NULL, /* security descriptor */
3162 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003163 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003164 NULL); /* handle to template file */
3165 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003166 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003167 {
3168 /* Retry with non-wide function (for Windows 98). */
3169 vim_free(wn);
3170 wn = NULL;
3171 }
3172 }
3173 if (wn == NULL)
3174#endif
3175 hFile = CreateFile(fname, /* file name */
3176 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003177 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003178 NULL, /* security descriptor */
3179 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003180 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003181 NULL); /* handle to template file */
3182
3183 if (hFile != INVALID_HANDLE_VALUE)
3184 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003185 if (GetFileInformationByHandle(hFile, info) != 0)
3186 res = FILEINFO_OK;
3187 else
3188 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003189 CloseHandle(hFile);
3190 }
3191
3192#ifdef FEAT_MBYTE
3193 vim_free(wn);
3194#endif
3195 return res;
3196}
3197
3198/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003199 * get file attributes for `name'
3200 * -1 : error
3201 * else FILE_ATTRIBUTE_* defined in winnt.h
3202 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003203 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003204win32_getattrs(char_u *name)
3205{
3206 int attr;
3207#ifdef FEAT_MBYTE
3208 WCHAR *p = NULL;
3209
3210 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3211 p = enc_to_utf16(name, NULL);
3212
3213 if (p != NULL)
3214 {
3215 attr = GetFileAttributesW(p);
3216 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3217 {
3218 /* Retry with non-wide function (for Windows 98). */
3219 vim_free(p);
3220 p = NULL;
3221 }
3222 }
3223 if (p == NULL)
3224#endif
3225 attr = GetFileAttributes((char *)name);
3226#ifdef FEAT_MBYTE
3227 vim_free(p);
3228#endif
3229 return attr;
3230}
3231
3232/*
3233 * set file attributes for `name' to `attrs'
3234 *
3235 * return -1 for failure, 0 otherwise
3236 */
3237 static
3238 int
3239win32_setattrs(char_u *name, int attrs)
3240{
3241 int res;
3242#ifdef FEAT_MBYTE
3243 WCHAR *p = NULL;
3244
3245 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3246 p = enc_to_utf16(name, NULL);
3247
3248 if (p != NULL)
3249 {
3250 res = SetFileAttributesW(p, attrs);
3251 if (res == FALSE
3252 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3253 {
3254 /* Retry with non-wide function (for Windows 98). */
3255 vim_free(p);
3256 p = NULL;
3257 }
3258 }
3259 if (p == NULL)
3260#endif
3261 res = SetFileAttributes((char *)name, attrs);
3262#ifdef FEAT_MBYTE
3263 vim_free(p);
3264#endif
3265 return res ? 0 : -1;
3266}
3267
3268/*
3269 * Set archive flag for "name".
3270 */
3271 static
3272 int
3273win32_set_archive(char_u *name)
3274{
3275 int attrs = win32_getattrs(name);
3276 if (attrs == -1)
3277 return -1;
3278
3279 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3280 return win32_setattrs(name, attrs);
3281}
3282
3283/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003284 * Return TRUE if file or directory "name" is writable (not readonly).
3285 * Strange semantics of Win32: a readonly directory is writable, but you can't
3286 * delete a file. Let's say this means it is writable.
3287 */
3288 int
3289mch_writable(char_u *name)
3290{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003291 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003293 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3294 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003295}
3296
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297/*
3298 * Return 1 if "name" can be executed, 0 if not.
3299 * Return -1 if unknown.
3300 */
3301 int
3302mch_can_exe(char_u *name)
3303{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003304 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003305 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003306 char_u *p;
3307
3308 if (len >= _MAX_PATH) /* safety check */
3309 return FALSE;
3310
3311 /* If there already is an extension try using the name directly. Also do
3312 * this with a Unix-shell like 'shell'. */
3313 if (vim_strchr(gettail(name), '.') != NULL
3314 || strstr((char *)gettail(p_sh), "sh") != NULL)
3315 if (executable_exists((char *)name))
3316 return TRUE;
3317
3318 /*
3319 * Loop over all extensions in $PATHEXT.
3320 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003321 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003322 p = mch_getenv("PATHEXT");
3323 if (p == NULL)
3324 p = (char_u *)".com;.exe;.bat;.cmd";
3325 while (*p)
3326 {
3327 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3328 {
3329 /* A single "." means no extension is added. */
3330 buf[len] = NUL;
3331 ++p;
3332 if (*p)
3333 ++p;
3334 }
3335 else
3336 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
3337 if (executable_exists((char *)buf))
3338 return TRUE;
3339 }
3340 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342
3343/*
3344 * Check what "name" is:
3345 * NODE_NORMAL: file or directory (or doesn't exist)
3346 * NODE_WRITABLE: writable device, socket, fifo, etc.
3347 * NODE_OTHER: non-writable things
3348 */
3349 int
3350mch_nodetype(char_u *name)
3351{
3352 HANDLE hFile;
3353 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003354#ifdef FEAT_MBYTE
3355 WCHAR *wn = NULL;
3356#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357
Bram Moolenaar043545e2006-10-10 16:44:07 +00003358 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3359 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3360 * here. */
3361 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3362 return NODE_WRITABLE;
3363
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003364#ifdef FEAT_MBYTE
3365 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3366 {
3367 wn = enc_to_utf16(name, NULL);
3368 if (wn != NULL)
3369 {
3370 hFile = CreateFileW(wn, /* file name */
3371 GENERIC_WRITE, /* access mode */
3372 0, /* share mode */
3373 NULL, /* security descriptor */
3374 OPEN_EXISTING, /* creation disposition */
3375 0, /* file attributes */
3376 NULL); /* handle to template file */
3377 if (hFile == INVALID_HANDLE_VALUE
3378 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3379 {
3380 /* Retry with non-wide function (for Windows 98). */
3381 vim_free(wn);
3382 wn = NULL;
3383 }
3384 }
3385 }
3386 if (wn == NULL)
3387#endif
3388 hFile = CreateFile(name, /* file name */
3389 GENERIC_WRITE, /* access mode */
3390 0, /* share mode */
3391 NULL, /* security descriptor */
3392 OPEN_EXISTING, /* creation disposition */
3393 0, /* file attributes */
3394 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003396#ifdef FEAT_MBYTE
3397 vim_free(wn);
3398#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399 if (hFile == INVALID_HANDLE_VALUE)
3400 return NODE_NORMAL;
3401
3402 type = GetFileType(hFile);
3403 CloseHandle(hFile);
3404 if (type == FILE_TYPE_CHAR)
3405 return NODE_WRITABLE;
3406 if (type == FILE_TYPE_DISK)
3407 return NODE_NORMAL;
3408 return NODE_OTHER;
3409}
3410
3411#ifdef HAVE_ACL
3412struct my_acl
3413{
3414 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3415 PSID pSidOwner;
3416 PSID pSidGroup;
3417 PACL pDacl;
3418 PACL pSacl;
3419};
3420#endif
3421
3422/*
3423 * Return a pointer to the ACL of file "fname" in allocated memory.
3424 * Return NULL if the ACL is not available for whatever reason.
3425 */
3426 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003427mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003428{
3429#ifndef HAVE_ACL
3430 return (vim_acl_T)NULL;
3431#else
3432 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003433 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434
3435 /* This only works on Windows NT and 2000. */
3436 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3437 {
3438 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3439 if (p != NULL)
3440 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003441# ifdef FEAT_MBYTE
3442 WCHAR *wn = NULL;
3443
3444 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3445 wn = enc_to_utf16(fname, NULL);
3446 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003448 /* Try to retrieve the entire security descriptor. */
3449 err = pGetNamedSecurityInfoW(
3450 wn, // Abstract filename
3451 SE_FILE_OBJECT, // File Object
3452 OWNER_SECURITY_INFORMATION |
3453 GROUP_SECURITY_INFORMATION |
3454 DACL_SECURITY_INFORMATION |
3455 SACL_SECURITY_INFORMATION,
3456 &p->pSidOwner, // Ownership information.
3457 &p->pSidGroup, // Group membership.
3458 &p->pDacl, // Discretionary information.
3459 &p->pSacl, // For auditing purposes.
3460 &p->pSecurityDescriptor);
3461 if (err == ERROR_ACCESS_DENIED ||
3462 err == ERROR_PRIVILEGE_NOT_HELD)
3463 {
3464 /* Retrieve only DACL. */
3465 (void)pGetNamedSecurityInfoW(
3466 wn,
3467 SE_FILE_OBJECT,
3468 DACL_SECURITY_INFORMATION,
3469 NULL,
3470 NULL,
3471 &p->pDacl,
3472 NULL,
3473 &p->pSecurityDescriptor);
3474 }
3475 if (p->pSecurityDescriptor == NULL)
3476 {
3477 mch_free_acl((vim_acl_T)p);
3478 p = NULL;
3479 }
3480 vim_free(wn);
3481 }
3482 else
3483# endif
3484 {
3485 /* Try to retrieve the entire security descriptor. */
3486 err = pGetNamedSecurityInfo(
3487 (LPSTR)fname, // Abstract filename
3488 SE_FILE_OBJECT, // File Object
3489 OWNER_SECURITY_INFORMATION |
3490 GROUP_SECURITY_INFORMATION |
3491 DACL_SECURITY_INFORMATION |
3492 SACL_SECURITY_INFORMATION,
3493 &p->pSidOwner, // Ownership information.
3494 &p->pSidGroup, // Group membership.
3495 &p->pDacl, // Discretionary information.
3496 &p->pSacl, // For auditing purposes.
3497 &p->pSecurityDescriptor);
3498 if (err == ERROR_ACCESS_DENIED ||
3499 err == ERROR_PRIVILEGE_NOT_HELD)
3500 {
3501 /* Retrieve only DACL. */
3502 (void)pGetNamedSecurityInfo(
3503 (LPSTR)fname,
3504 SE_FILE_OBJECT,
3505 DACL_SECURITY_INFORMATION,
3506 NULL,
3507 NULL,
3508 &p->pDacl,
3509 NULL,
3510 &p->pSecurityDescriptor);
3511 }
3512 if (p->pSecurityDescriptor == NULL)
3513 {
3514 mch_free_acl((vim_acl_T)p);
3515 p = NULL;
3516 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517 }
3518 }
3519 }
3520
3521 return (vim_acl_T)p;
3522#endif
3523}
3524
Bram Moolenaar27515922013-06-29 15:36:26 +02003525#ifdef HAVE_ACL
3526/*
3527 * Check if "acl" contains inherited ACE.
3528 */
3529 static BOOL
3530is_acl_inherited(PACL acl)
3531{
3532 DWORD i;
3533 ACL_SIZE_INFORMATION acl_info;
3534 PACCESS_ALLOWED_ACE ace;
3535
3536 acl_info.AceCount = 0;
3537 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3538 for (i = 0; i < acl_info.AceCount; i++)
3539 {
3540 GetAce(acl, i, (LPVOID *)&ace);
3541 if (ace->Header.AceFlags & INHERITED_ACE)
3542 return TRUE;
3543 }
3544 return FALSE;
3545}
3546#endif
3547
Bram Moolenaar071d4272004-06-13 20:20:40 +00003548/*
3549 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3550 * Errors are ignored.
3551 * This must only be called with "acl" equal to what mch_get_acl() returned.
3552 */
3553 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003554mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555{
3556#ifdef HAVE_ACL
3557 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003558 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559
3560 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003561 {
3562# ifdef FEAT_MBYTE
3563 WCHAR *wn = NULL;
3564# endif
3565
3566 /* Set security flags */
3567 if (p->pSidOwner)
3568 sec_info |= OWNER_SECURITY_INFORMATION;
3569 if (p->pSidGroup)
3570 sec_info |= GROUP_SECURITY_INFORMATION;
3571 if (p->pDacl)
3572 {
3573 sec_info |= DACL_SECURITY_INFORMATION;
3574 /* Do not inherit its parent's DACL.
3575 * If the DACL is inherited, Cygwin permissions would be changed.
3576 */
3577 if (!is_acl_inherited(p->pDacl))
3578 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3579 }
3580 if (p->pSacl)
3581 sec_info |= SACL_SECURITY_INFORMATION;
3582
3583# ifdef FEAT_MBYTE
3584 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3585 wn = enc_to_utf16(fname, NULL);
3586 if (wn != NULL)
3587 {
3588 (void)pSetNamedSecurityInfoW(
3589 wn, // Abstract filename
3590 SE_FILE_OBJECT, // File Object
3591 sec_info,
3592 p->pSidOwner, // Ownership information.
3593 p->pSidGroup, // Group membership.
3594 p->pDacl, // Discretionary information.
3595 p->pSacl // For auditing purposes.
3596 );
3597 vim_free(wn);
3598 }
3599 else
3600# endif
3601 {
3602 (void)pSetNamedSecurityInfo(
3603 (LPSTR)fname, // Abstract filename
3604 SE_FILE_OBJECT, // File Object
3605 sec_info,
3606 p->pSidOwner, // Ownership information.
3607 p->pSidGroup, // Group membership.
3608 p->pDacl, // Discretionary information.
3609 p->pSacl // For auditing purposes.
3610 );
3611 }
3612 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613#endif
3614}
3615
3616 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003617mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618{
3619#ifdef HAVE_ACL
3620 struct my_acl *p = (struct my_acl *)acl;
3621
3622 if (p != NULL)
3623 {
3624 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3625 vim_free(p);
3626 }
3627#endif
3628}
3629
3630#ifndef FEAT_GUI_W32
3631
3632/*
3633 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3634 */
3635 static BOOL WINAPI
3636handler_routine(
3637 DWORD dwCtrlType)
3638{
3639 switch (dwCtrlType)
3640 {
3641 case CTRL_C_EVENT:
3642 if (ctrl_c_interrupts)
3643 g_fCtrlCPressed = TRUE;
3644 return TRUE;
3645
3646 case CTRL_BREAK_EVENT:
3647 g_fCBrkPressed = TRUE;
3648 return TRUE;
3649
3650 /* fatal events: shut down gracefully */
3651 case CTRL_CLOSE_EVENT:
3652 case CTRL_LOGOFF_EVENT:
3653 case CTRL_SHUTDOWN_EVENT:
3654 windgoto((int)Rows - 1, 0);
3655 g_fForceExit = TRUE;
3656
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003657 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658 (dwCtrlType == CTRL_CLOSE_EVENT
3659 ? _("close")
3660 : dwCtrlType == CTRL_LOGOFF_EVENT
3661 ? _("logoff")
3662 : _("shutdown")));
3663#ifdef DEBUG
3664 OutputDebugString(IObuff);
3665#endif
3666
3667 preserve_exit(); /* output IObuff, preserve files and exit */
3668
3669 return TRUE; /* not reached */
3670
3671 default:
3672 return FALSE;
3673 }
3674}
3675
3676
3677/*
3678 * set the tty in (raw) ? "raw" : "cooked" mode
3679 */
3680 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003681mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003682{
3683 DWORD cmodein;
3684 DWORD cmodeout;
3685 BOOL bEnableHandler;
3686
3687 GetConsoleMode(g_hConIn, &cmodein);
3688 GetConsoleMode(g_hConOut, &cmodeout);
3689 if (tmode == TMODE_RAW)
3690 {
3691 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3692 ENABLE_ECHO_INPUT);
3693#ifdef FEAT_MOUSE
3694 if (g_fMouseActive)
3695 cmodein |= ENABLE_MOUSE_INPUT;
3696#endif
3697 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3698 bEnableHandler = TRUE;
3699 }
3700 else /* cooked */
3701 {
3702 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3703 ENABLE_ECHO_INPUT);
3704 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3705 bEnableHandler = FALSE;
3706 }
3707 SetConsoleMode(g_hConIn, cmodein);
3708 SetConsoleMode(g_hConOut, cmodeout);
3709 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3710
3711#ifdef MCH_WRITE_DUMP
3712 if (fdDump)
3713 {
3714 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3715 tmode == TMODE_RAW ? "raw" :
3716 tmode == TMODE_COOK ? "cooked" : "normal",
3717 cmodein, cmodeout);
3718 fflush(fdDump);
3719 }
3720#endif
3721}
3722
3723
3724/*
3725 * Get the size of the current window in `Rows' and `Columns'
3726 * Return OK when size could be determined, FAIL otherwise.
3727 */
3728 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003729mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730{
3731 CONSOLE_SCREEN_BUFFER_INFO csbi;
3732
3733 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3734 {
3735 /*
3736 * For some reason, we are trying to get the screen dimensions
3737 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3738 * variables are really intended to mean the size of Vim screen
3739 * while in termcap mode.
3740 */
3741 Rows = g_cbTermcap.Info.dwSize.Y;
3742 Columns = g_cbTermcap.Info.dwSize.X;
3743 }
3744 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3745 {
3746 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3747 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3748 }
3749 else
3750 {
3751 Rows = 25;
3752 Columns = 80;
3753 }
3754 return OK;
3755}
3756
3757/*
3758 * Set a console window to `xSize' * `ySize'
3759 */
3760 static void
3761ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003762 HANDLE hConsole,
3763 int xSize,
3764 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765{
3766 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3767 SMALL_RECT srWindowRect; /* hold the new console size */
3768 COORD coordScreen;
3769
3770#ifdef MCH_WRITE_DUMP
3771 if (fdDump)
3772 {
3773 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3774 fflush(fdDump);
3775 }
3776#endif
3777
3778 /* get the largest size we can size the console window to */
3779 coordScreen = GetLargestConsoleWindowSize(hConsole);
3780
3781 /* define the new console window size and scroll position */
3782 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3783 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3784 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3785
3786 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3787 {
3788 int sx, sy;
3789
3790 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3791 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3792 if (sy < ySize || sx < xSize)
3793 {
3794 /*
3795 * Increasing number of lines/columns, do buffer first.
3796 * Use the maximal size in x and y direction.
3797 */
3798 if (sy < ySize)
3799 coordScreen.Y = ySize;
3800 else
3801 coordScreen.Y = sy;
3802 if (sx < xSize)
3803 coordScreen.X = xSize;
3804 else
3805 coordScreen.X = sx;
3806 SetConsoleScreenBufferSize(hConsole, coordScreen);
3807 }
3808 }
3809
3810 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3811 {
3812#ifdef MCH_WRITE_DUMP
3813 if (fdDump)
3814 {
3815 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3816 GetLastError());
3817 fflush(fdDump);
3818 }
3819#endif
3820 }
3821
3822 /* define the new console buffer size */
3823 coordScreen.X = xSize;
3824 coordScreen.Y = ySize;
3825
3826 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3827 {
3828#ifdef MCH_WRITE_DUMP
3829 if (fdDump)
3830 {
3831 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3832 GetLastError());
3833 fflush(fdDump);
3834 }
3835#endif
3836 }
3837}
3838
3839
3840/*
3841 * Set the console window to `Rows' * `Columns'
3842 */
3843 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003844mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003845{
3846 COORD coordScreen;
3847
3848 /* Don't change window size while still starting up */
3849 if (suppress_winsize != 0)
3850 {
3851 suppress_winsize = 2;
3852 return;
3853 }
3854
3855 if (term_console)
3856 {
3857 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3858
3859 /* Clamp Rows and Columns to reasonable values */
3860 if (Rows > coordScreen.Y)
3861 Rows = coordScreen.Y;
3862 if (Columns > coordScreen.X)
3863 Columns = coordScreen.X;
3864
3865 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3866 }
3867}
3868
3869/*
3870 * Rows and/or Columns has changed.
3871 */
3872 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003873mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874{
3875 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3876}
3877
3878
3879/*
3880 * Called when started up, to set the winsize that was delayed.
3881 */
3882 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003883mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884{
3885 if (suppress_winsize == 2)
3886 {
3887 suppress_winsize = 0;
3888 mch_set_shellsize();
3889 shell_resized();
3890 }
3891 suppress_winsize = 0;
3892}
3893#endif /* FEAT_GUI_W32 */
3894
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003895 static BOOL
3896vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003897 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003898 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003899 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003900 STARTUPINFO *si,
3901 PROCESS_INFORMATION *pi)
3902{
3903# ifdef FEAT_MBYTE
3904 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3905 {
3906 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
3907
3908 if (wcmd != NULL)
3909 {
3910 BOOL ret;
3911 ret = CreateProcessW(
3912 NULL, /* Executable name */
3913 wcmd, /* Command to execute */
3914 NULL, /* Process security attributes */
3915 NULL, /* Thread security attributes */
3916 inherit_handles, /* Inherit handles */
3917 flags, /* Creation flags */
3918 NULL, /* Environment */
3919 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003920 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003921 pi); /* Process information */
3922 vim_free(wcmd);
3923 return ret;
3924 }
3925 }
3926#endif
3927 return CreateProcess(
3928 NULL, /* Executable name */
3929 cmd, /* Command to execute */
3930 NULL, /* Process security attributes */
3931 NULL, /* Thread security attributes */
3932 inherit_handles, /* Inherit handles */
3933 flags, /* Creation flags */
3934 NULL, /* Environment */
3935 NULL, /* Current directory */
3936 si, /* Startup information */
3937 pi); /* Process information */
3938}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939
3940
3941#if defined(FEAT_GUI_W32) || defined(PROTO)
3942
3943/*
3944 * Specialised version of system() for Win32 GUI mode.
3945 * This version proceeds as follows:
3946 * 1. Create a console window for use by the subprocess
3947 * 2. Run the subprocess (it gets the allocated console by default)
3948 * 3. Wait for the subprocess to terminate and get its exit code
3949 * 4. Prompt the user to press a key to close the console window
3950 */
3951 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003952mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003953{
3954 STARTUPINFO si;
3955 PROCESS_INFORMATION pi;
3956 DWORD ret = 0;
3957 HWND hwnd = GetFocus();
3958
3959 si.cb = sizeof(si);
3960 si.lpReserved = NULL;
3961 si.lpDesktop = NULL;
3962 si.lpTitle = NULL;
3963 si.dwFlags = STARTF_USESHOWWINDOW;
3964 /*
3965 * It's nicer to run a filter command in a minimized window, but in
3966 * Windows 95 this makes the command MUCH slower. We can't do it under
3967 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003968 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003969 */
3970 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003971 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003972 else
3973 si.wShowWindow = SW_SHOWNORMAL;
3974 si.cbReserved2 = 0;
3975 si.lpReserved2 = NULL;
3976
3977 /* There is a strange error on Windows 95 when using "c:\\command.com".
3978 * When the "c:\\" is left out it works OK...? */
3979 if (mch_windows95()
3980 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3981 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3982 cmd += 3;
3983
3984 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003985 vim_create_process(cmd, FALSE,
3986 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987
3988 /* Wait for the command to terminate before continuing */
3989 if (g_PlatformId != VER_PLATFORM_WIN32s)
3990 {
3991#ifdef FEAT_GUI
3992 int delay = 1;
3993
3994 /* Keep updating the window while waiting for the shell to finish. */
3995 for (;;)
3996 {
3997 MSG msg;
3998
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003999 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004000 {
4001 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004002 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004003 delay = 1;
4004 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004005 }
4006 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4007 break;
4008
4009 /* We start waiting for a very short time and then increase it, so
4010 * that we respond quickly when the process is quick, and don't
4011 * consume too much overhead when it's slow. */
4012 if (delay < 50)
4013 delay += 10;
4014 }
4015#else
4016 WaitForSingleObject(pi.hProcess, INFINITE);
4017#endif
4018
4019 /* Get the command exit code */
4020 GetExitCodeProcess(pi.hProcess, &ret);
4021 }
4022 else
4023 {
4024 /*
4025 * This ugly code is the only quick way of performing
4026 * a synchronous spawn under Win32s. Yuk.
4027 */
4028 num_windows = 0;
4029 EnumWindows(win32ssynch_cb, 0);
4030 old_num_windows = num_windows;
4031 do
4032 {
4033 Sleep(1000);
4034 num_windows = 0;
4035 EnumWindows(win32ssynch_cb, 0);
4036 } while (num_windows == old_num_windows);
4037 ret = 0;
4038 }
4039
4040 /* Close the handles to the subprocess, so that it goes away */
4041 CloseHandle(pi.hThread);
4042 CloseHandle(pi.hProcess);
4043
4044 /* Try to get input focus back. Doesn't always work though. */
4045 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4046
4047 return ret;
4048}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004049
4050/*
4051 * Thread launched by the gui to send the current buffer data to the
4052 * process. This way avoid to hang up vim totally if the children
4053 * process take a long time to process the lines.
4054 */
4055 static DWORD WINAPI
4056sub_process_writer(LPVOID param)
4057{
4058 HANDLE g_hChildStd_IN_Wr = param;
4059 linenr_T lnum = curbuf->b_op_start.lnum;
4060 DWORD len = 0;
4061 DWORD l;
4062 char_u *lp = ml_get(lnum);
4063 char_u *s;
4064 int written = 0;
4065
4066 for (;;)
4067 {
4068 l = (DWORD)STRLEN(lp + written);
4069 if (l == 0)
4070 len = 0;
4071 else if (lp[written] == NL)
4072 {
4073 /* NL -> NUL translation */
4074 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4075 }
4076 else
4077 {
4078 s = vim_strchr(lp + written, NL);
4079 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4080 s == NULL ? l : (DWORD)(s - (lp + written)),
4081 &len, NULL);
4082 }
4083 if (len == (int)l)
4084 {
4085 /* Finished a line, add a NL, unless this line should not have
4086 * one. */
4087 if (lnum != curbuf->b_op_end.lnum
4088 || !curbuf->b_p_bin
4089 || (lnum != curbuf->b_no_eol_lnum
4090 && (lnum != curbuf->b_ml.ml_line_count
4091 || curbuf->b_p_eol)))
4092 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004093 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004094 }
4095
4096 ++lnum;
4097 if (lnum > curbuf->b_op_end.lnum)
4098 break;
4099
4100 lp = ml_get(lnum);
4101 written = 0;
4102 }
4103 else if (len > 0)
4104 written += len;
4105 }
4106
4107 /* finished all the lines, close pipe */
4108 CloseHandle(g_hChildStd_IN_Wr);
4109 ExitThread(0);
4110}
4111
4112
4113# define BUFLEN 100 /* length for buffer, stolen from unix version */
4114
4115/*
4116 * This function read from the children's stdout and write the
4117 * data on screen or in the buffer accordingly.
4118 */
4119 static void
4120dump_pipe(int options,
4121 HANDLE g_hChildStd_OUT_Rd,
4122 garray_T *ga,
4123 char_u buffer[],
4124 DWORD *buffer_off)
4125{
4126 DWORD availableBytes = 0;
4127 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004128 int ret;
4129 DWORD len;
4130 DWORD toRead;
4131 int repeatCount;
4132
4133 /* we query the pipe to see if there is any data to read
4134 * to avoid to perform a blocking read */
4135 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4136 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004137 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004138 NULL, /* number of read bytes */
4139 &availableBytes, /* available bytes total */
4140 NULL); /* byteLeft */
4141
4142 repeatCount = 0;
4143 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004144 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004145 {
4146 repeatCount++;
4147 toRead =
4148# ifdef FEAT_MBYTE
4149 (DWORD)(BUFLEN - *buffer_off);
4150# else
4151 (DWORD)BUFLEN;
4152# endif
4153 toRead = availableBytes < toRead ? availableBytes : toRead;
4154 ReadFile(g_hChildStd_OUT_Rd, buffer
4155# ifdef FEAT_MBYTE
4156 + *buffer_off, toRead
4157# else
4158 , toRead
4159# endif
4160 , &len, NULL);
4161
4162 /* If we haven't read anything, there is a problem */
4163 if (len == 0)
4164 break;
4165
4166 availableBytes -= len;
4167
4168 if (options & SHELL_READ)
4169 {
4170 /* Do NUL -> NL translation, append NL separated
4171 * lines to the current buffer. */
4172 for (i = 0; i < len; ++i)
4173 {
4174 if (buffer[i] == NL)
4175 append_ga_line(ga);
4176 else if (buffer[i] == NUL)
4177 ga_append(ga, NL);
4178 else
4179 ga_append(ga, buffer[i]);
4180 }
4181 }
4182# ifdef FEAT_MBYTE
4183 else if (has_mbyte)
4184 {
4185 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004186 int c;
4187 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004188
4189 len += *buffer_off;
4190 buffer[len] = NUL;
4191
4192 /* Check if the last character in buffer[] is
4193 * incomplete, keep these bytes for the next
4194 * round. */
4195 for (p = buffer; p < buffer + len; p += l)
4196 {
4197 l = mb_cptr2len(p);
4198 if (l == 0)
4199 l = 1; /* NUL byte? */
4200 else if (MB_BYTE2LEN(*p) != l)
4201 break;
4202 }
4203 if (p == buffer) /* no complete character */
4204 {
4205 /* avoid getting stuck at an illegal byte */
4206 if (len >= 12)
4207 ++p;
4208 else
4209 {
4210 *buffer_off = len;
4211 return;
4212 }
4213 }
4214 c = *p;
4215 *p = NUL;
4216 msg_puts(buffer);
4217 if (p < buffer + len)
4218 {
4219 *p = c;
4220 *buffer_off = (DWORD)((buffer + len) - p);
4221 mch_memmove(buffer, p, *buffer_off);
4222 return;
4223 }
4224 *buffer_off = 0;
4225 }
4226# endif /* FEAT_MBYTE */
4227 else
4228 {
4229 buffer[len] = NUL;
4230 msg_puts(buffer);
4231 }
4232
4233 windgoto(msg_row, msg_col);
4234 cursor_on();
4235 out_flush();
4236 }
4237}
4238
4239/*
4240 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4241 * for communication and doesn't open any new window.
4242 */
4243 static int
4244mch_system_piped(char *cmd, int options)
4245{
4246 STARTUPINFO si;
4247 PROCESS_INFORMATION pi;
4248 DWORD ret = 0;
4249
4250 HANDLE g_hChildStd_IN_Rd = NULL;
4251 HANDLE g_hChildStd_IN_Wr = NULL;
4252 HANDLE g_hChildStd_OUT_Rd = NULL;
4253 HANDLE g_hChildStd_OUT_Wr = NULL;
4254
4255 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4256 DWORD len;
4257
4258 /* buffer used to receive keys */
4259 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4260 int ta_len = 0; /* valid bytes in ta_buf[] */
4261
4262 DWORD i;
4263 int c;
4264 int noread_cnt = 0;
4265 garray_T ga;
4266 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004267 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004268 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004269
4270 SECURITY_ATTRIBUTES saAttr;
4271
4272 /* Set the bInheritHandle flag so pipe handles are inherited. */
4273 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4274 saAttr.bInheritHandle = TRUE;
4275 saAttr.lpSecurityDescriptor = NULL;
4276
4277 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4278 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4279 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4280 /* Create a pipe for the child process's STDIN. */
4281 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4282 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4283 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4284 {
4285 CloseHandle(g_hChildStd_IN_Rd);
4286 CloseHandle(g_hChildStd_IN_Wr);
4287 CloseHandle(g_hChildStd_OUT_Rd);
4288 CloseHandle(g_hChildStd_OUT_Wr);
4289 MSG_PUTS(_("\nCannot create pipes\n"));
4290 }
4291
4292 si.cb = sizeof(si);
4293 si.lpReserved = NULL;
4294 si.lpDesktop = NULL;
4295 si.lpTitle = NULL;
4296 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4297
4298 /* set-up our file redirection */
4299 si.hStdError = g_hChildStd_OUT_Wr;
4300 si.hStdOutput = g_hChildStd_OUT_Wr;
4301 si.hStdInput = g_hChildStd_IN_Rd;
4302 si.wShowWindow = SW_HIDE;
4303 si.cbReserved2 = 0;
4304 si.lpReserved2 = NULL;
4305
4306 if (options & SHELL_READ)
4307 ga_init2(&ga, 1, BUFLEN);
4308
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004309 if (cmd != NULL)
4310 {
4311 p = (char *)vim_strsave((char_u *)cmd);
4312 if (p != NULL)
4313 unescape_shellxquote((char_u *)p, p_sxe);
4314 else
4315 p = cmd;
4316 }
4317
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004318 /* Now, run the command.
4319 * About "Inherit handles" being TRUE: this command can be litigious,
4320 * handle inheritance was deactivated for pending temp file, but, if we
4321 * deactivate it, the pipes don't work for some reason. */
4322 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004323
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004324 if (p != cmd)
4325 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004326
4327 /* Close our unused side of the pipes */
4328 CloseHandle(g_hChildStd_IN_Rd);
4329 CloseHandle(g_hChildStd_OUT_Wr);
4330
4331 if (options & SHELL_WRITE)
4332 {
4333 HANDLE thread =
4334 CreateThread(NULL, /* security attributes */
4335 0, /* default stack size */
4336 sub_process_writer, /* function to be executed */
4337 g_hChildStd_IN_Wr, /* parameter */
4338 0, /* creation flag, start immediately */
4339 NULL); /* we don't care about thread id */
4340 CloseHandle(thread);
4341 g_hChildStd_IN_Wr = NULL;
4342 }
4343
4344 /* Keep updating the window while waiting for the shell to finish. */
4345 for (;;)
4346 {
4347 MSG msg;
4348
Bram Moolenaar175d0702013-12-11 18:36:33 +01004349 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004350 {
4351 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004352 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004353 }
4354
4355 /* write pipe information in the window */
4356 if ((options & (SHELL_READ|SHELL_WRITE))
4357# ifdef FEAT_GUI
4358 || gui.in_use
4359# endif
4360 )
4361 {
4362 len = 0;
4363 if (!(options & SHELL_EXPAND)
4364 && ((options &
4365 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4366 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4367# ifdef FEAT_GUI
4368 || gui.in_use
4369# endif
4370 )
4371 && (ta_len > 0 || noread_cnt > 4))
4372 {
4373 if (ta_len == 0)
4374 {
4375 /* Get extra characters when we don't have any. Reset the
4376 * counter and timer. */
4377 noread_cnt = 0;
4378# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4379 gettimeofday(&start_tv, NULL);
4380# endif
4381 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4382 }
4383 if (ta_len > 0 || len > 0)
4384 {
4385 /*
4386 * For pipes: Check for CTRL-C: send interrupt signal to
4387 * child. Check for CTRL-D: EOF, close pipe to child.
4388 */
4389 if (len == 1 && cmd != NULL)
4390 {
4391 if (ta_buf[ta_len] == Ctrl_C)
4392 {
4393 /* Learn what exit code is expected, for
4394 * now put 9 as SIGKILL */
4395 TerminateProcess(pi.hProcess, 9);
4396 }
4397 if (ta_buf[ta_len] == Ctrl_D)
4398 {
4399 CloseHandle(g_hChildStd_IN_Wr);
4400 g_hChildStd_IN_Wr = NULL;
4401 }
4402 }
4403
4404 /* replace K_BS by <BS> and K_DEL by <DEL> */
4405 for (i = ta_len; i < ta_len + len; ++i)
4406 {
4407 if (ta_buf[i] == CSI && len - i > 2)
4408 {
4409 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4410 if (c == K_DEL || c == K_KDEL || c == K_BS)
4411 {
4412 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4413 (size_t)(len - i - 2));
4414 if (c == K_DEL || c == K_KDEL)
4415 ta_buf[i] = DEL;
4416 else
4417 ta_buf[i] = Ctrl_H;
4418 len -= 2;
4419 }
4420 }
4421 else if (ta_buf[i] == '\r')
4422 ta_buf[i] = '\n';
4423# ifdef FEAT_MBYTE
4424 if (has_mbyte)
4425 i += (*mb_ptr2len_len)(ta_buf + i,
4426 ta_len + len - i) - 1;
4427# endif
4428 }
4429
4430 /*
4431 * For pipes: echo the typed characters. For a pty this
4432 * does not seem to work.
4433 */
4434 for (i = ta_len; i < ta_len + len; ++i)
4435 {
4436 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4437 msg_putchar(ta_buf[i]);
4438# ifdef FEAT_MBYTE
4439 else if (has_mbyte)
4440 {
4441 int l = (*mb_ptr2len)(ta_buf + i);
4442
4443 msg_outtrans_len(ta_buf + i, l);
4444 i += l - 1;
4445 }
4446# endif
4447 else
4448 msg_outtrans_len(ta_buf + i, 1);
4449 }
4450 windgoto(msg_row, msg_col);
4451 out_flush();
4452
4453 ta_len += len;
4454
4455 /*
4456 * Write the characters to the child, unless EOF has been
4457 * typed for pipes. Write one character at a time, to
4458 * avoid losing too much typeahead. When writing buffer
4459 * lines, drop the typed characters (only check for
4460 * CTRL-C).
4461 */
4462 if (options & SHELL_WRITE)
4463 ta_len = 0;
4464 else if (g_hChildStd_IN_Wr != NULL)
4465 {
4466 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4467 1, &len, NULL);
4468 // if we are typing in, we want to keep things reactive
4469 delay = 1;
4470 if (len > 0)
4471 {
4472 ta_len -= len;
4473 mch_memmove(ta_buf, ta_buf + len, ta_len);
4474 }
4475 }
4476 }
4477 }
4478 }
4479
4480 if (ta_len)
4481 ui_inchar_undo(ta_buf, ta_len);
4482
4483 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4484 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004485 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004486 break;
4487 }
4488
4489 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004490 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004491
4492 /* We start waiting for a very short time and then increase it, so
4493 * that we respond quickly when the process is quick, and don't
4494 * consume too much overhead when it's slow. */
4495 if (delay < 50)
4496 delay += 10;
4497 }
4498
4499 /* Close the pipe */
4500 CloseHandle(g_hChildStd_OUT_Rd);
4501 if (g_hChildStd_IN_Wr != NULL)
4502 CloseHandle(g_hChildStd_IN_Wr);
4503
4504 WaitForSingleObject(pi.hProcess, INFINITE);
4505
4506 /* Get the command exit code */
4507 GetExitCodeProcess(pi.hProcess, &ret);
4508
4509 if (options & SHELL_READ)
4510 {
4511 if (ga.ga_len > 0)
4512 {
4513 append_ga_line(&ga);
4514 /* remember that the NL was missing */
4515 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4516 }
4517 else
4518 curbuf->b_no_eol_lnum = 0;
4519 ga_clear(&ga);
4520 }
4521
4522 /* Close the handles to the subprocess, so that it goes away */
4523 CloseHandle(pi.hThread);
4524 CloseHandle(pi.hProcess);
4525
4526 return ret;
4527}
4528
4529 static int
4530mch_system(char *cmd, int options)
4531{
4532 /* if we can pipe and the shelltemp option is off */
4533 if (allowPiping && !p_stmp)
4534 return mch_system_piped(cmd, options);
4535 else
4536 return mch_system_classic(cmd, options);
4537}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004538#else
4539
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004540# ifdef FEAT_MBYTE
4541 static int
4542mch_system(char *cmd, int options)
4543{
4544 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4545 {
4546 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4547 if (wcmd != NULL)
4548 {
4549 int ret = _wsystem(wcmd);
4550 vim_free(wcmd);
4551 return ret;
4552 }
4553 }
4554 return system(cmd);
4555}
4556# else
4557# define mch_system(c, o) system(c)
4558# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004559
4560#endif
4561
4562/*
4563 * Either execute a command by calling the shell or start a new shell
4564 */
4565 int
4566mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004567 char_u *cmd,
4568 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569{
4570 int x = 0;
4571 int tmode = cur_tmode;
4572#ifdef FEAT_TITLE
4573 char szShellTitle[512];
4574
4575 /* Change the title to reflect that we are in a subshell. */
4576 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
4577 {
4578 if (cmd == NULL)
4579 strcat(szShellTitle, " :sh");
4580 else
4581 {
4582 strcat(szShellTitle, " - !");
4583 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4584 strcat(szShellTitle, cmd);
4585 }
4586 mch_settitle(szShellTitle, NULL);
4587 }
4588#endif
4589
4590 out_flush();
4591
4592#ifdef MCH_WRITE_DUMP
4593 if (fdDump)
4594 {
4595 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4596 fflush(fdDump);
4597 }
4598#endif
4599
4600 /*
4601 * Catch all deadly signals while running the external command, because a
4602 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4603 */
4604 signal(SIGINT, SIG_IGN);
4605#if defined(__GNUC__) && !defined(__MINGW32__)
4606 signal(SIGKILL, SIG_IGN);
4607#else
4608 signal(SIGBREAK, SIG_IGN);
4609#endif
4610 signal(SIGILL, SIG_IGN);
4611 signal(SIGFPE, SIG_IGN);
4612 signal(SIGSEGV, SIG_IGN);
4613 signal(SIGTERM, SIG_IGN);
4614 signal(SIGABRT, SIG_IGN);
4615
4616 if (options & SHELL_COOKED)
4617 settmode(TMODE_COOK); /* set to normal mode */
4618
4619 if (cmd == NULL)
4620 {
4621 x = mch_system(p_sh, options);
4622 }
4623 else
4624 {
4625 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004626 char_u *newcmd = NULL;
4627 char_u *cmdbase = cmd;
4628 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004629
4630 /* Skip a leading ", ( and "(. */
4631 if (*cmdbase == '"' )
4632 ++cmdbase;
4633 if (*cmdbase == '(')
4634 ++cmdbase;
4635
4636 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4637 {
4638 STARTUPINFO si;
4639 PROCESS_INFORMATION pi;
4640 DWORD flags = CREATE_NEW_CONSOLE;
4641 char_u *p;
4642
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004643 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004644 si.cb = sizeof(si);
4645 si.lpReserved = NULL;
4646 si.lpDesktop = NULL;
4647 si.lpTitle = NULL;
4648 si.dwFlags = 0;
4649 si.cbReserved2 = 0;
4650 si.lpReserved2 = NULL;
4651
4652 cmdbase = skipwhite(cmdbase + 5);
4653 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4654 && vim_iswhite(cmdbase[4]))
4655 {
4656 cmdbase = skipwhite(cmdbase + 4);
4657 si.dwFlags = STARTF_USESHOWWINDOW;
4658 si.wShowWindow = SW_SHOWMINNOACTIVE;
4659 }
4660 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4661 && vim_iswhite(cmdbase[2]))
4662 {
4663 cmdbase = skipwhite(cmdbase + 2);
4664 flags = CREATE_NO_WINDOW;
4665 si.dwFlags = STARTF_USESTDHANDLES;
4666 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004667 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004668 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004669 NULL, // Security att.
4670 OPEN_EXISTING, // Open flags
4671 FILE_ATTRIBUTE_NORMAL, // File att.
4672 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004673 si.hStdOutput = si.hStdInput;
4674 si.hStdError = si.hStdInput;
4675 }
4676
4677 /* Remove a trailing ", ) and )" if they have a match
4678 * at the start of the command. */
4679 if (cmdbase > cmd)
4680 {
4681 p = cmdbase + STRLEN(cmdbase);
4682 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4683 *--p = NUL;
4684 if (p > cmdbase && p[-1] == ')'
4685 && (*cmd =='(' || cmd[1] == '('))
4686 *--p = NUL;
4687 }
4688
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004689 newcmd = cmdbase;
4690 unescape_shellxquote(cmdbase, p_sxe);
4691
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004692 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004693 * If creating new console, arguments are passed to the
4694 * 'cmd.exe' as-is. If it's not, arguments are not treated
4695 * correctly for current 'cmd.exe'. So unescape characters in
4696 * shellxescape except '|' for avoiding to be treated as
4697 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004698 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004699 if (flags != CREATE_NEW_CONSOLE)
4700 {
4701 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004702 char_u *cmd_shell = mch_getenv("COMSPEC");
4703
4704 if (cmd_shell == NULL || *cmd_shell == NUL)
4705 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004706
4707 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4708 if (subcmd != NULL)
4709 {
4710 /* make "cmd.exe /c arguments" */
4711 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004712 newcmd = lalloc(cmdlen, TRUE);
4713 if (newcmd != NULL)
4714 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004715 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004716 else
4717 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004718 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004719 }
4720 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004721
4722 /*
4723 * Now, start the command as a process, so that it doesn't
4724 * inherit our handles which causes unpleasant dangling swap
4725 * files if we exit before the spawned process
4726 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004727 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004728 x = 0;
4729 else
4730 {
4731 x = -1;
4732#ifdef FEAT_GUI_W32
4733 EMSG(_("E371: Command not found"));
4734#endif
4735 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004736
4737 if (newcmd != cmdbase)
4738 vim_free(newcmd);
4739
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004740 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004741 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004742 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004743 CloseHandle(si.hStdInput);
4744 }
4745 /* Close the handles to the subprocess, so that it goes away */
4746 CloseHandle(pi.hThread);
4747 CloseHandle(pi.hProcess);
4748 }
4749 else
4750 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004751 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004752#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004753 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004755 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4756
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004757 newcmd = lalloc(cmdlen, TRUE);
4758 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004759 {
4760#if defined(FEAT_GUI_W32)
4761 if (need_vimrun_warning)
4762 {
4763 MessageBox(NULL,
4764 _("VIMRUN.EXE not found in your $PATH.\n"
4765 "External commands will not pause after completion.\n"
4766 "See :help win32-vimrun for more information."),
4767 _("Vim Warning"),
4768 MB_ICONWARNING);
4769 need_vimrun_warning = FALSE;
4770 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004771 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772 /* Use vimrun to execute the command. It opens a console
4773 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004774 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004775 vimrun_path,
4776 (msg_silent != 0 || (options & SHELL_DOOUT))
4777 ? "-s " : "",
4778 p_sh, p_shcf, cmd);
4779 else
4780#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004781 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004782 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004784 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004786 }
4787 }
4788
4789 if (tmode == TMODE_RAW)
4790 settmode(TMODE_RAW); /* set to raw mode */
4791
4792 /* Print the return value, unless "vimrun" was used. */
4793 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4794#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004795 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4796 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797#endif
4798 )
4799 {
4800 smsg(_("shell returned %d"), x);
4801 msg_putchar('\n');
4802 }
4803#ifdef FEAT_TITLE
4804 resettitle();
4805#endif
4806
4807 signal(SIGINT, SIG_DFL);
4808#if defined(__GNUC__) && !defined(__MINGW32__)
4809 signal(SIGKILL, SIG_DFL);
4810#else
4811 signal(SIGBREAK, SIG_DFL);
4812#endif
4813 signal(SIGILL, SIG_DFL);
4814 signal(SIGFPE, SIG_DFL);
4815 signal(SIGSEGV, SIG_DFL);
4816 signal(SIGTERM, SIG_DFL);
4817 signal(SIGABRT, SIG_DFL);
4818
4819 return x;
4820}
4821
4822
4823#ifndef FEAT_GUI_W32
4824
4825/*
4826 * Start termcap mode
4827 */
4828 static void
4829termcap_mode_start(void)
4830{
4831 DWORD cmodein;
4832
4833 if (g_fTermcapMode)
4834 return;
4835
4836 SaveConsoleBuffer(&g_cbNonTermcap);
4837
4838 if (g_cbTermcap.IsValid)
4839 {
4840 /*
4841 * We've been in termcap mode before. Restore certain screen
4842 * characteristics, including the buffer size and the window
4843 * size. Since we will be redrawing the screen, we don't need
4844 * to restore the actual contents of the buffer.
4845 */
4846 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4847 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4848 Rows = g_cbTermcap.Info.dwSize.Y;
4849 Columns = g_cbTermcap.Info.dwSize.X;
4850 }
4851 else
4852 {
4853 /*
4854 * This is our first time entering termcap mode. Clear the console
4855 * screen buffer, and resize the buffer to match the current window
4856 * size. We will use this as the size of our editing environment.
4857 */
4858 ClearConsoleBuffer(g_attrCurrent);
4859 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4860 }
4861
4862#ifdef FEAT_TITLE
4863 resettitle();
4864#endif
4865
4866 GetConsoleMode(g_hConIn, &cmodein);
4867#ifdef FEAT_MOUSE
4868 if (g_fMouseActive)
4869 cmodein |= ENABLE_MOUSE_INPUT;
4870 else
4871 cmodein &= ~ENABLE_MOUSE_INPUT;
4872#endif
4873 cmodein |= ENABLE_WINDOW_INPUT;
4874 SetConsoleMode(g_hConIn, cmodein);
4875
4876 redraw_later_clear();
4877 g_fTermcapMode = TRUE;
4878}
4879
4880
4881/*
4882 * End termcap mode
4883 */
4884 static void
4885termcap_mode_end(void)
4886{
4887 DWORD cmodein;
4888 ConsoleBuffer *cb;
4889 COORD coord;
4890 DWORD dwDummy;
4891
4892 if (!g_fTermcapMode)
4893 return;
4894
4895 SaveConsoleBuffer(&g_cbTermcap);
4896
4897 GetConsoleMode(g_hConIn, &cmodein);
4898 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4899 SetConsoleMode(g_hConIn, cmodein);
4900
4901#ifdef FEAT_RESTORE_ORIG_SCREEN
4902 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4903#else
4904 cb = &g_cbNonTermcap;
4905#endif
4906 RestoreConsoleBuffer(cb, p_rs);
4907 SetConsoleCursorInfo(g_hConOut, &g_cci);
4908
4909 if (p_rs || exiting)
4910 {
4911 /*
4912 * Clear anything that happens to be on the current line.
4913 */
4914 coord.X = 0;
4915 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4916 FillConsoleOutputCharacter(g_hConOut, ' ',
4917 cb->Info.dwSize.X, coord, &dwDummy);
4918 /*
4919 * The following is just for aesthetics. If we are exiting without
4920 * restoring the screen, then we want to have a prompt string
4921 * appear at the bottom line. However, the command interpreter
4922 * seems to always advance the cursor one line before displaying
4923 * the prompt string, which causes the screen to scroll. To
4924 * counter this, move the cursor up one line before exiting.
4925 */
4926 if (exiting && !p_rs)
4927 coord.Y--;
4928 /*
4929 * Position the cursor at the leftmost column of the desired row.
4930 */
4931 SetConsoleCursorPosition(g_hConOut, coord);
4932 }
4933
4934 g_fTermcapMode = FALSE;
4935}
4936#endif /* FEAT_GUI_W32 */
4937
4938
4939#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004940/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004941 void
4942mch_write(
4943 char_u *s,
4944 int len)
4945{
4946 /* never used */
4947}
4948
4949#else
4950
4951/*
4952 * clear `n' chars, starting from `coord'
4953 */
4954 static void
4955clear_chars(
4956 COORD coord,
4957 DWORD n)
4958{
4959 DWORD dwDummy;
4960
4961 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4962 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4963}
4964
4965
4966/*
4967 * Clear the screen
4968 */
4969 static void
4970clear_screen(void)
4971{
4972 g_coord.X = g_coord.Y = 0;
4973 clear_chars(g_coord, Rows * Columns);
4974}
4975
4976
4977/*
4978 * Clear to end of display
4979 */
4980 static void
4981clear_to_end_of_display(void)
4982{
4983 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4984 * Columns + (Columns - g_coord.X));
4985}
4986
4987
4988/*
4989 * Clear to end of line
4990 */
4991 static void
4992clear_to_end_of_line(void)
4993{
4994 clear_chars(g_coord, Columns - g_coord.X);
4995}
4996
4997
4998/*
4999 * Scroll the scroll region up by `cLines' lines
5000 */
5001 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005002scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005003{
5004 COORD oldcoord = g_coord;
5005
5006 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5007 delete_lines(cLines);
5008
5009 g_coord = oldcoord;
5010}
5011
5012
5013/*
5014 * Set the scroll region
5015 */
5016 static void
5017set_scroll_region(
5018 unsigned left,
5019 unsigned top,
5020 unsigned right,
5021 unsigned bottom)
5022{
5023 if (left >= right
5024 || top >= bottom
5025 || right > (unsigned) Columns - 1
5026 || bottom > (unsigned) Rows - 1)
5027 return;
5028
5029 g_srScrollRegion.Left = left;
5030 g_srScrollRegion.Top = top;
5031 g_srScrollRegion.Right = right;
5032 g_srScrollRegion.Bottom = bottom;
5033}
5034
5035
5036/*
5037 * Insert `cLines' lines at the current cursor position
5038 */
5039 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005040insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005041{
5042 SMALL_RECT source;
5043 COORD dest;
5044 CHAR_INFO fill;
5045
5046 dest.X = 0;
5047 dest.Y = g_coord.Y + cLines;
5048
5049 source.Left = 0;
5050 source.Top = g_coord.Y;
5051 source.Right = g_srScrollRegion.Right;
5052 source.Bottom = g_srScrollRegion.Bottom - cLines;
5053
5054 fill.Char.AsciiChar = ' ';
5055 fill.Attributes = g_attrCurrent;
5056
5057 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5058
5059 /* Here we have to deal with a win32 console flake: If the scroll
5060 * region looks like abc and we scroll c to a and fill with d we get
5061 * cbd... if we scroll block c one line at a time to a, we get cdd...
5062 * vim expects cdd consistently... So we have to deal with that
5063 * here... (this also occurs scrolling the same way in the other
5064 * direction). */
5065
5066 if (source.Bottom < dest.Y)
5067 {
5068 COORD coord;
5069
5070 coord.X = 0;
5071 coord.Y = source.Bottom;
5072 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5073 }
5074}
5075
5076
5077/*
5078 * Delete `cLines' lines at the current cursor position
5079 */
5080 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005081delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082{
5083 SMALL_RECT source;
5084 COORD dest;
5085 CHAR_INFO fill;
5086 int nb;
5087
5088 dest.X = 0;
5089 dest.Y = g_coord.Y;
5090
5091 source.Left = 0;
5092 source.Top = g_coord.Y + cLines;
5093 source.Right = g_srScrollRegion.Right;
5094 source.Bottom = g_srScrollRegion.Bottom;
5095
5096 fill.Char.AsciiChar = ' ';
5097 fill.Attributes = g_attrCurrent;
5098
5099 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5100
5101 /* Here we have to deal with a win32 console flake: If the scroll
5102 * region looks like abc and we scroll c to a and fill with d we get
5103 * cbd... if we scroll block c one line at a time to a, we get cdd...
5104 * vim expects cdd consistently... So we have to deal with that
5105 * here... (this also occurs scrolling the same way in the other
5106 * direction). */
5107
5108 nb = dest.Y + (source.Bottom - source.Top) + 1;
5109
5110 if (nb < source.Top)
5111 {
5112 COORD coord;
5113
5114 coord.X = 0;
5115 coord.Y = nb;
5116 clear_chars(coord, Columns * (source.Top - nb));
5117 }
5118}
5119
5120
5121/*
5122 * Set the cursor position
5123 */
5124 static void
5125gotoxy(
5126 unsigned x,
5127 unsigned y)
5128{
5129 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5130 return;
5131
5132 /* external cursor coords are 1-based; internal are 0-based */
5133 g_coord.X = x - 1;
5134 g_coord.Y = y - 1;
5135 SetConsoleCursorPosition(g_hConOut, g_coord);
5136}
5137
5138
5139/*
5140 * Set the current text attribute = (foreground | background)
5141 * See ../doc/os_win32.txt for the numbers.
5142 */
5143 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005144textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005145{
5146 g_attrCurrent = wAttr;
5147
5148 SetConsoleTextAttribute(g_hConOut, wAttr);
5149}
5150
5151
5152 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005153textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005154{
5155 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
5156
5157 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5158}
5159
5160
5161 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005162textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005163{
5164 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
5165
5166 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5167}
5168
5169
5170/*
5171 * restore the default text attribute (whatever we started with)
5172 */
5173 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005174normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175{
5176 textattr(g_attrDefault);
5177}
5178
5179
5180static WORD g_attrPreStandout = 0;
5181
5182/*
5183 * Make the text standout, by brightening it
5184 */
5185 static void
5186standout(void)
5187{
5188 g_attrPreStandout = g_attrCurrent;
5189 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5190}
5191
5192
5193/*
5194 * Turn off standout mode
5195 */
5196 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005197standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198{
5199 if (g_attrPreStandout)
5200 {
5201 textattr(g_attrPreStandout);
5202 g_attrPreStandout = 0;
5203 }
5204}
5205
5206
5207/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005208 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 */
5210 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005211mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005212{
5213 char_u *p;
5214 int n;
5215
5216 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5217 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5218 if (T_ME[0] == ESC && T_ME[1] == '|')
5219 {
5220 p = T_ME + 2;
5221 n = getdigits(&p);
5222 if (*p == 'm' && n > 0)
5223 {
5224 cterm_normal_fg_color = (n & 0xf) + 1;
5225 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5226 }
5227 }
5228}
5229
5230
5231/*
5232 * visual bell: flash the screen
5233 */
5234 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005235visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236{
5237 COORD coordOrigin = {0, 0};
5238 WORD attrFlash = ~g_attrCurrent & 0xff;
5239
5240 DWORD dwDummy;
5241 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5242
5243 if (oldattrs == NULL)
5244 return;
5245 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5246 coordOrigin, &dwDummy);
5247 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5248 coordOrigin, &dwDummy);
5249
5250 Sleep(15); /* wait for 15 msec */
5251 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5252 coordOrigin, &dwDummy);
5253 vim_free(oldattrs);
5254}
5255
5256
5257/*
5258 * Make the cursor visible or invisible
5259 */
5260 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005261cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005262{
5263 s_cursor_visible = fVisible;
5264#ifdef MCH_CURSOR_SHAPE
5265 mch_update_cursor();
5266#endif
5267}
5268
5269
5270/*
5271 * write `cchToWrite' characters in `pchBuf' to the screen
5272 * Returns the number of characters actually written (at least one).
5273 */
5274 static BOOL
5275write_chars(
5276 LPCSTR pchBuf,
5277 DWORD cchToWrite)
5278{
5279 COORD coord = g_coord;
5280 DWORD written;
5281
5282 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
5283 coord, &written);
5284 /* When writing fails or didn't write a single character, pretend one
5285 * character was written, otherwise we get stuck. */
5286 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
5287 coord, &written) == 0
5288 || written == 0)
5289 written = 1;
5290
5291 g_coord.X += (SHORT) written;
5292
5293 while (g_coord.X > g_srScrollRegion.Right)
5294 {
5295 g_coord.X -= (SHORT) Columns;
5296 if (g_coord.Y < g_srScrollRegion.Bottom)
5297 g_coord.Y++;
5298 }
5299
5300 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5301
5302 return written;
5303}
5304
5305
5306/*
5307 * mch_write(): write the output buffer to the screen, translating ESC
5308 * sequences into calls to console output routines.
5309 */
5310 void
5311mch_write(
5312 char_u *s,
5313 int len)
5314{
5315 s[len] = NUL;
5316
5317 if (!term_console)
5318 {
5319 write(1, s, (unsigned)len);
5320 return;
5321 }
5322
5323 /* translate ESC | sequences into faked bios calls */
5324 while (len--)
5325 {
5326 /* optimization: use one single write_chars for runs of text,
5327 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005328 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005329
5330 if (p_wd)
5331 {
5332 WaitForChar(p_wd);
5333 if (prefix != 0)
5334 prefix = 1;
5335 }
5336
5337 if (prefix != 0)
5338 {
5339 DWORD nWritten;
5340
5341 nWritten = write_chars(s, prefix);
5342#ifdef MCH_WRITE_DUMP
5343 if (fdDump)
5344 {
5345 fputc('>', fdDump);
5346 fwrite(s, sizeof(char_u), nWritten, fdDump);
5347 fputs("<\n", fdDump);
5348 }
5349#endif
5350 len -= (nWritten - 1);
5351 s += nWritten;
5352 }
5353 else if (s[0] == '\n')
5354 {
5355 /* \n, newline: go to the beginning of the next line or scroll */
5356 if (g_coord.Y == g_srScrollRegion.Bottom)
5357 {
5358 scroll(1);
5359 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5360 }
5361 else
5362 {
5363 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5364 }
5365#ifdef MCH_WRITE_DUMP
5366 if (fdDump)
5367 fputs("\\n\n", fdDump);
5368#endif
5369 s++;
5370 }
5371 else if (s[0] == '\r')
5372 {
5373 /* \r, carriage return: go to beginning of line */
5374 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5375#ifdef MCH_WRITE_DUMP
5376 if (fdDump)
5377 fputs("\\r\n", fdDump);
5378#endif
5379 s++;
5380 }
5381 else if (s[0] == '\b')
5382 {
5383 /* \b, backspace: move cursor one position left */
5384 if (g_coord.X > g_srScrollRegion.Left)
5385 g_coord.X--;
5386 else if (g_coord.Y > g_srScrollRegion.Top)
5387 {
5388 g_coord.X = g_srScrollRegion.Right;
5389 g_coord.Y--;
5390 }
5391 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5392#ifdef MCH_WRITE_DUMP
5393 if (fdDump)
5394 fputs("\\b\n", fdDump);
5395#endif
5396 s++;
5397 }
5398 else if (s[0] == '\a')
5399 {
5400 /* \a, bell */
5401 MessageBeep(0xFFFFFFFF);
5402#ifdef MCH_WRITE_DUMP
5403 if (fdDump)
5404 fputs("\\a\n", fdDump);
5405#endif
5406 s++;
5407 }
5408 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5409 {
5410#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005411 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005412#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005413 char_u *p;
5414 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005415
5416 switch (s[2])
5417 {
5418 /* one or two numeric arguments, separated by ';' */
5419
5420 case '0': case '1': case '2': case '3': case '4':
5421 case '5': case '6': case '7': case '8': case '9':
5422 p = s + 2;
5423 arg1 = getdigits(&p); /* no check for length! */
5424 if (p > s + len)
5425 break;
5426
5427 if (*p == ';')
5428 {
5429 ++p;
5430 arg2 = getdigits(&p); /* no check for length! */
5431 if (p > s + len)
5432 break;
5433
5434 if (*p == 'H')
5435 gotoxy(arg2, arg1);
5436 else if (*p == 'r')
5437 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5438 }
5439 else if (*p == 'A')
5440 {
5441 /* move cursor up arg1 lines in same column */
5442 gotoxy(g_coord.X + 1,
5443 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5444 }
5445 else if (*p == 'C')
5446 {
5447 /* move cursor right arg1 columns in same line */
5448 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5449 g_coord.Y + 1);
5450 }
5451 else if (*p == 'H')
5452 {
5453 gotoxy(1, arg1);
5454 }
5455 else if (*p == 'L')
5456 {
5457 insert_lines(arg1);
5458 }
5459 else if (*p == 'm')
5460 {
5461 if (arg1 == 0)
5462 normvideo();
5463 else
5464 textattr((WORD) arg1);
5465 }
5466 else if (*p == 'f')
5467 {
5468 textcolor((WORD) arg1);
5469 }
5470 else if (*p == 'b')
5471 {
5472 textbackground((WORD) arg1);
5473 }
5474 else if (*p == 'M')
5475 {
5476 delete_lines(arg1);
5477 }
5478
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005479 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005480 s = p + 1;
5481 break;
5482
5483
5484 /* Three-character escape sequences */
5485
5486 case 'A':
5487 /* move cursor up one line in same column */
5488 gotoxy(g_coord.X + 1,
5489 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5490 goto got3;
5491
5492 case 'B':
5493 visual_bell();
5494 goto got3;
5495
5496 case 'C':
5497 /* move cursor right one column in same line */
5498 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5499 g_coord.Y + 1);
5500 goto got3;
5501
5502 case 'E':
5503 termcap_mode_end();
5504 goto got3;
5505
5506 case 'F':
5507 standout();
5508 goto got3;
5509
5510 case 'f':
5511 standend();
5512 goto got3;
5513
5514 case 'H':
5515 gotoxy(1, 1);
5516 goto got3;
5517
5518 case 'j':
5519 clear_to_end_of_display();
5520 goto got3;
5521
5522 case 'J':
5523 clear_screen();
5524 goto got3;
5525
5526 case 'K':
5527 clear_to_end_of_line();
5528 goto got3;
5529
5530 case 'L':
5531 insert_lines(1);
5532 goto got3;
5533
5534 case 'M':
5535 delete_lines(1);
5536 goto got3;
5537
5538 case 'S':
5539 termcap_mode_start();
5540 goto got3;
5541
5542 case 'V':
5543 cursor_visible(TRUE);
5544 goto got3;
5545
5546 case 'v':
5547 cursor_visible(FALSE);
5548 goto got3;
5549
5550 got3:
5551 s += 3;
5552 len -= 2;
5553 }
5554
5555#ifdef MCH_WRITE_DUMP
5556 if (fdDump)
5557 {
5558 fputs("ESC | ", fdDump);
5559 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5560 fputc('\n', fdDump);
5561 }
5562#endif
5563 }
5564 else
5565 {
5566 /* Write a single character */
5567 DWORD nWritten;
5568
5569 nWritten = write_chars(s, 1);
5570#ifdef MCH_WRITE_DUMP
5571 if (fdDump)
5572 {
5573 fputc('>', fdDump);
5574 fwrite(s, sizeof(char_u), nWritten, fdDump);
5575 fputs("<\n", fdDump);
5576 }
5577#endif
5578
5579 len -= (nWritten - 1);
5580 s += nWritten;
5581 }
5582 }
5583
5584#ifdef MCH_WRITE_DUMP
5585 if (fdDump)
5586 fflush(fdDump);
5587#endif
5588}
5589
5590#endif /* FEAT_GUI_W32 */
5591
5592
5593/*
5594 * Delay for half a second.
5595 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005596/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005597 void
5598mch_delay(
5599 long msec,
5600 int ignoreinput)
5601{
5602#ifdef FEAT_GUI_W32
5603 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005604#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005606# ifdef FEAT_MZSCHEME
5607 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5608 {
5609 int towait = p_mzq;
5610
5611 /* if msec is large enough, wait by portions in p_mzq */
5612 while (msec > 0)
5613 {
5614 mzvim_check_threads();
5615 if (msec < towait)
5616 towait = msec;
5617 Sleep(towait);
5618 msec -= towait;
5619 }
5620 }
5621 else
5622# endif
5623 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 else
5625 WaitForChar(msec);
5626#endif
5627}
5628
5629
5630/*
5631 * this version of remove is not scared by a readonly (backup) file
5632 * Return 0 for success, -1 for failure.
5633 */
5634 int
5635mch_remove(char_u *name)
5636{
5637#ifdef FEAT_MBYTE
5638 WCHAR *wn = NULL;
5639 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005640#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005642 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5643
5644#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5646 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005647 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648 if (wn != NULL)
5649 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 n = DeleteFileW(wn) ? 0 : -1;
5651 vim_free(wn);
5652 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5653 return n;
5654 /* Retry with non-wide function (for Windows 98). */
5655 }
5656 }
5657#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658 return DeleteFile(name) ? 0 : -1;
5659}
5660
5661
5662/*
5663 * check for an "interrupt signal": CTRL-break or CTRL-C
5664 */
5665 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005666mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667{
5668#ifndef FEAT_GUI_W32 /* never used */
5669 if (g_fCtrlCPressed || g_fCBrkPressed)
5670 {
5671 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5672 got_int = TRUE;
5673 }
5674#endif
5675}
5676
5677
Bram Moolenaar071d4272004-06-13 20:20:40 +00005678#ifdef FEAT_MBYTE
5679/*
5680 * Same code as below, but with wide functions and no comments.
5681 * Return 0 for success, non-zero for failure.
5682 */
5683 int
5684mch_wrename(WCHAR *wold, WCHAR *wnew)
5685{
5686 WCHAR *p;
5687 int i;
5688 WCHAR szTempFile[_MAX_PATH + 1];
5689 WCHAR szNewPath[_MAX_PATH + 1];
5690 HANDLE hf;
5691
5692 if (!mch_windows95())
5693 {
5694 p = wold;
5695 for (i = 0; wold[i] != NUL; ++i)
5696 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5697 && wold[i + 1] != 0)
5698 p = wold + i + 1;
5699 if ((int)(wold + i - p) < 8 || p[6] != '~')
5700 return (MoveFileW(wold, wnew) == 0);
5701 }
5702
5703 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5704 return -1;
5705 *p = NUL;
5706
5707 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5708 return -2;
5709
5710 if (!DeleteFileW(szTempFile))
5711 return -3;
5712
5713 if (!MoveFileW(wold, szTempFile))
5714 return -4;
5715
5716 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5717 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5718 return -5;
5719 if (!CloseHandle(hf))
5720 return -6;
5721
5722 if (!MoveFileW(szTempFile, wnew))
5723 {
5724 (void)MoveFileW(szTempFile, wold);
5725 return -7;
5726 }
5727
5728 DeleteFileW(szTempFile);
5729
5730 if (!DeleteFileW(wold))
5731 return -8;
5732
5733 return 0;
5734}
5735#endif
5736
5737
5738/*
5739 * mch_rename() works around a bug in rename (aka MoveFile) in
5740 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5741 * file whose short file name is "FOO.BAR" (its long file name will
5742 * be correct: "foo.bar~"). Because a file can be accessed by
5743 * either its SFN or its LFN, "foo.bar" has effectively been
5744 * renamed to "foo.bar", which is not at all what was wanted. This
5745 * seems to happen only when renaming files with three-character
5746 * extensions by appending a suffix that does not include ".".
5747 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5748 *
5749 * There is another problem, which isn't really a bug but isn't right either:
5750 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5751 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5752 * service pack 6. Doesn't seem to happen on Windows 98.
5753 *
5754 * Like rename(), returns 0 upon success, non-zero upon failure.
5755 * Should probably set errno appropriately when errors occur.
5756 */
5757 int
5758mch_rename(
5759 const char *pszOldFile,
5760 const char *pszNewFile)
5761{
5762 char szTempFile[_MAX_PATH+1];
5763 char szNewPath[_MAX_PATH+1];
5764 char *pszFilePart;
5765 HANDLE hf;
5766#ifdef FEAT_MBYTE
5767 WCHAR *wold = NULL;
5768 WCHAR *wnew = NULL;
5769 int retval = -1;
5770
5771 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5772 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005773 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5774 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775 if (wold != NULL && wnew != NULL)
5776 retval = mch_wrename(wold, wnew);
5777 vim_free(wold);
5778 vim_free(wnew);
5779 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5780 return retval;
5781 /* Retry with non-wide function (for Windows 98). */
5782 }
5783#endif
5784
5785 /*
5786 * No need to play tricks if not running Windows 95, unless the file name
5787 * contains a "~" as the seventh character.
5788 */
5789 if (!mch_windows95())
5790 {
5791 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5792 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5793 return rename(pszOldFile, pszNewFile);
5794 }
5795
5796 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5797 * a directory, no error is returned and pszFilePart will be NULL. */
5798 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5799 || pszFilePart == NULL)
5800 return -1;
5801 *pszFilePart = NUL;
5802
5803 /* Get (and create) a unique temporary file name in directory of new file */
5804 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5805 return -2;
5806
5807 /* blow the temp file away */
5808 if (!DeleteFile(szTempFile))
5809 return -3;
5810
5811 /* rename old file to the temp file */
5812 if (!MoveFile(pszOldFile, szTempFile))
5813 return -4;
5814
5815 /* now create an empty file called pszOldFile; this prevents the operating
5816 * system using pszOldFile as an alias (SFN) if we're renaming within the
5817 * same directory. For example, we're editing a file called
5818 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5819 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5820 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005821 * cause all sorts of problems later in buf_write(). So, we create an
5822 * empty file called filena~1.txt and the system will have to find some
5823 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005824 */
5825 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5826 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5827 return -5;
5828 if (!CloseHandle(hf))
5829 return -6;
5830
5831 /* rename the temp file to the new file */
5832 if (!MoveFile(szTempFile, pszNewFile))
5833 {
5834 /* Renaming failed. Rename the file back to its old name, so that it
5835 * looks like nothing happened. */
5836 (void)MoveFile(szTempFile, pszOldFile);
5837
5838 return -7;
5839 }
5840
5841 /* Seems to be left around on Novell filesystems */
5842 DeleteFile(szTempFile);
5843
5844 /* finally, remove the empty old file */
5845 if (!DeleteFile(pszOldFile))
5846 return -8;
5847
5848 return 0; /* success */
5849}
5850
5851/*
5852 * Get the default shell for the current hardware platform
5853 */
5854 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005855default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856{
5857 char* psz = NULL;
5858
5859 PlatformId();
5860
5861 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5862 psz = "cmd.exe";
5863 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5864 psz = "command.com";
5865
5866 return psz;
5867}
5868
5869/*
5870 * mch_access() extends access() to do more detailed check on network drives.
5871 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5872 */
5873 int
5874mch_access(char *n, int p)
5875{
5876 HANDLE hFile;
5877 DWORD am;
5878 int retval = -1; /* default: fail */
5879#ifdef FEAT_MBYTE
5880 WCHAR *wn = NULL;
5881
5882 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005883 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884#endif
5885
5886 if (mch_isdir(n))
5887 {
5888 char TempName[_MAX_PATH + 16] = "";
5889#ifdef FEAT_MBYTE
5890 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5891#endif
5892
5893 if (p & R_OK)
5894 {
5895 /* Read check is performed by seeing if we can do a find file on
5896 * the directory for any file. */
5897#ifdef FEAT_MBYTE
5898 if (wn != NULL)
5899 {
5900 int i;
5901 WIN32_FIND_DATAW d;
5902
5903 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5904 TempNameW[i] = wn[i];
5905 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5906 TempNameW[i++] = '\\';
5907 TempNameW[i++] = '*';
5908 TempNameW[i++] = 0;
5909
5910 hFile = FindFirstFileW(TempNameW, &d);
5911 if (hFile == INVALID_HANDLE_VALUE)
5912 {
5913 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5914 goto getout;
5915
5916 /* Retry with non-wide function (for Windows 98). */
5917 vim_free(wn);
5918 wn = NULL;
5919 }
5920 else
5921 (void)FindClose(hFile);
5922 }
5923 if (wn == NULL)
5924#endif
5925 {
5926 char *pch;
5927 WIN32_FIND_DATA d;
5928
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005929 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930 pch = TempName + STRLEN(TempName) - 1;
5931 if (*pch != '\\' && *pch != '/')
5932 *++pch = '\\';
5933 *++pch = '*';
5934 *++pch = NUL;
5935
5936 hFile = FindFirstFile(TempName, &d);
5937 if (hFile == INVALID_HANDLE_VALUE)
5938 goto getout;
5939 (void)FindClose(hFile);
5940 }
5941 }
5942
5943 if (p & W_OK)
5944 {
5945 /* Trying to create a temporary file in the directory should catch
5946 * directories on read-only network shares. However, in
5947 * directories whose ACL allows writes but denies deletes will end
5948 * up keeping the temporary file :-(. */
5949#ifdef FEAT_MBYTE
5950 if (wn != NULL)
5951 {
5952 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5953 {
5954 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5955 goto getout;
5956
5957 /* Retry with non-wide function (for Windows 98). */
5958 vim_free(wn);
5959 wn = NULL;
5960 }
5961 else
5962 DeleteFileW(TempNameW);
5963 }
5964 if (wn == NULL)
5965#endif
5966 {
5967 if (!GetTempFileName(n, "VIM", 0, TempName))
5968 goto getout;
5969 mch_remove((char_u *)TempName);
5970 }
5971 }
5972 }
5973 else
5974 {
5975 /* Trying to open the file for the required access does ACL, read-only
5976 * network share, and file attribute checks. */
5977 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5978 | ((p & R_OK) ? GENERIC_READ : 0);
5979#ifdef FEAT_MBYTE
5980 if (wn != NULL)
5981 {
5982 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5983 if (hFile == INVALID_HANDLE_VALUE
5984 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5985 {
5986 /* Retry with non-wide function (for Windows 98). */
5987 vim_free(wn);
5988 wn = NULL;
5989 }
5990 }
5991 if (wn == NULL)
5992#endif
5993 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5994 if (hFile == INVALID_HANDLE_VALUE)
5995 goto getout;
5996 CloseHandle(hFile);
5997 }
5998
5999 retval = 0; /* success */
6000getout:
6001#ifdef FEAT_MBYTE
6002 vim_free(wn);
6003#endif
6004 return retval;
6005}
6006
6007#if defined(FEAT_MBYTE) || defined(PROTO)
6008/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006009 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006010 */
6011 int
6012mch_open(char *name, int flags, int mode)
6013{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006014 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6015# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006016 WCHAR *wn;
6017 int f;
6018
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006019 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006021 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022 if (wn != NULL)
6023 {
6024 f = _wopen(wn, flags, mode);
6025 vim_free(wn);
6026 if (f >= 0)
6027 return f;
6028 /* Retry with non-wide function (for Windows 98). Can't use
6029 * GetLastError() here and it's unclear what errno gets set to if
6030 * the _wopen() fails for missing wide functions. */
6031 }
6032 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006033# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034
6035 return open(name, flags, mode);
6036}
6037
6038/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006039 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006040 */
6041 FILE *
6042mch_fopen(char *name, char *mode)
6043{
6044 WCHAR *wn, *wm;
6045 FILE *f = NULL;
6046
6047 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6048# ifdef __BORLANDC__
6049 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6050 && g_PlatformId == VER_PLATFORM_WIN32_NT
6051# endif
6052 )
6053 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006054# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006055 /* Work around an annoying assertion in the Microsoft debug CRT
6056 * when mode's text/binary setting doesn't match _get_fmode(). */
6057 char newMode = mode[strlen(mode) - 1];
6058 int oldMode = 0;
6059
6060 _get_fmode(&oldMode);
6061 if (newMode == 't')
6062 _set_fmode(_O_TEXT);
6063 else if (newMode == 'b')
6064 _set_fmode(_O_BINARY);
6065# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006066 wn = enc_to_utf16(name, NULL);
6067 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068 if (wn != NULL && wm != NULL)
6069 f = _wfopen(wn, wm);
6070 vim_free(wn);
6071 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006072
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006073# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006074 _set_fmode(oldMode);
6075# endif
6076
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077 if (f != NULL)
6078 return f;
6079 /* Retry with non-wide function (for Windows 98). Can't use
6080 * GetLastError() here and it's unclear what errno gets set to if
6081 * the _wfopen() fails for missing wide functions. */
6082 }
6083
6084 return fopen(name, mode);
6085}
6086#endif
6087
6088#ifdef FEAT_MBYTE
6089/*
6090 * SUB STREAM (aka info stream) handling:
6091 *
6092 * NTFS can have sub streams for each file. Normal contents of file is
6093 * stored in the main stream, and extra contents (author information and
6094 * title and so on) can be stored in sub stream. After Windows 2000, user
6095 * can access and store those informations in sub streams via explorer's
6096 * property menuitem in right click menu. Those informations in sub streams
6097 * were lost when copying only the main stream. So we have to copy sub
6098 * streams.
6099 *
6100 * Incomplete explanation:
6101 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6102 * More useful info and an example:
6103 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6104 */
6105
6106/*
6107 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6108 * and write to stream "substream" of file "to".
6109 * Errors are ignored.
6110 */
6111 static void
6112copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6113{
6114 HANDLE hTo;
6115 WCHAR *to_name;
6116
6117 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6118 wcscpy(to_name, to);
6119 wcscat(to_name, substream);
6120
6121 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6122 FILE_ATTRIBUTE_NORMAL, NULL);
6123 if (hTo != INVALID_HANDLE_VALUE)
6124 {
6125 long done;
6126 DWORD todo;
6127 DWORD readcnt, written;
6128 char buf[4096];
6129
6130 /* Copy block of bytes at a time. Abort when something goes wrong. */
6131 for (done = 0; done < len; done += written)
6132 {
6133 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006134 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6135 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6137 FALSE, FALSE, context)
6138 || readcnt != todo
6139 || !WriteFile(hTo, buf, todo, &written, NULL)
6140 || written != todo)
6141 break;
6142 }
6143 CloseHandle(hTo);
6144 }
6145
6146 free(to_name);
6147}
6148
6149/*
6150 * Copy info streams from file "from" to file "to".
6151 */
6152 static void
6153copy_infostreams(char_u *from, char_u *to)
6154{
6155 WCHAR *fromw;
6156 WCHAR *tow;
6157 HANDLE sh;
6158 WIN32_STREAM_ID sid;
6159 int headersize;
6160 WCHAR streamname[_MAX_PATH];
6161 DWORD readcount;
6162 void *context = NULL;
6163 DWORD lo, hi;
6164 int len;
6165
6166 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006167 fromw = enc_to_utf16(from, NULL);
6168 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169 if (fromw != NULL && tow != NULL)
6170 {
6171 /* Open the file for reading. */
6172 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6173 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6174 if (sh != INVALID_HANDLE_VALUE)
6175 {
6176 /* Use BackupRead() to find the info streams. Repeat until we
6177 * have done them all.*/
6178 for (;;)
6179 {
6180 /* Get the header to find the length of the stream name. If
6181 * the "readcount" is zero we have done all info streams. */
6182 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006183 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6185 &readcount, FALSE, FALSE, &context)
6186 || readcount == 0)
6187 break;
6188
6189 /* We only deal with streams that have a name. The normal
6190 * file data appears to be without a name, even though docs
6191 * suggest it is called "::$DATA". */
6192 if (sid.dwStreamNameSize > 0)
6193 {
6194 /* Read the stream name. */
6195 if (!BackupRead(sh, (LPBYTE)streamname,
6196 sid.dwStreamNameSize,
6197 &readcount, FALSE, FALSE, &context))
6198 break;
6199
6200 /* Copy an info stream with a name ":anything:$DATA".
6201 * Skip "::$DATA", it has no stream name (examples suggest
6202 * it might be used for the normal file contents).
6203 * Note that BackupRead() counts bytes, but the name is in
6204 * wide characters. */
6205 len = readcount / sizeof(WCHAR);
6206 streamname[len] = 0;
6207 if (len > 7 && wcsicmp(streamname + len - 6,
6208 L":$DATA") == 0)
6209 {
6210 streamname[len - 6] = 0;
6211 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006212 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006213 }
6214 }
6215
6216 /* Advance to the next stream. We might try seeking too far,
6217 * but BackupSeek() doesn't skip over stream borders, thus
6218 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006219 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220 &lo, &hi, &context);
6221 }
6222
6223 /* Clear the context. */
6224 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6225
6226 CloseHandle(sh);
6227 }
6228 }
6229 vim_free(fromw);
6230 vim_free(tow);
6231}
6232#endif
6233
6234/*
6235 * Copy file attributes from file "from" to file "to".
6236 * For Windows NT and later we copy info streams.
6237 * Always returns zero, errors are ignored.
6238 */
6239 int
6240mch_copy_file_attribute(char_u *from, char_u *to)
6241{
6242#ifdef FEAT_MBYTE
6243 /* File streams only work on Windows NT and later. */
6244 PlatformId();
6245 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6246 copy_infostreams(from, to);
6247#endif
6248 return 0;
6249}
6250
6251#if defined(MYRESETSTKOFLW) || defined(PROTO)
6252/*
6253 * Recreate a destroyed stack guard page in win32.
6254 * Written by Benjamin Peterson.
6255 */
6256
6257/* These magic numbers are from the MS header files */
6258#define MIN_STACK_WIN9X 17
6259#define MIN_STACK_WINNT 2
6260
6261/*
6262 * This function does the same thing as _resetstkoflw(), which is only
6263 * available in DevStudio .net and later.
6264 * Returns 0 for failure, 1 for success.
6265 */
6266 int
6267myresetstkoflw(void)
6268{
6269 BYTE *pStackPtr;
6270 BYTE *pGuardPage;
6271 BYTE *pStackBase;
6272 BYTE *pLowestPossiblePage;
6273 MEMORY_BASIC_INFORMATION mbi;
6274 SYSTEM_INFO si;
6275 DWORD nPageSize;
6276 DWORD dummy;
6277
6278 /* This code will not work on win32s. */
6279 PlatformId();
6280 if (g_PlatformId == VER_PLATFORM_WIN32s)
6281 return 0;
6282
6283 /* We need to know the system page size. */
6284 GetSystemInfo(&si);
6285 nPageSize = si.dwPageSize;
6286
6287 /* ...and the current stack pointer */
6288 pStackPtr = (BYTE*)_alloca(1);
6289
6290 /* ...and the base of the stack. */
6291 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6292 return 0;
6293 pStackBase = (BYTE*)mbi.AllocationBase;
6294
6295 /* ...and the page thats min_stack_req pages away from stack base; this is
6296 * the lowest page we could use. */
6297 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6298 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6299
6300 /* On Win95, we want the next page down from the end of the stack. */
6301 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6302 {
6303 /* Find the page that's only 1 page down from the page that the stack
6304 * ptr is in. */
6305 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6306 / (DWORD)nPageSize) - 1));
6307 if (pGuardPage < pLowestPossiblePage)
6308 return 0;
6309
6310 /* Apply the noaccess attribute to the page -- there's no guard
6311 * attribute in win95-type OSes. */
6312 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6313 return 0;
6314 }
6315 else
6316 {
6317 /* On NT, however, we want the first committed page in the stack Start
6318 * at the stack base and move forward through memory until we find a
6319 * committed block. */
6320 BYTE *pBlock = pStackBase;
6321
Bram Moolenaara466c992005-07-09 21:03:22 +00006322 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323 {
6324 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6325 return 0;
6326
6327 pBlock += mbi.RegionSize;
6328
6329 if (mbi.State & MEM_COMMIT)
6330 break;
6331 }
6332
6333 /* mbi now describes the first committed block in the stack. */
6334 if (mbi.Protect & PAGE_GUARD)
6335 return 1;
6336
6337 /* decide where the guard page should start */
6338 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6339 pGuardPage = pLowestPossiblePage;
6340 else
6341 pGuardPage = (BYTE*)mbi.BaseAddress;
6342
6343 /* allocate the guard page */
6344 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6345 return 0;
6346
6347 /* apply the guard attribute to the page */
6348 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6349 &dummy))
6350 return 0;
6351 }
6352
6353 return 1;
6354}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006355#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006356
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006357
6358#if defined(FEAT_MBYTE) || defined(PROTO)
6359/*
6360 * The command line arguments in UCS2
6361 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006362static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006363static LPWSTR *ArglistW = NULL;
6364static int global_argc = 0;
6365static char **global_argv;
6366
6367static int used_file_argc = 0; /* last argument in global_argv[] used
6368 for the argument list. */
6369static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6370 command line arguments added to
6371 the argument list */
6372static int used_file_count = 0; /* nr of entries in used_file_indexes */
6373static int used_file_literal = FALSE; /* take file names literally */
6374static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006375static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006376static int used_alist_count = 0;
6377
6378
6379/*
6380 * Get the command line arguments. Unicode version.
6381 * Returns argc. Zero when something fails.
6382 */
6383 int
6384get_cmd_argsW(char ***argvp)
6385{
6386 char **argv = NULL;
6387 int argc = 0;
6388 int i;
6389
6390 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6391 if (ArglistW != NULL)
6392 {
6393 argv = malloc((nArgsW + 1) * sizeof(char *));
6394 if (argv != NULL)
6395 {
6396 argc = nArgsW;
6397 argv[argc] = NULL;
6398 for (i = 0; i < argc; ++i)
6399 {
6400 int len;
6401
6402 /* Convert each Unicode argument to the current codepage. */
6403 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006404 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006405 (LPSTR *)&argv[i], &len, 0, 0);
6406 if (argv[i] == NULL)
6407 {
6408 /* Out of memory, clear everything. */
6409 while (i > 0)
6410 free(argv[--i]);
6411 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006412 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006413 argc = 0;
6414 }
6415 }
6416 }
6417 }
6418
6419 global_argc = argc;
6420 global_argv = argv;
6421 if (argc > 0)
6422 used_file_indexes = malloc(argc * sizeof(int));
6423
6424 if (argvp != NULL)
6425 *argvp = argv;
6426 return argc;
6427}
6428
6429 void
6430free_cmd_argsW(void)
6431{
6432 if (ArglistW != NULL)
6433 {
6434 GlobalFree(ArglistW);
6435 ArglistW = NULL;
6436 }
6437}
6438
6439/*
6440 * Remember "name" is an argument that was added to the argument list.
6441 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6442 * is called.
6443 */
6444 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006445used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006446{
6447 int i;
6448
6449 if (used_file_indexes == NULL)
6450 return;
6451 for (i = used_file_argc + 1; i < global_argc; ++i)
6452 if (STRCMP(global_argv[i], name) == 0)
6453 {
6454 used_file_argc = i;
6455 used_file_indexes[used_file_count++] = i;
6456 break;
6457 }
6458 used_file_literal = literal;
6459 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006460 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006461}
6462
6463/*
6464 * Remember the length of the argument list as it was. If it changes then we
6465 * leave it alone when 'encoding' is set.
6466 */
6467 void
6468set_alist_count(void)
6469{
6470 used_alist_count = GARGCOUNT;
6471}
6472
6473/*
6474 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6475 * has been changed while starting up. Use the UCS-2 command line arguments
6476 * and convert them to 'encoding'.
6477 */
6478 void
6479fix_arg_enc(void)
6480{
6481 int i;
6482 int idx;
6483 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006484 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006485
6486 /* Safety checks:
6487 * - if argument count differs between the wide and non-wide argument
6488 * list, something must be wrong.
6489 * - the file name arguments must have been located.
6490 * - the length of the argument list wasn't changed by the user.
6491 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006492 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006493 || ArglistW == NULL
6494 || used_file_indexes == NULL
6495 || used_file_count == 0
6496 || used_alist_count != GARGCOUNT)
6497 return;
6498
Bram Moolenaar86b68352004-12-27 21:59:20 +00006499 /* Remember the buffer numbers for the arguments. */
6500 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6501 if (fnum_list == NULL)
6502 return; /* out of memory */
6503 for (i = 0; i < GARGCOUNT; ++i)
6504 fnum_list[i] = GARGLIST[i].ae_fnum;
6505
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006506 /* Clear the argument list. Make room for the new arguments. */
6507 alist_clear(&global_alist);
6508 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006509 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006510
6511 for (i = 0; i < used_file_count; ++i)
6512 {
6513 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006514 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006515 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006516 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006517#ifdef FEAT_DIFF
6518 /* When using diff mode may need to concatenate file name to
6519 * directory name. Just like it's done in main(). */
6520 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6521 && !mch_isdir(alist_name(&GARGLIST[0])))
6522 {
6523 char_u *r;
6524
6525 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6526 if (r != NULL)
6527 {
6528 vim_free(str);
6529 str = r;
6530 }
6531 }
6532#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006533 /* Re-use the old buffer by renaming it. When not using literal
6534 * names it's done by alist_expand() below. */
6535 if (used_file_literal)
6536 buf_set_name(fnum_list[i], str);
6537
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006538 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006539 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006540 }
6541
6542 if (!used_file_literal)
6543 {
6544 /* Now expand wildcards in the arguments. */
6545 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6546 * filename characters but are excluded from 'isfname' to make
6547 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6548 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006549 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006550 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6551 }
6552
6553 /* If wildcard expansion failed, we are editing the first file of the
6554 * arglist and there is no file name: Edit the first argument now. */
6555 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6556 {
6557 do_cmdline_cmd((char_u *)":rewind");
6558 if (GARGCOUNT == 1 && used_file_full_path)
6559 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6560 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006561
6562 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006563}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564#endif