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