blob: e9ec5f7c06da557723140d3242012b632a50476d [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 Moolenaar3a69e112014-01-10 13:51:42 +0100235/*
236 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100237 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100238 */
239 static BOOL
240read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100241 HANDLE hInput,
242 INPUT_RECORD *lpBuffer,
243 DWORD nLength,
244 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100245{
246 enum
247 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100248 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100249 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100250 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100251 static DWORD s_dwIndex = 0;
252 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100253 DWORD dwEvents;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100254
255 if (s_dwMax == 0)
256 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100257 if (nLength == -1)
258 return PeekConsoleInput(hInput, lpBuffer, 1, lpEvents);
259 if (!ReadConsoleInput(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100260 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100261 s_dwIndex = 0;
262 s_dwMax = dwEvents;
263 if (dwEvents == 0)
264 {
265 *lpEvents = 0;
266 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100267 }
268 }
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100269 *lpBuffer = s_irCache[s_dwIndex];
270 if (nLength != -1 && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100271 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100272 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100273 return TRUE;
274}
275
276/*
277 * Version of PeekConsoleInput() that works with IME.
278 */
279 static BOOL
280peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100281 HANDLE hInput,
282 INPUT_RECORD *lpBuffer,
283 DWORD nLength,
284 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100286 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100287}
288
Bram Moolenaar071d4272004-06-13 20:20:40 +0000289 static void
290get_exe_name(void)
291{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100292 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
293 * as the maximum length that works (plus a NUL byte). */
294#define MAX_ENV_PATH_LEN 8192
295 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200296 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297
298 if (exe_name == NULL)
299 {
300 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100301 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000302 if (*temp != NUL)
303 exe_name = FullName_save((char_u *)temp, FALSE);
304 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000305
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200306 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000307 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200308 exe_path = vim_strnsave(exe_name,
309 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200310 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000311 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200312 /* Append our starting directory to $PATH, so that when doing
313 * "!xxd" it's found in our starting directory. Needed because
314 * SearchPath() also looks there. */
315 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100316 if (p == NULL
317 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200318 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100319 if (p == NULL || *p == NUL)
320 temp[0] = NUL;
321 else
322 {
323 STRCPY(temp, p);
324 STRCAT(temp, ";");
325 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200326 STRCAT(temp, exe_path);
327 vim_setenv((char_u *)"PATH", temp);
328 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000329 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000331}
332
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200333/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100334 * Unescape characters in "p" that appear in "escaped".
335 */
336 static void
337unescape_shellxquote(char_u *p, char_u *escaped)
338{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100339 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100340 int n;
341
342 while (*p != NUL)
343 {
344 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
345 mch_memmove(p, p + 1, l--);
346#ifdef FEAT_MBYTE
347 n = (*mb_ptr2len)(p);
348#else
349 n = 1;
350#endif
351 p += n;
352 l -= n;
353 }
354}
355
356/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200357 * Load library "name".
358 */
359 HINSTANCE
360vimLoadLib(char *name)
361{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200362 HINSTANCE dll = NULL;
363 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200364
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200365 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
366 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200367 if (exe_path == NULL)
368 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200369 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200370 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200371#ifdef FEAT_MBYTE
372 WCHAR old_dirw[MAXPATHL];
373
374 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
375 {
376 /* Change directory to where the executable is, both to make
377 * sure we find a .dll there and to avoid looking for a .dll
378 * in the current directory. */
379 SetCurrentDirectory(exe_path);
380 dll = LoadLibrary(name);
381 SetCurrentDirectoryW(old_dirw);
382 return dll;
383 }
384 /* Retry with non-wide function (for Windows 98). */
385 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
386#endif
387 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
388 {
389 /* Change directory to where the executable is, both to make
390 * sure we find a .dll there and to avoid looking for a .dll
391 * in the current directory. */
392 SetCurrentDirectory(exe_path);
393 dll = LoadLibrary(name);
394 SetCurrentDirectory(old_dir);
395 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200396 }
397 return dll;
398}
399
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
401# ifndef GETTEXT_DLL
402# define GETTEXT_DLL "libintl.dll"
403# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200404/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000405static char *null_libintl_gettext(const char *);
406static char *null_libintl_textdomain(const char *);
407static char *null_libintl_bindtextdomain(const char *, const char *);
408static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200410static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000411char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
412char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
413char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000415char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
416 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000417
418 int
419dyn_libintl_init(char *libname)
420{
421 int i;
422 static struct
423 {
424 char *name;
425 FARPROC *ptr;
426 } libintl_entry[] =
427 {
428 {"gettext", (FARPROC*)&dyn_libintl_gettext},
429 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
430 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
431 {NULL, NULL}
432 };
433
434 /* No need to initialize twice. */
435 if (hLibintlDLL)
436 return 1;
437 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200438 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 if (!hLibintlDLL)
440 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200441 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 verbose_enter();
444 EMSG2(_(e_loadlib), GETTEXT_DLL);
445 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200447 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448 }
449 for (i = 0; libintl_entry[i].name != NULL
450 && libintl_entry[i].ptr != NULL; ++i)
451 {
452 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
453 libintl_entry[i].name)) == NULL)
454 {
455 dyn_libintl_end();
456 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000457 {
458 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000460 verbose_leave();
461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000462 return 0;
463 }
464 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000465
466 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000467 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000468 "bind_textdomain_codeset");
469 if (dyn_libintl_bind_textdomain_codeset == NULL)
470 dyn_libintl_bind_textdomain_codeset =
471 null_libintl_bind_textdomain_codeset;
472
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473 return 1;
474}
475
476 void
477dyn_libintl_end()
478{
479 if (hLibintlDLL)
480 FreeLibrary(hLibintlDLL);
481 hLibintlDLL = NULL;
482 dyn_libintl_gettext = null_libintl_gettext;
483 dyn_libintl_textdomain = null_libintl_textdomain;
484 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000485 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486}
487
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000488/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000489 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000490null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491{
492 return (char*)msgid;
493}
494
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000495/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000497null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498{
499 return NULL;
500}
501
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000502/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000504null_libintl_bind_textdomain_codeset(const char *domainname,
505 const char *codeset)
506{
507 return NULL;
508}
509
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000510/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000511 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000512null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000513{
514 return NULL;
515}
516
517#endif /* DYNAMIC_GETTEXT */
518
519/* This symbol is not defined in older versions of the SDK or Visual C++ */
520
521#ifndef VER_PLATFORM_WIN32_WINDOWS
522# define VER_PLATFORM_WIN32_WINDOWS 1
523#endif
524
525DWORD g_PlatformId;
526
527#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100528# ifndef PROTO
529# include <aclapi.h>
530# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200531# ifndef PROTECTED_DACL_SECURITY_INFORMATION
532# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
533# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100534
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535/*
536 * These are needed to dynamically load the ADVAPI DLL, which is not
537 * implemented under Windows 95 (and causes VIM to crash)
538 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200539typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000540 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200541typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
543 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200544# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200545typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200546 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200547typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200548 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
549 PSECURITY_DESCRIPTOR *);
550# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000551
552static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
553static PSNSECINFO pSetNamedSecurityInfo;
554static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200555# ifdef FEAT_MBYTE
556static PSNSECINFOW pSetNamedSecurityInfoW;
557static PGNSECINFOW pGetNamedSecurityInfoW;
558# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559#endif
560
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200561typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
562
563static BOOL allowPiping = FALSE;
564static PSETHANDLEINFORMATION pSetHandleInformation;
565
Bram Moolenaar27515922013-06-29 15:36:26 +0200566#ifdef HAVE_ACL
567/*
568 * Enables or disables the specified privilege.
569 */
570 static BOOL
571win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
572{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100573 BOOL bResult;
574 LUID luid;
575 HANDLE hToken;
576 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200577
578 if (!OpenProcessToken(GetCurrentProcess(),
579 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
580 return FALSE;
581
582 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
583 {
584 CloseHandle(hToken);
585 return FALSE;
586 }
587
588 tokenPrivileges.PrivilegeCount = 1;
589 tokenPrivileges.Privileges[0].Luid = luid;
590 tokenPrivileges.Privileges[0].Attributes = bEnable ?
591 SE_PRIVILEGE_ENABLED : 0;
592
593 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
594 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
595
596 CloseHandle(hToken);
597
598 return bResult && GetLastError() == ERROR_SUCCESS;
599}
600#endif
601
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602/*
603 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
604 * VER_PLATFORM_WIN32_WINDOWS (Win95).
605 */
606 void
607PlatformId(void)
608{
609 static int done = FALSE;
610
611 if (!done)
612 {
613 OSVERSIONINFO ovi;
614
615 ovi.dwOSVersionInfoSize = sizeof(ovi);
616 GetVersionEx(&ovi);
617
618 g_PlatformId = ovi.dwPlatformId;
619
620#ifdef HAVE_ACL
621 /*
622 * Load the ADVAPI runtime if we are on anything
623 * other than Windows 95
624 */
625 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
626 {
627 /*
628 * do this load. Problems: Doesn't unload at end of run (this is
629 * theoretically okay, since Windows should unload it when VIM
630 * terminates). Should we be using the 'mch_libcall' routines?
631 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
632 * time we verify security...
633 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200634 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000635 if (advapi_lib != NULL)
636 {
637 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
638 "SetNamedSecurityInfoA");
639 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
640 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200641# ifdef FEAT_MBYTE
642 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
643 "SetNamedSecurityInfoW");
644 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
645 "GetNamedSecurityInfoW");
646# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000647 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200648 || pGetNamedSecurityInfo == NULL
649# ifdef FEAT_MBYTE
650 || pSetNamedSecurityInfoW == NULL
651 || pGetNamedSecurityInfoW == NULL
652# endif
653 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654 {
655 /* If we can't get the function addresses, set advapi_lib
656 * to NULL so that we don't use them. */
657 FreeLibrary(advapi_lib);
658 advapi_lib = NULL;
659 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200660 /* Enable privilege for getting or setting SACLs. */
661 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000662 }
663 }
664#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200665 /*
666 * If we are on windows NT, try to load the pipe functions, only
667 * available from Win2K.
668 */
669 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
670 {
671 HANDLE kernel32 = GetModuleHandle("kernel32");
672 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
673 kernel32, "SetHandleInformation");
674
675 allowPiping = pSetHandleInformation != NULL;
676 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 done = TRUE;
678 }
679}
680
681/*
682 * Return TRUE when running on Windows 95 (or 98 or ME).
683 * Only to be used after mch_init().
684 */
685 int
686mch_windows95(void)
687{
688 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
689}
690
691#ifdef FEAT_GUI_W32
692/*
693 * Used to work around the "can't do synchronous spawn"
694 * problem on Win32s, without resorting to Universal Thunk.
695 */
696static int old_num_windows;
697static int num_windows;
698
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000699/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700 static BOOL CALLBACK
701win32ssynch_cb(HWND hwnd, LPARAM lparam)
702{
703 num_windows++;
704 return TRUE;
705}
706#endif
707
708#ifndef FEAT_GUI_W32
709
710#define SHIFT (SHIFT_PRESSED)
711#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
712#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
713#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
714
715
716/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
717 * We map function keys to their ANSI terminal equivalents, as produced
718 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
719 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
720 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
721 * combinations of function/arrow/etc keys.
722 */
723
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000724static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725{
726 WORD wVirtKey;
727 BOOL fAnsiKey;
728 int chAlone;
729 int chShift;
730 int chCtrl;
731 int chAlt;
732} VirtKeyMap[] =
733{
734
735/* Key ANSI alone shift ctrl alt */
736 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
737
738 { VK_F1, TRUE, ';', 'T', '^', 'h', },
739 { VK_F2, TRUE, '<', 'U', '_', 'i', },
740 { VK_F3, TRUE, '=', 'V', '`', 'j', },
741 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
742 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
743 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
744 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
745 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
746 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
747 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
748 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
749 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
750
751 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
752 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
753 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
754 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
755 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
756 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
757 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
758 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
759 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
760 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
761
762 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
763
764#if 0
765 /* Most people don't have F13-F20, but what the hell... */
766 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
767 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
768 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
769 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
770 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
771 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
772 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
773 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
774#endif
775 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
776 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
777 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
778 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
779
780 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
781 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
782 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
783 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
784 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
785 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
786 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
787 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
788 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
789 /* Sorry, out of number space! <negri>*/
790 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
791
792};
793
794
795#ifdef _MSC_VER
796// The ToAscii bug destroys several registers. Need to turn off optimization
797// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000798# pragma warning(push)
799# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800# pragma optimize("", off)
801#endif
802
803#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
804# define AChar AsciiChar
805#else
806# define AChar uChar.AsciiChar
807#endif
808
809/* The return code indicates key code size. */
810 static int
811#ifdef __BORLANDC__
812 __stdcall
813#endif
814win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000815 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816{
817 UINT uMods = pker->dwControlKeyState;
818 static int s_iIsDead = 0;
819 static WORD awAnsiCode[2];
820 static BYTE abKeystate[256];
821
822
823 if (s_iIsDead == 2)
824 {
825 pker->AChar = (CHAR) awAnsiCode[1];
826 s_iIsDead = 0;
827 return 1;
828 }
829
830 if (pker->AChar != 0)
831 return 1;
832
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200833 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834
835 // Should only be non-NULL on NT 4.0
836 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
837 {
838 CHAR szKLID[KL_NAMELENGTH];
839
840 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
841 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
842 }
843
844 /* Clear any pending dead keys */
845 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
846
847 if (uMods & SHIFT_PRESSED)
848 abKeystate[VK_SHIFT] = 0x80;
849 if (uMods & CAPSLOCK_ON)
850 abKeystate[VK_CAPITAL] = 1;
851
852 if ((uMods & ALT_GR) == ALT_GR)
853 {
854 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
855 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
856 }
857
858 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
859 abKeystate, awAnsiCode, 0);
860
861 if (s_iIsDead > 0)
862 pker->AChar = (CHAR) awAnsiCode[0];
863
864 return s_iIsDead;
865}
866
867#ifdef _MSC_VER
868/* MUST switch optimization on again here, otherwise a call to
869 * decode_key_event() may crash (e.g. when hitting caps-lock) */
870# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000871# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000872
873# if (_MSC_VER < 1100)
874/* MUST turn off global optimisation for this next function, or
875 * pressing ctrl-minus in insert mode crashes Vim when built with
876 * VC4.1. -- negri. */
877# pragma optimize("g", off)
878# endif
879#endif
880
881static BOOL g_fJustGotFocus = FALSE;
882
883/*
884 * Decode a KEY_EVENT into one or two keystrokes
885 */
886 static BOOL
887decode_key_event(
888 KEY_EVENT_RECORD *pker,
889 char_u *pch,
890 char_u *pch2,
891 int *pmodifiers,
892 BOOL fDoPost)
893{
894 int i;
895 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
896
897 *pch = *pch2 = NUL;
898 g_fJustGotFocus = FALSE;
899
900 /* ignore key up events */
901 if (!pker->bKeyDown)
902 return FALSE;
903
904 /* ignore some keystrokes */
905 switch (pker->wVirtualKeyCode)
906 {
907 /* modifiers */
908 case VK_SHIFT:
909 case VK_CONTROL:
910 case VK_MENU: /* Alt key */
911 return FALSE;
912
913 default:
914 break;
915 }
916
917 /* special cases */
918 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
919 {
920 /* Ctrl-6 is Ctrl-^ */
921 if (pker->wVirtualKeyCode == '6')
922 {
923 *pch = Ctrl_HAT;
924 return TRUE;
925 }
926 /* Ctrl-2 is Ctrl-@ */
927 else if (pker->wVirtualKeyCode == '2')
928 {
929 *pch = NUL;
930 return TRUE;
931 }
932 /* Ctrl-- is Ctrl-_ */
933 else if (pker->wVirtualKeyCode == 0xBD)
934 {
935 *pch = Ctrl__;
936 return TRUE;
937 }
938 }
939
940 /* Shift-TAB */
941 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
942 {
943 *pch = K_NUL;
944 *pch2 = '\017';
945 return TRUE;
946 }
947
948 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
949 {
950 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
951 {
952 if (nModifs == 0)
953 *pch = VirtKeyMap[i].chAlone;
954 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
955 *pch = VirtKeyMap[i].chShift;
956 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
957 *pch = VirtKeyMap[i].chCtrl;
958 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
959 *pch = VirtKeyMap[i].chAlt;
960
961 if (*pch != 0)
962 {
963 if (VirtKeyMap[i].fAnsiKey)
964 {
965 *pch2 = *pch;
966 *pch = K_NUL;
967 }
968
969 return TRUE;
970 }
971 }
972 }
973
974 i = win32_kbd_patch_key(pker);
975
976 if (i < 0)
977 *pch = NUL;
978 else
979 {
980 *pch = (i > 0) ? pker->AChar : NUL;
981
982 if (pmodifiers != NULL)
983 {
984 /* Pass on the ALT key as a modifier, but only when not combined
985 * with CTRL (which is ALTGR). */
986 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
987 *pmodifiers |= MOD_MASK_ALT;
988
989 /* Pass on SHIFT only for special keys, because we don't know when
990 * it's already included with the character. */
991 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
992 *pmodifiers |= MOD_MASK_SHIFT;
993
994 /* Pass on CTRL only for non-special keys, because we don't know
995 * when it's already included with the character. And not when
996 * combined with ALT (which is ALTGR). */
997 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
998 && *pch >= 0x20 && *pch < 0x80)
999 *pmodifiers |= MOD_MASK_CTRL;
1000 }
1001 }
1002
1003 return (*pch != NUL);
1004}
1005
1006#ifdef _MSC_VER
1007# pragma optimize("", on)
1008#endif
1009
1010#endif /* FEAT_GUI_W32 */
1011
1012
1013#ifdef FEAT_MOUSE
1014
1015/*
1016 * For the GUI the mouse handling is in gui_w32.c.
1017 */
1018# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001019/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001021mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022{
1023}
1024# else
1025static int g_fMouseAvail = FALSE; /* mouse present */
1026static int g_fMouseActive = FALSE; /* mouse enabled */
1027static int g_nMouseClick = -1; /* mouse status */
1028static int g_xMouse; /* mouse x coordinate */
1029static int g_yMouse; /* mouse y coordinate */
1030
1031/*
1032 * Enable or disable mouse input
1033 */
1034 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001035mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036{
1037 DWORD cmodein;
1038
1039 if (!g_fMouseAvail)
1040 return;
1041
1042 g_fMouseActive = on;
1043 GetConsoleMode(g_hConIn, &cmodein);
1044
1045 if (g_fMouseActive)
1046 cmodein |= ENABLE_MOUSE_INPUT;
1047 else
1048 cmodein &= ~ENABLE_MOUSE_INPUT;
1049
1050 SetConsoleMode(g_hConIn, cmodein);
1051}
1052
1053
1054/*
1055 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1056 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1057 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1058 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1059 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1060 * and we return the mouse position in g_xMouse and g_yMouse.
1061 *
1062 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1063 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1064 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1065 *
1066 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1067 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1068 *
1069 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1070 * moves, even if it stays within the same character cell. We ignore
1071 * all MOUSE_MOVED messages if the position hasn't really changed, and
1072 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1073 * we're only interested in MOUSE_DRAG).
1074 *
1075 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1076 * 2-button mouses by pressing the left & right buttons simultaneously.
1077 * In practice, it's almost impossible to click both at the same time,
1078 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1079 * in such cases, if the user is clicking quickly.
1080 */
1081 static BOOL
1082decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001083 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084{
1085 static int s_nOldButton = -1;
1086 static int s_nOldMouseClick = -1;
1087 static int s_xOldMouse = -1;
1088 static int s_yOldMouse = -1;
1089 static linenr_T s_old_topline = 0;
1090#ifdef FEAT_DIFF
1091 static int s_old_topfill = 0;
1092#endif
1093 static int s_cClicks = 1;
1094 static BOOL s_fReleased = TRUE;
1095 static DWORD s_dwLastClickTime = 0;
1096 static BOOL s_fNextIsMiddle = FALSE;
1097
1098 static DWORD cButtons = 0; /* number of buttons supported */
1099
1100 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1101 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1102 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1103 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1104
1105 int nButton;
1106
1107 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1108 cButtons = 2;
1109
1110 if (!g_fMouseAvail || !g_fMouseActive)
1111 {
1112 g_nMouseClick = -1;
1113 return FALSE;
1114 }
1115
1116 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1117 if (g_fJustGotFocus)
1118 {
1119 g_fJustGotFocus = FALSE;
1120 return FALSE;
1121 }
1122
1123 /* unprocessed mouse click? */
1124 if (g_nMouseClick != -1)
1125 return TRUE;
1126
1127 nButton = -1;
1128 g_xMouse = pmer->dwMousePosition.X;
1129 g_yMouse = pmer->dwMousePosition.Y;
1130
1131 if (pmer->dwEventFlags == MOUSE_MOVED)
1132 {
1133 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1134 * events even when the mouse moves only within a char cell.) */
1135 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1136 return FALSE;
1137 }
1138
1139 /* If no buttons are pressed... */
1140 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1141 {
1142 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1143 if (s_fReleased)
1144 return FALSE;
1145
1146 nButton = MOUSE_RELEASE;
1147 s_fReleased = TRUE;
1148 }
1149 else /* one or more buttons pressed */
1150 {
1151 /* on a 2-button mouse, hold down left and right buttons
1152 * simultaneously to get MIDDLE. */
1153
1154 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1155 {
1156 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1157
1158 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001159 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160 if (dwLR == LEFT || dwLR == RIGHT)
1161 {
1162 for (;;)
1163 {
1164 /* wait a short time for next input event */
1165 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1166 != WAIT_OBJECT_0)
1167 break;
1168 else
1169 {
1170 DWORD cRecords = 0;
1171 INPUT_RECORD ir;
1172 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1173
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001174 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175
1176 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1177 || !(pmer2->dwButtonState & LEFT_RIGHT))
1178 break;
1179 else
1180 {
1181 if (pmer2->dwEventFlags != MOUSE_MOVED)
1182 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001183 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001184
1185 return decode_mouse_event(pmer2);
1186 }
1187 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1188 s_yOldMouse == pmer2->dwMousePosition.Y)
1189 {
1190 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001191 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192
1193 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001194 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195
1196 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1197 break;
1198 }
1199 else
1200 break;
1201 }
1202 }
1203 }
1204 }
1205 }
1206
1207 if (s_fNextIsMiddle)
1208 {
1209 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1210 ? MOUSE_DRAG : MOUSE_MIDDLE;
1211 s_fNextIsMiddle = FALSE;
1212 }
1213 else if (cButtons == 2 &&
1214 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1215 {
1216 nButton = MOUSE_MIDDLE;
1217
1218 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1219 {
1220 s_fNextIsMiddle = TRUE;
1221 nButton = MOUSE_RELEASE;
1222 }
1223 }
1224 else if ((pmer->dwButtonState & LEFT) == LEFT)
1225 nButton = MOUSE_LEFT;
1226 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1227 nButton = MOUSE_MIDDLE;
1228 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1229 nButton = MOUSE_RIGHT;
1230
1231 if (! s_fReleased && ! s_fNextIsMiddle
1232 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1233 return FALSE;
1234
1235 s_fReleased = s_fNextIsMiddle;
1236 }
1237
1238 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1239 {
1240 /* button pressed or released, without mouse moving */
1241 if (nButton != -1 && nButton != MOUSE_RELEASE)
1242 {
1243 DWORD dwCurrentTime = GetTickCount();
1244
1245 if (s_xOldMouse != g_xMouse
1246 || s_yOldMouse != g_yMouse
1247 || s_nOldButton != nButton
1248 || s_old_topline != curwin->w_topline
1249#ifdef FEAT_DIFF
1250 || s_old_topfill != curwin->w_topfill
1251#endif
1252 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1253 {
1254 s_cClicks = 1;
1255 }
1256 else if (++s_cClicks > 4)
1257 {
1258 s_cClicks = 1;
1259 }
1260
1261 s_dwLastClickTime = dwCurrentTime;
1262 }
1263 }
1264 else if (pmer->dwEventFlags == MOUSE_MOVED)
1265 {
1266 if (nButton != -1 && nButton != MOUSE_RELEASE)
1267 nButton = MOUSE_DRAG;
1268
1269 s_cClicks = 1;
1270 }
1271
1272 if (nButton == -1)
1273 return FALSE;
1274
1275 if (nButton != MOUSE_RELEASE)
1276 s_nOldButton = nButton;
1277
1278 g_nMouseClick = nButton;
1279
1280 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1281 g_nMouseClick |= MOUSE_SHIFT;
1282 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1283 g_nMouseClick |= MOUSE_CTRL;
1284 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1285 g_nMouseClick |= MOUSE_ALT;
1286
1287 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1288 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1289
1290 /* only pass on interesting (i.e., different) mouse events */
1291 if (s_xOldMouse == g_xMouse
1292 && s_yOldMouse == g_yMouse
1293 && s_nOldMouseClick == g_nMouseClick)
1294 {
1295 g_nMouseClick = -1;
1296 return FALSE;
1297 }
1298
1299 s_xOldMouse = g_xMouse;
1300 s_yOldMouse = g_yMouse;
1301 s_old_topline = curwin->w_topline;
1302#ifdef FEAT_DIFF
1303 s_old_topfill = curwin->w_topfill;
1304#endif
1305 s_nOldMouseClick = g_nMouseClick;
1306
1307 return TRUE;
1308}
1309
1310# endif /* FEAT_GUI_W32 */
1311#endif /* FEAT_MOUSE */
1312
1313
1314#ifdef MCH_CURSOR_SHAPE
1315/*
1316 * Set the shape of the cursor.
1317 * 'thickness' can be from 1 (thin) to 99 (block)
1318 */
1319 static void
1320mch_set_cursor_shape(int thickness)
1321{
1322 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1323 ConsoleCursorInfo.dwSize = thickness;
1324 ConsoleCursorInfo.bVisible = s_cursor_visible;
1325
1326 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1327 if (s_cursor_visible)
1328 SetConsoleCursorPosition(g_hConOut, g_coord);
1329}
1330
1331 void
1332mch_update_cursor(void)
1333{
1334 int idx;
1335 int thickness;
1336
1337 /*
1338 * How the cursor is drawn depends on the current mode.
1339 */
1340 idx = get_shape_idx(FALSE);
1341
1342 if (shape_table[idx].shape == SHAPE_BLOCK)
1343 thickness = 99; /* 100 doesn't work on W95 */
1344 else
1345 thickness = shape_table[idx].percentage;
1346 mch_set_cursor_shape(thickness);
1347}
1348#endif
1349
1350#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1351/*
1352 * Handle FOCUS_EVENT.
1353 */
1354 static void
1355handle_focus_event(INPUT_RECORD ir)
1356{
1357 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1358 ui_focus_change((int)g_fJustGotFocus);
1359}
1360
1361/*
1362 * Wait until console input from keyboard or mouse is available,
1363 * or the time is up.
1364 * Return TRUE if something is available FALSE if not.
1365 */
1366 static int
1367WaitForChar(long msec)
1368{
1369 DWORD dwNow = 0, dwEndTime = 0;
1370 INPUT_RECORD ir;
1371 DWORD cRecords;
1372 char_u ch, ch2;
1373
1374 if (msec > 0)
1375 /* Wait until the specified time has elapsed. */
1376 dwEndTime = GetTickCount() + msec;
1377 else if (msec < 0)
1378 /* Wait forever. */
1379 dwEndTime = INFINITE;
1380
1381 /* We need to loop until the end of the time period, because
1382 * we might get multiple unusable mouse events in that time.
1383 */
1384 for (;;)
1385 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001386#ifdef FEAT_MZSCHEME
1387 mzvim_check_threads();
1388#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001389#ifdef FEAT_CLIENTSERVER
1390 serverProcessPendingMessages();
1391#endif
1392 if (0
1393#ifdef FEAT_MOUSE
1394 || g_nMouseClick != -1
1395#endif
1396#ifdef FEAT_CLIENTSERVER
1397 || input_available()
1398#endif
1399 )
1400 return TRUE;
1401
1402 if (msec > 0)
1403 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001404 /* If the specified wait time has passed, return. Beware that
1405 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001406 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001407 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408 break;
1409 }
1410 if (msec != 0)
1411 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001412 DWORD dwWaitTime = dwEndTime - dwNow;
1413
1414#ifdef FEAT_MZSCHEME
1415 if (mzthreads_allowed() && p_mzq > 0
1416 && (msec < 0 || (long)dwWaitTime > p_mzq))
1417 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1418#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001419#ifdef FEAT_CLIENTSERVER
1420 /* Wait for either an event on the console input or a message in
1421 * the client-server window. */
1422 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001423 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001424#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001425 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426#endif
1427 continue;
1428 }
1429
1430 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001431 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432
1433#ifdef FEAT_MBYTE_IME
1434 if (State & CMDLINE && msg_row == Rows - 1)
1435 {
1436 CONSOLE_SCREEN_BUFFER_INFO csbi;
1437
1438 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1439 {
1440 if (csbi.dwCursorPosition.Y != msg_row)
1441 {
1442 /* The screen is now messed up, must redraw the
1443 * command line and later all the windows. */
1444 redraw_all_later(CLEAR);
1445 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1446 redrawcmd();
1447 }
1448 }
1449 }
1450#endif
1451
1452 if (cRecords > 0)
1453 {
1454 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1455 {
1456#ifdef FEAT_MBYTE_IME
1457 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1458 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1459 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1460 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1461 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001462 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001463 continue;
1464 }
1465#endif
1466 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1467 NULL, FALSE))
1468 return TRUE;
1469 }
1470
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001471 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472
1473 if (ir.EventType == FOCUS_EVENT)
1474 handle_focus_event(ir);
1475 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1476 shell_resized();
1477#ifdef FEAT_MOUSE
1478 else if (ir.EventType == MOUSE_EVENT
1479 && decode_mouse_event(&ir.Event.MouseEvent))
1480 return TRUE;
1481#endif
1482 }
1483 else if (msec == 0)
1484 break;
1485 }
1486
1487#ifdef FEAT_CLIENTSERVER
1488 /* Something might have been received while we were waiting. */
1489 if (input_available())
1490 return TRUE;
1491#endif
1492 return FALSE;
1493}
1494
1495#ifndef FEAT_GUI_MSWIN
1496/*
1497 * return non-zero if a character is available
1498 */
1499 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001500mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501{
1502 return WaitForChar(0L);
1503}
1504#endif
1505
1506/*
1507 * Create the console input. Used when reading stdin doesn't work.
1508 */
1509 static void
1510create_conin(void)
1511{
1512 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1513 FILE_SHARE_READ|FILE_SHARE_WRITE,
1514 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001515 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516 did_create_conin = TRUE;
1517}
1518
1519/*
1520 * Get a keystroke or a mouse event
1521 */
1522 static char_u
1523tgetch(int *pmodifiers, char_u *pch2)
1524{
1525 char_u ch;
1526
1527 for (;;)
1528 {
1529 INPUT_RECORD ir;
1530 DWORD cRecords = 0;
1531
1532#ifdef FEAT_CLIENTSERVER
1533 (void)WaitForChar(-1L);
1534 if (input_available())
1535 return 0;
1536# ifdef FEAT_MOUSE
1537 if (g_nMouseClick != -1)
1538 return 0;
1539# endif
1540#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001541 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001542 {
1543 if (did_create_conin)
1544 read_error_exit();
1545 create_conin();
1546 continue;
1547 }
1548
1549 if (ir.EventType == KEY_EVENT)
1550 {
1551 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1552 pmodifiers, TRUE))
1553 return ch;
1554 }
1555 else if (ir.EventType == FOCUS_EVENT)
1556 handle_focus_event(ir);
1557 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1558 shell_resized();
1559#ifdef FEAT_MOUSE
1560 else if (ir.EventType == MOUSE_EVENT)
1561 {
1562 if (decode_mouse_event(&ir.Event.MouseEvent))
1563 return 0;
1564 }
1565#endif
1566 }
1567}
1568#endif /* !FEAT_GUI_W32 */
1569
1570
1571/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001572 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 * Get one or more characters from the keyboard or the mouse.
1574 * If time == 0, do not wait for characters.
1575 * If time == n, wait a short time for characters.
1576 * If time == -1, wait forever for characters.
1577 * Returns the number of characters read into buf.
1578 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001579/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 int
1581mch_inchar(
1582 char_u *buf,
1583 int maxlen,
1584 long time,
1585 int tb_change_cnt)
1586{
1587#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1588
1589 int len;
1590 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591#define TYPEAHEADLEN 20
1592 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1593 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001594#ifdef FEAT_MBYTE
1595 static char_u *rest = NULL; /* unconverted rest of previous read */
1596 static int restlen = 0;
1597 int unconverted;
1598#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599
1600 /* First use any typeahead that was kept because "buf" was too small. */
1601 if (typeaheadlen > 0)
1602 goto theend;
1603
1604#ifdef FEAT_SNIFF
1605 if (want_sniff_request)
1606 {
1607 if (sniff_request_waiting)
1608 {
1609 /* return K_SNIFF */
1610 typeahead[typeaheadlen++] = CSI;
1611 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1612 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1613 sniff_request_waiting = 0;
1614 want_sniff_request = 0;
1615 goto theend;
1616 }
1617 else if (time < 0 || time > 250)
1618 {
1619 /* don't wait too long, a request might be pending */
1620 time = 250;
1621 }
1622 }
1623#endif
1624
1625 if (time >= 0)
1626 {
1627 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629 }
1630 else /* time == -1, wait forever */
1631 {
1632 mch_set_winsize_now(); /* Allow winsize changes from now on */
1633
Bram Moolenaar3918c952005-03-15 22:34:55 +00001634 /*
1635 * If there is no character available within 2 seconds (default)
1636 * write the autoscript file to disk. Or cause the CursorHold event
1637 * to be triggered.
1638 */
1639 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 {
1641#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001642 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001644 buf[0] = K_SPECIAL;
1645 buf[1] = KS_EXTRA;
1646 buf[2] = (int)KE_CURSORHOLD;
1647 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648 }
1649#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001650 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651 }
1652 }
1653
1654 /*
1655 * Try to read as many characters as there are, until the buffer is full.
1656 */
1657
1658 /* we will get at least one key. Get more if they are available. */
1659 g_fCBrkPressed = FALSE;
1660
1661#ifdef MCH_WRITE_DUMP
1662 if (fdDump)
1663 fputc('[', fdDump);
1664#endif
1665
1666 /* Keep looping until there is something in the typeahead buffer and more
1667 * to get and still room in the buffer (up to two bytes for a char and
1668 * three bytes for a modifier). */
1669 while ((typeaheadlen == 0 || WaitForChar(0L))
1670 && typeaheadlen + 5 <= TYPEAHEADLEN)
1671 {
1672 if (typebuf_changed(tb_change_cnt))
1673 {
1674 /* "buf" may be invalid now if a client put something in the
1675 * typeahead buffer and "buf" is in the typeahead buffer. */
1676 typeaheadlen = 0;
1677 break;
1678 }
1679#ifdef FEAT_MOUSE
1680 if (g_nMouseClick != -1)
1681 {
1682# ifdef MCH_WRITE_DUMP
1683 if (fdDump)
1684 fprintf(fdDump, "{%02x @ %d, %d}",
1685 g_nMouseClick, g_xMouse, g_yMouse);
1686# endif
1687 typeahead[typeaheadlen++] = ESC + 128;
1688 typeahead[typeaheadlen++] = 'M';
1689 typeahead[typeaheadlen++] = g_nMouseClick;
1690 typeahead[typeaheadlen++] = g_xMouse + '!';
1691 typeahead[typeaheadlen++] = g_yMouse + '!';
1692 g_nMouseClick = -1;
1693 }
1694 else
1695#endif
1696 {
1697 char_u ch2 = NUL;
1698 int modifiers = 0;
1699
1700 c = tgetch(&modifiers, &ch2);
1701
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001702#ifdef FEAT_MBYTE
1703 /* stolen from fill_input_buf() in ui.c */
1704 if (rest != NULL)
1705 {
1706 /* Use remainder of previous call, starts with an invalid
1707 * character that may become valid when reading more. */
1708 if (restlen > TYPEAHEADLEN - typeaheadlen)
1709 unconverted = TYPEAHEADLEN - typeaheadlen;
1710 else
1711 unconverted = restlen;
1712 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1713 if (unconverted == restlen)
1714 {
1715 vim_free(rest);
1716 rest = NULL;
1717 }
1718 else
1719 {
1720 restlen -= unconverted;
1721 mch_memmove(rest, rest + unconverted, restlen);
1722 }
1723 typeaheadlen += unconverted;
1724 }
1725 else
1726 unconverted = 0;
1727#endif
1728
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 if (typebuf_changed(tb_change_cnt))
1730 {
1731 /* "buf" may be invalid now if a client put something in the
1732 * typeahead buffer and "buf" is in the typeahead buffer. */
1733 typeaheadlen = 0;
1734 break;
1735 }
1736
1737 if (c == Ctrl_C && ctrl_c_interrupts)
1738 {
1739#if defined(FEAT_CLIENTSERVER)
1740 trash_input_buf();
1741#endif
1742 got_int = TRUE;
1743 }
1744
1745#ifdef FEAT_MOUSE
1746 if (g_nMouseClick == -1)
1747#endif
1748 {
1749 int n = 1;
1750
1751 /* A key may have one or two bytes. */
1752 typeahead[typeaheadlen] = c;
1753 if (ch2 != NUL)
1754 {
1755 typeahead[typeaheadlen + 1] = ch2;
1756 ++n;
1757 }
1758#ifdef FEAT_MBYTE
1759 /* Only convert normal characters, not special keys. Need to
1760 * convert before applying ALT, otherwise mapping <M-x> breaks
1761 * when 'tenc' is set. */
1762 if (input_conv.vc_type != CONV_NONE
1763 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001764 {
1765 typeaheadlen -= unconverted;
1766 n = convert_input_safe(typeahead + typeaheadlen,
1767 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1768 rest == NULL ? &rest : NULL, &restlen);
1769 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001770#endif
1771
1772 /* Use the ALT key to set the 8th bit of the character
1773 * when it's one byte, the 8th bit isn't set yet and not
1774 * using a double-byte encoding (would become a lead
1775 * byte). */
1776 if ((modifiers & MOD_MASK_ALT)
1777 && n == 1
1778 && (typeahead[typeaheadlen] & 0x80) == 0
1779#ifdef FEAT_MBYTE
1780 && !enc_dbcs
1781#endif
1782 )
1783 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001784#ifdef FEAT_MBYTE
1785 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1786 typeahead + typeaheadlen);
1787#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001789#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001790 modifiers &= ~MOD_MASK_ALT;
1791 }
1792
1793 if (modifiers != 0)
1794 {
1795 /* Prepend modifiers to the character. */
1796 mch_memmove(typeahead + typeaheadlen + 3,
1797 typeahead + typeaheadlen, n);
1798 typeahead[typeaheadlen++] = K_SPECIAL;
1799 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1800 typeahead[typeaheadlen++] = modifiers;
1801 }
1802
1803 typeaheadlen += n;
1804
1805#ifdef MCH_WRITE_DUMP
1806 if (fdDump)
1807 fputc(c, fdDump);
1808#endif
1809 }
1810 }
1811 }
1812
1813#ifdef MCH_WRITE_DUMP
1814 if (fdDump)
1815 {
1816 fputs("]\n", fdDump);
1817 fflush(fdDump);
1818 }
1819#endif
1820
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821theend:
1822 /* Move typeahead to "buf", as much as fits. */
1823 len = 0;
1824 while (len < maxlen && typeaheadlen > 0)
1825 {
1826 buf[len++] = typeahead[0];
1827 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1828 }
1829 return len;
1830
1831#else /* FEAT_GUI_W32 */
1832 return 0;
1833#endif /* FEAT_GUI_W32 */
1834}
1835
Bram Moolenaar82881492012-11-20 16:53:39 +01001836#ifndef PROTO
1837# ifndef __MINGW32__
1838# include <shellapi.h> /* required for FindExecutable() */
1839# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840#endif
1841
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001842/*
1843 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001844 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001845 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 static int
1847executable_exists(char *name)
1848{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001849 char *dum;
1850 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001852#ifdef FEAT_MBYTE
1853 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001855 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001856 WCHAR fnamew[_MAX_PATH];
1857 WCHAR *dumw;
1858 long n;
1859
1860 if (p != NULL)
1861 {
1862 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1863 vim_free(p);
1864 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1865 {
1866 if (n == 0)
1867 return FALSE;
1868 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1869 return FALSE;
1870 return TRUE;
1871 }
1872 /* Retry with non-wide function (for Windows 98). */
1873 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001874 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001875#endif
1876 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1877 return FALSE;
1878 if (mch_isdir(fname))
1879 return FALSE;
1880 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881}
1882
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001883#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001884 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001885/*
1886 * Bad parameter handler.
1887 *
1888 * Certain MS CRT functions will intentionally crash when passed invalid
1889 * parameters to highlight possible security holes. Setting this function as
1890 * the bad parameter handler will prevent the crash.
1891 *
1892 * In debug builds the parameters contain CRT information that might help track
1893 * down the source of a problem, but in non-debug builds the arguments are all
1894 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1895 * worth allowing these to make debugging of issues easier.
1896 */
1897 static void
1898bad_param_handler(const wchar_t *expression,
1899 const wchar_t *function,
1900 const wchar_t *file,
1901 unsigned int line,
1902 uintptr_t pReserved)
1903{
1904}
1905
1906# define SET_INVALID_PARAM_HANDLER \
1907 ((void)_set_invalid_parameter_handler(bad_param_handler))
1908#else
1909# define SET_INVALID_PARAM_HANDLER
1910#endif
1911
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912#ifdef FEAT_GUI_W32
1913
1914/*
1915 * GUI version of mch_init().
1916 */
1917 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001918mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001919{
1920#ifndef __MINGW32__
1921 extern int _fmode;
1922#endif
1923
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001924 /* Silently handle invalid parameters to CRT functions */
1925 SET_INVALID_PARAM_HANDLER;
1926
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927 /* Let critical errors result in a failure, not in a dialog box. Required
1928 * for the timestamp test to work on removed floppies. */
1929 SetErrorMode(SEM_FAILCRITICALERRORS);
1930
1931 _fmode = O_BINARY; /* we do our own CR-LF translation */
1932
1933 /* Specify window size. Is there a place to get the default from? */
1934 Rows = 25;
1935 Columns = 80;
1936
1937 /* Look for 'vimrun' */
1938 if (!gui_is_win32s())
1939 {
1940 char_u vimrun_location[_MAX_PATH + 4];
1941
1942 /* First try in same directory as gvim.exe */
1943 STRCPY(vimrun_location, exe_name);
1944 STRCPY(gettail(vimrun_location), "vimrun.exe");
1945 if (mch_getperm(vimrun_location) >= 0)
1946 {
1947 if (*skiptowhite(vimrun_location) != NUL)
1948 {
1949 /* Enclose path with white space in double quotes. */
1950 mch_memmove(vimrun_location + 1, vimrun_location,
1951 STRLEN(vimrun_location) + 1);
1952 *vimrun_location = '"';
1953 STRCPY(gettail(vimrun_location), "vimrun\" ");
1954 }
1955 else
1956 STRCPY(gettail(vimrun_location), "vimrun ");
1957
1958 vimrun_path = (char *)vim_strsave(vimrun_location);
1959 s_dont_use_vimrun = FALSE;
1960 }
1961 else if (executable_exists("vimrun.exe"))
1962 s_dont_use_vimrun = FALSE;
1963
1964 /* Don't give the warning for a missing vimrun.exe right now, but only
1965 * when vimrun was supposed to be used. Don't bother people that do
1966 * not need vimrun.exe. */
1967 if (s_dont_use_vimrun)
1968 need_vimrun_warning = TRUE;
1969 }
1970
1971 /*
1972 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1973 * Otherwise the default "findstr /n" is used.
1974 */
1975 if (!executable_exists("findstr.exe"))
1976 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1977
1978#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001979 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980#endif
1981}
1982
1983
1984#else /* FEAT_GUI_W32 */
1985
1986#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1987#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1988
1989/*
1990 * ClearConsoleBuffer()
1991 * Description:
1992 * Clears the entire contents of the console screen buffer, using the
1993 * specified attribute.
1994 * Returns:
1995 * TRUE on success
1996 */
1997 static BOOL
1998ClearConsoleBuffer(WORD wAttribute)
1999{
2000 CONSOLE_SCREEN_BUFFER_INFO csbi;
2001 COORD coord;
2002 DWORD NumCells, dummy;
2003
2004 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2005 return FALSE;
2006
2007 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2008 coord.X = 0;
2009 coord.Y = 0;
2010 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2011 coord, &dummy))
2012 {
2013 return FALSE;
2014 }
2015 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2016 coord, &dummy))
2017 {
2018 return FALSE;
2019 }
2020
2021 return TRUE;
2022}
2023
2024/*
2025 * FitConsoleWindow()
2026 * Description:
2027 * Checks if the console window will fit within given buffer dimensions.
2028 * Also, if requested, will shrink the window to fit.
2029 * Returns:
2030 * TRUE on success
2031 */
2032 static BOOL
2033FitConsoleWindow(
2034 COORD dwBufferSize,
2035 BOOL WantAdjust)
2036{
2037 CONSOLE_SCREEN_BUFFER_INFO csbi;
2038 COORD dwWindowSize;
2039 BOOL NeedAdjust = FALSE;
2040
2041 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2042 {
2043 /*
2044 * A buffer resize will fail if the current console window does
2045 * not lie completely within that buffer. To avoid this, we might
2046 * have to move and possibly shrink the window.
2047 */
2048 if (csbi.srWindow.Right >= dwBufferSize.X)
2049 {
2050 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2051 if (dwWindowSize.X > dwBufferSize.X)
2052 dwWindowSize.X = dwBufferSize.X;
2053 csbi.srWindow.Right = dwBufferSize.X - 1;
2054 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2055 NeedAdjust = TRUE;
2056 }
2057 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2058 {
2059 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2060 if (dwWindowSize.Y > dwBufferSize.Y)
2061 dwWindowSize.Y = dwBufferSize.Y;
2062 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2063 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2064 NeedAdjust = TRUE;
2065 }
2066 if (NeedAdjust && WantAdjust)
2067 {
2068 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2069 return FALSE;
2070 }
2071 return TRUE;
2072 }
2073
2074 return FALSE;
2075}
2076
2077typedef struct ConsoleBufferStruct
2078{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002079 BOOL IsValid;
2080 CONSOLE_SCREEN_BUFFER_INFO Info;
2081 PCHAR_INFO Buffer;
2082 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083} ConsoleBuffer;
2084
2085/*
2086 * SaveConsoleBuffer()
2087 * Description:
2088 * Saves important information about the console buffer, including the
2089 * actual buffer contents. The saved information is suitable for later
2090 * restoration by RestoreConsoleBuffer().
2091 * Returns:
2092 * TRUE if all information was saved; FALSE otherwise
2093 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2094 */
2095 static BOOL
2096SaveConsoleBuffer(
2097 ConsoleBuffer *cb)
2098{
2099 DWORD NumCells;
2100 COORD BufferCoord;
2101 SMALL_RECT ReadRegion;
2102 WORD Y, Y_incr;
2103
2104 if (cb == NULL)
2105 return FALSE;
2106
2107 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2108 {
2109 cb->IsValid = FALSE;
2110 return FALSE;
2111 }
2112 cb->IsValid = TRUE;
2113
2114 /*
2115 * Allocate a buffer large enough to hold the entire console screen
2116 * buffer. If this ConsoleBuffer structure has already been initialized
2117 * with a buffer of the correct size, then just use that one.
2118 */
2119 if (!cb->IsValid || cb->Buffer == NULL ||
2120 cb->BufferSize.X != cb->Info.dwSize.X ||
2121 cb->BufferSize.Y != cb->Info.dwSize.Y)
2122 {
2123 cb->BufferSize.X = cb->Info.dwSize.X;
2124 cb->BufferSize.Y = cb->Info.dwSize.Y;
2125 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002126 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2128 if (cb->Buffer == NULL)
2129 return FALSE;
2130 }
2131
2132 /*
2133 * We will now copy the console screen buffer into our buffer.
2134 * ReadConsoleOutput() seems to be limited as far as how much you
2135 * can read at a time. Empirically, this number seems to be about
2136 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2137 * in chunks until it is all copied. The chunks will all have the
2138 * same horizontal characteristics, so initialize them now. The
2139 * height of each chunk will be (12000 / width).
2140 */
2141 BufferCoord.X = 0;
2142 ReadRegion.Left = 0;
2143 ReadRegion.Right = cb->Info.dwSize.X - 1;
2144 Y_incr = 12000 / cb->Info.dwSize.X;
2145 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2146 {
2147 /*
2148 * Read into position (0, Y) in our buffer.
2149 */
2150 BufferCoord.Y = Y;
2151 /*
2152 * Read the region whose top left corner is (0, Y) and whose bottom
2153 * right corner is (width - 1, Y + Y_incr - 1). This should define
2154 * a region of size width by Y_incr. Don't worry if this region is
2155 * too large for the remaining buffer; it will be cropped.
2156 */
2157 ReadRegion.Top = Y;
2158 ReadRegion.Bottom = Y + Y_incr - 1;
2159 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2160 cb->Buffer, /* our buffer */
2161 cb->BufferSize, /* dimensions of our buffer */
2162 BufferCoord, /* offset in our buffer */
2163 &ReadRegion)) /* region to save */
2164 {
2165 vim_free(cb->Buffer);
2166 cb->Buffer = NULL;
2167 return FALSE;
2168 }
2169 }
2170
2171 return TRUE;
2172}
2173
2174/*
2175 * RestoreConsoleBuffer()
2176 * Description:
2177 * Restores important information about the console buffer, including the
2178 * actual buffer contents, if desired. The information to restore is in
2179 * the same format used by SaveConsoleBuffer().
2180 * Returns:
2181 * TRUE on success
2182 */
2183 static BOOL
2184RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002185 ConsoleBuffer *cb,
2186 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002187{
2188 COORD BufferCoord;
2189 SMALL_RECT WriteRegion;
2190
2191 if (cb == NULL || !cb->IsValid)
2192 return FALSE;
2193
2194 /*
2195 * Before restoring the buffer contents, clear the current buffer, and
2196 * restore the cursor position and window information. Doing this now
2197 * prevents old buffer contents from "flashing" onto the screen.
2198 */
2199 if (RestoreScreen)
2200 ClearConsoleBuffer(cb->Info.wAttributes);
2201
2202 FitConsoleWindow(cb->Info.dwSize, TRUE);
2203 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2204 return FALSE;
2205 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2206 return FALSE;
2207
2208 if (!RestoreScreen)
2209 {
2210 /*
2211 * No need to restore the screen buffer contents, so we're done.
2212 */
2213 return TRUE;
2214 }
2215
2216 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2217 return FALSE;
2218 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2219 return FALSE;
2220
2221 /*
2222 * Restore the screen buffer contents.
2223 */
2224 if (cb->Buffer != NULL)
2225 {
2226 BufferCoord.X = 0;
2227 BufferCoord.Y = 0;
2228 WriteRegion.Left = 0;
2229 WriteRegion.Top = 0;
2230 WriteRegion.Right = cb->Info.dwSize.X - 1;
2231 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2232 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2233 cb->Buffer, /* our buffer */
2234 cb->BufferSize, /* dimensions of our buffer */
2235 BufferCoord, /* offset in our buffer */
2236 &WriteRegion)) /* region to restore */
2237 {
2238 return FALSE;
2239 }
2240 }
2241
2242 return TRUE;
2243}
2244
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002245#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246#ifdef FEAT_RESTORE_ORIG_SCREEN
2247static ConsoleBuffer g_cbOrig = { 0 };
2248#endif
2249static ConsoleBuffer g_cbNonTermcap = { 0 };
2250static ConsoleBuffer g_cbTermcap = { 0 };
2251
2252#ifdef FEAT_TITLE
2253#ifdef __BORLANDC__
2254typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2255#else
2256typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2257#endif
2258char g_szOrigTitle[256] = { 0 };
2259HWND g_hWnd = NULL; /* also used in os_mswin.c */
2260static HICON g_hOrigIconSmall = NULL;
2261static HICON g_hOrigIcon = NULL;
2262static HICON g_hVimIcon = NULL;
2263static BOOL g_fCanChangeIcon = FALSE;
2264
2265/* ICON* are not defined in VC++ 4.0 */
2266#ifndef ICON_SMALL
2267#define ICON_SMALL 0
2268#endif
2269#ifndef ICON_BIG
2270#define ICON_BIG 1
2271#endif
2272/*
2273 * GetConsoleIcon()
2274 * Description:
2275 * Attempts to retrieve the small icon and/or the big icon currently in
2276 * use by a given window.
2277 * Returns:
2278 * TRUE on success
2279 */
2280 static BOOL
2281GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002282 HWND hWnd,
2283 HICON *phIconSmall,
2284 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285{
2286 if (hWnd == NULL)
2287 return FALSE;
2288
2289 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002290 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2291 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002293 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2294 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002295 return TRUE;
2296}
2297
2298/*
2299 * SetConsoleIcon()
2300 * Description:
2301 * Attempts to change the small icon and/or the big icon currently in
2302 * use by a given window.
2303 * Returns:
2304 * TRUE on success
2305 */
2306 static BOOL
2307SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002308 HWND hWnd,
2309 HICON hIconSmall,
2310 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002311{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002312 HICON hPrevIconSmall;
2313 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314
2315 if (hWnd == NULL)
2316 return FALSE;
2317
2318 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002319 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2320 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002322 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2323 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324 return TRUE;
2325}
2326
2327/*
2328 * SaveConsoleTitleAndIcon()
2329 * Description:
2330 * Saves the current console window title in g_szOrigTitle, for later
2331 * restoration. Also, attempts to obtain a handle to the console window,
2332 * and use it to save the small and big icons currently in use by the
2333 * console window. This is not always possible on some versions of Windows;
2334 * nor is it possible when running Vim remotely using Telnet (since the
2335 * console window the user sees is owned by a remote process).
2336 */
2337 static void
2338SaveConsoleTitleAndIcon(void)
2339{
2340 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2341
2342 /* Save the original title. */
2343 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2344 return;
2345
2346 /*
2347 * Obtain a handle to the console window using GetConsoleWindow() from
2348 * KERNEL32.DLL; we need to handle in order to change the window icon.
2349 * This function only exists on NT-based Windows, starting with Windows
2350 * 2000. On older operating systems, we can't change the window icon
2351 * anyway.
2352 */
2353 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2354 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2355 "GetConsoleWindow")) != NULL)
2356 {
2357 g_hWnd = (*GetConsoleWindowProc)();
2358 }
2359 if (g_hWnd == NULL)
2360 return;
2361
2362 /* Save the original console window icon. */
2363 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2364 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2365 return;
2366
2367 /* Extract the first icon contained in the Vim executable. */
2368 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2369 if (g_hVimIcon != NULL)
2370 g_fCanChangeIcon = TRUE;
2371}
2372#endif
2373
2374static int g_fWindInitCalled = FALSE;
2375static int g_fTermcapMode = FALSE;
2376static CONSOLE_CURSOR_INFO g_cci;
2377static DWORD g_cmodein = 0;
2378static DWORD g_cmodeout = 0;
2379
2380/*
2381 * non-GUI version of mch_init().
2382 */
2383 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002384mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385{
2386#ifndef FEAT_RESTORE_ORIG_SCREEN
2387 CONSOLE_SCREEN_BUFFER_INFO csbi;
2388#endif
2389#ifndef __MINGW32__
2390 extern int _fmode;
2391#endif
2392
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002393 /* Silently handle invalid parameters to CRT functions */
2394 SET_INVALID_PARAM_HANDLER;
2395
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 /* Let critical errors result in a failure, not in a dialog box. Required
2397 * for the timestamp test to work on removed floppies. */
2398 SetErrorMode(SEM_FAILCRITICALERRORS);
2399
2400 _fmode = O_BINARY; /* we do our own CR-LF translation */
2401 out_flush();
2402
2403 /* Obtain handles for the standard Console I/O devices */
2404 if (read_cmd_fd == 0)
2405 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2406 else
2407 create_conin();
2408 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2409
2410#ifdef FEAT_RESTORE_ORIG_SCREEN
2411 /* Save the initial console buffer for later restoration */
2412 SaveConsoleBuffer(&g_cbOrig);
2413 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2414#else
2415 /* Get current text attributes */
2416 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2417 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2418#endif
2419 if (cterm_normal_fg_color == 0)
2420 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2421 if (cterm_normal_bg_color == 0)
2422 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2423
2424 /* set termcap codes to current text attributes */
2425 update_tcap(g_attrCurrent);
2426
2427 GetConsoleCursorInfo(g_hConOut, &g_cci);
2428 GetConsoleMode(g_hConIn, &g_cmodein);
2429 GetConsoleMode(g_hConOut, &g_cmodeout);
2430
2431#ifdef FEAT_TITLE
2432 SaveConsoleTitleAndIcon();
2433 /*
2434 * Set both the small and big icons of the console window to Vim's icon.
2435 * Note that Vim presently only has one size of icon (32x32), but it
2436 * automatically gets scaled down to 16x16 when setting the small icon.
2437 */
2438 if (g_fCanChangeIcon)
2439 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2440#endif
2441
2442 ui_get_shellsize();
2443
2444#ifdef MCH_WRITE_DUMP
2445 fdDump = fopen("dump", "wt");
2446
2447 if (fdDump)
2448 {
2449 time_t t;
2450
2451 time(&t);
2452 fputs(ctime(&t), fdDump);
2453 fflush(fdDump);
2454 }
2455#endif
2456
2457 g_fWindInitCalled = TRUE;
2458
2459#ifdef FEAT_MOUSE
2460 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2461#endif
2462
2463#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002464 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465#endif
2466
2467 /* This will be NULL on anything but NT 4.0 */
2468 s_pfnGetConsoleKeyboardLayoutName =
2469 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2470 "GetConsoleKeyboardLayoutNameA");
2471}
2472
2473/*
2474 * non-GUI version of mch_exit().
2475 * Shut down and exit with status `r'
2476 * Careful: mch_exit() may be called before mch_init()!
2477 */
2478 void
2479mch_exit(int r)
2480{
2481 stoptermcap();
2482
2483 if (g_fWindInitCalled)
2484 settmode(TMODE_COOK);
2485
2486 ml_close_all(TRUE); /* remove all memfiles */
2487
2488 if (g_fWindInitCalled)
2489 {
2490#ifdef FEAT_TITLE
2491 mch_restore_title(3);
2492 /*
2493 * Restore both the small and big icons of the console window to
2494 * what they were at startup. Don't do this when the window is
2495 * closed, Vim would hang here.
2496 */
2497 if (g_fCanChangeIcon && !g_fForceExit)
2498 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2499#endif
2500
2501#ifdef MCH_WRITE_DUMP
2502 if (fdDump)
2503 {
2504 time_t t;
2505
2506 time(&t);
2507 fputs(ctime(&t), fdDump);
2508 fclose(fdDump);
2509 }
2510 fdDump = NULL;
2511#endif
2512 }
2513
2514 SetConsoleCursorInfo(g_hConOut, &g_cci);
2515 SetConsoleMode(g_hConIn, g_cmodein);
2516 SetConsoleMode(g_hConOut, g_cmodeout);
2517
2518#ifdef DYNAMIC_GETTEXT
2519 dyn_libintl_end();
2520#endif
2521
2522 exit(r);
2523}
2524#endif /* !FEAT_GUI_W32 */
2525
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526/*
2527 * Do we have an interactive window?
2528 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002529/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 int
2531mch_check_win(
2532 int argc,
2533 char **argv)
2534{
2535 get_exe_name();
2536
2537#ifdef FEAT_GUI_W32
2538 return OK; /* GUI always has a tty */
2539#else
2540 if (isatty(1))
2541 return OK;
2542 return FAIL;
2543#endif
2544}
2545
2546
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002547#ifdef FEAT_MBYTE
2548/*
2549 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2550 * if it already exists. When "len" is > 0, also expand short to long
2551 * filenames.
2552 * Return FAIL if wide functions are not available, OK otherwise.
2553 * NOTE: much of this is identical to fname_case(), keep in sync!
2554 */
2555 static int
2556fname_casew(
2557 WCHAR *name,
2558 int len)
2559{
2560 WCHAR szTrueName[_MAX_PATH + 2];
2561 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2562 WCHAR *ptrue, *ptruePrev;
2563 WCHAR *porig, *porigPrev;
2564 int flen;
2565 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002566 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002567 int c;
2568 int slen;
2569
2570 flen = (int)wcslen(name);
2571 if (flen > _MAX_PATH)
2572 return OK;
2573
2574 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2575
2576 /* Build the new name in szTrueName[] one component at a time. */
2577 porig = name;
2578 ptrue = szTrueName;
2579
2580 if (iswalpha(porig[0]) && porig[1] == L':')
2581 {
2582 /* copy leading drive letter */
2583 *ptrue++ = *porig++;
2584 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002585 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002586 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002587
2588 while (*porig != NUL)
2589 {
2590 /* copy \ characters */
2591 while (*porig == psepc)
2592 *ptrue++ = *porig++;
2593
2594 ptruePrev = ptrue;
2595 porigPrev = porig;
2596 while (*porig != NUL && *porig != psepc)
2597 {
2598 *ptrue++ = *porig++;
2599 }
2600 *ptrue = NUL;
2601
2602 /* To avoid a slow failure append "\*" when searching a directory,
2603 * server or network share. */
2604 wcscpy(szTrueNameTemp, szTrueName);
2605 slen = (int)wcslen(szTrueNameTemp);
2606 if (*porig == psepc && slen + 2 < _MAX_PATH)
2607 wcscpy(szTrueNameTemp + slen, L"\\*");
2608
2609 /* Skip "", "." and "..". */
2610 if (ptrue > ptruePrev
2611 && (ptruePrev[0] != L'.'
2612 || (ptruePrev[1] != NUL
2613 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2614 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2615 != INVALID_HANDLE_VALUE)
2616 {
2617 c = *porig;
2618 *porig = NUL;
2619
2620 /* Only use the match when it's the same name (ignoring case) or
2621 * expansion is allowed and there is a match with the short name
2622 * and there is enough room. */
2623 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2624 || (len > 0
2625 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2626 && (int)(ptruePrev - szTrueName)
2627 + (int)wcslen(fb.cFileName) < len)))
2628 {
2629 wcscpy(ptruePrev, fb.cFileName);
2630
2631 /* Look for exact match and prefer it if found. Must be a
2632 * long name, otherwise there would be only one match. */
2633 while (FindNextFileW(hFind, &fb))
2634 {
2635 if (*fb.cAlternateFileName != NUL
2636 && (wcscoll(porigPrev, fb.cFileName) == 0
2637 || (len > 0
2638 && (_wcsicoll(porigPrev,
2639 fb.cAlternateFileName) == 0
2640 && (int)(ptruePrev - szTrueName)
2641 + (int)wcslen(fb.cFileName) < len))))
2642 {
2643 wcscpy(ptruePrev, fb.cFileName);
2644 break;
2645 }
2646 }
2647 }
2648 FindClose(hFind);
2649 *porig = c;
2650 ptrue = ptruePrev + wcslen(ptruePrev);
2651 }
2652 else if (hFind == INVALID_HANDLE_VALUE
2653 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2654 return FAIL;
2655 }
2656
2657 wcscpy(name, szTrueName);
2658 return OK;
2659}
2660#endif
2661
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662/*
2663 * fname_case(): Set the case of the file name, if it already exists.
2664 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002665 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666 */
2667 void
2668fname_case(
2669 char_u *name,
2670 int len)
2671{
2672 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002673 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002674 char *ptrue, *ptruePrev;
2675 char *porig, *porigPrev;
2676 int flen;
2677 WIN32_FIND_DATA fb;
2678 HANDLE hFind;
2679 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002680 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002681
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002682 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002683 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684 return;
2685
2686 slash_adjust(name);
2687
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002688#ifdef FEAT_MBYTE
2689 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2690 {
2691 WCHAR *p = enc_to_utf16(name, NULL);
2692
2693 if (p != NULL)
2694 {
2695 char_u *q;
2696 WCHAR buf[_MAX_PATH + 2];
2697
2698 wcscpy(buf, p);
2699 vim_free(p);
2700
2701 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2702 {
2703 q = utf16_to_enc(buf, NULL);
2704 if (q != NULL)
2705 {
2706 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2707 vim_free(q);
2708 return;
2709 }
2710 }
2711 }
2712 /* Retry with non-wide function (for Windows 98). */
2713 }
2714#endif
2715
2716 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2717 * So we should check this after calling wide function. */
2718 if (flen > _MAX_PATH)
2719 return;
2720
Bram Moolenaar071d4272004-06-13 20:20:40 +00002721 /* Build the new name in szTrueName[] one component at a time. */
2722 porig = name;
2723 ptrue = szTrueName;
2724
2725 if (isalpha(porig[0]) && porig[1] == ':')
2726 {
2727 /* copy leading drive letter */
2728 *ptrue++ = *porig++;
2729 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002731 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732
2733 while (*porig != NUL)
2734 {
2735 /* copy \ characters */
2736 while (*porig == psepc)
2737 *ptrue++ = *porig++;
2738
2739 ptruePrev = ptrue;
2740 porigPrev = porig;
2741 while (*porig != NUL && *porig != psepc)
2742 {
2743#ifdef FEAT_MBYTE
2744 int l;
2745
2746 if (enc_dbcs)
2747 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002748 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749 while (--l >= 0)
2750 *ptrue++ = *porig++;
2751 }
2752 else
2753#endif
2754 *ptrue++ = *porig++;
2755 }
2756 *ptrue = NUL;
2757
Bram Moolenaar464c9252010-10-13 20:37:41 +02002758 /* To avoid a slow failure append "\*" when searching a directory,
2759 * server or network share. */
2760 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002761 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002762 if (*porig == psepc && slen + 2 < _MAX_PATH)
2763 STRCPY(szTrueNameTemp + slen, "\\*");
2764
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765 /* Skip "", "." and "..". */
2766 if (ptrue > ptruePrev
2767 && (ptruePrev[0] != '.'
2768 || (ptruePrev[1] != NUL
2769 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002770 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771 != INVALID_HANDLE_VALUE)
2772 {
2773 c = *porig;
2774 *porig = NUL;
2775
2776 /* Only use the match when it's the same name (ignoring case) or
2777 * expansion is allowed and there is a match with the short name
2778 * and there is enough room. */
2779 if (_stricoll(porigPrev, fb.cFileName) == 0
2780 || (len > 0
2781 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2782 && (int)(ptruePrev - szTrueName)
2783 + (int)strlen(fb.cFileName) < len)))
2784 {
2785 STRCPY(ptruePrev, fb.cFileName);
2786
2787 /* Look for exact match and prefer it if found. Must be a
2788 * long name, otherwise there would be only one match. */
2789 while (FindNextFile(hFind, &fb))
2790 {
2791 if (*fb.cAlternateFileName != NUL
2792 && (strcoll(porigPrev, fb.cFileName) == 0
2793 || (len > 0
2794 && (_stricoll(porigPrev,
2795 fb.cAlternateFileName) == 0
2796 && (int)(ptruePrev - szTrueName)
2797 + (int)strlen(fb.cFileName) < len))))
2798 {
2799 STRCPY(ptruePrev, fb.cFileName);
2800 break;
2801 }
2802 }
2803 }
2804 FindClose(hFind);
2805 *porig = c;
2806 ptrue = ptruePrev + strlen(ptruePrev);
2807 }
2808 }
2809
2810 STRCPY(name, szTrueName);
2811}
2812
2813
2814/*
2815 * Insert user name in s[len].
2816 */
2817 int
2818mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002819 char_u *s,
2820 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002821{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002822 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002823 DWORD cch = sizeof szUserName;
2824
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002825#ifdef FEAT_MBYTE
2826 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2827 {
2828 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2829 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2830
2831 if (GetUserNameW(wszUserName, &wcch))
2832 {
2833 char_u *p = utf16_to_enc(wszUserName, NULL);
2834
2835 if (p != NULL)
2836 {
2837 vim_strncpy(s, p, len - 1);
2838 vim_free(p);
2839 return OK;
2840 }
2841 }
2842 /* Retry with non-wide function (for Windows 98). */
2843 }
2844#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845 if (GetUserName(szUserName, &cch))
2846 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002847 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848 return OK;
2849 }
2850 s[0] = NUL;
2851 return FAIL;
2852}
2853
2854
2855/*
2856 * Insert host name in s[len].
2857 */
2858 void
2859mch_get_host_name(
2860 char_u *s,
2861 int len)
2862{
2863 DWORD cch = len;
2864
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002865#ifdef FEAT_MBYTE
2866 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2867 {
2868 WCHAR wszHostName[256 + 1];
2869 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2870
2871 if (GetComputerNameW(wszHostName, &wcch))
2872 {
2873 char_u *p = utf16_to_enc(wszHostName, NULL);
2874
2875 if (p != NULL)
2876 {
2877 vim_strncpy(s, p, len - 1);
2878 vim_free(p);
2879 return;
2880 }
2881 }
2882 /* Retry with non-wide function (for Windows 98). */
2883 }
2884#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002886 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887}
2888
2889
2890/*
2891 * return process ID
2892 */
2893 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002894mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895{
2896 return (long)GetCurrentProcessId();
2897}
2898
2899
2900/*
2901 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2902 * Return OK for success, FAIL for failure.
2903 */
2904 int
2905mch_dirname(
2906 char_u *buf,
2907 int len)
2908{
2909 /*
2910 * Originally this was:
2911 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2912 * But the Win32s known bug list says that getcwd() doesn't work
2913 * so use the Win32 system call instead. <Negri>
2914 */
2915#ifdef FEAT_MBYTE
2916 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2917 {
2918 WCHAR wbuf[_MAX_PATH + 1];
2919
2920 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2921 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002922 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923
2924 if (p != NULL)
2925 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002926 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 vim_free(p);
2928 return OK;
2929 }
2930 }
2931 /* Retry with non-wide function (for Windows 98). */
2932 }
2933#endif
2934 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2935}
2936
2937/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002938 * Get file permissions for "name".
2939 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940 */
2941 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002942mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002944 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002945 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002947 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002948 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949}
2950
2951
2952/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002953 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002954 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002955 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 */
2957 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002958mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002960 long n = -1;
2961
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962#ifdef FEAT_MBYTE
2963 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2964 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002965 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966
2967 if (p != NULL)
2968 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002969 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002971 if (n == -1 && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2972 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973 /* Retry with non-wide function (for Windows 98). */
2974 }
2975 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002976 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002978 n = _chmod(name, perm);
2979 if (n == -1)
2980 return FAIL;
2981
2982 win32_set_archive(name);
2983
2984 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985}
2986
2987/*
2988 * Set hidden flag for "name".
2989 */
2990 void
2991mch_hide(char_u *name)
2992{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002993 int attrs = win32_getattrs(name);
2994 if (attrs == -1)
2995 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002997 attrs |= FILE_ATTRIBUTE_HIDDEN;
2998 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999}
3000
3001/*
3002 * return TRUE if "name" is a directory
3003 * return FALSE if "name" is not a directory or upon error
3004 */
3005 int
3006mch_isdir(char_u *name)
3007{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003008 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009
3010 if (f == -1)
3011 return FALSE; /* file does not exist at all */
3012
3013 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3014}
3015
3016/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003017 * Create directory "name".
3018 * Return 0 on success, -1 on error.
3019 */
3020 int
3021mch_mkdir(char_u *name)
3022{
3023#ifdef FEAT_MBYTE
3024 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3025 {
3026 WCHAR *p;
3027 int retval;
3028
3029 p = enc_to_utf16(name, NULL);
3030 if (p == NULL)
3031 return -1;
3032 retval = _wmkdir(p);
3033 vim_free(p);
3034 return retval;
3035 }
3036#endif
3037 return _mkdir(name);
3038}
3039
3040/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003041 * Return TRUE if file "fname" has more than one link.
3042 */
3043 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003044mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003045{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003046 BY_HANDLE_FILE_INFORMATION info;
3047
3048 return win32_fileinfo(fname, &info) == FILEINFO_OK
3049 && info.nNumberOfLinks > 1;
3050}
3051
3052/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003053 * Return TRUE if file "fname" is a symbolic link.
3054 */
3055 int
3056mch_is_symbolic_link(char_u *fname)
3057{
3058 HANDLE hFind;
3059 int res = FALSE;
3060 WIN32_FIND_DATAA findDataA;
3061 DWORD fileFlags = 0, reparseTag = 0;
3062#ifdef FEAT_MBYTE
3063 WCHAR *wn = NULL;
3064 WIN32_FIND_DATAW findDataW;
3065
3066 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3067 wn = enc_to_utf16(fname, NULL);
3068 if (wn != NULL)
3069 {
3070 hFind = FindFirstFileW(wn, &findDataW);
3071 vim_free(wn);
3072 if (hFind == INVALID_HANDLE_VALUE
3073 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3074 {
3075 /* Retry with non-wide function (for Windows 98). */
3076 hFind = FindFirstFile(fname, &findDataA);
3077 if (hFind != INVALID_HANDLE_VALUE)
3078 {
3079 fileFlags = findDataA.dwFileAttributes;
3080 reparseTag = findDataA.dwReserved0;
3081 }
3082 }
3083 else
3084 {
3085 fileFlags = findDataW.dwFileAttributes;
3086 reparseTag = findDataW.dwReserved0;
3087 }
3088 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003089 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003090#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003091 {
3092 hFind = FindFirstFile(fname, &findDataA);
3093 if (hFind != INVALID_HANDLE_VALUE)
3094 {
3095 fileFlags = findDataA.dwFileAttributes;
3096 reparseTag = findDataA.dwReserved0;
3097 }
3098 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003099
3100 if (hFind != INVALID_HANDLE_VALUE)
3101 FindClose(hFind);
3102
3103 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3104 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3105 res = TRUE;
3106
3107 return res;
3108}
3109
3110/*
3111 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3112 * link.
3113 */
3114 int
3115mch_is_linked(char_u *fname)
3116{
3117 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3118 return TRUE;
3119 return FALSE;
3120}
3121
3122/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003123 * Get the by-handle-file-information for "fname".
3124 * Returns FILEINFO_OK when OK.
3125 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3126 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3127 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3128 */
3129 int
3130win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3131{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003132 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003133 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003134#ifdef FEAT_MBYTE
3135 WCHAR *wn = NULL;
3136
3137 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003138 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003139 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003140 if (wn == NULL)
3141 res = FILEINFO_ENC_FAIL;
3142 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003143 if (wn != NULL)
3144 {
3145 hFile = CreateFileW(wn, /* file name */
3146 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003147 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003148 NULL, /* security descriptor */
3149 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003150 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003151 NULL); /* handle to template file */
3152 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003153 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003154 {
3155 /* Retry with non-wide function (for Windows 98). */
3156 vim_free(wn);
3157 wn = NULL;
3158 }
3159 }
3160 if (wn == NULL)
3161#endif
3162 hFile = CreateFile(fname, /* file name */
3163 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003164 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003165 NULL, /* security descriptor */
3166 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003167 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003168 NULL); /* handle to template file */
3169
3170 if (hFile != INVALID_HANDLE_VALUE)
3171 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003172 if (GetFileInformationByHandle(hFile, info) != 0)
3173 res = FILEINFO_OK;
3174 else
3175 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003176 CloseHandle(hFile);
3177 }
3178
3179#ifdef FEAT_MBYTE
3180 vim_free(wn);
3181#endif
3182 return res;
3183}
3184
3185/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003186 * get file attributes for `name'
3187 * -1 : error
3188 * else FILE_ATTRIBUTE_* defined in winnt.h
3189 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003190 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003191win32_getattrs(char_u *name)
3192{
3193 int attr;
3194#ifdef FEAT_MBYTE
3195 WCHAR *p = NULL;
3196
3197 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3198 p = enc_to_utf16(name, NULL);
3199
3200 if (p != NULL)
3201 {
3202 attr = GetFileAttributesW(p);
3203 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3204 {
3205 /* Retry with non-wide function (for Windows 98). */
3206 vim_free(p);
3207 p = NULL;
3208 }
3209 }
3210 if (p == NULL)
3211#endif
3212 attr = GetFileAttributes((char *)name);
3213#ifdef FEAT_MBYTE
3214 vim_free(p);
3215#endif
3216 return attr;
3217}
3218
3219/*
3220 * set file attributes for `name' to `attrs'
3221 *
3222 * return -1 for failure, 0 otherwise
3223 */
3224 static
3225 int
3226win32_setattrs(char_u *name, int attrs)
3227{
3228 int res;
3229#ifdef FEAT_MBYTE
3230 WCHAR *p = NULL;
3231
3232 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3233 p = enc_to_utf16(name, NULL);
3234
3235 if (p != NULL)
3236 {
3237 res = SetFileAttributesW(p, attrs);
3238 if (res == FALSE
3239 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3240 {
3241 /* Retry with non-wide function (for Windows 98). */
3242 vim_free(p);
3243 p = NULL;
3244 }
3245 }
3246 if (p == NULL)
3247#endif
3248 res = SetFileAttributes((char *)name, attrs);
3249#ifdef FEAT_MBYTE
3250 vim_free(p);
3251#endif
3252 return res ? 0 : -1;
3253}
3254
3255/*
3256 * Set archive flag for "name".
3257 */
3258 static
3259 int
3260win32_set_archive(char_u *name)
3261{
3262 int attrs = win32_getattrs(name);
3263 if (attrs == -1)
3264 return -1;
3265
3266 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3267 return win32_setattrs(name, attrs);
3268}
3269
3270/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271 * Return TRUE if file or directory "name" is writable (not readonly).
3272 * Strange semantics of Win32: a readonly directory is writable, but you can't
3273 * delete a file. Let's say this means it is writable.
3274 */
3275 int
3276mch_writable(char_u *name)
3277{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003278 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003280 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3281 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003282}
3283
Bram Moolenaar071d4272004-06-13 20:20:40 +00003284/*
3285 * Return 1 if "name" can be executed, 0 if not.
3286 * Return -1 if unknown.
3287 */
3288 int
3289mch_can_exe(char_u *name)
3290{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003291 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003292 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003293 char_u *p;
3294
3295 if (len >= _MAX_PATH) /* safety check */
3296 return FALSE;
3297
3298 /* If there already is an extension try using the name directly. Also do
3299 * this with a Unix-shell like 'shell'. */
3300 if (vim_strchr(gettail(name), '.') != NULL
3301 || strstr((char *)gettail(p_sh), "sh") != NULL)
3302 if (executable_exists((char *)name))
3303 return TRUE;
3304
3305 /*
3306 * Loop over all extensions in $PATHEXT.
3307 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003308 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003309 p = mch_getenv("PATHEXT");
3310 if (p == NULL)
3311 p = (char_u *)".com;.exe;.bat;.cmd";
3312 while (*p)
3313 {
3314 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3315 {
3316 /* A single "." means no extension is added. */
3317 buf[len] = NUL;
3318 ++p;
3319 if (*p)
3320 ++p;
3321 }
3322 else
3323 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
3324 if (executable_exists((char *)buf))
3325 return TRUE;
3326 }
3327 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003329
3330/*
3331 * Check what "name" is:
3332 * NODE_NORMAL: file or directory (or doesn't exist)
3333 * NODE_WRITABLE: writable device, socket, fifo, etc.
3334 * NODE_OTHER: non-writable things
3335 */
3336 int
3337mch_nodetype(char_u *name)
3338{
3339 HANDLE hFile;
3340 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003341#ifdef FEAT_MBYTE
3342 WCHAR *wn = NULL;
3343#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344
Bram Moolenaar043545e2006-10-10 16:44:07 +00003345 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3346 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3347 * here. */
3348 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3349 return NODE_WRITABLE;
3350
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003351#ifdef FEAT_MBYTE
3352 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3353 {
3354 wn = enc_to_utf16(name, NULL);
3355 if (wn != NULL)
3356 {
3357 hFile = CreateFileW(wn, /* file name */
3358 GENERIC_WRITE, /* access mode */
3359 0, /* share mode */
3360 NULL, /* security descriptor */
3361 OPEN_EXISTING, /* creation disposition */
3362 0, /* file attributes */
3363 NULL); /* handle to template file */
3364 if (hFile == INVALID_HANDLE_VALUE
3365 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3366 {
3367 /* Retry with non-wide function (for Windows 98). */
3368 vim_free(wn);
3369 wn = NULL;
3370 }
3371 }
3372 }
3373 if (wn == NULL)
3374#endif
3375 hFile = CreateFile(name, /* file name */
3376 GENERIC_WRITE, /* access mode */
3377 0, /* share mode */
3378 NULL, /* security descriptor */
3379 OPEN_EXISTING, /* creation disposition */
3380 0, /* file attributes */
3381 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003383#ifdef FEAT_MBYTE
3384 vim_free(wn);
3385#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386 if (hFile == INVALID_HANDLE_VALUE)
3387 return NODE_NORMAL;
3388
3389 type = GetFileType(hFile);
3390 CloseHandle(hFile);
3391 if (type == FILE_TYPE_CHAR)
3392 return NODE_WRITABLE;
3393 if (type == FILE_TYPE_DISK)
3394 return NODE_NORMAL;
3395 return NODE_OTHER;
3396}
3397
3398#ifdef HAVE_ACL
3399struct my_acl
3400{
3401 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3402 PSID pSidOwner;
3403 PSID pSidGroup;
3404 PACL pDacl;
3405 PACL pSacl;
3406};
3407#endif
3408
3409/*
3410 * Return a pointer to the ACL of file "fname" in allocated memory.
3411 * Return NULL if the ACL is not available for whatever reason.
3412 */
3413 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003414mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415{
3416#ifndef HAVE_ACL
3417 return (vim_acl_T)NULL;
3418#else
3419 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003420 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003421
3422 /* This only works on Windows NT and 2000. */
3423 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3424 {
3425 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3426 if (p != NULL)
3427 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003428# ifdef FEAT_MBYTE
3429 WCHAR *wn = NULL;
3430
3431 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3432 wn = enc_to_utf16(fname, NULL);
3433 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003435 /* Try to retrieve the entire security descriptor. */
3436 err = pGetNamedSecurityInfoW(
3437 wn, // Abstract filename
3438 SE_FILE_OBJECT, // File Object
3439 OWNER_SECURITY_INFORMATION |
3440 GROUP_SECURITY_INFORMATION |
3441 DACL_SECURITY_INFORMATION |
3442 SACL_SECURITY_INFORMATION,
3443 &p->pSidOwner, // Ownership information.
3444 &p->pSidGroup, // Group membership.
3445 &p->pDacl, // Discretionary information.
3446 &p->pSacl, // For auditing purposes.
3447 &p->pSecurityDescriptor);
3448 if (err == ERROR_ACCESS_DENIED ||
3449 err == ERROR_PRIVILEGE_NOT_HELD)
3450 {
3451 /* Retrieve only DACL. */
3452 (void)pGetNamedSecurityInfoW(
3453 wn,
3454 SE_FILE_OBJECT,
3455 DACL_SECURITY_INFORMATION,
3456 NULL,
3457 NULL,
3458 &p->pDacl,
3459 NULL,
3460 &p->pSecurityDescriptor);
3461 }
3462 if (p->pSecurityDescriptor == NULL)
3463 {
3464 mch_free_acl((vim_acl_T)p);
3465 p = NULL;
3466 }
3467 vim_free(wn);
3468 }
3469 else
3470# endif
3471 {
3472 /* Try to retrieve the entire security descriptor. */
3473 err = pGetNamedSecurityInfo(
3474 (LPSTR)fname, // Abstract filename
3475 SE_FILE_OBJECT, // File Object
3476 OWNER_SECURITY_INFORMATION |
3477 GROUP_SECURITY_INFORMATION |
3478 DACL_SECURITY_INFORMATION |
3479 SACL_SECURITY_INFORMATION,
3480 &p->pSidOwner, // Ownership information.
3481 &p->pSidGroup, // Group membership.
3482 &p->pDacl, // Discretionary information.
3483 &p->pSacl, // For auditing purposes.
3484 &p->pSecurityDescriptor);
3485 if (err == ERROR_ACCESS_DENIED ||
3486 err == ERROR_PRIVILEGE_NOT_HELD)
3487 {
3488 /* Retrieve only DACL. */
3489 (void)pGetNamedSecurityInfo(
3490 (LPSTR)fname,
3491 SE_FILE_OBJECT,
3492 DACL_SECURITY_INFORMATION,
3493 NULL,
3494 NULL,
3495 &p->pDacl,
3496 NULL,
3497 &p->pSecurityDescriptor);
3498 }
3499 if (p->pSecurityDescriptor == NULL)
3500 {
3501 mch_free_acl((vim_acl_T)p);
3502 p = NULL;
3503 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504 }
3505 }
3506 }
3507
3508 return (vim_acl_T)p;
3509#endif
3510}
3511
Bram Moolenaar27515922013-06-29 15:36:26 +02003512#ifdef HAVE_ACL
3513/*
3514 * Check if "acl" contains inherited ACE.
3515 */
3516 static BOOL
3517is_acl_inherited(PACL acl)
3518{
3519 DWORD i;
3520 ACL_SIZE_INFORMATION acl_info;
3521 PACCESS_ALLOWED_ACE ace;
3522
3523 acl_info.AceCount = 0;
3524 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3525 for (i = 0; i < acl_info.AceCount; i++)
3526 {
3527 GetAce(acl, i, (LPVOID *)&ace);
3528 if (ace->Header.AceFlags & INHERITED_ACE)
3529 return TRUE;
3530 }
3531 return FALSE;
3532}
3533#endif
3534
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535/*
3536 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3537 * Errors are ignored.
3538 * This must only be called with "acl" equal to what mch_get_acl() returned.
3539 */
3540 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003541mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003542{
3543#ifdef HAVE_ACL
3544 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003545 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003546
3547 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003548 {
3549# ifdef FEAT_MBYTE
3550 WCHAR *wn = NULL;
3551# endif
3552
3553 /* Set security flags */
3554 if (p->pSidOwner)
3555 sec_info |= OWNER_SECURITY_INFORMATION;
3556 if (p->pSidGroup)
3557 sec_info |= GROUP_SECURITY_INFORMATION;
3558 if (p->pDacl)
3559 {
3560 sec_info |= DACL_SECURITY_INFORMATION;
3561 /* Do not inherit its parent's DACL.
3562 * If the DACL is inherited, Cygwin permissions would be changed.
3563 */
3564 if (!is_acl_inherited(p->pDacl))
3565 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3566 }
3567 if (p->pSacl)
3568 sec_info |= SACL_SECURITY_INFORMATION;
3569
3570# ifdef FEAT_MBYTE
3571 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3572 wn = enc_to_utf16(fname, NULL);
3573 if (wn != NULL)
3574 {
3575 (void)pSetNamedSecurityInfoW(
3576 wn, // Abstract filename
3577 SE_FILE_OBJECT, // File Object
3578 sec_info,
3579 p->pSidOwner, // Ownership information.
3580 p->pSidGroup, // Group membership.
3581 p->pDacl, // Discretionary information.
3582 p->pSacl // For auditing purposes.
3583 );
3584 vim_free(wn);
3585 }
3586 else
3587# endif
3588 {
3589 (void)pSetNamedSecurityInfo(
3590 (LPSTR)fname, // Abstract filename
3591 SE_FILE_OBJECT, // File Object
3592 sec_info,
3593 p->pSidOwner, // Ownership information.
3594 p->pSidGroup, // Group membership.
3595 p->pDacl, // Discretionary information.
3596 p->pSacl // For auditing purposes.
3597 );
3598 }
3599 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600#endif
3601}
3602
3603 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003604mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605{
3606#ifdef HAVE_ACL
3607 struct my_acl *p = (struct my_acl *)acl;
3608
3609 if (p != NULL)
3610 {
3611 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3612 vim_free(p);
3613 }
3614#endif
3615}
3616
3617#ifndef FEAT_GUI_W32
3618
3619/*
3620 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3621 */
3622 static BOOL WINAPI
3623handler_routine(
3624 DWORD dwCtrlType)
3625{
3626 switch (dwCtrlType)
3627 {
3628 case CTRL_C_EVENT:
3629 if (ctrl_c_interrupts)
3630 g_fCtrlCPressed = TRUE;
3631 return TRUE;
3632
3633 case CTRL_BREAK_EVENT:
3634 g_fCBrkPressed = TRUE;
3635 return TRUE;
3636
3637 /* fatal events: shut down gracefully */
3638 case CTRL_CLOSE_EVENT:
3639 case CTRL_LOGOFF_EVENT:
3640 case CTRL_SHUTDOWN_EVENT:
3641 windgoto((int)Rows - 1, 0);
3642 g_fForceExit = TRUE;
3643
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003644 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003645 (dwCtrlType == CTRL_CLOSE_EVENT
3646 ? _("close")
3647 : dwCtrlType == CTRL_LOGOFF_EVENT
3648 ? _("logoff")
3649 : _("shutdown")));
3650#ifdef DEBUG
3651 OutputDebugString(IObuff);
3652#endif
3653
3654 preserve_exit(); /* output IObuff, preserve files and exit */
3655
3656 return TRUE; /* not reached */
3657
3658 default:
3659 return FALSE;
3660 }
3661}
3662
3663
3664/*
3665 * set the tty in (raw) ? "raw" : "cooked" mode
3666 */
3667 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003668mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003669{
3670 DWORD cmodein;
3671 DWORD cmodeout;
3672 BOOL bEnableHandler;
3673
3674 GetConsoleMode(g_hConIn, &cmodein);
3675 GetConsoleMode(g_hConOut, &cmodeout);
3676 if (tmode == TMODE_RAW)
3677 {
3678 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3679 ENABLE_ECHO_INPUT);
3680#ifdef FEAT_MOUSE
3681 if (g_fMouseActive)
3682 cmodein |= ENABLE_MOUSE_INPUT;
3683#endif
3684 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3685 bEnableHandler = TRUE;
3686 }
3687 else /* cooked */
3688 {
3689 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3690 ENABLE_ECHO_INPUT);
3691 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3692 bEnableHandler = FALSE;
3693 }
3694 SetConsoleMode(g_hConIn, cmodein);
3695 SetConsoleMode(g_hConOut, cmodeout);
3696 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3697
3698#ifdef MCH_WRITE_DUMP
3699 if (fdDump)
3700 {
3701 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3702 tmode == TMODE_RAW ? "raw" :
3703 tmode == TMODE_COOK ? "cooked" : "normal",
3704 cmodein, cmodeout);
3705 fflush(fdDump);
3706 }
3707#endif
3708}
3709
3710
3711/*
3712 * Get the size of the current window in `Rows' and `Columns'
3713 * Return OK when size could be determined, FAIL otherwise.
3714 */
3715 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003716mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717{
3718 CONSOLE_SCREEN_BUFFER_INFO csbi;
3719
3720 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3721 {
3722 /*
3723 * For some reason, we are trying to get the screen dimensions
3724 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3725 * variables are really intended to mean the size of Vim screen
3726 * while in termcap mode.
3727 */
3728 Rows = g_cbTermcap.Info.dwSize.Y;
3729 Columns = g_cbTermcap.Info.dwSize.X;
3730 }
3731 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3732 {
3733 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3734 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3735 }
3736 else
3737 {
3738 Rows = 25;
3739 Columns = 80;
3740 }
3741 return OK;
3742}
3743
3744/*
3745 * Set a console window to `xSize' * `ySize'
3746 */
3747 static void
3748ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003749 HANDLE hConsole,
3750 int xSize,
3751 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003752{
3753 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3754 SMALL_RECT srWindowRect; /* hold the new console size */
3755 COORD coordScreen;
3756
3757#ifdef MCH_WRITE_DUMP
3758 if (fdDump)
3759 {
3760 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3761 fflush(fdDump);
3762 }
3763#endif
3764
3765 /* get the largest size we can size the console window to */
3766 coordScreen = GetLargestConsoleWindowSize(hConsole);
3767
3768 /* define the new console window size and scroll position */
3769 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3770 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3771 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3772
3773 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3774 {
3775 int sx, sy;
3776
3777 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3778 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3779 if (sy < ySize || sx < xSize)
3780 {
3781 /*
3782 * Increasing number of lines/columns, do buffer first.
3783 * Use the maximal size in x and y direction.
3784 */
3785 if (sy < ySize)
3786 coordScreen.Y = ySize;
3787 else
3788 coordScreen.Y = sy;
3789 if (sx < xSize)
3790 coordScreen.X = xSize;
3791 else
3792 coordScreen.X = sx;
3793 SetConsoleScreenBufferSize(hConsole, coordScreen);
3794 }
3795 }
3796
3797 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3798 {
3799#ifdef MCH_WRITE_DUMP
3800 if (fdDump)
3801 {
3802 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3803 GetLastError());
3804 fflush(fdDump);
3805 }
3806#endif
3807 }
3808
3809 /* define the new console buffer size */
3810 coordScreen.X = xSize;
3811 coordScreen.Y = ySize;
3812
3813 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3814 {
3815#ifdef MCH_WRITE_DUMP
3816 if (fdDump)
3817 {
3818 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3819 GetLastError());
3820 fflush(fdDump);
3821 }
3822#endif
3823 }
3824}
3825
3826
3827/*
3828 * Set the console window to `Rows' * `Columns'
3829 */
3830 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003831mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832{
3833 COORD coordScreen;
3834
3835 /* Don't change window size while still starting up */
3836 if (suppress_winsize != 0)
3837 {
3838 suppress_winsize = 2;
3839 return;
3840 }
3841
3842 if (term_console)
3843 {
3844 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3845
3846 /* Clamp Rows and Columns to reasonable values */
3847 if (Rows > coordScreen.Y)
3848 Rows = coordScreen.Y;
3849 if (Columns > coordScreen.X)
3850 Columns = coordScreen.X;
3851
3852 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3853 }
3854}
3855
3856/*
3857 * Rows and/or Columns has changed.
3858 */
3859 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003860mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861{
3862 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3863}
3864
3865
3866/*
3867 * Called when started up, to set the winsize that was delayed.
3868 */
3869 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003870mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003871{
3872 if (suppress_winsize == 2)
3873 {
3874 suppress_winsize = 0;
3875 mch_set_shellsize();
3876 shell_resized();
3877 }
3878 suppress_winsize = 0;
3879}
3880#endif /* FEAT_GUI_W32 */
3881
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003882 static BOOL
3883vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003884 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003885 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003886 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003887 STARTUPINFO *si,
3888 PROCESS_INFORMATION *pi)
3889{
3890# ifdef FEAT_MBYTE
3891 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3892 {
3893 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
3894
3895 if (wcmd != NULL)
3896 {
3897 BOOL ret;
3898 ret = CreateProcessW(
3899 NULL, /* Executable name */
3900 wcmd, /* Command to execute */
3901 NULL, /* Process security attributes */
3902 NULL, /* Thread security attributes */
3903 inherit_handles, /* Inherit handles */
3904 flags, /* Creation flags */
3905 NULL, /* Environment */
3906 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003907 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003908 pi); /* Process information */
3909 vim_free(wcmd);
3910 return ret;
3911 }
3912 }
3913#endif
3914 return CreateProcess(
3915 NULL, /* Executable name */
3916 cmd, /* Command to execute */
3917 NULL, /* Process security attributes */
3918 NULL, /* Thread security attributes */
3919 inherit_handles, /* Inherit handles */
3920 flags, /* Creation flags */
3921 NULL, /* Environment */
3922 NULL, /* Current directory */
3923 si, /* Startup information */
3924 pi); /* Process information */
3925}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926
3927
3928#if defined(FEAT_GUI_W32) || defined(PROTO)
3929
3930/*
3931 * Specialised version of system() for Win32 GUI mode.
3932 * This version proceeds as follows:
3933 * 1. Create a console window for use by the subprocess
3934 * 2. Run the subprocess (it gets the allocated console by default)
3935 * 3. Wait for the subprocess to terminate and get its exit code
3936 * 4. Prompt the user to press a key to close the console window
3937 */
3938 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003939mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003940{
3941 STARTUPINFO si;
3942 PROCESS_INFORMATION pi;
3943 DWORD ret = 0;
3944 HWND hwnd = GetFocus();
3945
3946 si.cb = sizeof(si);
3947 si.lpReserved = NULL;
3948 si.lpDesktop = NULL;
3949 si.lpTitle = NULL;
3950 si.dwFlags = STARTF_USESHOWWINDOW;
3951 /*
3952 * It's nicer to run a filter command in a minimized window, but in
3953 * Windows 95 this makes the command MUCH slower. We can't do it under
3954 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003955 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956 */
3957 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003958 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003959 else
3960 si.wShowWindow = SW_SHOWNORMAL;
3961 si.cbReserved2 = 0;
3962 si.lpReserved2 = NULL;
3963
3964 /* There is a strange error on Windows 95 when using "c:\\command.com".
3965 * When the "c:\\" is left out it works OK...? */
3966 if (mch_windows95()
3967 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3968 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3969 cmd += 3;
3970
3971 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003972 vim_create_process(cmd, FALSE,
3973 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974
3975 /* Wait for the command to terminate before continuing */
3976 if (g_PlatformId != VER_PLATFORM_WIN32s)
3977 {
3978#ifdef FEAT_GUI
3979 int delay = 1;
3980
3981 /* Keep updating the window while waiting for the shell to finish. */
3982 for (;;)
3983 {
3984 MSG msg;
3985
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003986 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 {
3988 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003989 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003990 delay = 1;
3991 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003992 }
3993 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3994 break;
3995
3996 /* We start waiting for a very short time and then increase it, so
3997 * that we respond quickly when the process is quick, and don't
3998 * consume too much overhead when it's slow. */
3999 if (delay < 50)
4000 delay += 10;
4001 }
4002#else
4003 WaitForSingleObject(pi.hProcess, INFINITE);
4004#endif
4005
4006 /* Get the command exit code */
4007 GetExitCodeProcess(pi.hProcess, &ret);
4008 }
4009 else
4010 {
4011 /*
4012 * This ugly code is the only quick way of performing
4013 * a synchronous spawn under Win32s. Yuk.
4014 */
4015 num_windows = 0;
4016 EnumWindows(win32ssynch_cb, 0);
4017 old_num_windows = num_windows;
4018 do
4019 {
4020 Sleep(1000);
4021 num_windows = 0;
4022 EnumWindows(win32ssynch_cb, 0);
4023 } while (num_windows == old_num_windows);
4024 ret = 0;
4025 }
4026
4027 /* Close the handles to the subprocess, so that it goes away */
4028 CloseHandle(pi.hThread);
4029 CloseHandle(pi.hProcess);
4030
4031 /* Try to get input focus back. Doesn't always work though. */
4032 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4033
4034 return ret;
4035}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004036
4037/*
4038 * Thread launched by the gui to send the current buffer data to the
4039 * process. This way avoid to hang up vim totally if the children
4040 * process take a long time to process the lines.
4041 */
4042 static DWORD WINAPI
4043sub_process_writer(LPVOID param)
4044{
4045 HANDLE g_hChildStd_IN_Wr = param;
4046 linenr_T lnum = curbuf->b_op_start.lnum;
4047 DWORD len = 0;
4048 DWORD l;
4049 char_u *lp = ml_get(lnum);
4050 char_u *s;
4051 int written = 0;
4052
4053 for (;;)
4054 {
4055 l = (DWORD)STRLEN(lp + written);
4056 if (l == 0)
4057 len = 0;
4058 else if (lp[written] == NL)
4059 {
4060 /* NL -> NUL translation */
4061 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4062 }
4063 else
4064 {
4065 s = vim_strchr(lp + written, NL);
4066 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4067 s == NULL ? l : (DWORD)(s - (lp + written)),
4068 &len, NULL);
4069 }
4070 if (len == (int)l)
4071 {
4072 /* Finished a line, add a NL, unless this line should not have
4073 * one. */
4074 if (lnum != curbuf->b_op_end.lnum
4075 || !curbuf->b_p_bin
4076 || (lnum != curbuf->b_no_eol_lnum
4077 && (lnum != curbuf->b_ml.ml_line_count
4078 || curbuf->b_p_eol)))
4079 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004080 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004081 }
4082
4083 ++lnum;
4084 if (lnum > curbuf->b_op_end.lnum)
4085 break;
4086
4087 lp = ml_get(lnum);
4088 written = 0;
4089 }
4090 else if (len > 0)
4091 written += len;
4092 }
4093
4094 /* finished all the lines, close pipe */
4095 CloseHandle(g_hChildStd_IN_Wr);
4096 ExitThread(0);
4097}
4098
4099
4100# define BUFLEN 100 /* length for buffer, stolen from unix version */
4101
4102/*
4103 * This function read from the children's stdout and write the
4104 * data on screen or in the buffer accordingly.
4105 */
4106 static void
4107dump_pipe(int options,
4108 HANDLE g_hChildStd_OUT_Rd,
4109 garray_T *ga,
4110 char_u buffer[],
4111 DWORD *buffer_off)
4112{
4113 DWORD availableBytes = 0;
4114 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004115 int ret;
4116 DWORD len;
4117 DWORD toRead;
4118 int repeatCount;
4119
4120 /* we query the pipe to see if there is any data to read
4121 * to avoid to perform a blocking read */
4122 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4123 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004124 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004125 NULL, /* number of read bytes */
4126 &availableBytes, /* available bytes total */
4127 NULL); /* byteLeft */
4128
4129 repeatCount = 0;
4130 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004131 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004132 {
4133 repeatCount++;
4134 toRead =
4135# ifdef FEAT_MBYTE
4136 (DWORD)(BUFLEN - *buffer_off);
4137# else
4138 (DWORD)BUFLEN;
4139# endif
4140 toRead = availableBytes < toRead ? availableBytes : toRead;
4141 ReadFile(g_hChildStd_OUT_Rd, buffer
4142# ifdef FEAT_MBYTE
4143 + *buffer_off, toRead
4144# else
4145 , toRead
4146# endif
4147 , &len, NULL);
4148
4149 /* If we haven't read anything, there is a problem */
4150 if (len == 0)
4151 break;
4152
4153 availableBytes -= len;
4154
4155 if (options & SHELL_READ)
4156 {
4157 /* Do NUL -> NL translation, append NL separated
4158 * lines to the current buffer. */
4159 for (i = 0; i < len; ++i)
4160 {
4161 if (buffer[i] == NL)
4162 append_ga_line(ga);
4163 else if (buffer[i] == NUL)
4164 ga_append(ga, NL);
4165 else
4166 ga_append(ga, buffer[i]);
4167 }
4168 }
4169# ifdef FEAT_MBYTE
4170 else if (has_mbyte)
4171 {
4172 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004173 int c;
4174 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004175
4176 len += *buffer_off;
4177 buffer[len] = NUL;
4178
4179 /* Check if the last character in buffer[] is
4180 * incomplete, keep these bytes for the next
4181 * round. */
4182 for (p = buffer; p < buffer + len; p += l)
4183 {
4184 l = mb_cptr2len(p);
4185 if (l == 0)
4186 l = 1; /* NUL byte? */
4187 else if (MB_BYTE2LEN(*p) != l)
4188 break;
4189 }
4190 if (p == buffer) /* no complete character */
4191 {
4192 /* avoid getting stuck at an illegal byte */
4193 if (len >= 12)
4194 ++p;
4195 else
4196 {
4197 *buffer_off = len;
4198 return;
4199 }
4200 }
4201 c = *p;
4202 *p = NUL;
4203 msg_puts(buffer);
4204 if (p < buffer + len)
4205 {
4206 *p = c;
4207 *buffer_off = (DWORD)((buffer + len) - p);
4208 mch_memmove(buffer, p, *buffer_off);
4209 return;
4210 }
4211 *buffer_off = 0;
4212 }
4213# endif /* FEAT_MBYTE */
4214 else
4215 {
4216 buffer[len] = NUL;
4217 msg_puts(buffer);
4218 }
4219
4220 windgoto(msg_row, msg_col);
4221 cursor_on();
4222 out_flush();
4223 }
4224}
4225
4226/*
4227 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4228 * for communication and doesn't open any new window.
4229 */
4230 static int
4231mch_system_piped(char *cmd, int options)
4232{
4233 STARTUPINFO si;
4234 PROCESS_INFORMATION pi;
4235 DWORD ret = 0;
4236
4237 HANDLE g_hChildStd_IN_Rd = NULL;
4238 HANDLE g_hChildStd_IN_Wr = NULL;
4239 HANDLE g_hChildStd_OUT_Rd = NULL;
4240 HANDLE g_hChildStd_OUT_Wr = NULL;
4241
4242 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4243 DWORD len;
4244
4245 /* buffer used to receive keys */
4246 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4247 int ta_len = 0; /* valid bytes in ta_buf[] */
4248
4249 DWORD i;
4250 int c;
4251 int noread_cnt = 0;
4252 garray_T ga;
4253 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004254 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004255 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004256
4257 SECURITY_ATTRIBUTES saAttr;
4258
4259 /* Set the bInheritHandle flag so pipe handles are inherited. */
4260 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4261 saAttr.bInheritHandle = TRUE;
4262 saAttr.lpSecurityDescriptor = NULL;
4263
4264 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4265 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4266 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4267 /* Create a pipe for the child process's STDIN. */
4268 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4269 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4270 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4271 {
4272 CloseHandle(g_hChildStd_IN_Rd);
4273 CloseHandle(g_hChildStd_IN_Wr);
4274 CloseHandle(g_hChildStd_OUT_Rd);
4275 CloseHandle(g_hChildStd_OUT_Wr);
4276 MSG_PUTS(_("\nCannot create pipes\n"));
4277 }
4278
4279 si.cb = sizeof(si);
4280 si.lpReserved = NULL;
4281 si.lpDesktop = NULL;
4282 si.lpTitle = NULL;
4283 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4284
4285 /* set-up our file redirection */
4286 si.hStdError = g_hChildStd_OUT_Wr;
4287 si.hStdOutput = g_hChildStd_OUT_Wr;
4288 si.hStdInput = g_hChildStd_IN_Rd;
4289 si.wShowWindow = SW_HIDE;
4290 si.cbReserved2 = 0;
4291 si.lpReserved2 = NULL;
4292
4293 if (options & SHELL_READ)
4294 ga_init2(&ga, 1, BUFLEN);
4295
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004296 if (cmd != NULL)
4297 {
4298 p = (char *)vim_strsave((char_u *)cmd);
4299 if (p != NULL)
4300 unescape_shellxquote((char_u *)p, p_sxe);
4301 else
4302 p = cmd;
4303 }
4304
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004305 /* Now, run the command.
4306 * About "Inherit handles" being TRUE: this command can be litigious,
4307 * handle inheritance was deactivated for pending temp file, but, if we
4308 * deactivate it, the pipes don't work for some reason. */
4309 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004310
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004311 if (p != cmd)
4312 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004313
4314 /* Close our unused side of the pipes */
4315 CloseHandle(g_hChildStd_IN_Rd);
4316 CloseHandle(g_hChildStd_OUT_Wr);
4317
4318 if (options & SHELL_WRITE)
4319 {
4320 HANDLE thread =
4321 CreateThread(NULL, /* security attributes */
4322 0, /* default stack size */
4323 sub_process_writer, /* function to be executed */
4324 g_hChildStd_IN_Wr, /* parameter */
4325 0, /* creation flag, start immediately */
4326 NULL); /* we don't care about thread id */
4327 CloseHandle(thread);
4328 g_hChildStd_IN_Wr = NULL;
4329 }
4330
4331 /* Keep updating the window while waiting for the shell to finish. */
4332 for (;;)
4333 {
4334 MSG msg;
4335
Bram Moolenaar175d0702013-12-11 18:36:33 +01004336 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004337 {
4338 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004339 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004340 }
4341
4342 /* write pipe information in the window */
4343 if ((options & (SHELL_READ|SHELL_WRITE))
4344# ifdef FEAT_GUI
4345 || gui.in_use
4346# endif
4347 )
4348 {
4349 len = 0;
4350 if (!(options & SHELL_EXPAND)
4351 && ((options &
4352 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4353 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4354# ifdef FEAT_GUI
4355 || gui.in_use
4356# endif
4357 )
4358 && (ta_len > 0 || noread_cnt > 4))
4359 {
4360 if (ta_len == 0)
4361 {
4362 /* Get extra characters when we don't have any. Reset the
4363 * counter and timer. */
4364 noread_cnt = 0;
4365# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4366 gettimeofday(&start_tv, NULL);
4367# endif
4368 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4369 }
4370 if (ta_len > 0 || len > 0)
4371 {
4372 /*
4373 * For pipes: Check for CTRL-C: send interrupt signal to
4374 * child. Check for CTRL-D: EOF, close pipe to child.
4375 */
4376 if (len == 1 && cmd != NULL)
4377 {
4378 if (ta_buf[ta_len] == Ctrl_C)
4379 {
4380 /* Learn what exit code is expected, for
4381 * now put 9 as SIGKILL */
4382 TerminateProcess(pi.hProcess, 9);
4383 }
4384 if (ta_buf[ta_len] == Ctrl_D)
4385 {
4386 CloseHandle(g_hChildStd_IN_Wr);
4387 g_hChildStd_IN_Wr = NULL;
4388 }
4389 }
4390
4391 /* replace K_BS by <BS> and K_DEL by <DEL> */
4392 for (i = ta_len; i < ta_len + len; ++i)
4393 {
4394 if (ta_buf[i] == CSI && len - i > 2)
4395 {
4396 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4397 if (c == K_DEL || c == K_KDEL || c == K_BS)
4398 {
4399 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4400 (size_t)(len - i - 2));
4401 if (c == K_DEL || c == K_KDEL)
4402 ta_buf[i] = DEL;
4403 else
4404 ta_buf[i] = Ctrl_H;
4405 len -= 2;
4406 }
4407 }
4408 else if (ta_buf[i] == '\r')
4409 ta_buf[i] = '\n';
4410# ifdef FEAT_MBYTE
4411 if (has_mbyte)
4412 i += (*mb_ptr2len_len)(ta_buf + i,
4413 ta_len + len - i) - 1;
4414# endif
4415 }
4416
4417 /*
4418 * For pipes: echo the typed characters. For a pty this
4419 * does not seem to work.
4420 */
4421 for (i = ta_len; i < ta_len + len; ++i)
4422 {
4423 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4424 msg_putchar(ta_buf[i]);
4425# ifdef FEAT_MBYTE
4426 else if (has_mbyte)
4427 {
4428 int l = (*mb_ptr2len)(ta_buf + i);
4429
4430 msg_outtrans_len(ta_buf + i, l);
4431 i += l - 1;
4432 }
4433# endif
4434 else
4435 msg_outtrans_len(ta_buf + i, 1);
4436 }
4437 windgoto(msg_row, msg_col);
4438 out_flush();
4439
4440 ta_len += len;
4441
4442 /*
4443 * Write the characters to the child, unless EOF has been
4444 * typed for pipes. Write one character at a time, to
4445 * avoid losing too much typeahead. When writing buffer
4446 * lines, drop the typed characters (only check for
4447 * CTRL-C).
4448 */
4449 if (options & SHELL_WRITE)
4450 ta_len = 0;
4451 else if (g_hChildStd_IN_Wr != NULL)
4452 {
4453 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4454 1, &len, NULL);
4455 // if we are typing in, we want to keep things reactive
4456 delay = 1;
4457 if (len > 0)
4458 {
4459 ta_len -= len;
4460 mch_memmove(ta_buf, ta_buf + len, ta_len);
4461 }
4462 }
4463 }
4464 }
4465 }
4466
4467 if (ta_len)
4468 ui_inchar_undo(ta_buf, ta_len);
4469
4470 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4471 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004472 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004473 break;
4474 }
4475
4476 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004477 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004478
4479 /* We start waiting for a very short time and then increase it, so
4480 * that we respond quickly when the process is quick, and don't
4481 * consume too much overhead when it's slow. */
4482 if (delay < 50)
4483 delay += 10;
4484 }
4485
4486 /* Close the pipe */
4487 CloseHandle(g_hChildStd_OUT_Rd);
4488 if (g_hChildStd_IN_Wr != NULL)
4489 CloseHandle(g_hChildStd_IN_Wr);
4490
4491 WaitForSingleObject(pi.hProcess, INFINITE);
4492
4493 /* Get the command exit code */
4494 GetExitCodeProcess(pi.hProcess, &ret);
4495
4496 if (options & SHELL_READ)
4497 {
4498 if (ga.ga_len > 0)
4499 {
4500 append_ga_line(&ga);
4501 /* remember that the NL was missing */
4502 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4503 }
4504 else
4505 curbuf->b_no_eol_lnum = 0;
4506 ga_clear(&ga);
4507 }
4508
4509 /* Close the handles to the subprocess, so that it goes away */
4510 CloseHandle(pi.hThread);
4511 CloseHandle(pi.hProcess);
4512
4513 return ret;
4514}
4515
4516 static int
4517mch_system(char *cmd, int options)
4518{
4519 /* if we can pipe and the shelltemp option is off */
4520 if (allowPiping && !p_stmp)
4521 return mch_system_piped(cmd, options);
4522 else
4523 return mch_system_classic(cmd, options);
4524}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004525#else
4526
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004527# ifdef FEAT_MBYTE
4528 static int
4529mch_system(char *cmd, int options)
4530{
4531 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4532 {
4533 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4534 if (wcmd != NULL)
4535 {
4536 int ret = _wsystem(wcmd);
4537 vim_free(wcmd);
4538 return ret;
4539 }
4540 }
4541 return system(cmd);
4542}
4543# else
4544# define mch_system(c, o) system(c)
4545# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004546
4547#endif
4548
4549/*
4550 * Either execute a command by calling the shell or start a new shell
4551 */
4552 int
4553mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004554 char_u *cmd,
4555 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556{
4557 int x = 0;
4558 int tmode = cur_tmode;
4559#ifdef FEAT_TITLE
4560 char szShellTitle[512];
4561
4562 /* Change the title to reflect that we are in a subshell. */
4563 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
4564 {
4565 if (cmd == NULL)
4566 strcat(szShellTitle, " :sh");
4567 else
4568 {
4569 strcat(szShellTitle, " - !");
4570 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4571 strcat(szShellTitle, cmd);
4572 }
4573 mch_settitle(szShellTitle, NULL);
4574 }
4575#endif
4576
4577 out_flush();
4578
4579#ifdef MCH_WRITE_DUMP
4580 if (fdDump)
4581 {
4582 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4583 fflush(fdDump);
4584 }
4585#endif
4586
4587 /*
4588 * Catch all deadly signals while running the external command, because a
4589 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4590 */
4591 signal(SIGINT, SIG_IGN);
4592#if defined(__GNUC__) && !defined(__MINGW32__)
4593 signal(SIGKILL, SIG_IGN);
4594#else
4595 signal(SIGBREAK, SIG_IGN);
4596#endif
4597 signal(SIGILL, SIG_IGN);
4598 signal(SIGFPE, SIG_IGN);
4599 signal(SIGSEGV, SIG_IGN);
4600 signal(SIGTERM, SIG_IGN);
4601 signal(SIGABRT, SIG_IGN);
4602
4603 if (options & SHELL_COOKED)
4604 settmode(TMODE_COOK); /* set to normal mode */
4605
4606 if (cmd == NULL)
4607 {
4608 x = mch_system(p_sh, options);
4609 }
4610 else
4611 {
4612 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004613 char_u *newcmd = NULL;
4614 char_u *cmdbase = cmd;
4615 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004616
4617 /* Skip a leading ", ( and "(. */
4618 if (*cmdbase == '"' )
4619 ++cmdbase;
4620 if (*cmdbase == '(')
4621 ++cmdbase;
4622
4623 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4624 {
4625 STARTUPINFO si;
4626 PROCESS_INFORMATION pi;
4627 DWORD flags = CREATE_NEW_CONSOLE;
4628 char_u *p;
4629
4630 si.cb = sizeof(si);
4631 si.lpReserved = NULL;
4632 si.lpDesktop = NULL;
4633 si.lpTitle = NULL;
4634 si.dwFlags = 0;
4635 si.cbReserved2 = 0;
4636 si.lpReserved2 = NULL;
4637
4638 cmdbase = skipwhite(cmdbase + 5);
4639 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4640 && vim_iswhite(cmdbase[4]))
4641 {
4642 cmdbase = skipwhite(cmdbase + 4);
4643 si.dwFlags = STARTF_USESHOWWINDOW;
4644 si.wShowWindow = SW_SHOWMINNOACTIVE;
4645 }
4646 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4647 && vim_iswhite(cmdbase[2]))
4648 {
4649 cmdbase = skipwhite(cmdbase + 2);
4650 flags = CREATE_NO_WINDOW;
4651 si.dwFlags = STARTF_USESTDHANDLES;
4652 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004653 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004654 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004655 NULL, // Security att.
4656 OPEN_EXISTING, // Open flags
4657 FILE_ATTRIBUTE_NORMAL, // File att.
4658 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004659 si.hStdOutput = si.hStdInput;
4660 si.hStdError = si.hStdInput;
4661 }
4662
4663 /* Remove a trailing ", ) and )" if they have a match
4664 * at the start of the command. */
4665 if (cmdbase > cmd)
4666 {
4667 p = cmdbase + STRLEN(cmdbase);
4668 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4669 *--p = NUL;
4670 if (p > cmdbase && p[-1] == ')'
4671 && (*cmd =='(' || cmd[1] == '('))
4672 *--p = NUL;
4673 }
4674
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004675 newcmd = cmdbase;
4676 unescape_shellxquote(cmdbase, p_sxe);
4677
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004678 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004679 * If creating new console, arguments are passed to the
4680 * 'cmd.exe' as-is. If it's not, arguments are not treated
4681 * correctly for current 'cmd.exe'. So unescape characters in
4682 * shellxescape except '|' for avoiding to be treated as
4683 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004684 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004685 if (flags != CREATE_NEW_CONSOLE)
4686 {
4687 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004688 char_u *cmd_shell = mch_getenv("COMSPEC");
4689
4690 if (cmd_shell == NULL || *cmd_shell == NUL)
4691 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004692
4693 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4694 if (subcmd != NULL)
4695 {
4696 /* make "cmd.exe /c arguments" */
4697 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004698 newcmd = lalloc(cmdlen, TRUE);
4699 if (newcmd != NULL)
4700 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004701 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004702 else
4703 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004704 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004705 }
4706 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004707
4708 /*
4709 * Now, start the command as a process, so that it doesn't
4710 * inherit our handles which causes unpleasant dangling swap
4711 * files if we exit before the spawned process
4712 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004713 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004714 x = 0;
4715 else
4716 {
4717 x = -1;
4718#ifdef FEAT_GUI_W32
4719 EMSG(_("E371: Command not found"));
4720#endif
4721 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004722
4723 if (newcmd != cmdbase)
4724 vim_free(newcmd);
4725
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004726 if (si.hStdInput != NULL)
4727 {
4728 /* Close the handle to \\.\NUL */
4729 CloseHandle(si.hStdInput);
4730 }
4731 /* Close the handles to the subprocess, so that it goes away */
4732 CloseHandle(pi.hThread);
4733 CloseHandle(pi.hProcess);
4734 }
4735 else
4736 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004737 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004739 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004741 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4742
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004743 newcmd = lalloc(cmdlen, TRUE);
4744 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 {
4746#if defined(FEAT_GUI_W32)
4747 if (need_vimrun_warning)
4748 {
4749 MessageBox(NULL,
4750 _("VIMRUN.EXE not found in your $PATH.\n"
4751 "External commands will not pause after completion.\n"
4752 "See :help win32-vimrun for more information."),
4753 _("Vim Warning"),
4754 MB_ICONWARNING);
4755 need_vimrun_warning = FALSE;
4756 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004757 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758 /* Use vimrun to execute the command. It opens a console
4759 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004760 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761 vimrun_path,
4762 (msg_silent != 0 || (options & SHELL_DOOUT))
4763 ? "-s " : "",
4764 p_sh, p_shcf, cmd);
4765 else
4766#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004767 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004768 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004770 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772 }
4773 }
4774
4775 if (tmode == TMODE_RAW)
4776 settmode(TMODE_RAW); /* set to raw mode */
4777
4778 /* Print the return value, unless "vimrun" was used. */
4779 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4780#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004781 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4782 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783#endif
4784 )
4785 {
4786 smsg(_("shell returned %d"), x);
4787 msg_putchar('\n');
4788 }
4789#ifdef FEAT_TITLE
4790 resettitle();
4791#endif
4792
4793 signal(SIGINT, SIG_DFL);
4794#if defined(__GNUC__) && !defined(__MINGW32__)
4795 signal(SIGKILL, SIG_DFL);
4796#else
4797 signal(SIGBREAK, SIG_DFL);
4798#endif
4799 signal(SIGILL, SIG_DFL);
4800 signal(SIGFPE, SIG_DFL);
4801 signal(SIGSEGV, SIG_DFL);
4802 signal(SIGTERM, SIG_DFL);
4803 signal(SIGABRT, SIG_DFL);
4804
4805 return x;
4806}
4807
4808
4809#ifndef FEAT_GUI_W32
4810
4811/*
4812 * Start termcap mode
4813 */
4814 static void
4815termcap_mode_start(void)
4816{
4817 DWORD cmodein;
4818
4819 if (g_fTermcapMode)
4820 return;
4821
4822 SaveConsoleBuffer(&g_cbNonTermcap);
4823
4824 if (g_cbTermcap.IsValid)
4825 {
4826 /*
4827 * We've been in termcap mode before. Restore certain screen
4828 * characteristics, including the buffer size and the window
4829 * size. Since we will be redrawing the screen, we don't need
4830 * to restore the actual contents of the buffer.
4831 */
4832 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4833 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4834 Rows = g_cbTermcap.Info.dwSize.Y;
4835 Columns = g_cbTermcap.Info.dwSize.X;
4836 }
4837 else
4838 {
4839 /*
4840 * This is our first time entering termcap mode. Clear the console
4841 * screen buffer, and resize the buffer to match the current window
4842 * size. We will use this as the size of our editing environment.
4843 */
4844 ClearConsoleBuffer(g_attrCurrent);
4845 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4846 }
4847
4848#ifdef FEAT_TITLE
4849 resettitle();
4850#endif
4851
4852 GetConsoleMode(g_hConIn, &cmodein);
4853#ifdef FEAT_MOUSE
4854 if (g_fMouseActive)
4855 cmodein |= ENABLE_MOUSE_INPUT;
4856 else
4857 cmodein &= ~ENABLE_MOUSE_INPUT;
4858#endif
4859 cmodein |= ENABLE_WINDOW_INPUT;
4860 SetConsoleMode(g_hConIn, cmodein);
4861
4862 redraw_later_clear();
4863 g_fTermcapMode = TRUE;
4864}
4865
4866
4867/*
4868 * End termcap mode
4869 */
4870 static void
4871termcap_mode_end(void)
4872{
4873 DWORD cmodein;
4874 ConsoleBuffer *cb;
4875 COORD coord;
4876 DWORD dwDummy;
4877
4878 if (!g_fTermcapMode)
4879 return;
4880
4881 SaveConsoleBuffer(&g_cbTermcap);
4882
4883 GetConsoleMode(g_hConIn, &cmodein);
4884 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4885 SetConsoleMode(g_hConIn, cmodein);
4886
4887#ifdef FEAT_RESTORE_ORIG_SCREEN
4888 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4889#else
4890 cb = &g_cbNonTermcap;
4891#endif
4892 RestoreConsoleBuffer(cb, p_rs);
4893 SetConsoleCursorInfo(g_hConOut, &g_cci);
4894
4895 if (p_rs || exiting)
4896 {
4897 /*
4898 * Clear anything that happens to be on the current line.
4899 */
4900 coord.X = 0;
4901 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4902 FillConsoleOutputCharacter(g_hConOut, ' ',
4903 cb->Info.dwSize.X, coord, &dwDummy);
4904 /*
4905 * The following is just for aesthetics. If we are exiting without
4906 * restoring the screen, then we want to have a prompt string
4907 * appear at the bottom line. However, the command interpreter
4908 * seems to always advance the cursor one line before displaying
4909 * the prompt string, which causes the screen to scroll. To
4910 * counter this, move the cursor up one line before exiting.
4911 */
4912 if (exiting && !p_rs)
4913 coord.Y--;
4914 /*
4915 * Position the cursor at the leftmost column of the desired row.
4916 */
4917 SetConsoleCursorPosition(g_hConOut, coord);
4918 }
4919
4920 g_fTermcapMode = FALSE;
4921}
4922#endif /* FEAT_GUI_W32 */
4923
4924
4925#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004926/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004927 void
4928mch_write(
4929 char_u *s,
4930 int len)
4931{
4932 /* never used */
4933}
4934
4935#else
4936
4937/*
4938 * clear `n' chars, starting from `coord'
4939 */
4940 static void
4941clear_chars(
4942 COORD coord,
4943 DWORD n)
4944{
4945 DWORD dwDummy;
4946
4947 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4948 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4949}
4950
4951
4952/*
4953 * Clear the screen
4954 */
4955 static void
4956clear_screen(void)
4957{
4958 g_coord.X = g_coord.Y = 0;
4959 clear_chars(g_coord, Rows * Columns);
4960}
4961
4962
4963/*
4964 * Clear to end of display
4965 */
4966 static void
4967clear_to_end_of_display(void)
4968{
4969 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4970 * Columns + (Columns - g_coord.X));
4971}
4972
4973
4974/*
4975 * Clear to end of line
4976 */
4977 static void
4978clear_to_end_of_line(void)
4979{
4980 clear_chars(g_coord, Columns - g_coord.X);
4981}
4982
4983
4984/*
4985 * Scroll the scroll region up by `cLines' lines
4986 */
4987 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004988scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989{
4990 COORD oldcoord = g_coord;
4991
4992 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4993 delete_lines(cLines);
4994
4995 g_coord = oldcoord;
4996}
4997
4998
4999/*
5000 * Set the scroll region
5001 */
5002 static void
5003set_scroll_region(
5004 unsigned left,
5005 unsigned top,
5006 unsigned right,
5007 unsigned bottom)
5008{
5009 if (left >= right
5010 || top >= bottom
5011 || right > (unsigned) Columns - 1
5012 || bottom > (unsigned) Rows - 1)
5013 return;
5014
5015 g_srScrollRegion.Left = left;
5016 g_srScrollRegion.Top = top;
5017 g_srScrollRegion.Right = right;
5018 g_srScrollRegion.Bottom = bottom;
5019}
5020
5021
5022/*
5023 * Insert `cLines' lines at the current cursor position
5024 */
5025 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005026insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005027{
5028 SMALL_RECT source;
5029 COORD dest;
5030 CHAR_INFO fill;
5031
5032 dest.X = 0;
5033 dest.Y = g_coord.Y + cLines;
5034
5035 source.Left = 0;
5036 source.Top = g_coord.Y;
5037 source.Right = g_srScrollRegion.Right;
5038 source.Bottom = g_srScrollRegion.Bottom - cLines;
5039
5040 fill.Char.AsciiChar = ' ';
5041 fill.Attributes = g_attrCurrent;
5042
5043 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5044
5045 /* Here we have to deal with a win32 console flake: If the scroll
5046 * region looks like abc and we scroll c to a and fill with d we get
5047 * cbd... if we scroll block c one line at a time to a, we get cdd...
5048 * vim expects cdd consistently... So we have to deal with that
5049 * here... (this also occurs scrolling the same way in the other
5050 * direction). */
5051
5052 if (source.Bottom < dest.Y)
5053 {
5054 COORD coord;
5055
5056 coord.X = 0;
5057 coord.Y = source.Bottom;
5058 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5059 }
5060}
5061
5062
5063/*
5064 * Delete `cLines' lines at the current cursor position
5065 */
5066 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005067delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005068{
5069 SMALL_RECT source;
5070 COORD dest;
5071 CHAR_INFO fill;
5072 int nb;
5073
5074 dest.X = 0;
5075 dest.Y = g_coord.Y;
5076
5077 source.Left = 0;
5078 source.Top = g_coord.Y + cLines;
5079 source.Right = g_srScrollRegion.Right;
5080 source.Bottom = g_srScrollRegion.Bottom;
5081
5082 fill.Char.AsciiChar = ' ';
5083 fill.Attributes = g_attrCurrent;
5084
5085 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5086
5087 /* Here we have to deal with a win32 console flake: If the scroll
5088 * region looks like abc and we scroll c to a and fill with d we get
5089 * cbd... if we scroll block c one line at a time to a, we get cdd...
5090 * vim expects cdd consistently... So we have to deal with that
5091 * here... (this also occurs scrolling the same way in the other
5092 * direction). */
5093
5094 nb = dest.Y + (source.Bottom - source.Top) + 1;
5095
5096 if (nb < source.Top)
5097 {
5098 COORD coord;
5099
5100 coord.X = 0;
5101 coord.Y = nb;
5102 clear_chars(coord, Columns * (source.Top - nb));
5103 }
5104}
5105
5106
5107/*
5108 * Set the cursor position
5109 */
5110 static void
5111gotoxy(
5112 unsigned x,
5113 unsigned y)
5114{
5115 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5116 return;
5117
5118 /* external cursor coords are 1-based; internal are 0-based */
5119 g_coord.X = x - 1;
5120 g_coord.Y = y - 1;
5121 SetConsoleCursorPosition(g_hConOut, g_coord);
5122}
5123
5124
5125/*
5126 * Set the current text attribute = (foreground | background)
5127 * See ../doc/os_win32.txt for the numbers.
5128 */
5129 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005130textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005131{
5132 g_attrCurrent = wAttr;
5133
5134 SetConsoleTextAttribute(g_hConOut, wAttr);
5135}
5136
5137
5138 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005139textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005140{
5141 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
5142
5143 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5144}
5145
5146
5147 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005148textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005149{
5150 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
5151
5152 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5153}
5154
5155
5156/*
5157 * restore the default text attribute (whatever we started with)
5158 */
5159 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005160normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005161{
5162 textattr(g_attrDefault);
5163}
5164
5165
5166static WORD g_attrPreStandout = 0;
5167
5168/*
5169 * Make the text standout, by brightening it
5170 */
5171 static void
5172standout(void)
5173{
5174 g_attrPreStandout = g_attrCurrent;
5175 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5176}
5177
5178
5179/*
5180 * Turn off standout mode
5181 */
5182 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005183standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184{
5185 if (g_attrPreStandout)
5186 {
5187 textattr(g_attrPreStandout);
5188 g_attrPreStandout = 0;
5189 }
5190}
5191
5192
5193/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005194 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195 */
5196 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005197mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198{
5199 char_u *p;
5200 int n;
5201
5202 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5203 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5204 if (T_ME[0] == ESC && T_ME[1] == '|')
5205 {
5206 p = T_ME + 2;
5207 n = getdigits(&p);
5208 if (*p == 'm' && n > 0)
5209 {
5210 cterm_normal_fg_color = (n & 0xf) + 1;
5211 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5212 }
5213 }
5214}
5215
5216
5217/*
5218 * visual bell: flash the screen
5219 */
5220 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005221visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222{
5223 COORD coordOrigin = {0, 0};
5224 WORD attrFlash = ~g_attrCurrent & 0xff;
5225
5226 DWORD dwDummy;
5227 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5228
5229 if (oldattrs == NULL)
5230 return;
5231 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5232 coordOrigin, &dwDummy);
5233 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5234 coordOrigin, &dwDummy);
5235
5236 Sleep(15); /* wait for 15 msec */
5237 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5238 coordOrigin, &dwDummy);
5239 vim_free(oldattrs);
5240}
5241
5242
5243/*
5244 * Make the cursor visible or invisible
5245 */
5246 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005247cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005248{
5249 s_cursor_visible = fVisible;
5250#ifdef MCH_CURSOR_SHAPE
5251 mch_update_cursor();
5252#endif
5253}
5254
5255
5256/*
5257 * write `cchToWrite' characters in `pchBuf' to the screen
5258 * Returns the number of characters actually written (at least one).
5259 */
5260 static BOOL
5261write_chars(
5262 LPCSTR pchBuf,
5263 DWORD cchToWrite)
5264{
5265 COORD coord = g_coord;
5266 DWORD written;
5267
5268 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
5269 coord, &written);
5270 /* When writing fails or didn't write a single character, pretend one
5271 * character was written, otherwise we get stuck. */
5272 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
5273 coord, &written) == 0
5274 || written == 0)
5275 written = 1;
5276
5277 g_coord.X += (SHORT) written;
5278
5279 while (g_coord.X > g_srScrollRegion.Right)
5280 {
5281 g_coord.X -= (SHORT) Columns;
5282 if (g_coord.Y < g_srScrollRegion.Bottom)
5283 g_coord.Y++;
5284 }
5285
5286 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5287
5288 return written;
5289}
5290
5291
5292/*
5293 * mch_write(): write the output buffer to the screen, translating ESC
5294 * sequences into calls to console output routines.
5295 */
5296 void
5297mch_write(
5298 char_u *s,
5299 int len)
5300{
5301 s[len] = NUL;
5302
5303 if (!term_console)
5304 {
5305 write(1, s, (unsigned)len);
5306 return;
5307 }
5308
5309 /* translate ESC | sequences into faked bios calls */
5310 while (len--)
5311 {
5312 /* optimization: use one single write_chars for runs of text,
5313 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005314 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005315
5316 if (p_wd)
5317 {
5318 WaitForChar(p_wd);
5319 if (prefix != 0)
5320 prefix = 1;
5321 }
5322
5323 if (prefix != 0)
5324 {
5325 DWORD nWritten;
5326
5327 nWritten = write_chars(s, prefix);
5328#ifdef MCH_WRITE_DUMP
5329 if (fdDump)
5330 {
5331 fputc('>', fdDump);
5332 fwrite(s, sizeof(char_u), nWritten, fdDump);
5333 fputs("<\n", fdDump);
5334 }
5335#endif
5336 len -= (nWritten - 1);
5337 s += nWritten;
5338 }
5339 else if (s[0] == '\n')
5340 {
5341 /* \n, newline: go to the beginning of the next line or scroll */
5342 if (g_coord.Y == g_srScrollRegion.Bottom)
5343 {
5344 scroll(1);
5345 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5346 }
5347 else
5348 {
5349 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5350 }
5351#ifdef MCH_WRITE_DUMP
5352 if (fdDump)
5353 fputs("\\n\n", fdDump);
5354#endif
5355 s++;
5356 }
5357 else if (s[0] == '\r')
5358 {
5359 /* \r, carriage return: go to beginning of line */
5360 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5361#ifdef MCH_WRITE_DUMP
5362 if (fdDump)
5363 fputs("\\r\n", fdDump);
5364#endif
5365 s++;
5366 }
5367 else if (s[0] == '\b')
5368 {
5369 /* \b, backspace: move cursor one position left */
5370 if (g_coord.X > g_srScrollRegion.Left)
5371 g_coord.X--;
5372 else if (g_coord.Y > g_srScrollRegion.Top)
5373 {
5374 g_coord.X = g_srScrollRegion.Right;
5375 g_coord.Y--;
5376 }
5377 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5378#ifdef MCH_WRITE_DUMP
5379 if (fdDump)
5380 fputs("\\b\n", fdDump);
5381#endif
5382 s++;
5383 }
5384 else if (s[0] == '\a')
5385 {
5386 /* \a, bell */
5387 MessageBeep(0xFFFFFFFF);
5388#ifdef MCH_WRITE_DUMP
5389 if (fdDump)
5390 fputs("\\a\n", fdDump);
5391#endif
5392 s++;
5393 }
5394 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5395 {
5396#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005397 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005398#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005399 char_u *p;
5400 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005401
5402 switch (s[2])
5403 {
5404 /* one or two numeric arguments, separated by ';' */
5405
5406 case '0': case '1': case '2': case '3': case '4':
5407 case '5': case '6': case '7': case '8': case '9':
5408 p = s + 2;
5409 arg1 = getdigits(&p); /* no check for length! */
5410 if (p > s + len)
5411 break;
5412
5413 if (*p == ';')
5414 {
5415 ++p;
5416 arg2 = getdigits(&p); /* no check for length! */
5417 if (p > s + len)
5418 break;
5419
5420 if (*p == 'H')
5421 gotoxy(arg2, arg1);
5422 else if (*p == 'r')
5423 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5424 }
5425 else if (*p == 'A')
5426 {
5427 /* move cursor up arg1 lines in same column */
5428 gotoxy(g_coord.X + 1,
5429 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5430 }
5431 else if (*p == 'C')
5432 {
5433 /* move cursor right arg1 columns in same line */
5434 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5435 g_coord.Y + 1);
5436 }
5437 else if (*p == 'H')
5438 {
5439 gotoxy(1, arg1);
5440 }
5441 else if (*p == 'L')
5442 {
5443 insert_lines(arg1);
5444 }
5445 else if (*p == 'm')
5446 {
5447 if (arg1 == 0)
5448 normvideo();
5449 else
5450 textattr((WORD) arg1);
5451 }
5452 else if (*p == 'f')
5453 {
5454 textcolor((WORD) arg1);
5455 }
5456 else if (*p == 'b')
5457 {
5458 textbackground((WORD) arg1);
5459 }
5460 else if (*p == 'M')
5461 {
5462 delete_lines(arg1);
5463 }
5464
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005465 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005466 s = p + 1;
5467 break;
5468
5469
5470 /* Three-character escape sequences */
5471
5472 case 'A':
5473 /* move cursor up one line in same column */
5474 gotoxy(g_coord.X + 1,
5475 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5476 goto got3;
5477
5478 case 'B':
5479 visual_bell();
5480 goto got3;
5481
5482 case 'C':
5483 /* move cursor right one column in same line */
5484 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5485 g_coord.Y + 1);
5486 goto got3;
5487
5488 case 'E':
5489 termcap_mode_end();
5490 goto got3;
5491
5492 case 'F':
5493 standout();
5494 goto got3;
5495
5496 case 'f':
5497 standend();
5498 goto got3;
5499
5500 case 'H':
5501 gotoxy(1, 1);
5502 goto got3;
5503
5504 case 'j':
5505 clear_to_end_of_display();
5506 goto got3;
5507
5508 case 'J':
5509 clear_screen();
5510 goto got3;
5511
5512 case 'K':
5513 clear_to_end_of_line();
5514 goto got3;
5515
5516 case 'L':
5517 insert_lines(1);
5518 goto got3;
5519
5520 case 'M':
5521 delete_lines(1);
5522 goto got3;
5523
5524 case 'S':
5525 termcap_mode_start();
5526 goto got3;
5527
5528 case 'V':
5529 cursor_visible(TRUE);
5530 goto got3;
5531
5532 case 'v':
5533 cursor_visible(FALSE);
5534 goto got3;
5535
5536 got3:
5537 s += 3;
5538 len -= 2;
5539 }
5540
5541#ifdef MCH_WRITE_DUMP
5542 if (fdDump)
5543 {
5544 fputs("ESC | ", fdDump);
5545 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5546 fputc('\n', fdDump);
5547 }
5548#endif
5549 }
5550 else
5551 {
5552 /* Write a single character */
5553 DWORD nWritten;
5554
5555 nWritten = write_chars(s, 1);
5556#ifdef MCH_WRITE_DUMP
5557 if (fdDump)
5558 {
5559 fputc('>', fdDump);
5560 fwrite(s, sizeof(char_u), nWritten, fdDump);
5561 fputs("<\n", fdDump);
5562 }
5563#endif
5564
5565 len -= (nWritten - 1);
5566 s += nWritten;
5567 }
5568 }
5569
5570#ifdef MCH_WRITE_DUMP
5571 if (fdDump)
5572 fflush(fdDump);
5573#endif
5574}
5575
5576#endif /* FEAT_GUI_W32 */
5577
5578
5579/*
5580 * Delay for half a second.
5581 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005582/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005583 void
5584mch_delay(
5585 long msec,
5586 int ignoreinput)
5587{
5588#ifdef FEAT_GUI_W32
5589 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005590#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005592# ifdef FEAT_MZSCHEME
5593 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5594 {
5595 int towait = p_mzq;
5596
5597 /* if msec is large enough, wait by portions in p_mzq */
5598 while (msec > 0)
5599 {
5600 mzvim_check_threads();
5601 if (msec < towait)
5602 towait = msec;
5603 Sleep(towait);
5604 msec -= towait;
5605 }
5606 }
5607 else
5608# endif
5609 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610 else
5611 WaitForChar(msec);
5612#endif
5613}
5614
5615
5616/*
5617 * this version of remove is not scared by a readonly (backup) file
5618 * Return 0 for success, -1 for failure.
5619 */
5620 int
5621mch_remove(char_u *name)
5622{
5623#ifdef FEAT_MBYTE
5624 WCHAR *wn = NULL;
5625 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005626#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005628 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5629
5630#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5632 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005633 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634 if (wn != NULL)
5635 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636 n = DeleteFileW(wn) ? 0 : -1;
5637 vim_free(wn);
5638 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5639 return n;
5640 /* Retry with non-wide function (for Windows 98). */
5641 }
5642 }
5643#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005644 return DeleteFile(name) ? 0 : -1;
5645}
5646
5647
5648/*
5649 * check for an "interrupt signal": CTRL-break or CTRL-C
5650 */
5651 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005652mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005653{
5654#ifndef FEAT_GUI_W32 /* never used */
5655 if (g_fCtrlCPressed || g_fCBrkPressed)
5656 {
5657 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5658 got_int = TRUE;
5659 }
5660#endif
5661}
5662
5663
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664#ifdef FEAT_MBYTE
5665/*
5666 * Same code as below, but with wide functions and no comments.
5667 * Return 0 for success, non-zero for failure.
5668 */
5669 int
5670mch_wrename(WCHAR *wold, WCHAR *wnew)
5671{
5672 WCHAR *p;
5673 int i;
5674 WCHAR szTempFile[_MAX_PATH + 1];
5675 WCHAR szNewPath[_MAX_PATH + 1];
5676 HANDLE hf;
5677
5678 if (!mch_windows95())
5679 {
5680 p = wold;
5681 for (i = 0; wold[i] != NUL; ++i)
5682 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5683 && wold[i + 1] != 0)
5684 p = wold + i + 1;
5685 if ((int)(wold + i - p) < 8 || p[6] != '~')
5686 return (MoveFileW(wold, wnew) == 0);
5687 }
5688
5689 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5690 return -1;
5691 *p = NUL;
5692
5693 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5694 return -2;
5695
5696 if (!DeleteFileW(szTempFile))
5697 return -3;
5698
5699 if (!MoveFileW(wold, szTempFile))
5700 return -4;
5701
5702 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5703 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5704 return -5;
5705 if (!CloseHandle(hf))
5706 return -6;
5707
5708 if (!MoveFileW(szTempFile, wnew))
5709 {
5710 (void)MoveFileW(szTempFile, wold);
5711 return -7;
5712 }
5713
5714 DeleteFileW(szTempFile);
5715
5716 if (!DeleteFileW(wold))
5717 return -8;
5718
5719 return 0;
5720}
5721#endif
5722
5723
5724/*
5725 * mch_rename() works around a bug in rename (aka MoveFile) in
5726 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5727 * file whose short file name is "FOO.BAR" (its long file name will
5728 * be correct: "foo.bar~"). Because a file can be accessed by
5729 * either its SFN or its LFN, "foo.bar" has effectively been
5730 * renamed to "foo.bar", which is not at all what was wanted. This
5731 * seems to happen only when renaming files with three-character
5732 * extensions by appending a suffix that does not include ".".
5733 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5734 *
5735 * There is another problem, which isn't really a bug but isn't right either:
5736 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5737 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5738 * service pack 6. Doesn't seem to happen on Windows 98.
5739 *
5740 * Like rename(), returns 0 upon success, non-zero upon failure.
5741 * Should probably set errno appropriately when errors occur.
5742 */
5743 int
5744mch_rename(
5745 const char *pszOldFile,
5746 const char *pszNewFile)
5747{
5748 char szTempFile[_MAX_PATH+1];
5749 char szNewPath[_MAX_PATH+1];
5750 char *pszFilePart;
5751 HANDLE hf;
5752#ifdef FEAT_MBYTE
5753 WCHAR *wold = NULL;
5754 WCHAR *wnew = NULL;
5755 int retval = -1;
5756
5757 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5758 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005759 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5760 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761 if (wold != NULL && wnew != NULL)
5762 retval = mch_wrename(wold, wnew);
5763 vim_free(wold);
5764 vim_free(wnew);
5765 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5766 return retval;
5767 /* Retry with non-wide function (for Windows 98). */
5768 }
5769#endif
5770
5771 /*
5772 * No need to play tricks if not running Windows 95, unless the file name
5773 * contains a "~" as the seventh character.
5774 */
5775 if (!mch_windows95())
5776 {
5777 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5778 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5779 return rename(pszOldFile, pszNewFile);
5780 }
5781
5782 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5783 * a directory, no error is returned and pszFilePart will be NULL. */
5784 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5785 || pszFilePart == NULL)
5786 return -1;
5787 *pszFilePart = NUL;
5788
5789 /* Get (and create) a unique temporary file name in directory of new file */
5790 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5791 return -2;
5792
5793 /* blow the temp file away */
5794 if (!DeleteFile(szTempFile))
5795 return -3;
5796
5797 /* rename old file to the temp file */
5798 if (!MoveFile(pszOldFile, szTempFile))
5799 return -4;
5800
5801 /* now create an empty file called pszOldFile; this prevents the operating
5802 * system using pszOldFile as an alias (SFN) if we're renaming within the
5803 * same directory. For example, we're editing a file called
5804 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5805 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5806 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005807 * cause all sorts of problems later in buf_write(). So, we create an
5808 * empty file called filena~1.txt and the system will have to find some
5809 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005810 */
5811 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5812 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5813 return -5;
5814 if (!CloseHandle(hf))
5815 return -6;
5816
5817 /* rename the temp file to the new file */
5818 if (!MoveFile(szTempFile, pszNewFile))
5819 {
5820 /* Renaming failed. Rename the file back to its old name, so that it
5821 * looks like nothing happened. */
5822 (void)MoveFile(szTempFile, pszOldFile);
5823
5824 return -7;
5825 }
5826
5827 /* Seems to be left around on Novell filesystems */
5828 DeleteFile(szTempFile);
5829
5830 /* finally, remove the empty old file */
5831 if (!DeleteFile(pszOldFile))
5832 return -8;
5833
5834 return 0; /* success */
5835}
5836
5837/*
5838 * Get the default shell for the current hardware platform
5839 */
5840 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005841default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842{
5843 char* psz = NULL;
5844
5845 PlatformId();
5846
5847 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5848 psz = "cmd.exe";
5849 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5850 psz = "command.com";
5851
5852 return psz;
5853}
5854
5855/*
5856 * mch_access() extends access() to do more detailed check on network drives.
5857 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5858 */
5859 int
5860mch_access(char *n, int p)
5861{
5862 HANDLE hFile;
5863 DWORD am;
5864 int retval = -1; /* default: fail */
5865#ifdef FEAT_MBYTE
5866 WCHAR *wn = NULL;
5867
5868 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005869 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005870#endif
5871
5872 if (mch_isdir(n))
5873 {
5874 char TempName[_MAX_PATH + 16] = "";
5875#ifdef FEAT_MBYTE
5876 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5877#endif
5878
5879 if (p & R_OK)
5880 {
5881 /* Read check is performed by seeing if we can do a find file on
5882 * the directory for any file. */
5883#ifdef FEAT_MBYTE
5884 if (wn != NULL)
5885 {
5886 int i;
5887 WIN32_FIND_DATAW d;
5888
5889 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5890 TempNameW[i] = wn[i];
5891 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5892 TempNameW[i++] = '\\';
5893 TempNameW[i++] = '*';
5894 TempNameW[i++] = 0;
5895
5896 hFile = FindFirstFileW(TempNameW, &d);
5897 if (hFile == INVALID_HANDLE_VALUE)
5898 {
5899 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5900 goto getout;
5901
5902 /* Retry with non-wide function (for Windows 98). */
5903 vim_free(wn);
5904 wn = NULL;
5905 }
5906 else
5907 (void)FindClose(hFile);
5908 }
5909 if (wn == NULL)
5910#endif
5911 {
5912 char *pch;
5913 WIN32_FIND_DATA d;
5914
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005915 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005916 pch = TempName + STRLEN(TempName) - 1;
5917 if (*pch != '\\' && *pch != '/')
5918 *++pch = '\\';
5919 *++pch = '*';
5920 *++pch = NUL;
5921
5922 hFile = FindFirstFile(TempName, &d);
5923 if (hFile == INVALID_HANDLE_VALUE)
5924 goto getout;
5925 (void)FindClose(hFile);
5926 }
5927 }
5928
5929 if (p & W_OK)
5930 {
5931 /* Trying to create a temporary file in the directory should catch
5932 * directories on read-only network shares. However, in
5933 * directories whose ACL allows writes but denies deletes will end
5934 * up keeping the temporary file :-(. */
5935#ifdef FEAT_MBYTE
5936 if (wn != NULL)
5937 {
5938 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5939 {
5940 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5941 goto getout;
5942
5943 /* Retry with non-wide function (for Windows 98). */
5944 vim_free(wn);
5945 wn = NULL;
5946 }
5947 else
5948 DeleteFileW(TempNameW);
5949 }
5950 if (wn == NULL)
5951#endif
5952 {
5953 if (!GetTempFileName(n, "VIM", 0, TempName))
5954 goto getout;
5955 mch_remove((char_u *)TempName);
5956 }
5957 }
5958 }
5959 else
5960 {
5961 /* Trying to open the file for the required access does ACL, read-only
5962 * network share, and file attribute checks. */
5963 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5964 | ((p & R_OK) ? GENERIC_READ : 0);
5965#ifdef FEAT_MBYTE
5966 if (wn != NULL)
5967 {
5968 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5969 if (hFile == INVALID_HANDLE_VALUE
5970 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5971 {
5972 /* Retry with non-wide function (for Windows 98). */
5973 vim_free(wn);
5974 wn = NULL;
5975 }
5976 }
5977 if (wn == NULL)
5978#endif
5979 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5980 if (hFile == INVALID_HANDLE_VALUE)
5981 goto getout;
5982 CloseHandle(hFile);
5983 }
5984
5985 retval = 0; /* success */
5986getout:
5987#ifdef FEAT_MBYTE
5988 vim_free(wn);
5989#endif
5990 return retval;
5991}
5992
5993#if defined(FEAT_MBYTE) || defined(PROTO)
5994/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005995 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005996 */
5997 int
5998mch_open(char *name, int flags, int mode)
5999{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006000 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6001# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002 WCHAR *wn;
6003 int f;
6004
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006005 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006007 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008 if (wn != NULL)
6009 {
6010 f = _wopen(wn, flags, mode);
6011 vim_free(wn);
6012 if (f >= 0)
6013 return f;
6014 /* Retry with non-wide function (for Windows 98). Can't use
6015 * GetLastError() here and it's unclear what errno gets set to if
6016 * the _wopen() fails for missing wide functions. */
6017 }
6018 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006019# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020
6021 return open(name, flags, mode);
6022}
6023
6024/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006025 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026 */
6027 FILE *
6028mch_fopen(char *name, char *mode)
6029{
6030 WCHAR *wn, *wm;
6031 FILE *f = NULL;
6032
6033 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6034# ifdef __BORLANDC__
6035 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6036 && g_PlatformId == VER_PLATFORM_WIN32_NT
6037# endif
6038 )
6039 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006040# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006041 /* Work around an annoying assertion in the Microsoft debug CRT
6042 * when mode's text/binary setting doesn't match _get_fmode(). */
6043 char newMode = mode[strlen(mode) - 1];
6044 int oldMode = 0;
6045
6046 _get_fmode(&oldMode);
6047 if (newMode == 't')
6048 _set_fmode(_O_TEXT);
6049 else if (newMode == 'b')
6050 _set_fmode(_O_BINARY);
6051# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006052 wn = enc_to_utf16(name, NULL);
6053 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054 if (wn != NULL && wm != NULL)
6055 f = _wfopen(wn, wm);
6056 vim_free(wn);
6057 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006058
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006059# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006060 _set_fmode(oldMode);
6061# endif
6062
Bram Moolenaar071d4272004-06-13 20:20:40 +00006063 if (f != NULL)
6064 return f;
6065 /* Retry with non-wide function (for Windows 98). Can't use
6066 * GetLastError() here and it's unclear what errno gets set to if
6067 * the _wfopen() fails for missing wide functions. */
6068 }
6069
6070 return fopen(name, mode);
6071}
6072#endif
6073
6074#ifdef FEAT_MBYTE
6075/*
6076 * SUB STREAM (aka info stream) handling:
6077 *
6078 * NTFS can have sub streams for each file. Normal contents of file is
6079 * stored in the main stream, and extra contents (author information and
6080 * title and so on) can be stored in sub stream. After Windows 2000, user
6081 * can access and store those informations in sub streams via explorer's
6082 * property menuitem in right click menu. Those informations in sub streams
6083 * were lost when copying only the main stream. So we have to copy sub
6084 * streams.
6085 *
6086 * Incomplete explanation:
6087 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6088 * More useful info and an example:
6089 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6090 */
6091
6092/*
6093 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6094 * and write to stream "substream" of file "to".
6095 * Errors are ignored.
6096 */
6097 static void
6098copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6099{
6100 HANDLE hTo;
6101 WCHAR *to_name;
6102
6103 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6104 wcscpy(to_name, to);
6105 wcscat(to_name, substream);
6106
6107 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6108 FILE_ATTRIBUTE_NORMAL, NULL);
6109 if (hTo != INVALID_HANDLE_VALUE)
6110 {
6111 long done;
6112 DWORD todo;
6113 DWORD readcnt, written;
6114 char buf[4096];
6115
6116 /* Copy block of bytes at a time. Abort when something goes wrong. */
6117 for (done = 0; done < len; done += written)
6118 {
6119 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006120 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6121 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6123 FALSE, FALSE, context)
6124 || readcnt != todo
6125 || !WriteFile(hTo, buf, todo, &written, NULL)
6126 || written != todo)
6127 break;
6128 }
6129 CloseHandle(hTo);
6130 }
6131
6132 free(to_name);
6133}
6134
6135/*
6136 * Copy info streams from file "from" to file "to".
6137 */
6138 static void
6139copy_infostreams(char_u *from, char_u *to)
6140{
6141 WCHAR *fromw;
6142 WCHAR *tow;
6143 HANDLE sh;
6144 WIN32_STREAM_ID sid;
6145 int headersize;
6146 WCHAR streamname[_MAX_PATH];
6147 DWORD readcount;
6148 void *context = NULL;
6149 DWORD lo, hi;
6150 int len;
6151
6152 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006153 fromw = enc_to_utf16(from, NULL);
6154 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155 if (fromw != NULL && tow != NULL)
6156 {
6157 /* Open the file for reading. */
6158 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6159 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6160 if (sh != INVALID_HANDLE_VALUE)
6161 {
6162 /* Use BackupRead() to find the info streams. Repeat until we
6163 * have done them all.*/
6164 for (;;)
6165 {
6166 /* Get the header to find the length of the stream name. If
6167 * the "readcount" is zero we have done all info streams. */
6168 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006169 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6171 &readcount, FALSE, FALSE, &context)
6172 || readcount == 0)
6173 break;
6174
6175 /* We only deal with streams that have a name. The normal
6176 * file data appears to be without a name, even though docs
6177 * suggest it is called "::$DATA". */
6178 if (sid.dwStreamNameSize > 0)
6179 {
6180 /* Read the stream name. */
6181 if (!BackupRead(sh, (LPBYTE)streamname,
6182 sid.dwStreamNameSize,
6183 &readcount, FALSE, FALSE, &context))
6184 break;
6185
6186 /* Copy an info stream with a name ":anything:$DATA".
6187 * Skip "::$DATA", it has no stream name (examples suggest
6188 * it might be used for the normal file contents).
6189 * Note that BackupRead() counts bytes, but the name is in
6190 * wide characters. */
6191 len = readcount / sizeof(WCHAR);
6192 streamname[len] = 0;
6193 if (len > 7 && wcsicmp(streamname + len - 6,
6194 L":$DATA") == 0)
6195 {
6196 streamname[len - 6] = 0;
6197 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006198 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006199 }
6200 }
6201
6202 /* Advance to the next stream. We might try seeking too far,
6203 * but BackupSeek() doesn't skip over stream borders, thus
6204 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006205 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 &lo, &hi, &context);
6207 }
6208
6209 /* Clear the context. */
6210 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6211
6212 CloseHandle(sh);
6213 }
6214 }
6215 vim_free(fromw);
6216 vim_free(tow);
6217}
6218#endif
6219
6220/*
6221 * Copy file attributes from file "from" to file "to".
6222 * For Windows NT and later we copy info streams.
6223 * Always returns zero, errors are ignored.
6224 */
6225 int
6226mch_copy_file_attribute(char_u *from, char_u *to)
6227{
6228#ifdef FEAT_MBYTE
6229 /* File streams only work on Windows NT and later. */
6230 PlatformId();
6231 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6232 copy_infostreams(from, to);
6233#endif
6234 return 0;
6235}
6236
6237#if defined(MYRESETSTKOFLW) || defined(PROTO)
6238/*
6239 * Recreate a destroyed stack guard page in win32.
6240 * Written by Benjamin Peterson.
6241 */
6242
6243/* These magic numbers are from the MS header files */
6244#define MIN_STACK_WIN9X 17
6245#define MIN_STACK_WINNT 2
6246
6247/*
6248 * This function does the same thing as _resetstkoflw(), which is only
6249 * available in DevStudio .net and later.
6250 * Returns 0 for failure, 1 for success.
6251 */
6252 int
6253myresetstkoflw(void)
6254{
6255 BYTE *pStackPtr;
6256 BYTE *pGuardPage;
6257 BYTE *pStackBase;
6258 BYTE *pLowestPossiblePage;
6259 MEMORY_BASIC_INFORMATION mbi;
6260 SYSTEM_INFO si;
6261 DWORD nPageSize;
6262 DWORD dummy;
6263
6264 /* This code will not work on win32s. */
6265 PlatformId();
6266 if (g_PlatformId == VER_PLATFORM_WIN32s)
6267 return 0;
6268
6269 /* We need to know the system page size. */
6270 GetSystemInfo(&si);
6271 nPageSize = si.dwPageSize;
6272
6273 /* ...and the current stack pointer */
6274 pStackPtr = (BYTE*)_alloca(1);
6275
6276 /* ...and the base of the stack. */
6277 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6278 return 0;
6279 pStackBase = (BYTE*)mbi.AllocationBase;
6280
6281 /* ...and the page thats min_stack_req pages away from stack base; this is
6282 * the lowest page we could use. */
6283 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6284 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6285
6286 /* On Win95, we want the next page down from the end of the stack. */
6287 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6288 {
6289 /* Find the page that's only 1 page down from the page that the stack
6290 * ptr is in. */
6291 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6292 / (DWORD)nPageSize) - 1));
6293 if (pGuardPage < pLowestPossiblePage)
6294 return 0;
6295
6296 /* Apply the noaccess attribute to the page -- there's no guard
6297 * attribute in win95-type OSes. */
6298 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6299 return 0;
6300 }
6301 else
6302 {
6303 /* On NT, however, we want the first committed page in the stack Start
6304 * at the stack base and move forward through memory until we find a
6305 * committed block. */
6306 BYTE *pBlock = pStackBase;
6307
Bram Moolenaara466c992005-07-09 21:03:22 +00006308 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 {
6310 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6311 return 0;
6312
6313 pBlock += mbi.RegionSize;
6314
6315 if (mbi.State & MEM_COMMIT)
6316 break;
6317 }
6318
6319 /* mbi now describes the first committed block in the stack. */
6320 if (mbi.Protect & PAGE_GUARD)
6321 return 1;
6322
6323 /* decide where the guard page should start */
6324 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6325 pGuardPage = pLowestPossiblePage;
6326 else
6327 pGuardPage = (BYTE*)mbi.BaseAddress;
6328
6329 /* allocate the guard page */
6330 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6331 return 0;
6332
6333 /* apply the guard attribute to the page */
6334 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6335 &dummy))
6336 return 0;
6337 }
6338
6339 return 1;
6340}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006341#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006343
6344#if defined(FEAT_MBYTE) || defined(PROTO)
6345/*
6346 * The command line arguments in UCS2
6347 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006348static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006349static LPWSTR *ArglistW = NULL;
6350static int global_argc = 0;
6351static char **global_argv;
6352
6353static int used_file_argc = 0; /* last argument in global_argv[] used
6354 for the argument list. */
6355static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6356 command line arguments added to
6357 the argument list */
6358static int used_file_count = 0; /* nr of entries in used_file_indexes */
6359static int used_file_literal = FALSE; /* take file names literally */
6360static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006361static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006362static int used_alist_count = 0;
6363
6364
6365/*
6366 * Get the command line arguments. Unicode version.
6367 * Returns argc. Zero when something fails.
6368 */
6369 int
6370get_cmd_argsW(char ***argvp)
6371{
6372 char **argv = NULL;
6373 int argc = 0;
6374 int i;
6375
6376 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6377 if (ArglistW != NULL)
6378 {
6379 argv = malloc((nArgsW + 1) * sizeof(char *));
6380 if (argv != NULL)
6381 {
6382 argc = nArgsW;
6383 argv[argc] = NULL;
6384 for (i = 0; i < argc; ++i)
6385 {
6386 int len;
6387
6388 /* Convert each Unicode argument to the current codepage. */
6389 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006390 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006391 (LPSTR *)&argv[i], &len, 0, 0);
6392 if (argv[i] == NULL)
6393 {
6394 /* Out of memory, clear everything. */
6395 while (i > 0)
6396 free(argv[--i]);
6397 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006398 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006399 argc = 0;
6400 }
6401 }
6402 }
6403 }
6404
6405 global_argc = argc;
6406 global_argv = argv;
6407 if (argc > 0)
6408 used_file_indexes = malloc(argc * sizeof(int));
6409
6410 if (argvp != NULL)
6411 *argvp = argv;
6412 return argc;
6413}
6414
6415 void
6416free_cmd_argsW(void)
6417{
6418 if (ArglistW != NULL)
6419 {
6420 GlobalFree(ArglistW);
6421 ArglistW = NULL;
6422 }
6423}
6424
6425/*
6426 * Remember "name" is an argument that was added to the argument list.
6427 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6428 * is called.
6429 */
6430 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006431used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006432{
6433 int i;
6434
6435 if (used_file_indexes == NULL)
6436 return;
6437 for (i = used_file_argc + 1; i < global_argc; ++i)
6438 if (STRCMP(global_argv[i], name) == 0)
6439 {
6440 used_file_argc = i;
6441 used_file_indexes[used_file_count++] = i;
6442 break;
6443 }
6444 used_file_literal = literal;
6445 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006446 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006447}
6448
6449/*
6450 * Remember the length of the argument list as it was. If it changes then we
6451 * leave it alone when 'encoding' is set.
6452 */
6453 void
6454set_alist_count(void)
6455{
6456 used_alist_count = GARGCOUNT;
6457}
6458
6459/*
6460 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6461 * has been changed while starting up. Use the UCS-2 command line arguments
6462 * and convert them to 'encoding'.
6463 */
6464 void
6465fix_arg_enc(void)
6466{
6467 int i;
6468 int idx;
6469 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006470 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006471
6472 /* Safety checks:
6473 * - if argument count differs between the wide and non-wide argument
6474 * list, something must be wrong.
6475 * - the file name arguments must have been located.
6476 * - the length of the argument list wasn't changed by the user.
6477 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006478 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006479 || ArglistW == NULL
6480 || used_file_indexes == NULL
6481 || used_file_count == 0
6482 || used_alist_count != GARGCOUNT)
6483 return;
6484
Bram Moolenaar86b68352004-12-27 21:59:20 +00006485 /* Remember the buffer numbers for the arguments. */
6486 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6487 if (fnum_list == NULL)
6488 return; /* out of memory */
6489 for (i = 0; i < GARGCOUNT; ++i)
6490 fnum_list[i] = GARGLIST[i].ae_fnum;
6491
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006492 /* Clear the argument list. Make room for the new arguments. */
6493 alist_clear(&global_alist);
6494 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006495 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006496
6497 for (i = 0; i < used_file_count; ++i)
6498 {
6499 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006500 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006501 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006502 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006503#ifdef FEAT_DIFF
6504 /* When using diff mode may need to concatenate file name to
6505 * directory name. Just like it's done in main(). */
6506 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6507 && !mch_isdir(alist_name(&GARGLIST[0])))
6508 {
6509 char_u *r;
6510
6511 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6512 if (r != NULL)
6513 {
6514 vim_free(str);
6515 str = r;
6516 }
6517 }
6518#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006519 /* Re-use the old buffer by renaming it. When not using literal
6520 * names it's done by alist_expand() below. */
6521 if (used_file_literal)
6522 buf_set_name(fnum_list[i], str);
6523
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006524 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006525 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006526 }
6527
6528 if (!used_file_literal)
6529 {
6530 /* Now expand wildcards in the arguments. */
6531 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6532 * filename characters but are excluded from 'isfname' to make
6533 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6534 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006535 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006536 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6537 }
6538
6539 /* If wildcard expansion failed, we are editing the first file of the
6540 * arglist and there is no file name: Edit the first argument now. */
6541 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6542 {
6543 do_cmdline_cmd((char_u *)":rewind");
6544 if (GARGCOUNT == 1 && used_file_full_path)
6545 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6546 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006547
6548 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006549}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006550#endif