blob: ef0b6cc0bc7e2eb1ac66d6716a6960efc85e3826 [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 Moolenaar071d4272004-06-13 20:20:40 +0000135#endif
136
137#ifndef FEAT_GUI_W32
138/* Undocumented API in kernel32.dll needed to work around dead key bug in
139 * console-mode applications in NT 4.0. If you switch keyboard layouts
140 * in a console app to a layout that includes dead keys and then hit a
141 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
142 * and Michael Dietrich for helping me figure out this workaround.
143 */
144
145/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
146#ifndef WINBASEAPI
147# define WINBASEAPI __stdcall
148#endif
149#if defined(__BORLANDC__)
150typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
151#else
152typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
153#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000154static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000155#endif
156
157#if defined(__BORLANDC__)
158/* Strangely Borland uses a non-standard name. */
159# define wcsicmp(a, b) wcscmpi((a), (b))
160#endif
161
Bram Moolenaar82881492012-11-20 16:53:39 +0100162#ifndef PROTO
163
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200164/* Enable common dialogs input unicode from IME if posible. */
165#ifdef FEAT_MBYTE
166LRESULT (WINAPI *pDispatchMessage)(LPMSG) = DispatchMessage;
167BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
168BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
169BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
170#endif
171
Bram Moolenaar82881492012-11-20 16:53:39 +0100172#endif /* PROTO */
173
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174#ifndef FEAT_GUI_W32
175/* Win32 Console handles for input and output */
176static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
177static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
178
179/* Win32 Screen buffer,coordinate,console I/O information */
180static SMALL_RECT g_srScrollRegion;
181static COORD g_coord; /* 0-based, but external coords are 1-based */
182
183/* The attribute of the screen when the editor was started */
184static WORD g_attrDefault = 7; /* lightgray text on black background */
185static WORD g_attrCurrent;
186
187static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
188static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
189static int g_fForceExit = FALSE; /* set when forcefully exiting */
190
191static void termcap_mode_start(void);
192static void termcap_mode_end(void);
193static void clear_chars(COORD coord, DWORD n);
194static void clear_screen(void);
195static void clear_to_end_of_display(void);
196static void clear_to_end_of_line(void);
197static void scroll(unsigned cLines);
198static void set_scroll_region(unsigned left, unsigned top,
199 unsigned right, unsigned bottom);
200static void insert_lines(unsigned cLines);
201static void delete_lines(unsigned cLines);
202static void gotoxy(unsigned x, unsigned y);
203static void normvideo(void);
204static void textattr(WORD wAttr);
205static void textcolor(WORD wAttr);
206static void textbackground(WORD wAttr);
207static void standout(void);
208static void standend(void);
209static void visual_bell(void);
210static void cursor_visible(BOOL fVisible);
211static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
212static char_u tgetch(int *pmodifiers, char_u *pch2);
213static void create_conin(void);
214static int s_cursor_visible = TRUE;
215static int did_create_conin = FALSE;
216#else
217static int s_dont_use_vimrun = TRUE;
218static int need_vimrun_warning = FALSE;
219static char *vimrun_path = "vimrun ";
220#endif
221
222#ifndef FEAT_GUI_W32
223static int suppress_winsize = 1; /* don't fiddle with console */
224#endif
225
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200226static char_u *exe_path = NULL;
227
Bram Moolenaar071d4272004-06-13 20:20:40 +0000228 static void
229get_exe_name(void)
230{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100231 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
232 * as the maximum length that works (plus a NUL byte). */
233#define MAX_ENV_PATH_LEN 8192
234 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236
237 if (exe_name == NULL)
238 {
239 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100240 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000241 if (*temp != NUL)
242 exe_name = FullName_save((char_u *)temp, FALSE);
243 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000244
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200245 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000246 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200247 exe_path = vim_strnsave(exe_name,
248 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200249 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000250 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200251 /* Append our starting directory to $PATH, so that when doing
252 * "!xxd" it's found in our starting directory. Needed because
253 * SearchPath() also looks there. */
254 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100255 if (p == NULL
256 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200257 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100258 if (p == NULL || *p == NUL)
259 temp[0] = NUL;
260 else
261 {
262 STRCPY(temp, p);
263 STRCAT(temp, ";");
264 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200265 STRCAT(temp, exe_path);
266 vim_setenv((char_u *)"PATH", temp);
267 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000268 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000269 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000270}
271
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200272/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100273 * Unescape characters in "p" that appear in "escaped".
274 */
275 static void
276unescape_shellxquote(char_u *p, char_u *escaped)
277{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100278 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100279 int n;
280
281 while (*p != NUL)
282 {
283 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
284 mch_memmove(p, p + 1, l--);
285#ifdef FEAT_MBYTE
286 n = (*mb_ptr2len)(p);
287#else
288 n = 1;
289#endif
290 p += n;
291 l -= n;
292 }
293}
294
295/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200296 * Load library "name".
297 */
298 HINSTANCE
299vimLoadLib(char *name)
300{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200301 HINSTANCE dll = NULL;
302 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200303
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200304 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
305 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200306 if (exe_path == NULL)
307 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200308 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200309 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200310#ifdef FEAT_MBYTE
311 WCHAR old_dirw[MAXPATHL];
312
313 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
314 {
315 /* Change directory to where the executable is, both to make
316 * sure we find a .dll there and to avoid looking for a .dll
317 * in the current directory. */
318 SetCurrentDirectory(exe_path);
319 dll = LoadLibrary(name);
320 SetCurrentDirectoryW(old_dirw);
321 return dll;
322 }
323 /* Retry with non-wide function (for Windows 98). */
324 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
325#endif
326 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
327 {
328 /* Change directory to where the executable is, both to make
329 * sure we find a .dll there and to avoid looking for a .dll
330 * in the current directory. */
331 SetCurrentDirectory(exe_path);
332 dll = LoadLibrary(name);
333 SetCurrentDirectory(old_dir);
334 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200335 }
336 return dll;
337}
338
Bram Moolenaar071d4272004-06-13 20:20:40 +0000339#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
340# ifndef GETTEXT_DLL
341# define GETTEXT_DLL "libintl.dll"
342# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200343/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000344static char *null_libintl_gettext(const char *);
345static char *null_libintl_textdomain(const char *);
346static char *null_libintl_bindtextdomain(const char *, const char *);
347static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000348
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200349static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000350char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
351char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
352char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000353 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000354char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
355 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000356
357 int
358dyn_libintl_init(char *libname)
359{
360 int i;
361 static struct
362 {
363 char *name;
364 FARPROC *ptr;
365 } libintl_entry[] =
366 {
367 {"gettext", (FARPROC*)&dyn_libintl_gettext},
368 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
369 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
370 {NULL, NULL}
371 };
372
373 /* No need to initialize twice. */
374 if (hLibintlDLL)
375 return 1;
376 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200377 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000378 if (!hLibintlDLL)
379 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200380 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000381 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200382 verbose_enter();
383 EMSG2(_(e_loadlib), GETTEXT_DLL);
384 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000385 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200386 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000387 }
388 for (i = 0; libintl_entry[i].name != NULL
389 && libintl_entry[i].ptr != NULL; ++i)
390 {
391 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
392 libintl_entry[i].name)) == NULL)
393 {
394 dyn_libintl_end();
395 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000396 {
397 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000399 verbose_leave();
400 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401 return 0;
402 }
403 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000404
405 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000406 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000407 "bind_textdomain_codeset");
408 if (dyn_libintl_bind_textdomain_codeset == NULL)
409 dyn_libintl_bind_textdomain_codeset =
410 null_libintl_bind_textdomain_codeset;
411
Bram Moolenaar071d4272004-06-13 20:20:40 +0000412 return 1;
413}
414
415 void
416dyn_libintl_end()
417{
418 if (hLibintlDLL)
419 FreeLibrary(hLibintlDLL);
420 hLibintlDLL = NULL;
421 dyn_libintl_gettext = null_libintl_gettext;
422 dyn_libintl_textdomain = null_libintl_textdomain;
423 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000424 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425}
426
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000427/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000429null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430{
431 return (char*)msgid;
432}
433
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000434/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000436null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437{
438 return NULL;
439}
440
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000441/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000443null_libintl_bind_textdomain_codeset(const char *domainname,
444 const char *codeset)
445{
446 return NULL;
447}
448
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000449/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000450 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000451null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452{
453 return NULL;
454}
455
456#endif /* DYNAMIC_GETTEXT */
457
458/* This symbol is not defined in older versions of the SDK or Visual C++ */
459
460#ifndef VER_PLATFORM_WIN32_WINDOWS
461# define VER_PLATFORM_WIN32_WINDOWS 1
462#endif
463
464DWORD g_PlatformId;
465
466#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100467# ifndef PROTO
468# include <aclapi.h>
469# endif
470
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471/*
472 * These are needed to dynamically load the ADVAPI DLL, which is not
473 * implemented under Windows 95 (and causes VIM to crash)
474 */
475typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
476 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
477typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
478 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
479 PSECURITY_DESCRIPTOR *);
480
481static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
482static PSNSECINFO pSetNamedSecurityInfo;
483static PGNSECINFO pGetNamedSecurityInfo;
484#endif
485
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200486typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
487
488static BOOL allowPiping = FALSE;
489static PSETHANDLEINFORMATION pSetHandleInformation;
490
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491/*
492 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
493 * VER_PLATFORM_WIN32_WINDOWS (Win95).
494 */
495 void
496PlatformId(void)
497{
498 static int done = FALSE;
499
500 if (!done)
501 {
502 OSVERSIONINFO ovi;
503
504 ovi.dwOSVersionInfoSize = sizeof(ovi);
505 GetVersionEx(&ovi);
506
507 g_PlatformId = ovi.dwPlatformId;
508
509#ifdef HAVE_ACL
510 /*
511 * Load the ADVAPI runtime if we are on anything
512 * other than Windows 95
513 */
514 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
515 {
516 /*
517 * do this load. Problems: Doesn't unload at end of run (this is
518 * theoretically okay, since Windows should unload it when VIM
519 * terminates). Should we be using the 'mch_libcall' routines?
520 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
521 * time we verify security...
522 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200523 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524 if (advapi_lib != NULL)
525 {
526 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
527 "SetNamedSecurityInfoA");
528 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
529 "GetNamedSecurityInfoA");
530 if (pSetNamedSecurityInfo == NULL
531 || pGetNamedSecurityInfo == NULL)
532 {
533 /* If we can't get the function addresses, set advapi_lib
534 * to NULL so that we don't use them. */
535 FreeLibrary(advapi_lib);
536 advapi_lib = NULL;
537 }
538 }
539 }
540#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200541 /*
542 * If we are on windows NT, try to load the pipe functions, only
543 * available from Win2K.
544 */
545 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
546 {
547 HANDLE kernel32 = GetModuleHandle("kernel32");
548 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
549 kernel32, "SetHandleInformation");
550
551 allowPiping = pSetHandleInformation != NULL;
552 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000553 done = TRUE;
554 }
555}
556
557/*
558 * Return TRUE when running on Windows 95 (or 98 or ME).
559 * Only to be used after mch_init().
560 */
561 int
562mch_windows95(void)
563{
564 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
565}
566
567#ifdef FEAT_GUI_W32
568/*
569 * Used to work around the "can't do synchronous spawn"
570 * problem on Win32s, without resorting to Universal Thunk.
571 */
572static int old_num_windows;
573static int num_windows;
574
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000575/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 static BOOL CALLBACK
577win32ssynch_cb(HWND hwnd, LPARAM lparam)
578{
579 num_windows++;
580 return TRUE;
581}
582#endif
583
584#ifndef FEAT_GUI_W32
585
586#define SHIFT (SHIFT_PRESSED)
587#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
588#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
589#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
590
591
592/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
593 * We map function keys to their ANSI terminal equivalents, as produced
594 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
595 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
596 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
597 * combinations of function/arrow/etc keys.
598 */
599
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000600static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601{
602 WORD wVirtKey;
603 BOOL fAnsiKey;
604 int chAlone;
605 int chShift;
606 int chCtrl;
607 int chAlt;
608} VirtKeyMap[] =
609{
610
611/* Key ANSI alone shift ctrl alt */
612 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
613
614 { VK_F1, TRUE, ';', 'T', '^', 'h', },
615 { VK_F2, TRUE, '<', 'U', '_', 'i', },
616 { VK_F3, TRUE, '=', 'V', '`', 'j', },
617 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
618 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
619 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
620 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
621 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
622 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
623 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
624 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
625 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
626
627 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
628 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
629 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
630 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
631 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
632 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
633 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
634 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
635 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
636 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
637
638 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
639
640#if 0
641 /* Most people don't have F13-F20, but what the hell... */
642 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
643 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
644 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
645 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
646 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
647 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
648 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
649 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
650#endif
651 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
652 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
653 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
654 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
655
656 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
657 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
658 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
659 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
660 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
661 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
662 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
663 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
664 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
665 /* Sorry, out of number space! <negri>*/
666 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
667
668};
669
670
671#ifdef _MSC_VER
672// The ToAscii bug destroys several registers. Need to turn off optimization
673// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000674# pragma warning(push)
675# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676# pragma optimize("", off)
677#endif
678
679#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
680# define AChar AsciiChar
681#else
682# define AChar uChar.AsciiChar
683#endif
684
685/* The return code indicates key code size. */
686 static int
687#ifdef __BORLANDC__
688 __stdcall
689#endif
690win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000691 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692{
693 UINT uMods = pker->dwControlKeyState;
694 static int s_iIsDead = 0;
695 static WORD awAnsiCode[2];
696 static BYTE abKeystate[256];
697
698
699 if (s_iIsDead == 2)
700 {
701 pker->AChar = (CHAR) awAnsiCode[1];
702 s_iIsDead = 0;
703 return 1;
704 }
705
706 if (pker->AChar != 0)
707 return 1;
708
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200709 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710
711 // Should only be non-NULL on NT 4.0
712 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
713 {
714 CHAR szKLID[KL_NAMELENGTH];
715
716 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
717 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
718 }
719
720 /* Clear any pending dead keys */
721 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
722
723 if (uMods & SHIFT_PRESSED)
724 abKeystate[VK_SHIFT] = 0x80;
725 if (uMods & CAPSLOCK_ON)
726 abKeystate[VK_CAPITAL] = 1;
727
728 if ((uMods & ALT_GR) == ALT_GR)
729 {
730 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
731 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
732 }
733
734 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
735 abKeystate, awAnsiCode, 0);
736
737 if (s_iIsDead > 0)
738 pker->AChar = (CHAR) awAnsiCode[0];
739
740 return s_iIsDead;
741}
742
743#ifdef _MSC_VER
744/* MUST switch optimization on again here, otherwise a call to
745 * decode_key_event() may crash (e.g. when hitting caps-lock) */
746# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000747# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748
749# if (_MSC_VER < 1100)
750/* MUST turn off global optimisation for this next function, or
751 * pressing ctrl-minus in insert mode crashes Vim when built with
752 * VC4.1. -- negri. */
753# pragma optimize("g", off)
754# endif
755#endif
756
757static BOOL g_fJustGotFocus = FALSE;
758
759/*
760 * Decode a KEY_EVENT into one or two keystrokes
761 */
762 static BOOL
763decode_key_event(
764 KEY_EVENT_RECORD *pker,
765 char_u *pch,
766 char_u *pch2,
767 int *pmodifiers,
768 BOOL fDoPost)
769{
770 int i;
771 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
772
773 *pch = *pch2 = NUL;
774 g_fJustGotFocus = FALSE;
775
776 /* ignore key up events */
777 if (!pker->bKeyDown)
778 return FALSE;
779
780 /* ignore some keystrokes */
781 switch (pker->wVirtualKeyCode)
782 {
783 /* modifiers */
784 case VK_SHIFT:
785 case VK_CONTROL:
786 case VK_MENU: /* Alt key */
787 return FALSE;
788
789 default:
790 break;
791 }
792
793 /* special cases */
794 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
795 {
796 /* Ctrl-6 is Ctrl-^ */
797 if (pker->wVirtualKeyCode == '6')
798 {
799 *pch = Ctrl_HAT;
800 return TRUE;
801 }
802 /* Ctrl-2 is Ctrl-@ */
803 else if (pker->wVirtualKeyCode == '2')
804 {
805 *pch = NUL;
806 return TRUE;
807 }
808 /* Ctrl-- is Ctrl-_ */
809 else if (pker->wVirtualKeyCode == 0xBD)
810 {
811 *pch = Ctrl__;
812 return TRUE;
813 }
814 }
815
816 /* Shift-TAB */
817 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
818 {
819 *pch = K_NUL;
820 *pch2 = '\017';
821 return TRUE;
822 }
823
824 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
825 {
826 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
827 {
828 if (nModifs == 0)
829 *pch = VirtKeyMap[i].chAlone;
830 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
831 *pch = VirtKeyMap[i].chShift;
832 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
833 *pch = VirtKeyMap[i].chCtrl;
834 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
835 *pch = VirtKeyMap[i].chAlt;
836
837 if (*pch != 0)
838 {
839 if (VirtKeyMap[i].fAnsiKey)
840 {
841 *pch2 = *pch;
842 *pch = K_NUL;
843 }
844
845 return TRUE;
846 }
847 }
848 }
849
850 i = win32_kbd_patch_key(pker);
851
852 if (i < 0)
853 *pch = NUL;
854 else
855 {
856 *pch = (i > 0) ? pker->AChar : NUL;
857
858 if (pmodifiers != NULL)
859 {
860 /* Pass on the ALT key as a modifier, but only when not combined
861 * with CTRL (which is ALTGR). */
862 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
863 *pmodifiers |= MOD_MASK_ALT;
864
865 /* Pass on SHIFT only for special keys, because we don't know when
866 * it's already included with the character. */
867 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
868 *pmodifiers |= MOD_MASK_SHIFT;
869
870 /* Pass on CTRL only for non-special keys, because we don't know
871 * when it's already included with the character. And not when
872 * combined with ALT (which is ALTGR). */
873 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
874 && *pch >= 0x20 && *pch < 0x80)
875 *pmodifiers |= MOD_MASK_CTRL;
876 }
877 }
878
879 return (*pch != NUL);
880}
881
882#ifdef _MSC_VER
883# pragma optimize("", on)
884#endif
885
886#endif /* FEAT_GUI_W32 */
887
888
889#ifdef FEAT_MOUSE
890
891/*
892 * For the GUI the mouse handling is in gui_w32.c.
893 */
894# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000895/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000897mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898{
899}
900# else
901static int g_fMouseAvail = FALSE; /* mouse present */
902static int g_fMouseActive = FALSE; /* mouse enabled */
903static int g_nMouseClick = -1; /* mouse status */
904static int g_xMouse; /* mouse x coordinate */
905static int g_yMouse; /* mouse y coordinate */
906
907/*
908 * Enable or disable mouse input
909 */
910 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000911mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912{
913 DWORD cmodein;
914
915 if (!g_fMouseAvail)
916 return;
917
918 g_fMouseActive = on;
919 GetConsoleMode(g_hConIn, &cmodein);
920
921 if (g_fMouseActive)
922 cmodein |= ENABLE_MOUSE_INPUT;
923 else
924 cmodein &= ~ENABLE_MOUSE_INPUT;
925
926 SetConsoleMode(g_hConIn, cmodein);
927}
928
929
930/*
931 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
932 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
933 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
934 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
935 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
936 * and we return the mouse position in g_xMouse and g_yMouse.
937 *
938 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
939 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
940 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
941 *
942 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
943 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
944 *
945 * Windows will send us MOUSE_MOVED notifications whenever the mouse
946 * moves, even if it stays within the same character cell. We ignore
947 * all MOUSE_MOVED messages if the position hasn't really changed, and
948 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
949 * we're only interested in MOUSE_DRAG).
950 *
951 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
952 * 2-button mouses by pressing the left & right buttons simultaneously.
953 * In practice, it's almost impossible to click both at the same time,
954 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
955 * in such cases, if the user is clicking quickly.
956 */
957 static BOOL
958decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000959 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960{
961 static int s_nOldButton = -1;
962 static int s_nOldMouseClick = -1;
963 static int s_xOldMouse = -1;
964 static int s_yOldMouse = -1;
965 static linenr_T s_old_topline = 0;
966#ifdef FEAT_DIFF
967 static int s_old_topfill = 0;
968#endif
969 static int s_cClicks = 1;
970 static BOOL s_fReleased = TRUE;
971 static DWORD s_dwLastClickTime = 0;
972 static BOOL s_fNextIsMiddle = FALSE;
973
974 static DWORD cButtons = 0; /* number of buttons supported */
975
976 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
977 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
978 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
979 const DWORD LEFT_RIGHT = LEFT | RIGHT;
980
981 int nButton;
982
983 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
984 cButtons = 2;
985
986 if (!g_fMouseAvail || !g_fMouseActive)
987 {
988 g_nMouseClick = -1;
989 return FALSE;
990 }
991
992 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
993 if (g_fJustGotFocus)
994 {
995 g_fJustGotFocus = FALSE;
996 return FALSE;
997 }
998
999 /* unprocessed mouse click? */
1000 if (g_nMouseClick != -1)
1001 return TRUE;
1002
1003 nButton = -1;
1004 g_xMouse = pmer->dwMousePosition.X;
1005 g_yMouse = pmer->dwMousePosition.Y;
1006
1007 if (pmer->dwEventFlags == MOUSE_MOVED)
1008 {
1009 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1010 * events even when the mouse moves only within a char cell.) */
1011 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1012 return FALSE;
1013 }
1014
1015 /* If no buttons are pressed... */
1016 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1017 {
1018 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1019 if (s_fReleased)
1020 return FALSE;
1021
1022 nButton = MOUSE_RELEASE;
1023 s_fReleased = TRUE;
1024 }
1025 else /* one or more buttons pressed */
1026 {
1027 /* on a 2-button mouse, hold down left and right buttons
1028 * simultaneously to get MIDDLE. */
1029
1030 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1031 {
1032 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1033
1034 /* if either left or right button only is pressed, see if the
1035 * the next mouse event has both of them pressed */
1036 if (dwLR == LEFT || dwLR == RIGHT)
1037 {
1038 for (;;)
1039 {
1040 /* wait a short time for next input event */
1041 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1042 != WAIT_OBJECT_0)
1043 break;
1044 else
1045 {
1046 DWORD cRecords = 0;
1047 INPUT_RECORD ir;
1048 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1049
1050 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1051
1052 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1053 || !(pmer2->dwButtonState & LEFT_RIGHT))
1054 break;
1055 else
1056 {
1057 if (pmer2->dwEventFlags != MOUSE_MOVED)
1058 {
1059 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1060
1061 return decode_mouse_event(pmer2);
1062 }
1063 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1064 s_yOldMouse == pmer2->dwMousePosition.Y)
1065 {
1066 /* throw away spurious mouse move */
1067 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1068
1069 /* are there any more mouse events in queue? */
1070 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1071
1072 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1073 break;
1074 }
1075 else
1076 break;
1077 }
1078 }
1079 }
1080 }
1081 }
1082
1083 if (s_fNextIsMiddle)
1084 {
1085 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1086 ? MOUSE_DRAG : MOUSE_MIDDLE;
1087 s_fNextIsMiddle = FALSE;
1088 }
1089 else if (cButtons == 2 &&
1090 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1091 {
1092 nButton = MOUSE_MIDDLE;
1093
1094 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1095 {
1096 s_fNextIsMiddle = TRUE;
1097 nButton = MOUSE_RELEASE;
1098 }
1099 }
1100 else if ((pmer->dwButtonState & LEFT) == LEFT)
1101 nButton = MOUSE_LEFT;
1102 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1103 nButton = MOUSE_MIDDLE;
1104 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1105 nButton = MOUSE_RIGHT;
1106
1107 if (! s_fReleased && ! s_fNextIsMiddle
1108 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1109 return FALSE;
1110
1111 s_fReleased = s_fNextIsMiddle;
1112 }
1113
1114 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1115 {
1116 /* button pressed or released, without mouse moving */
1117 if (nButton != -1 && nButton != MOUSE_RELEASE)
1118 {
1119 DWORD dwCurrentTime = GetTickCount();
1120
1121 if (s_xOldMouse != g_xMouse
1122 || s_yOldMouse != g_yMouse
1123 || s_nOldButton != nButton
1124 || s_old_topline != curwin->w_topline
1125#ifdef FEAT_DIFF
1126 || s_old_topfill != curwin->w_topfill
1127#endif
1128 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1129 {
1130 s_cClicks = 1;
1131 }
1132 else if (++s_cClicks > 4)
1133 {
1134 s_cClicks = 1;
1135 }
1136
1137 s_dwLastClickTime = dwCurrentTime;
1138 }
1139 }
1140 else if (pmer->dwEventFlags == MOUSE_MOVED)
1141 {
1142 if (nButton != -1 && nButton != MOUSE_RELEASE)
1143 nButton = MOUSE_DRAG;
1144
1145 s_cClicks = 1;
1146 }
1147
1148 if (nButton == -1)
1149 return FALSE;
1150
1151 if (nButton != MOUSE_RELEASE)
1152 s_nOldButton = nButton;
1153
1154 g_nMouseClick = nButton;
1155
1156 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1157 g_nMouseClick |= MOUSE_SHIFT;
1158 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1159 g_nMouseClick |= MOUSE_CTRL;
1160 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1161 g_nMouseClick |= MOUSE_ALT;
1162
1163 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1164 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1165
1166 /* only pass on interesting (i.e., different) mouse events */
1167 if (s_xOldMouse == g_xMouse
1168 && s_yOldMouse == g_yMouse
1169 && s_nOldMouseClick == g_nMouseClick)
1170 {
1171 g_nMouseClick = -1;
1172 return FALSE;
1173 }
1174
1175 s_xOldMouse = g_xMouse;
1176 s_yOldMouse = g_yMouse;
1177 s_old_topline = curwin->w_topline;
1178#ifdef FEAT_DIFF
1179 s_old_topfill = curwin->w_topfill;
1180#endif
1181 s_nOldMouseClick = g_nMouseClick;
1182
1183 return TRUE;
1184}
1185
1186# endif /* FEAT_GUI_W32 */
1187#endif /* FEAT_MOUSE */
1188
1189
1190#ifdef MCH_CURSOR_SHAPE
1191/*
1192 * Set the shape of the cursor.
1193 * 'thickness' can be from 1 (thin) to 99 (block)
1194 */
1195 static void
1196mch_set_cursor_shape(int thickness)
1197{
1198 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1199 ConsoleCursorInfo.dwSize = thickness;
1200 ConsoleCursorInfo.bVisible = s_cursor_visible;
1201
1202 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1203 if (s_cursor_visible)
1204 SetConsoleCursorPosition(g_hConOut, g_coord);
1205}
1206
1207 void
1208mch_update_cursor(void)
1209{
1210 int idx;
1211 int thickness;
1212
1213 /*
1214 * How the cursor is drawn depends on the current mode.
1215 */
1216 idx = get_shape_idx(FALSE);
1217
1218 if (shape_table[idx].shape == SHAPE_BLOCK)
1219 thickness = 99; /* 100 doesn't work on W95 */
1220 else
1221 thickness = shape_table[idx].percentage;
1222 mch_set_cursor_shape(thickness);
1223}
1224#endif
1225
1226#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1227/*
1228 * Handle FOCUS_EVENT.
1229 */
1230 static void
1231handle_focus_event(INPUT_RECORD ir)
1232{
1233 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1234 ui_focus_change((int)g_fJustGotFocus);
1235}
1236
1237/*
1238 * Wait until console input from keyboard or mouse is available,
1239 * or the time is up.
1240 * Return TRUE if something is available FALSE if not.
1241 */
1242 static int
1243WaitForChar(long msec)
1244{
1245 DWORD dwNow = 0, dwEndTime = 0;
1246 INPUT_RECORD ir;
1247 DWORD cRecords;
1248 char_u ch, ch2;
1249
1250 if (msec > 0)
1251 /* Wait until the specified time has elapsed. */
1252 dwEndTime = GetTickCount() + msec;
1253 else if (msec < 0)
1254 /* Wait forever. */
1255 dwEndTime = INFINITE;
1256
1257 /* We need to loop until the end of the time period, because
1258 * we might get multiple unusable mouse events in that time.
1259 */
1260 for (;;)
1261 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001262#ifdef FEAT_MZSCHEME
1263 mzvim_check_threads();
1264#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265#ifdef FEAT_CLIENTSERVER
1266 serverProcessPendingMessages();
1267#endif
1268 if (0
1269#ifdef FEAT_MOUSE
1270 || g_nMouseClick != -1
1271#endif
1272#ifdef FEAT_CLIENTSERVER
1273 || input_available()
1274#endif
1275 )
1276 return TRUE;
1277
1278 if (msec > 0)
1279 {
1280 /* If the specified wait time has passed, return. */
1281 dwNow = GetTickCount();
1282 if (dwNow >= dwEndTime)
1283 break;
1284 }
1285 if (msec != 0)
1286 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001287 DWORD dwWaitTime = dwEndTime - dwNow;
1288
1289#ifdef FEAT_MZSCHEME
1290 if (mzthreads_allowed() && p_mzq > 0
1291 && (msec < 0 || (long)dwWaitTime > p_mzq))
1292 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1293#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294#ifdef FEAT_CLIENTSERVER
1295 /* Wait for either an event on the console input or a message in
1296 * the client-server window. */
1297 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001298 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001300 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001301#endif
1302 continue;
1303 }
1304
1305 cRecords = 0;
1306 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1307
1308#ifdef FEAT_MBYTE_IME
1309 if (State & CMDLINE && msg_row == Rows - 1)
1310 {
1311 CONSOLE_SCREEN_BUFFER_INFO csbi;
1312
1313 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1314 {
1315 if (csbi.dwCursorPosition.Y != msg_row)
1316 {
1317 /* The screen is now messed up, must redraw the
1318 * command line and later all the windows. */
1319 redraw_all_later(CLEAR);
1320 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1321 redrawcmd();
1322 }
1323 }
1324 }
1325#endif
1326
1327 if (cRecords > 0)
1328 {
1329 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1330 {
1331#ifdef FEAT_MBYTE_IME
1332 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1333 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1334 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1335 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1336 {
1337 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1338 continue;
1339 }
1340#endif
1341 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1342 NULL, FALSE))
1343 return TRUE;
1344 }
1345
1346 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1347
1348 if (ir.EventType == FOCUS_EVENT)
1349 handle_focus_event(ir);
1350 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1351 shell_resized();
1352#ifdef FEAT_MOUSE
1353 else if (ir.EventType == MOUSE_EVENT
1354 && decode_mouse_event(&ir.Event.MouseEvent))
1355 return TRUE;
1356#endif
1357 }
1358 else if (msec == 0)
1359 break;
1360 }
1361
1362#ifdef FEAT_CLIENTSERVER
1363 /* Something might have been received while we were waiting. */
1364 if (input_available())
1365 return TRUE;
1366#endif
1367 return FALSE;
1368}
1369
1370#ifndef FEAT_GUI_MSWIN
1371/*
1372 * return non-zero if a character is available
1373 */
1374 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001375mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001376{
1377 return WaitForChar(0L);
1378}
1379#endif
1380
1381/*
1382 * Create the console input. Used when reading stdin doesn't work.
1383 */
1384 static void
1385create_conin(void)
1386{
1387 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1388 FILE_SHARE_READ|FILE_SHARE_WRITE,
1389 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001390 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001391 did_create_conin = TRUE;
1392}
1393
1394/*
1395 * Get a keystroke or a mouse event
1396 */
1397 static char_u
1398tgetch(int *pmodifiers, char_u *pch2)
1399{
1400 char_u ch;
1401
1402 for (;;)
1403 {
1404 INPUT_RECORD ir;
1405 DWORD cRecords = 0;
1406
1407#ifdef FEAT_CLIENTSERVER
1408 (void)WaitForChar(-1L);
1409 if (input_available())
1410 return 0;
1411# ifdef FEAT_MOUSE
1412 if (g_nMouseClick != -1)
1413 return 0;
1414# endif
1415#endif
1416 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1417 {
1418 if (did_create_conin)
1419 read_error_exit();
1420 create_conin();
1421 continue;
1422 }
1423
1424 if (ir.EventType == KEY_EVENT)
1425 {
1426 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1427 pmodifiers, TRUE))
1428 return ch;
1429 }
1430 else if (ir.EventType == FOCUS_EVENT)
1431 handle_focus_event(ir);
1432 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1433 shell_resized();
1434#ifdef FEAT_MOUSE
1435 else if (ir.EventType == MOUSE_EVENT)
1436 {
1437 if (decode_mouse_event(&ir.Event.MouseEvent))
1438 return 0;
1439 }
1440#endif
1441 }
1442}
1443#endif /* !FEAT_GUI_W32 */
1444
1445
1446/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001447 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448 * Get one or more characters from the keyboard or the mouse.
1449 * If time == 0, do not wait for characters.
1450 * If time == n, wait a short time for characters.
1451 * If time == -1, wait forever for characters.
1452 * Returns the number of characters read into buf.
1453 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001454/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 int
1456mch_inchar(
1457 char_u *buf,
1458 int maxlen,
1459 long time,
1460 int tb_change_cnt)
1461{
1462#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1463
1464 int len;
1465 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466#define TYPEAHEADLEN 20
1467 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1468 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001469#ifdef FEAT_MBYTE
1470 static char_u *rest = NULL; /* unconverted rest of previous read */
1471 static int restlen = 0;
1472 int unconverted;
1473#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474
1475 /* First use any typeahead that was kept because "buf" was too small. */
1476 if (typeaheadlen > 0)
1477 goto theend;
1478
1479#ifdef FEAT_SNIFF
1480 if (want_sniff_request)
1481 {
1482 if (sniff_request_waiting)
1483 {
1484 /* return K_SNIFF */
1485 typeahead[typeaheadlen++] = CSI;
1486 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1487 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1488 sniff_request_waiting = 0;
1489 want_sniff_request = 0;
1490 goto theend;
1491 }
1492 else if (time < 0 || time > 250)
1493 {
1494 /* don't wait too long, a request might be pending */
1495 time = 250;
1496 }
1497 }
1498#endif
1499
1500 if (time >= 0)
1501 {
1502 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 }
1505 else /* time == -1, wait forever */
1506 {
1507 mch_set_winsize_now(); /* Allow winsize changes from now on */
1508
Bram Moolenaar3918c952005-03-15 22:34:55 +00001509 /*
1510 * If there is no character available within 2 seconds (default)
1511 * write the autoscript file to disk. Or cause the CursorHold event
1512 * to be triggered.
1513 */
1514 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515 {
1516#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001517 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001519 buf[0] = K_SPECIAL;
1520 buf[1] = KS_EXTRA;
1521 buf[2] = (int)KE_CURSORHOLD;
1522 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 }
1524#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001525 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526 }
1527 }
1528
1529 /*
1530 * Try to read as many characters as there are, until the buffer is full.
1531 */
1532
1533 /* we will get at least one key. Get more if they are available. */
1534 g_fCBrkPressed = FALSE;
1535
1536#ifdef MCH_WRITE_DUMP
1537 if (fdDump)
1538 fputc('[', fdDump);
1539#endif
1540
1541 /* Keep looping until there is something in the typeahead buffer and more
1542 * to get and still room in the buffer (up to two bytes for a char and
1543 * three bytes for a modifier). */
1544 while ((typeaheadlen == 0 || WaitForChar(0L))
1545 && typeaheadlen + 5 <= TYPEAHEADLEN)
1546 {
1547 if (typebuf_changed(tb_change_cnt))
1548 {
1549 /* "buf" may be invalid now if a client put something in the
1550 * typeahead buffer and "buf" is in the typeahead buffer. */
1551 typeaheadlen = 0;
1552 break;
1553 }
1554#ifdef FEAT_MOUSE
1555 if (g_nMouseClick != -1)
1556 {
1557# ifdef MCH_WRITE_DUMP
1558 if (fdDump)
1559 fprintf(fdDump, "{%02x @ %d, %d}",
1560 g_nMouseClick, g_xMouse, g_yMouse);
1561# endif
1562 typeahead[typeaheadlen++] = ESC + 128;
1563 typeahead[typeaheadlen++] = 'M';
1564 typeahead[typeaheadlen++] = g_nMouseClick;
1565 typeahead[typeaheadlen++] = g_xMouse + '!';
1566 typeahead[typeaheadlen++] = g_yMouse + '!';
1567 g_nMouseClick = -1;
1568 }
1569 else
1570#endif
1571 {
1572 char_u ch2 = NUL;
1573 int modifiers = 0;
1574
1575 c = tgetch(&modifiers, &ch2);
1576
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001577#ifdef FEAT_MBYTE
1578 /* stolen from fill_input_buf() in ui.c */
1579 if (rest != NULL)
1580 {
1581 /* Use remainder of previous call, starts with an invalid
1582 * character that may become valid when reading more. */
1583 if (restlen > TYPEAHEADLEN - typeaheadlen)
1584 unconverted = TYPEAHEADLEN - typeaheadlen;
1585 else
1586 unconverted = restlen;
1587 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1588 if (unconverted == restlen)
1589 {
1590 vim_free(rest);
1591 rest = NULL;
1592 }
1593 else
1594 {
1595 restlen -= unconverted;
1596 mch_memmove(rest, rest + unconverted, restlen);
1597 }
1598 typeaheadlen += unconverted;
1599 }
1600 else
1601 unconverted = 0;
1602#endif
1603
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 if (typebuf_changed(tb_change_cnt))
1605 {
1606 /* "buf" may be invalid now if a client put something in the
1607 * typeahead buffer and "buf" is in the typeahead buffer. */
1608 typeaheadlen = 0;
1609 break;
1610 }
1611
1612 if (c == Ctrl_C && ctrl_c_interrupts)
1613 {
1614#if defined(FEAT_CLIENTSERVER)
1615 trash_input_buf();
1616#endif
1617 got_int = TRUE;
1618 }
1619
1620#ifdef FEAT_MOUSE
1621 if (g_nMouseClick == -1)
1622#endif
1623 {
1624 int n = 1;
1625
1626 /* A key may have one or two bytes. */
1627 typeahead[typeaheadlen] = c;
1628 if (ch2 != NUL)
1629 {
1630 typeahead[typeaheadlen + 1] = ch2;
1631 ++n;
1632 }
1633#ifdef FEAT_MBYTE
1634 /* Only convert normal characters, not special keys. Need to
1635 * convert before applying ALT, otherwise mapping <M-x> breaks
1636 * when 'tenc' is set. */
1637 if (input_conv.vc_type != CONV_NONE
1638 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001639 {
1640 typeaheadlen -= unconverted;
1641 n = convert_input_safe(typeahead + typeaheadlen,
1642 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1643 rest == NULL ? &rest : NULL, &restlen);
1644 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645#endif
1646
1647 /* Use the ALT key to set the 8th bit of the character
1648 * when it's one byte, the 8th bit isn't set yet and not
1649 * using a double-byte encoding (would become a lead
1650 * byte). */
1651 if ((modifiers & MOD_MASK_ALT)
1652 && n == 1
1653 && (typeahead[typeaheadlen] & 0x80) == 0
1654#ifdef FEAT_MBYTE
1655 && !enc_dbcs
1656#endif
1657 )
1658 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001659#ifdef FEAT_MBYTE
1660 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1661 typeahead + typeaheadlen);
1662#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001664#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665 modifiers &= ~MOD_MASK_ALT;
1666 }
1667
1668 if (modifiers != 0)
1669 {
1670 /* Prepend modifiers to the character. */
1671 mch_memmove(typeahead + typeaheadlen + 3,
1672 typeahead + typeaheadlen, n);
1673 typeahead[typeaheadlen++] = K_SPECIAL;
1674 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1675 typeahead[typeaheadlen++] = modifiers;
1676 }
1677
1678 typeaheadlen += n;
1679
1680#ifdef MCH_WRITE_DUMP
1681 if (fdDump)
1682 fputc(c, fdDump);
1683#endif
1684 }
1685 }
1686 }
1687
1688#ifdef MCH_WRITE_DUMP
1689 if (fdDump)
1690 {
1691 fputs("]\n", fdDump);
1692 fflush(fdDump);
1693 }
1694#endif
1695
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696theend:
1697 /* Move typeahead to "buf", as much as fits. */
1698 len = 0;
1699 while (len < maxlen && typeaheadlen > 0)
1700 {
1701 buf[len++] = typeahead[0];
1702 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1703 }
1704 return len;
1705
1706#else /* FEAT_GUI_W32 */
1707 return 0;
1708#endif /* FEAT_GUI_W32 */
1709}
1710
Bram Moolenaar82881492012-11-20 16:53:39 +01001711#ifndef PROTO
1712# ifndef __MINGW32__
1713# include <shellapi.h> /* required for FindExecutable() */
1714# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715#endif
1716
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001717/*
1718 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001719 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001720 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 static int
1722executable_exists(char *name)
1723{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001724 char *dum;
1725 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001727#ifdef FEAT_MBYTE
1728 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001730 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001731 WCHAR fnamew[_MAX_PATH];
1732 WCHAR *dumw;
1733 long n;
1734
1735 if (p != NULL)
1736 {
1737 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1738 vim_free(p);
1739 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1740 {
1741 if (n == 0)
1742 return FALSE;
1743 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1744 return FALSE;
1745 return TRUE;
1746 }
1747 /* Retry with non-wide function (for Windows 98). */
1748 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001750#endif
1751 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1752 return FALSE;
1753 if (mch_isdir(fname))
1754 return FALSE;
1755 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756}
1757
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001758#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001759 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001760/*
1761 * Bad parameter handler.
1762 *
1763 * Certain MS CRT functions will intentionally crash when passed invalid
1764 * parameters to highlight possible security holes. Setting this function as
1765 * the bad parameter handler will prevent the crash.
1766 *
1767 * In debug builds the parameters contain CRT information that might help track
1768 * down the source of a problem, but in non-debug builds the arguments are all
1769 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1770 * worth allowing these to make debugging of issues easier.
1771 */
1772 static void
1773bad_param_handler(const wchar_t *expression,
1774 const wchar_t *function,
1775 const wchar_t *file,
1776 unsigned int line,
1777 uintptr_t pReserved)
1778{
1779}
1780
1781# define SET_INVALID_PARAM_HANDLER \
1782 ((void)_set_invalid_parameter_handler(bad_param_handler))
1783#else
1784# define SET_INVALID_PARAM_HANDLER
1785#endif
1786
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787#ifdef FEAT_GUI_W32
1788
1789/*
1790 * GUI version of mch_init().
1791 */
1792 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001793mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794{
1795#ifndef __MINGW32__
1796 extern int _fmode;
1797#endif
1798
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001799 /* Silently handle invalid parameters to CRT functions */
1800 SET_INVALID_PARAM_HANDLER;
1801
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 /* Let critical errors result in a failure, not in a dialog box. Required
1803 * for the timestamp test to work on removed floppies. */
1804 SetErrorMode(SEM_FAILCRITICALERRORS);
1805
1806 _fmode = O_BINARY; /* we do our own CR-LF translation */
1807
1808 /* Specify window size. Is there a place to get the default from? */
1809 Rows = 25;
1810 Columns = 80;
1811
1812 /* Look for 'vimrun' */
1813 if (!gui_is_win32s())
1814 {
1815 char_u vimrun_location[_MAX_PATH + 4];
1816
1817 /* First try in same directory as gvim.exe */
1818 STRCPY(vimrun_location, exe_name);
1819 STRCPY(gettail(vimrun_location), "vimrun.exe");
1820 if (mch_getperm(vimrun_location) >= 0)
1821 {
1822 if (*skiptowhite(vimrun_location) != NUL)
1823 {
1824 /* Enclose path with white space in double quotes. */
1825 mch_memmove(vimrun_location + 1, vimrun_location,
1826 STRLEN(vimrun_location) + 1);
1827 *vimrun_location = '"';
1828 STRCPY(gettail(vimrun_location), "vimrun\" ");
1829 }
1830 else
1831 STRCPY(gettail(vimrun_location), "vimrun ");
1832
1833 vimrun_path = (char *)vim_strsave(vimrun_location);
1834 s_dont_use_vimrun = FALSE;
1835 }
1836 else if (executable_exists("vimrun.exe"))
1837 s_dont_use_vimrun = FALSE;
1838
1839 /* Don't give the warning for a missing vimrun.exe right now, but only
1840 * when vimrun was supposed to be used. Don't bother people that do
1841 * not need vimrun.exe. */
1842 if (s_dont_use_vimrun)
1843 need_vimrun_warning = TRUE;
1844 }
1845
1846 /*
1847 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1848 * Otherwise the default "findstr /n" is used.
1849 */
1850 if (!executable_exists("findstr.exe"))
1851 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1852
1853#ifdef FEAT_CLIPBOARD
1854 clip_init(TRUE);
1855
1856 /*
Bram Moolenaar7528dd62007-05-06 12:32:12 +00001857 * Vim's own clipboard format recognises whether the text is char, line,
1858 * or rectangular block. Only useful for copying between two Vims.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859 * "VimClipboard" was used for previous versions, using the first
1860 * character to specify MCHAR, MLINE or MBLOCK.
1861 */
1862 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1863 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1864#endif
1865}
1866
1867
1868#else /* FEAT_GUI_W32 */
1869
1870#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1871#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1872
1873/*
1874 * ClearConsoleBuffer()
1875 * Description:
1876 * Clears the entire contents of the console screen buffer, using the
1877 * specified attribute.
1878 * Returns:
1879 * TRUE on success
1880 */
1881 static BOOL
1882ClearConsoleBuffer(WORD wAttribute)
1883{
1884 CONSOLE_SCREEN_BUFFER_INFO csbi;
1885 COORD coord;
1886 DWORD NumCells, dummy;
1887
1888 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1889 return FALSE;
1890
1891 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1892 coord.X = 0;
1893 coord.Y = 0;
1894 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1895 coord, &dummy))
1896 {
1897 return FALSE;
1898 }
1899 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1900 coord, &dummy))
1901 {
1902 return FALSE;
1903 }
1904
1905 return TRUE;
1906}
1907
1908/*
1909 * FitConsoleWindow()
1910 * Description:
1911 * Checks if the console window will fit within given buffer dimensions.
1912 * Also, if requested, will shrink the window to fit.
1913 * Returns:
1914 * TRUE on success
1915 */
1916 static BOOL
1917FitConsoleWindow(
1918 COORD dwBufferSize,
1919 BOOL WantAdjust)
1920{
1921 CONSOLE_SCREEN_BUFFER_INFO csbi;
1922 COORD dwWindowSize;
1923 BOOL NeedAdjust = FALSE;
1924
1925 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1926 {
1927 /*
1928 * A buffer resize will fail if the current console window does
1929 * not lie completely within that buffer. To avoid this, we might
1930 * have to move and possibly shrink the window.
1931 */
1932 if (csbi.srWindow.Right >= dwBufferSize.X)
1933 {
1934 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1935 if (dwWindowSize.X > dwBufferSize.X)
1936 dwWindowSize.X = dwBufferSize.X;
1937 csbi.srWindow.Right = dwBufferSize.X - 1;
1938 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1939 NeedAdjust = TRUE;
1940 }
1941 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1942 {
1943 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1944 if (dwWindowSize.Y > dwBufferSize.Y)
1945 dwWindowSize.Y = dwBufferSize.Y;
1946 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1947 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1948 NeedAdjust = TRUE;
1949 }
1950 if (NeedAdjust && WantAdjust)
1951 {
1952 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1953 return FALSE;
1954 }
1955 return TRUE;
1956 }
1957
1958 return FALSE;
1959}
1960
1961typedef struct ConsoleBufferStruct
1962{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001963 BOOL IsValid;
1964 CONSOLE_SCREEN_BUFFER_INFO Info;
1965 PCHAR_INFO Buffer;
1966 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967} ConsoleBuffer;
1968
1969/*
1970 * SaveConsoleBuffer()
1971 * Description:
1972 * Saves important information about the console buffer, including the
1973 * actual buffer contents. The saved information is suitable for later
1974 * restoration by RestoreConsoleBuffer().
1975 * Returns:
1976 * TRUE if all information was saved; FALSE otherwise
1977 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1978 */
1979 static BOOL
1980SaveConsoleBuffer(
1981 ConsoleBuffer *cb)
1982{
1983 DWORD NumCells;
1984 COORD BufferCoord;
1985 SMALL_RECT ReadRegion;
1986 WORD Y, Y_incr;
1987
1988 if (cb == NULL)
1989 return FALSE;
1990
1991 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1992 {
1993 cb->IsValid = FALSE;
1994 return FALSE;
1995 }
1996 cb->IsValid = TRUE;
1997
1998 /*
1999 * Allocate a buffer large enough to hold the entire console screen
2000 * buffer. If this ConsoleBuffer structure has already been initialized
2001 * with a buffer of the correct size, then just use that one.
2002 */
2003 if (!cb->IsValid || cb->Buffer == NULL ||
2004 cb->BufferSize.X != cb->Info.dwSize.X ||
2005 cb->BufferSize.Y != cb->Info.dwSize.Y)
2006 {
2007 cb->BufferSize.X = cb->Info.dwSize.X;
2008 cb->BufferSize.Y = cb->Info.dwSize.Y;
2009 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002010 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002011 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2012 if (cb->Buffer == NULL)
2013 return FALSE;
2014 }
2015
2016 /*
2017 * We will now copy the console screen buffer into our buffer.
2018 * ReadConsoleOutput() seems to be limited as far as how much you
2019 * can read at a time. Empirically, this number seems to be about
2020 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2021 * in chunks until it is all copied. The chunks will all have the
2022 * same horizontal characteristics, so initialize them now. The
2023 * height of each chunk will be (12000 / width).
2024 */
2025 BufferCoord.X = 0;
2026 ReadRegion.Left = 0;
2027 ReadRegion.Right = cb->Info.dwSize.X - 1;
2028 Y_incr = 12000 / cb->Info.dwSize.X;
2029 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2030 {
2031 /*
2032 * Read into position (0, Y) in our buffer.
2033 */
2034 BufferCoord.Y = Y;
2035 /*
2036 * Read the region whose top left corner is (0, Y) and whose bottom
2037 * right corner is (width - 1, Y + Y_incr - 1). This should define
2038 * a region of size width by Y_incr. Don't worry if this region is
2039 * too large for the remaining buffer; it will be cropped.
2040 */
2041 ReadRegion.Top = Y;
2042 ReadRegion.Bottom = Y + Y_incr - 1;
2043 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2044 cb->Buffer, /* our buffer */
2045 cb->BufferSize, /* dimensions of our buffer */
2046 BufferCoord, /* offset in our buffer */
2047 &ReadRegion)) /* region to save */
2048 {
2049 vim_free(cb->Buffer);
2050 cb->Buffer = NULL;
2051 return FALSE;
2052 }
2053 }
2054
2055 return TRUE;
2056}
2057
2058/*
2059 * RestoreConsoleBuffer()
2060 * Description:
2061 * Restores important information about the console buffer, including the
2062 * actual buffer contents, if desired. The information to restore is in
2063 * the same format used by SaveConsoleBuffer().
2064 * Returns:
2065 * TRUE on success
2066 */
2067 static BOOL
2068RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002069 ConsoleBuffer *cb,
2070 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071{
2072 COORD BufferCoord;
2073 SMALL_RECT WriteRegion;
2074
2075 if (cb == NULL || !cb->IsValid)
2076 return FALSE;
2077
2078 /*
2079 * Before restoring the buffer contents, clear the current buffer, and
2080 * restore the cursor position and window information. Doing this now
2081 * prevents old buffer contents from "flashing" onto the screen.
2082 */
2083 if (RestoreScreen)
2084 ClearConsoleBuffer(cb->Info.wAttributes);
2085
2086 FitConsoleWindow(cb->Info.dwSize, TRUE);
2087 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2088 return FALSE;
2089 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2090 return FALSE;
2091
2092 if (!RestoreScreen)
2093 {
2094 /*
2095 * No need to restore the screen buffer contents, so we're done.
2096 */
2097 return TRUE;
2098 }
2099
2100 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2101 return FALSE;
2102 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2103 return FALSE;
2104
2105 /*
2106 * Restore the screen buffer contents.
2107 */
2108 if (cb->Buffer != NULL)
2109 {
2110 BufferCoord.X = 0;
2111 BufferCoord.Y = 0;
2112 WriteRegion.Left = 0;
2113 WriteRegion.Top = 0;
2114 WriteRegion.Right = cb->Info.dwSize.X - 1;
2115 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2116 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2117 cb->Buffer, /* our buffer */
2118 cb->BufferSize, /* dimensions of our buffer */
2119 BufferCoord, /* offset in our buffer */
2120 &WriteRegion)) /* region to restore */
2121 {
2122 return FALSE;
2123 }
2124 }
2125
2126 return TRUE;
2127}
2128
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002129#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002130#ifdef FEAT_RESTORE_ORIG_SCREEN
2131static ConsoleBuffer g_cbOrig = { 0 };
2132#endif
2133static ConsoleBuffer g_cbNonTermcap = { 0 };
2134static ConsoleBuffer g_cbTermcap = { 0 };
2135
2136#ifdef FEAT_TITLE
2137#ifdef __BORLANDC__
2138typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2139#else
2140typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2141#endif
2142char g_szOrigTitle[256] = { 0 };
2143HWND g_hWnd = NULL; /* also used in os_mswin.c */
2144static HICON g_hOrigIconSmall = NULL;
2145static HICON g_hOrigIcon = NULL;
2146static HICON g_hVimIcon = NULL;
2147static BOOL g_fCanChangeIcon = FALSE;
2148
2149/* ICON* are not defined in VC++ 4.0 */
2150#ifndef ICON_SMALL
2151#define ICON_SMALL 0
2152#endif
2153#ifndef ICON_BIG
2154#define ICON_BIG 1
2155#endif
2156/*
2157 * GetConsoleIcon()
2158 * Description:
2159 * Attempts to retrieve the small icon and/or the big icon currently in
2160 * use by a given window.
2161 * Returns:
2162 * TRUE on success
2163 */
2164 static BOOL
2165GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002166 HWND hWnd,
2167 HICON *phIconSmall,
2168 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002169{
2170 if (hWnd == NULL)
2171 return FALSE;
2172
2173 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002174 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2175 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002177 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2178 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 return TRUE;
2180}
2181
2182/*
2183 * SetConsoleIcon()
2184 * Description:
2185 * Attempts to change the small icon and/or the big icon currently in
2186 * use by a given window.
2187 * Returns:
2188 * TRUE on success
2189 */
2190 static BOOL
2191SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002192 HWND hWnd,
2193 HICON hIconSmall,
2194 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002196 HICON hPrevIconSmall;
2197 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198
2199 if (hWnd == NULL)
2200 return FALSE;
2201
2202 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002203 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2204 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002206 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2207 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208 return TRUE;
2209}
2210
2211/*
2212 * SaveConsoleTitleAndIcon()
2213 * Description:
2214 * Saves the current console window title in g_szOrigTitle, for later
2215 * restoration. Also, attempts to obtain a handle to the console window,
2216 * and use it to save the small and big icons currently in use by the
2217 * console window. This is not always possible on some versions of Windows;
2218 * nor is it possible when running Vim remotely using Telnet (since the
2219 * console window the user sees is owned by a remote process).
2220 */
2221 static void
2222SaveConsoleTitleAndIcon(void)
2223{
2224 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2225
2226 /* Save the original title. */
2227 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2228 return;
2229
2230 /*
2231 * Obtain a handle to the console window using GetConsoleWindow() from
2232 * KERNEL32.DLL; we need to handle in order to change the window icon.
2233 * This function only exists on NT-based Windows, starting with Windows
2234 * 2000. On older operating systems, we can't change the window icon
2235 * anyway.
2236 */
2237 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2238 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2239 "GetConsoleWindow")) != NULL)
2240 {
2241 g_hWnd = (*GetConsoleWindowProc)();
2242 }
2243 if (g_hWnd == NULL)
2244 return;
2245
2246 /* Save the original console window icon. */
2247 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2248 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2249 return;
2250
2251 /* Extract the first icon contained in the Vim executable. */
2252 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2253 if (g_hVimIcon != NULL)
2254 g_fCanChangeIcon = TRUE;
2255}
2256#endif
2257
2258static int g_fWindInitCalled = FALSE;
2259static int g_fTermcapMode = FALSE;
2260static CONSOLE_CURSOR_INFO g_cci;
2261static DWORD g_cmodein = 0;
2262static DWORD g_cmodeout = 0;
2263
2264/*
2265 * non-GUI version of mch_init().
2266 */
2267 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002268mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002269{
2270#ifndef FEAT_RESTORE_ORIG_SCREEN
2271 CONSOLE_SCREEN_BUFFER_INFO csbi;
2272#endif
2273#ifndef __MINGW32__
2274 extern int _fmode;
2275#endif
2276
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002277 /* Silently handle invalid parameters to CRT functions */
2278 SET_INVALID_PARAM_HANDLER;
2279
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280 /* Let critical errors result in a failure, not in a dialog box. Required
2281 * for the timestamp test to work on removed floppies. */
2282 SetErrorMode(SEM_FAILCRITICALERRORS);
2283
2284 _fmode = O_BINARY; /* we do our own CR-LF translation */
2285 out_flush();
2286
2287 /* Obtain handles for the standard Console I/O devices */
2288 if (read_cmd_fd == 0)
2289 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2290 else
2291 create_conin();
2292 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2293
2294#ifdef FEAT_RESTORE_ORIG_SCREEN
2295 /* Save the initial console buffer for later restoration */
2296 SaveConsoleBuffer(&g_cbOrig);
2297 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2298#else
2299 /* Get current text attributes */
2300 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2301 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2302#endif
2303 if (cterm_normal_fg_color == 0)
2304 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2305 if (cterm_normal_bg_color == 0)
2306 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2307
2308 /* set termcap codes to current text attributes */
2309 update_tcap(g_attrCurrent);
2310
2311 GetConsoleCursorInfo(g_hConOut, &g_cci);
2312 GetConsoleMode(g_hConIn, &g_cmodein);
2313 GetConsoleMode(g_hConOut, &g_cmodeout);
2314
2315#ifdef FEAT_TITLE
2316 SaveConsoleTitleAndIcon();
2317 /*
2318 * Set both the small and big icons of the console window to Vim's icon.
2319 * Note that Vim presently only has one size of icon (32x32), but it
2320 * automatically gets scaled down to 16x16 when setting the small icon.
2321 */
2322 if (g_fCanChangeIcon)
2323 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2324#endif
2325
2326 ui_get_shellsize();
2327
2328#ifdef MCH_WRITE_DUMP
2329 fdDump = fopen("dump", "wt");
2330
2331 if (fdDump)
2332 {
2333 time_t t;
2334
2335 time(&t);
2336 fputs(ctime(&t), fdDump);
2337 fflush(fdDump);
2338 }
2339#endif
2340
2341 g_fWindInitCalled = TRUE;
2342
2343#ifdef FEAT_MOUSE
2344 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2345#endif
2346
2347#ifdef FEAT_CLIPBOARD
2348 clip_init(TRUE);
2349
2350 /*
2351 * Vim's own clipboard format recognises whether the text is char, line, or
2352 * rectangular block. Only useful for copying between two Vims.
2353 * "VimClipboard" was used for previous versions, using the first
2354 * character to specify MCHAR, MLINE or MBLOCK.
2355 */
2356 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2357 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2358#endif
2359
2360 /* This will be NULL on anything but NT 4.0 */
2361 s_pfnGetConsoleKeyboardLayoutName =
2362 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2363 "GetConsoleKeyboardLayoutNameA");
2364}
2365
2366/*
2367 * non-GUI version of mch_exit().
2368 * Shut down and exit with status `r'
2369 * Careful: mch_exit() may be called before mch_init()!
2370 */
2371 void
2372mch_exit(int r)
2373{
2374 stoptermcap();
2375
2376 if (g_fWindInitCalled)
2377 settmode(TMODE_COOK);
2378
2379 ml_close_all(TRUE); /* remove all memfiles */
2380
2381 if (g_fWindInitCalled)
2382 {
2383#ifdef FEAT_TITLE
2384 mch_restore_title(3);
2385 /*
2386 * Restore both the small and big icons of the console window to
2387 * what they were at startup. Don't do this when the window is
2388 * closed, Vim would hang here.
2389 */
2390 if (g_fCanChangeIcon && !g_fForceExit)
2391 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2392#endif
2393
2394#ifdef MCH_WRITE_DUMP
2395 if (fdDump)
2396 {
2397 time_t t;
2398
2399 time(&t);
2400 fputs(ctime(&t), fdDump);
2401 fclose(fdDump);
2402 }
2403 fdDump = NULL;
2404#endif
2405 }
2406
2407 SetConsoleCursorInfo(g_hConOut, &g_cci);
2408 SetConsoleMode(g_hConIn, g_cmodein);
2409 SetConsoleMode(g_hConOut, g_cmodeout);
2410
2411#ifdef DYNAMIC_GETTEXT
2412 dyn_libintl_end();
2413#endif
2414
2415 exit(r);
2416}
2417#endif /* !FEAT_GUI_W32 */
2418
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419/*
2420 * Do we have an interactive window?
2421 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002422/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 int
2424mch_check_win(
2425 int argc,
2426 char **argv)
2427{
2428 get_exe_name();
2429
2430#ifdef FEAT_GUI_W32
2431 return OK; /* GUI always has a tty */
2432#else
2433 if (isatty(1))
2434 return OK;
2435 return FAIL;
2436#endif
2437}
2438
2439
2440/*
2441 * fname_case(): Set the case of the file name, if it already exists.
2442 * When "len" is > 0, also expand short to long filenames.
2443 */
2444 void
2445fname_case(
2446 char_u *name,
2447 int len)
2448{
2449 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002450 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 char *ptrue, *ptruePrev;
2452 char *porig, *porigPrev;
2453 int flen;
2454 WIN32_FIND_DATA fb;
2455 HANDLE hFind;
2456 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002457 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002459 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002460 if (flen == 0 || flen > _MAX_PATH)
2461 return;
2462
2463 slash_adjust(name);
2464
2465 /* Build the new name in szTrueName[] one component at a time. */
2466 porig = name;
2467 ptrue = szTrueName;
2468
2469 if (isalpha(porig[0]) && porig[1] == ':')
2470 {
2471 /* copy leading drive letter */
2472 *ptrue++ = *porig++;
2473 *ptrue++ = *porig++;
2474 *ptrue = NUL; /* in case nothing follows */
2475 }
2476
2477 while (*porig != NUL)
2478 {
2479 /* copy \ characters */
2480 while (*porig == psepc)
2481 *ptrue++ = *porig++;
2482
2483 ptruePrev = ptrue;
2484 porigPrev = porig;
2485 while (*porig != NUL && *porig != psepc)
2486 {
2487#ifdef FEAT_MBYTE
2488 int l;
2489
2490 if (enc_dbcs)
2491 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002492 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 while (--l >= 0)
2494 *ptrue++ = *porig++;
2495 }
2496 else
2497#endif
2498 *ptrue++ = *porig++;
2499 }
2500 *ptrue = NUL;
2501
Bram Moolenaar464c9252010-10-13 20:37:41 +02002502 /* To avoid a slow failure append "\*" when searching a directory,
2503 * server or network share. */
2504 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002505 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002506 if (*porig == psepc && slen + 2 < _MAX_PATH)
2507 STRCPY(szTrueNameTemp + slen, "\\*");
2508
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509 /* Skip "", "." and "..". */
2510 if (ptrue > ptruePrev
2511 && (ptruePrev[0] != '.'
2512 || (ptruePrev[1] != NUL
2513 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002514 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 != INVALID_HANDLE_VALUE)
2516 {
2517 c = *porig;
2518 *porig = NUL;
2519
2520 /* Only use the match when it's the same name (ignoring case) or
2521 * expansion is allowed and there is a match with the short name
2522 * and there is enough room. */
2523 if (_stricoll(porigPrev, fb.cFileName) == 0
2524 || (len > 0
2525 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2526 && (int)(ptruePrev - szTrueName)
2527 + (int)strlen(fb.cFileName) < len)))
2528 {
2529 STRCPY(ptruePrev, fb.cFileName);
2530
2531 /* Look for exact match and prefer it if found. Must be a
2532 * long name, otherwise there would be only one match. */
2533 while (FindNextFile(hFind, &fb))
2534 {
2535 if (*fb.cAlternateFileName != NUL
2536 && (strcoll(porigPrev, fb.cFileName) == 0
2537 || (len > 0
2538 && (_stricoll(porigPrev,
2539 fb.cAlternateFileName) == 0
2540 && (int)(ptruePrev - szTrueName)
2541 + (int)strlen(fb.cFileName) < len))))
2542 {
2543 STRCPY(ptruePrev, fb.cFileName);
2544 break;
2545 }
2546 }
2547 }
2548 FindClose(hFind);
2549 *porig = c;
2550 ptrue = ptruePrev + strlen(ptruePrev);
2551 }
2552 }
2553
2554 STRCPY(name, szTrueName);
2555}
2556
2557
2558/*
2559 * Insert user name in s[len].
2560 */
2561 int
2562mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002563 char_u *s,
2564 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002566 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567 DWORD cch = sizeof szUserName;
2568
2569 if (GetUserName(szUserName, &cch))
2570 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002571 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 return OK;
2573 }
2574 s[0] = NUL;
2575 return FAIL;
2576}
2577
2578
2579/*
2580 * Insert host name in s[len].
2581 */
2582 void
2583mch_get_host_name(
2584 char_u *s,
2585 int len)
2586{
2587 DWORD cch = len;
2588
2589 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002590 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591}
2592
2593
2594/*
2595 * return process ID
2596 */
2597 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002598mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599{
2600 return (long)GetCurrentProcessId();
2601}
2602
2603
2604/*
2605 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2606 * Return OK for success, FAIL for failure.
2607 */
2608 int
2609mch_dirname(
2610 char_u *buf,
2611 int len)
2612{
2613 /*
2614 * Originally this was:
2615 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2616 * But the Win32s known bug list says that getcwd() doesn't work
2617 * so use the Win32 system call instead. <Negri>
2618 */
2619#ifdef FEAT_MBYTE
2620 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2621 {
2622 WCHAR wbuf[_MAX_PATH + 1];
2623
2624 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2625 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002626 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002627
2628 if (p != NULL)
2629 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002630 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002631 vim_free(p);
2632 return OK;
2633 }
2634 }
2635 /* Retry with non-wide function (for Windows 98). */
2636 }
2637#endif
2638 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2639}
2640
2641/*
2642 * get file permissions for `name'
2643 * -1 : error
2644 * else FILE_ATTRIBUTE_* defined in winnt.h
2645 */
2646 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002647mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648{
2649#ifdef FEAT_MBYTE
2650 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2651 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002652 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653 long n;
2654
2655 if (p != NULL)
2656 {
2657 n = (long)GetFileAttributesW(p);
2658 vim_free(p);
2659 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2660 return n;
2661 /* Retry with non-wide function (for Windows 98). */
2662 }
2663 }
2664#endif
2665 return (long)GetFileAttributes((char *)name);
2666}
2667
2668
2669/*
2670 * set file permission for `name' to `perm'
2671 */
2672 int
2673mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002674 char_u *name,
2675 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676{
2677 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2678#ifdef FEAT_MBYTE
2679 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2680 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002681 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002682 long n;
2683
2684 if (p != NULL)
2685 {
2686 n = (long)SetFileAttributesW(p, perm);
2687 vim_free(p);
2688 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2689 return n ? OK : FAIL;
2690 /* Retry with non-wide function (for Windows 98). */
2691 }
2692 }
2693#endif
2694 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2695}
2696
2697/*
2698 * Set hidden flag for "name".
2699 */
2700 void
2701mch_hide(char_u *name)
2702{
2703 int perm;
2704#ifdef FEAT_MBYTE
2705 WCHAR *p = NULL;
2706
2707 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002708 p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709#endif
2710
2711#ifdef FEAT_MBYTE
2712 if (p != NULL)
2713 {
2714 perm = GetFileAttributesW(p);
2715 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2716 {
2717 /* Retry with non-wide function (for Windows 98). */
2718 vim_free(p);
2719 p = NULL;
2720 }
2721 }
2722 if (p == NULL)
2723#endif
2724 perm = GetFileAttributes((char *)name);
2725 if (perm >= 0)
2726 {
2727 perm |= FILE_ATTRIBUTE_HIDDEN;
2728#ifdef FEAT_MBYTE
2729 if (p != NULL)
2730 {
2731 if (SetFileAttributesW(p, perm) == 0
2732 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2733 {
2734 /* Retry with non-wide function (for Windows 98). */
2735 vim_free(p);
2736 p = NULL;
2737 }
2738 }
2739 if (p == NULL)
2740#endif
2741 SetFileAttributes((char *)name, perm);
2742 }
2743#ifdef FEAT_MBYTE
2744 vim_free(p);
2745#endif
2746}
2747
2748/*
2749 * return TRUE if "name" is a directory
2750 * return FALSE if "name" is not a directory or upon error
2751 */
2752 int
2753mch_isdir(char_u *name)
2754{
2755 int f = mch_getperm(name);
2756
2757 if (f == -1)
2758 return FALSE; /* file does not exist at all */
2759
2760 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2761}
2762
2763/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002764 * Create directory "name".
2765 * Return 0 on success, -1 on error.
2766 */
2767 int
2768mch_mkdir(char_u *name)
2769{
2770#ifdef FEAT_MBYTE
2771 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2772 {
2773 WCHAR *p;
2774 int retval;
2775
2776 p = enc_to_utf16(name, NULL);
2777 if (p == NULL)
2778 return -1;
2779 retval = _wmkdir(p);
2780 vim_free(p);
2781 return retval;
2782 }
2783#endif
2784 return _mkdir(name);
2785}
2786
2787/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002788 * Return TRUE if file "fname" has more than one link.
2789 */
2790 int
2791mch_is_linked(char_u *fname)
2792{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002793 BY_HANDLE_FILE_INFORMATION info;
2794
2795 return win32_fileinfo(fname, &info) == FILEINFO_OK
2796 && info.nNumberOfLinks > 1;
2797}
2798
2799/*
2800 * Get the by-handle-file-information for "fname".
2801 * Returns FILEINFO_OK when OK.
2802 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
2803 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
2804 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
2805 */
2806 int
2807win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
2808{
Bram Moolenaar03f48552006-02-28 23:52:23 +00002809 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002810 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002811#ifdef FEAT_MBYTE
2812 WCHAR *wn = NULL;
2813
2814 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002815 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002816 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002817 if (wn == NULL)
2818 res = FILEINFO_ENC_FAIL;
2819 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00002820 if (wn != NULL)
2821 {
2822 hFile = CreateFileW(wn, /* file name */
2823 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002824 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002825 NULL, /* security descriptor */
2826 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002827 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002828 NULL); /* handle to template file */
2829 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002830 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002831 {
2832 /* Retry with non-wide function (for Windows 98). */
2833 vim_free(wn);
2834 wn = NULL;
2835 }
2836 }
2837 if (wn == NULL)
2838#endif
2839 hFile = CreateFile(fname, /* file name */
2840 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002841 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002842 NULL, /* security descriptor */
2843 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002844 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002845 NULL); /* handle to template file */
2846
2847 if (hFile != INVALID_HANDLE_VALUE)
2848 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002849 if (GetFileInformationByHandle(hFile, info) != 0)
2850 res = FILEINFO_OK;
2851 else
2852 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002853 CloseHandle(hFile);
2854 }
2855
2856#ifdef FEAT_MBYTE
2857 vim_free(wn);
2858#endif
2859 return res;
2860}
2861
2862/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863 * Return TRUE if file or directory "name" is writable (not readonly).
2864 * Strange semantics of Win32: a readonly directory is writable, but you can't
2865 * delete a file. Let's say this means it is writable.
2866 */
2867 int
2868mch_writable(char_u *name)
2869{
2870 int perm = mch_getperm(name);
2871
2872 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2873 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2874}
2875
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876/*
2877 * Return 1 if "name" can be executed, 0 if not.
2878 * Return -1 if unknown.
2879 */
2880 int
2881mch_can_exe(char_u *name)
2882{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002883 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002884 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002885 char_u *p;
2886
2887 if (len >= _MAX_PATH) /* safety check */
2888 return FALSE;
2889
2890 /* If there already is an extension try using the name directly. Also do
2891 * this with a Unix-shell like 'shell'. */
2892 if (vim_strchr(gettail(name), '.') != NULL
2893 || strstr((char *)gettail(p_sh), "sh") != NULL)
2894 if (executable_exists((char *)name))
2895 return TRUE;
2896
2897 /*
2898 * Loop over all extensions in $PATHEXT.
2899 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002900 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002901 p = mch_getenv("PATHEXT");
2902 if (p == NULL)
2903 p = (char_u *)".com;.exe;.bat;.cmd";
2904 while (*p)
2905 {
2906 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2907 {
2908 /* A single "." means no extension is added. */
2909 buf[len] = NUL;
2910 ++p;
2911 if (*p)
2912 ++p;
2913 }
2914 else
2915 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2916 if (executable_exists((char *)buf))
2917 return TRUE;
2918 }
2919 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921
2922/*
2923 * Check what "name" is:
2924 * NODE_NORMAL: file or directory (or doesn't exist)
2925 * NODE_WRITABLE: writable device, socket, fifo, etc.
2926 * NODE_OTHER: non-writable things
2927 */
2928 int
2929mch_nodetype(char_u *name)
2930{
2931 HANDLE hFile;
2932 int type;
2933
Bram Moolenaar043545e2006-10-10 16:44:07 +00002934 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2935 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2936 * here. */
2937 if (STRNCMP(name, "\\\\.\\", 4) == 0)
2938 return NODE_WRITABLE;
2939
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940 hFile = CreateFile(name, /* file name */
2941 GENERIC_WRITE, /* access mode */
2942 0, /* share mode */
2943 NULL, /* security descriptor */
2944 OPEN_EXISTING, /* creation disposition */
2945 0, /* file attributes */
2946 NULL); /* handle to template file */
2947
2948 if (hFile == INVALID_HANDLE_VALUE)
2949 return NODE_NORMAL;
2950
2951 type = GetFileType(hFile);
2952 CloseHandle(hFile);
2953 if (type == FILE_TYPE_CHAR)
2954 return NODE_WRITABLE;
2955 if (type == FILE_TYPE_DISK)
2956 return NODE_NORMAL;
2957 return NODE_OTHER;
2958}
2959
2960#ifdef HAVE_ACL
2961struct my_acl
2962{
2963 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2964 PSID pSidOwner;
2965 PSID pSidGroup;
2966 PACL pDacl;
2967 PACL pSacl;
2968};
2969#endif
2970
2971/*
2972 * Return a pointer to the ACL of file "fname" in allocated memory.
2973 * Return NULL if the ACL is not available for whatever reason.
2974 */
2975 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002976mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977{
2978#ifndef HAVE_ACL
2979 return (vim_acl_T)NULL;
2980#else
2981 struct my_acl *p = NULL;
2982
2983 /* This only works on Windows NT and 2000. */
2984 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2985 {
2986 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2987 if (p != NULL)
2988 {
2989 if (pGetNamedSecurityInfo(
2990 (LPTSTR)fname, // Abstract filename
2991 SE_FILE_OBJECT, // File Object
2992 // Retrieve the entire security descriptor.
2993 OWNER_SECURITY_INFORMATION |
2994 GROUP_SECURITY_INFORMATION |
2995 DACL_SECURITY_INFORMATION |
2996 SACL_SECURITY_INFORMATION,
2997 &p->pSidOwner, // Ownership information.
2998 &p->pSidGroup, // Group membership.
2999 &p->pDacl, // Discretionary information.
3000 &p->pSacl, // For auditing purposes.
3001 &p->pSecurityDescriptor
3002 ) != ERROR_SUCCESS)
3003 {
3004 mch_free_acl((vim_acl_T)p);
3005 p = NULL;
3006 }
3007 }
3008 }
3009
3010 return (vim_acl_T)p;
3011#endif
3012}
3013
3014/*
3015 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3016 * Errors are ignored.
3017 * This must only be called with "acl" equal to what mch_get_acl() returned.
3018 */
3019 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003020mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021{
3022#ifdef HAVE_ACL
3023 struct my_acl *p = (struct my_acl *)acl;
3024
3025 if (p != NULL && advapi_lib != NULL)
3026 (void)pSetNamedSecurityInfo(
3027 (LPTSTR)fname, // Abstract filename
3028 SE_FILE_OBJECT, // File Object
3029 // Retrieve the entire security descriptor.
3030 OWNER_SECURITY_INFORMATION |
3031 GROUP_SECURITY_INFORMATION |
3032 DACL_SECURITY_INFORMATION |
3033 SACL_SECURITY_INFORMATION,
3034 p->pSidOwner, // Ownership information.
3035 p->pSidGroup, // Group membership.
3036 p->pDacl, // Discretionary information.
3037 p->pSacl // For auditing purposes.
3038 );
3039#endif
3040}
3041
3042 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003043mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044{
3045#ifdef HAVE_ACL
3046 struct my_acl *p = (struct my_acl *)acl;
3047
3048 if (p != NULL)
3049 {
3050 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3051 vim_free(p);
3052 }
3053#endif
3054}
3055
3056#ifndef FEAT_GUI_W32
3057
3058/*
3059 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3060 */
3061 static BOOL WINAPI
3062handler_routine(
3063 DWORD dwCtrlType)
3064{
3065 switch (dwCtrlType)
3066 {
3067 case CTRL_C_EVENT:
3068 if (ctrl_c_interrupts)
3069 g_fCtrlCPressed = TRUE;
3070 return TRUE;
3071
3072 case CTRL_BREAK_EVENT:
3073 g_fCBrkPressed = TRUE;
3074 return TRUE;
3075
3076 /* fatal events: shut down gracefully */
3077 case CTRL_CLOSE_EVENT:
3078 case CTRL_LOGOFF_EVENT:
3079 case CTRL_SHUTDOWN_EVENT:
3080 windgoto((int)Rows - 1, 0);
3081 g_fForceExit = TRUE;
3082
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003083 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084 (dwCtrlType == CTRL_CLOSE_EVENT
3085 ? _("close")
3086 : dwCtrlType == CTRL_LOGOFF_EVENT
3087 ? _("logoff")
3088 : _("shutdown")));
3089#ifdef DEBUG
3090 OutputDebugString(IObuff);
3091#endif
3092
3093 preserve_exit(); /* output IObuff, preserve files and exit */
3094
3095 return TRUE; /* not reached */
3096
3097 default:
3098 return FALSE;
3099 }
3100}
3101
3102
3103/*
3104 * set the tty in (raw) ? "raw" : "cooked" mode
3105 */
3106 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003107mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108{
3109 DWORD cmodein;
3110 DWORD cmodeout;
3111 BOOL bEnableHandler;
3112
3113 GetConsoleMode(g_hConIn, &cmodein);
3114 GetConsoleMode(g_hConOut, &cmodeout);
3115 if (tmode == TMODE_RAW)
3116 {
3117 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3118 ENABLE_ECHO_INPUT);
3119#ifdef FEAT_MOUSE
3120 if (g_fMouseActive)
3121 cmodein |= ENABLE_MOUSE_INPUT;
3122#endif
3123 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3124 bEnableHandler = TRUE;
3125 }
3126 else /* cooked */
3127 {
3128 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3129 ENABLE_ECHO_INPUT);
3130 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3131 bEnableHandler = FALSE;
3132 }
3133 SetConsoleMode(g_hConIn, cmodein);
3134 SetConsoleMode(g_hConOut, cmodeout);
3135 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3136
3137#ifdef MCH_WRITE_DUMP
3138 if (fdDump)
3139 {
3140 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3141 tmode == TMODE_RAW ? "raw" :
3142 tmode == TMODE_COOK ? "cooked" : "normal",
3143 cmodein, cmodeout);
3144 fflush(fdDump);
3145 }
3146#endif
3147}
3148
3149
3150/*
3151 * Get the size of the current window in `Rows' and `Columns'
3152 * Return OK when size could be determined, FAIL otherwise.
3153 */
3154 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003155mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156{
3157 CONSOLE_SCREEN_BUFFER_INFO csbi;
3158
3159 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3160 {
3161 /*
3162 * For some reason, we are trying to get the screen dimensions
3163 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3164 * variables are really intended to mean the size of Vim screen
3165 * while in termcap mode.
3166 */
3167 Rows = g_cbTermcap.Info.dwSize.Y;
3168 Columns = g_cbTermcap.Info.dwSize.X;
3169 }
3170 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3171 {
3172 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3173 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3174 }
3175 else
3176 {
3177 Rows = 25;
3178 Columns = 80;
3179 }
3180 return OK;
3181}
3182
3183/*
3184 * Set a console window to `xSize' * `ySize'
3185 */
3186 static void
3187ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003188 HANDLE hConsole,
3189 int xSize,
3190 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191{
3192 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3193 SMALL_RECT srWindowRect; /* hold the new console size */
3194 COORD coordScreen;
3195
3196#ifdef MCH_WRITE_DUMP
3197 if (fdDump)
3198 {
3199 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3200 fflush(fdDump);
3201 }
3202#endif
3203
3204 /* get the largest size we can size the console window to */
3205 coordScreen = GetLargestConsoleWindowSize(hConsole);
3206
3207 /* define the new console window size and scroll position */
3208 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3209 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3210 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3211
3212 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3213 {
3214 int sx, sy;
3215
3216 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3217 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3218 if (sy < ySize || sx < xSize)
3219 {
3220 /*
3221 * Increasing number of lines/columns, do buffer first.
3222 * Use the maximal size in x and y direction.
3223 */
3224 if (sy < ySize)
3225 coordScreen.Y = ySize;
3226 else
3227 coordScreen.Y = sy;
3228 if (sx < xSize)
3229 coordScreen.X = xSize;
3230 else
3231 coordScreen.X = sx;
3232 SetConsoleScreenBufferSize(hConsole, coordScreen);
3233 }
3234 }
3235
3236 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3237 {
3238#ifdef MCH_WRITE_DUMP
3239 if (fdDump)
3240 {
3241 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3242 GetLastError());
3243 fflush(fdDump);
3244 }
3245#endif
3246 }
3247
3248 /* define the new console buffer size */
3249 coordScreen.X = xSize;
3250 coordScreen.Y = ySize;
3251
3252 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3253 {
3254#ifdef MCH_WRITE_DUMP
3255 if (fdDump)
3256 {
3257 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3258 GetLastError());
3259 fflush(fdDump);
3260 }
3261#endif
3262 }
3263}
3264
3265
3266/*
3267 * Set the console window to `Rows' * `Columns'
3268 */
3269 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003270mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271{
3272 COORD coordScreen;
3273
3274 /* Don't change window size while still starting up */
3275 if (suppress_winsize != 0)
3276 {
3277 suppress_winsize = 2;
3278 return;
3279 }
3280
3281 if (term_console)
3282 {
3283 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3284
3285 /* Clamp Rows and Columns to reasonable values */
3286 if (Rows > coordScreen.Y)
3287 Rows = coordScreen.Y;
3288 if (Columns > coordScreen.X)
3289 Columns = coordScreen.X;
3290
3291 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3292 }
3293}
3294
3295/*
3296 * Rows and/or Columns has changed.
3297 */
3298 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003299mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003300{
3301 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3302}
3303
3304
3305/*
3306 * Called when started up, to set the winsize that was delayed.
3307 */
3308 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003309mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003310{
3311 if (suppress_winsize == 2)
3312 {
3313 suppress_winsize = 0;
3314 mch_set_shellsize();
3315 shell_resized();
3316 }
3317 suppress_winsize = 0;
3318}
3319#endif /* FEAT_GUI_W32 */
3320
3321
3322
3323#if defined(FEAT_GUI_W32) || defined(PROTO)
3324
3325/*
3326 * Specialised version of system() for Win32 GUI mode.
3327 * This version proceeds as follows:
3328 * 1. Create a console window for use by the subprocess
3329 * 2. Run the subprocess (it gets the allocated console by default)
3330 * 3. Wait for the subprocess to terminate and get its exit code
3331 * 4. Prompt the user to press a key to close the console window
3332 */
3333 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003334mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003335{
3336 STARTUPINFO si;
3337 PROCESS_INFORMATION pi;
3338 DWORD ret = 0;
3339 HWND hwnd = GetFocus();
3340
3341 si.cb = sizeof(si);
3342 si.lpReserved = NULL;
3343 si.lpDesktop = NULL;
3344 si.lpTitle = NULL;
3345 si.dwFlags = STARTF_USESHOWWINDOW;
3346 /*
3347 * It's nicer to run a filter command in a minimized window, but in
3348 * Windows 95 this makes the command MUCH slower. We can't do it under
3349 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003350 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003351 */
3352 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003353 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003354 else
3355 si.wShowWindow = SW_SHOWNORMAL;
3356 si.cbReserved2 = 0;
3357 si.lpReserved2 = NULL;
3358
3359 /* There is a strange error on Windows 95 when using "c:\\command.com".
3360 * When the "c:\\" is left out it works OK...? */
3361 if (mch_windows95()
3362 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3363 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3364 cmd += 3;
3365
3366 /* Now, run the command */
3367 CreateProcess(NULL, /* Executable name */
3368 cmd, /* Command to execute */
3369 NULL, /* Process security attributes */
3370 NULL, /* Thread security attributes */
3371 FALSE, /* Inherit handles */
3372 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3373 CREATE_NEW_CONSOLE,
3374 NULL, /* Environment */
3375 NULL, /* Current directory */
3376 &si, /* Startup information */
3377 &pi); /* Process information */
3378
3379
3380 /* Wait for the command to terminate before continuing */
3381 if (g_PlatformId != VER_PLATFORM_WIN32s)
3382 {
3383#ifdef FEAT_GUI
3384 int delay = 1;
3385
3386 /* Keep updating the window while waiting for the shell to finish. */
3387 for (;;)
3388 {
3389 MSG msg;
3390
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003391 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392 {
3393 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003394 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003395 delay = 1;
3396 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397 }
3398 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3399 break;
3400
3401 /* We start waiting for a very short time and then increase it, so
3402 * that we respond quickly when the process is quick, and don't
3403 * consume too much overhead when it's slow. */
3404 if (delay < 50)
3405 delay += 10;
3406 }
3407#else
3408 WaitForSingleObject(pi.hProcess, INFINITE);
3409#endif
3410
3411 /* Get the command exit code */
3412 GetExitCodeProcess(pi.hProcess, &ret);
3413 }
3414 else
3415 {
3416 /*
3417 * This ugly code is the only quick way of performing
3418 * a synchronous spawn under Win32s. Yuk.
3419 */
3420 num_windows = 0;
3421 EnumWindows(win32ssynch_cb, 0);
3422 old_num_windows = num_windows;
3423 do
3424 {
3425 Sleep(1000);
3426 num_windows = 0;
3427 EnumWindows(win32ssynch_cb, 0);
3428 } while (num_windows == old_num_windows);
3429 ret = 0;
3430 }
3431
3432 /* Close the handles to the subprocess, so that it goes away */
3433 CloseHandle(pi.hThread);
3434 CloseHandle(pi.hProcess);
3435
3436 /* Try to get input focus back. Doesn't always work though. */
3437 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3438
3439 return ret;
3440}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003441
3442/*
3443 * Thread launched by the gui to send the current buffer data to the
3444 * process. This way avoid to hang up vim totally if the children
3445 * process take a long time to process the lines.
3446 */
3447 static DWORD WINAPI
3448sub_process_writer(LPVOID param)
3449{
3450 HANDLE g_hChildStd_IN_Wr = param;
3451 linenr_T lnum = curbuf->b_op_start.lnum;
3452 DWORD len = 0;
3453 DWORD l;
3454 char_u *lp = ml_get(lnum);
3455 char_u *s;
3456 int written = 0;
3457
3458 for (;;)
3459 {
3460 l = (DWORD)STRLEN(lp + written);
3461 if (l == 0)
3462 len = 0;
3463 else if (lp[written] == NL)
3464 {
3465 /* NL -> NUL translation */
3466 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3467 }
3468 else
3469 {
3470 s = vim_strchr(lp + written, NL);
3471 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3472 s == NULL ? l : (DWORD)(s - (lp + written)),
3473 &len, NULL);
3474 }
3475 if (len == (int)l)
3476 {
3477 /* Finished a line, add a NL, unless this line should not have
3478 * one. */
3479 if (lnum != curbuf->b_op_end.lnum
3480 || !curbuf->b_p_bin
3481 || (lnum != curbuf->b_no_eol_lnum
3482 && (lnum != curbuf->b_ml.ml_line_count
3483 || curbuf->b_p_eol)))
3484 {
3485 WriteFile(g_hChildStd_IN_Wr, "\n", 1, &ignored, NULL);
3486 }
3487
3488 ++lnum;
3489 if (lnum > curbuf->b_op_end.lnum)
3490 break;
3491
3492 lp = ml_get(lnum);
3493 written = 0;
3494 }
3495 else if (len > 0)
3496 written += len;
3497 }
3498
3499 /* finished all the lines, close pipe */
3500 CloseHandle(g_hChildStd_IN_Wr);
3501 ExitThread(0);
3502}
3503
3504
3505# define BUFLEN 100 /* length for buffer, stolen from unix version */
3506
3507/*
3508 * This function read from the children's stdout and write the
3509 * data on screen or in the buffer accordingly.
3510 */
3511 static void
3512dump_pipe(int options,
3513 HANDLE g_hChildStd_OUT_Rd,
3514 garray_T *ga,
3515 char_u buffer[],
3516 DWORD *buffer_off)
3517{
3518 DWORD availableBytes = 0;
3519 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003520 int ret;
3521 DWORD len;
3522 DWORD toRead;
3523 int repeatCount;
3524
3525 /* we query the pipe to see if there is any data to read
3526 * to avoid to perform a blocking read */
3527 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3528 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003529 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003530 NULL, /* number of read bytes */
3531 &availableBytes, /* available bytes total */
3532 NULL); /* byteLeft */
3533
3534 repeatCount = 0;
3535 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003536 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003537 {
3538 repeatCount++;
3539 toRead =
3540# ifdef FEAT_MBYTE
3541 (DWORD)(BUFLEN - *buffer_off);
3542# else
3543 (DWORD)BUFLEN;
3544# endif
3545 toRead = availableBytes < toRead ? availableBytes : toRead;
3546 ReadFile(g_hChildStd_OUT_Rd, buffer
3547# ifdef FEAT_MBYTE
3548 + *buffer_off, toRead
3549# else
3550 , toRead
3551# endif
3552 , &len, NULL);
3553
3554 /* If we haven't read anything, there is a problem */
3555 if (len == 0)
3556 break;
3557
3558 availableBytes -= len;
3559
3560 if (options & SHELL_READ)
3561 {
3562 /* Do NUL -> NL translation, append NL separated
3563 * lines to the current buffer. */
3564 for (i = 0; i < len; ++i)
3565 {
3566 if (buffer[i] == NL)
3567 append_ga_line(ga);
3568 else if (buffer[i] == NUL)
3569 ga_append(ga, NL);
3570 else
3571 ga_append(ga, buffer[i]);
3572 }
3573 }
3574# ifdef FEAT_MBYTE
3575 else if (has_mbyte)
3576 {
3577 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003578 int c;
3579 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003580
3581 len += *buffer_off;
3582 buffer[len] = NUL;
3583
3584 /* Check if the last character in buffer[] is
3585 * incomplete, keep these bytes for the next
3586 * round. */
3587 for (p = buffer; p < buffer + len; p += l)
3588 {
3589 l = mb_cptr2len(p);
3590 if (l == 0)
3591 l = 1; /* NUL byte? */
3592 else if (MB_BYTE2LEN(*p) != l)
3593 break;
3594 }
3595 if (p == buffer) /* no complete character */
3596 {
3597 /* avoid getting stuck at an illegal byte */
3598 if (len >= 12)
3599 ++p;
3600 else
3601 {
3602 *buffer_off = len;
3603 return;
3604 }
3605 }
3606 c = *p;
3607 *p = NUL;
3608 msg_puts(buffer);
3609 if (p < buffer + len)
3610 {
3611 *p = c;
3612 *buffer_off = (DWORD)((buffer + len) - p);
3613 mch_memmove(buffer, p, *buffer_off);
3614 return;
3615 }
3616 *buffer_off = 0;
3617 }
3618# endif /* FEAT_MBYTE */
3619 else
3620 {
3621 buffer[len] = NUL;
3622 msg_puts(buffer);
3623 }
3624
3625 windgoto(msg_row, msg_col);
3626 cursor_on();
3627 out_flush();
3628 }
3629}
3630
3631/*
3632 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
3633 * for communication and doesn't open any new window.
3634 */
3635 static int
3636mch_system_piped(char *cmd, int options)
3637{
3638 STARTUPINFO si;
3639 PROCESS_INFORMATION pi;
3640 DWORD ret = 0;
3641
3642 HANDLE g_hChildStd_IN_Rd = NULL;
3643 HANDLE g_hChildStd_IN_Wr = NULL;
3644 HANDLE g_hChildStd_OUT_Rd = NULL;
3645 HANDLE g_hChildStd_OUT_Wr = NULL;
3646
3647 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
3648 DWORD len;
3649
3650 /* buffer used to receive keys */
3651 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3652 int ta_len = 0; /* valid bytes in ta_buf[] */
3653
3654 DWORD i;
3655 int c;
3656 int noread_cnt = 0;
3657 garray_T ga;
3658 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003659 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003660 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003661
3662 SECURITY_ATTRIBUTES saAttr;
3663
3664 /* Set the bInheritHandle flag so pipe handles are inherited. */
3665 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
3666 saAttr.bInheritHandle = TRUE;
3667 saAttr.lpSecurityDescriptor = NULL;
3668
3669 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
3670 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
3671 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
3672 /* Create a pipe for the child process's STDIN. */
3673 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
3674 /* Ensure the write handle to the pipe for STDIN is not inherited. */
3675 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
3676 {
3677 CloseHandle(g_hChildStd_IN_Rd);
3678 CloseHandle(g_hChildStd_IN_Wr);
3679 CloseHandle(g_hChildStd_OUT_Rd);
3680 CloseHandle(g_hChildStd_OUT_Wr);
3681 MSG_PUTS(_("\nCannot create pipes\n"));
3682 }
3683
3684 si.cb = sizeof(si);
3685 si.lpReserved = NULL;
3686 si.lpDesktop = NULL;
3687 si.lpTitle = NULL;
3688 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
3689
3690 /* set-up our file redirection */
3691 si.hStdError = g_hChildStd_OUT_Wr;
3692 si.hStdOutput = g_hChildStd_OUT_Wr;
3693 si.hStdInput = g_hChildStd_IN_Rd;
3694 si.wShowWindow = SW_HIDE;
3695 si.cbReserved2 = 0;
3696 si.lpReserved2 = NULL;
3697
3698 if (options & SHELL_READ)
3699 ga_init2(&ga, 1, BUFLEN);
3700
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003701 if (cmd != NULL)
3702 {
3703 p = (char *)vim_strsave((char_u *)cmd);
3704 if (p != NULL)
3705 unescape_shellxquote((char_u *)p, p_sxe);
3706 else
3707 p = cmd;
3708 }
3709
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003710 /* Now, run the command */
3711 CreateProcess(NULL, /* Executable name */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003712 p, /* Command to execute */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003713 NULL, /* Process security attributes */
3714 NULL, /* Thread security attributes */
3715
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003716 // this command can be litigious, handle inheritance was
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003717 // deactivated for pending temp file, but, if we deactivate
3718 // it, the pipes don't work for some reason.
3719 TRUE, /* Inherit handles, first deactivated,
3720 * but needed */
3721 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
3722 NULL, /* Environment */
3723 NULL, /* Current directory */
3724 &si, /* Startup information */
3725 &pi); /* Process information */
3726
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003727 if (p != cmd)
3728 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003729
3730 /* Close our unused side of the pipes */
3731 CloseHandle(g_hChildStd_IN_Rd);
3732 CloseHandle(g_hChildStd_OUT_Wr);
3733
3734 if (options & SHELL_WRITE)
3735 {
3736 HANDLE thread =
3737 CreateThread(NULL, /* security attributes */
3738 0, /* default stack size */
3739 sub_process_writer, /* function to be executed */
3740 g_hChildStd_IN_Wr, /* parameter */
3741 0, /* creation flag, start immediately */
3742 NULL); /* we don't care about thread id */
3743 CloseHandle(thread);
3744 g_hChildStd_IN_Wr = NULL;
3745 }
3746
3747 /* Keep updating the window while waiting for the shell to finish. */
3748 for (;;)
3749 {
3750 MSG msg;
3751
3752 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3753 {
3754 TranslateMessage(&msg);
3755 DispatchMessage(&msg);
3756 }
3757
3758 /* write pipe information in the window */
3759 if ((options & (SHELL_READ|SHELL_WRITE))
3760# ifdef FEAT_GUI
3761 || gui.in_use
3762# endif
3763 )
3764 {
3765 len = 0;
3766 if (!(options & SHELL_EXPAND)
3767 && ((options &
3768 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
3769 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
3770# ifdef FEAT_GUI
3771 || gui.in_use
3772# endif
3773 )
3774 && (ta_len > 0 || noread_cnt > 4))
3775 {
3776 if (ta_len == 0)
3777 {
3778 /* Get extra characters when we don't have any. Reset the
3779 * counter and timer. */
3780 noread_cnt = 0;
3781# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
3782 gettimeofday(&start_tv, NULL);
3783# endif
3784 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
3785 }
3786 if (ta_len > 0 || len > 0)
3787 {
3788 /*
3789 * For pipes: Check for CTRL-C: send interrupt signal to
3790 * child. Check for CTRL-D: EOF, close pipe to child.
3791 */
3792 if (len == 1 && cmd != NULL)
3793 {
3794 if (ta_buf[ta_len] == Ctrl_C)
3795 {
3796 /* Learn what exit code is expected, for
3797 * now put 9 as SIGKILL */
3798 TerminateProcess(pi.hProcess, 9);
3799 }
3800 if (ta_buf[ta_len] == Ctrl_D)
3801 {
3802 CloseHandle(g_hChildStd_IN_Wr);
3803 g_hChildStd_IN_Wr = NULL;
3804 }
3805 }
3806
3807 /* replace K_BS by <BS> and K_DEL by <DEL> */
3808 for (i = ta_len; i < ta_len + len; ++i)
3809 {
3810 if (ta_buf[i] == CSI && len - i > 2)
3811 {
3812 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
3813 if (c == K_DEL || c == K_KDEL || c == K_BS)
3814 {
3815 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
3816 (size_t)(len - i - 2));
3817 if (c == K_DEL || c == K_KDEL)
3818 ta_buf[i] = DEL;
3819 else
3820 ta_buf[i] = Ctrl_H;
3821 len -= 2;
3822 }
3823 }
3824 else if (ta_buf[i] == '\r')
3825 ta_buf[i] = '\n';
3826# ifdef FEAT_MBYTE
3827 if (has_mbyte)
3828 i += (*mb_ptr2len_len)(ta_buf + i,
3829 ta_len + len - i) - 1;
3830# endif
3831 }
3832
3833 /*
3834 * For pipes: echo the typed characters. For a pty this
3835 * does not seem to work.
3836 */
3837 for (i = ta_len; i < ta_len + len; ++i)
3838 {
3839 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
3840 msg_putchar(ta_buf[i]);
3841# ifdef FEAT_MBYTE
3842 else if (has_mbyte)
3843 {
3844 int l = (*mb_ptr2len)(ta_buf + i);
3845
3846 msg_outtrans_len(ta_buf + i, l);
3847 i += l - 1;
3848 }
3849# endif
3850 else
3851 msg_outtrans_len(ta_buf + i, 1);
3852 }
3853 windgoto(msg_row, msg_col);
3854 out_flush();
3855
3856 ta_len += len;
3857
3858 /*
3859 * Write the characters to the child, unless EOF has been
3860 * typed for pipes. Write one character at a time, to
3861 * avoid losing too much typeahead. When writing buffer
3862 * lines, drop the typed characters (only check for
3863 * CTRL-C).
3864 */
3865 if (options & SHELL_WRITE)
3866 ta_len = 0;
3867 else if (g_hChildStd_IN_Wr != NULL)
3868 {
3869 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
3870 1, &len, NULL);
3871 // if we are typing in, we want to keep things reactive
3872 delay = 1;
3873 if (len > 0)
3874 {
3875 ta_len -= len;
3876 mch_memmove(ta_buf, ta_buf + len, ta_len);
3877 }
3878 }
3879 }
3880 }
3881 }
3882
3883 if (ta_len)
3884 ui_inchar_undo(ta_buf, ta_len);
3885
3886 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3887 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003888 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003889 break;
3890 }
3891
3892 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003893 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003894
3895 /* We start waiting for a very short time and then increase it, so
3896 * that we respond quickly when the process is quick, and don't
3897 * consume too much overhead when it's slow. */
3898 if (delay < 50)
3899 delay += 10;
3900 }
3901
3902 /* Close the pipe */
3903 CloseHandle(g_hChildStd_OUT_Rd);
3904 if (g_hChildStd_IN_Wr != NULL)
3905 CloseHandle(g_hChildStd_IN_Wr);
3906
3907 WaitForSingleObject(pi.hProcess, INFINITE);
3908
3909 /* Get the command exit code */
3910 GetExitCodeProcess(pi.hProcess, &ret);
3911
3912 if (options & SHELL_READ)
3913 {
3914 if (ga.ga_len > 0)
3915 {
3916 append_ga_line(&ga);
3917 /* remember that the NL was missing */
3918 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
3919 }
3920 else
3921 curbuf->b_no_eol_lnum = 0;
3922 ga_clear(&ga);
3923 }
3924
3925 /* Close the handles to the subprocess, so that it goes away */
3926 CloseHandle(pi.hThread);
3927 CloseHandle(pi.hProcess);
3928
3929 return ret;
3930}
3931
3932 static int
3933mch_system(char *cmd, int options)
3934{
3935 /* if we can pipe and the shelltemp option is off */
3936 if (allowPiping && !p_stmp)
3937 return mch_system_piped(cmd, options);
3938 else
3939 return mch_system_classic(cmd, options);
3940}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003941#else
3942
3943# define mch_system(c, o) system(c)
3944
3945#endif
3946
3947/*
3948 * Either execute a command by calling the shell or start a new shell
3949 */
3950 int
3951mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003952 char_u *cmd,
3953 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003954{
3955 int x = 0;
3956 int tmode = cur_tmode;
3957#ifdef FEAT_TITLE
3958 char szShellTitle[512];
3959
3960 /* Change the title to reflect that we are in a subshell. */
3961 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3962 {
3963 if (cmd == NULL)
3964 strcat(szShellTitle, " :sh");
3965 else
3966 {
3967 strcat(szShellTitle, " - !");
3968 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3969 strcat(szShellTitle, cmd);
3970 }
3971 mch_settitle(szShellTitle, NULL);
3972 }
3973#endif
3974
3975 out_flush();
3976
3977#ifdef MCH_WRITE_DUMP
3978 if (fdDump)
3979 {
3980 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3981 fflush(fdDump);
3982 }
3983#endif
3984
3985 /*
3986 * Catch all deadly signals while running the external command, because a
3987 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3988 */
3989 signal(SIGINT, SIG_IGN);
3990#if defined(__GNUC__) && !defined(__MINGW32__)
3991 signal(SIGKILL, SIG_IGN);
3992#else
3993 signal(SIGBREAK, SIG_IGN);
3994#endif
3995 signal(SIGILL, SIG_IGN);
3996 signal(SIGFPE, SIG_IGN);
3997 signal(SIGSEGV, SIG_IGN);
3998 signal(SIGTERM, SIG_IGN);
3999 signal(SIGABRT, SIG_IGN);
4000
4001 if (options & SHELL_COOKED)
4002 settmode(TMODE_COOK); /* set to normal mode */
4003
4004 if (cmd == NULL)
4005 {
4006 x = mch_system(p_sh, options);
4007 }
4008 else
4009 {
4010 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004011 char_u *newcmd = NULL;
4012 char_u *cmdbase = cmd;
4013 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004014
4015 /* Skip a leading ", ( and "(. */
4016 if (*cmdbase == '"' )
4017 ++cmdbase;
4018 if (*cmdbase == '(')
4019 ++cmdbase;
4020
4021 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4022 {
4023 STARTUPINFO si;
4024 PROCESS_INFORMATION pi;
4025 DWORD flags = CREATE_NEW_CONSOLE;
4026 char_u *p;
4027
4028 si.cb = sizeof(si);
4029 si.lpReserved = NULL;
4030 si.lpDesktop = NULL;
4031 si.lpTitle = NULL;
4032 si.dwFlags = 0;
4033 si.cbReserved2 = 0;
4034 si.lpReserved2 = NULL;
4035
4036 cmdbase = skipwhite(cmdbase + 5);
4037 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4038 && vim_iswhite(cmdbase[4]))
4039 {
4040 cmdbase = skipwhite(cmdbase + 4);
4041 si.dwFlags = STARTF_USESHOWWINDOW;
4042 si.wShowWindow = SW_SHOWMINNOACTIVE;
4043 }
4044 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4045 && vim_iswhite(cmdbase[2]))
4046 {
4047 cmdbase = skipwhite(cmdbase + 2);
4048 flags = CREATE_NO_WINDOW;
4049 si.dwFlags = STARTF_USESTDHANDLES;
4050 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004051 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004052 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004053 NULL, // Security att.
4054 OPEN_EXISTING, // Open flags
4055 FILE_ATTRIBUTE_NORMAL, // File att.
4056 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004057 si.hStdOutput = si.hStdInput;
4058 si.hStdError = si.hStdInput;
4059 }
4060
4061 /* Remove a trailing ", ) and )" if they have a match
4062 * at the start of the command. */
4063 if (cmdbase > cmd)
4064 {
4065 p = cmdbase + STRLEN(cmdbase);
4066 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4067 *--p = NUL;
4068 if (p > cmdbase && p[-1] == ')'
4069 && (*cmd =='(' || cmd[1] == '('))
4070 *--p = NUL;
4071 }
4072
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004073 newcmd = cmdbase;
4074 unescape_shellxquote(cmdbase, p_sxe);
4075
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004076 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004077 * If creating new console, arguments are passed to the
4078 * 'cmd.exe' as-is. If it's not, arguments are not treated
4079 * correctly for current 'cmd.exe'. So unescape characters in
4080 * shellxescape except '|' for avoiding to be treated as
4081 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004082 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004083 if (flags != CREATE_NEW_CONSOLE)
4084 {
4085 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004086 char_u *cmd_shell = mch_getenv("COMSPEC");
4087
4088 if (cmd_shell == NULL || *cmd_shell == NUL)
4089 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004090
4091 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4092 if (subcmd != NULL)
4093 {
4094 /* make "cmd.exe /c arguments" */
4095 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004096 newcmd = lalloc(cmdlen, TRUE);
4097 if (newcmd != NULL)
4098 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004099 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004100 else
4101 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004102 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004103 }
4104 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004105
4106 /*
4107 * Now, start the command as a process, so that it doesn't
4108 * inherit our handles which causes unpleasant dangling swap
4109 * files if we exit before the spawned process
4110 */
4111 if (CreateProcess(NULL, // Executable name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004112 newcmd, // Command to execute
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004113 NULL, // Process security attributes
4114 NULL, // Thread security attributes
4115 FALSE, // Inherit handles
4116 flags, // Creation flags
4117 NULL, // Environment
4118 NULL, // Current directory
4119 &si, // Startup information
4120 &pi)) // Process information
4121 x = 0;
4122 else
4123 {
4124 x = -1;
4125#ifdef FEAT_GUI_W32
4126 EMSG(_("E371: Command not found"));
4127#endif
4128 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004129
4130 if (newcmd != cmdbase)
4131 vim_free(newcmd);
4132
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004133 if (si.hStdInput != NULL)
4134 {
4135 /* Close the handle to \\.\NUL */
4136 CloseHandle(si.hStdInput);
4137 }
4138 /* Close the handles to the subprocess, so that it goes away */
4139 CloseHandle(pi.hThread);
4140 CloseHandle(pi.hProcess);
4141 }
4142 else
4143 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004144 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004146 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004148 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4149
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004150 newcmd = lalloc(cmdlen, TRUE);
4151 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 {
4153#if defined(FEAT_GUI_W32)
4154 if (need_vimrun_warning)
4155 {
4156 MessageBox(NULL,
4157 _("VIMRUN.EXE not found in your $PATH.\n"
4158 "External commands will not pause after completion.\n"
4159 "See :help win32-vimrun for more information."),
4160 _("Vim Warning"),
4161 MB_ICONWARNING);
4162 need_vimrun_warning = FALSE;
4163 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004164 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165 /* Use vimrun to execute the command. It opens a console
4166 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004167 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 vimrun_path,
4169 (msg_silent != 0 || (options & SHELL_DOOUT))
4170 ? "-s " : "",
4171 p_sh, p_shcf, cmd);
4172 else
4173#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004174 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004175 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004177 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 }
4180 }
4181
4182 if (tmode == TMODE_RAW)
4183 settmode(TMODE_RAW); /* set to raw mode */
4184
4185 /* Print the return value, unless "vimrun" was used. */
4186 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4187#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004188 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4189 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004190#endif
4191 )
4192 {
4193 smsg(_("shell returned %d"), x);
4194 msg_putchar('\n');
4195 }
4196#ifdef FEAT_TITLE
4197 resettitle();
4198#endif
4199
4200 signal(SIGINT, SIG_DFL);
4201#if defined(__GNUC__) && !defined(__MINGW32__)
4202 signal(SIGKILL, SIG_DFL);
4203#else
4204 signal(SIGBREAK, SIG_DFL);
4205#endif
4206 signal(SIGILL, SIG_DFL);
4207 signal(SIGFPE, SIG_DFL);
4208 signal(SIGSEGV, SIG_DFL);
4209 signal(SIGTERM, SIG_DFL);
4210 signal(SIGABRT, SIG_DFL);
4211
4212 return x;
4213}
4214
4215
4216#ifndef FEAT_GUI_W32
4217
4218/*
4219 * Start termcap mode
4220 */
4221 static void
4222termcap_mode_start(void)
4223{
4224 DWORD cmodein;
4225
4226 if (g_fTermcapMode)
4227 return;
4228
4229 SaveConsoleBuffer(&g_cbNonTermcap);
4230
4231 if (g_cbTermcap.IsValid)
4232 {
4233 /*
4234 * We've been in termcap mode before. Restore certain screen
4235 * characteristics, including the buffer size and the window
4236 * size. Since we will be redrawing the screen, we don't need
4237 * to restore the actual contents of the buffer.
4238 */
4239 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4240 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4241 Rows = g_cbTermcap.Info.dwSize.Y;
4242 Columns = g_cbTermcap.Info.dwSize.X;
4243 }
4244 else
4245 {
4246 /*
4247 * This is our first time entering termcap mode. Clear the console
4248 * screen buffer, and resize the buffer to match the current window
4249 * size. We will use this as the size of our editing environment.
4250 */
4251 ClearConsoleBuffer(g_attrCurrent);
4252 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4253 }
4254
4255#ifdef FEAT_TITLE
4256 resettitle();
4257#endif
4258
4259 GetConsoleMode(g_hConIn, &cmodein);
4260#ifdef FEAT_MOUSE
4261 if (g_fMouseActive)
4262 cmodein |= ENABLE_MOUSE_INPUT;
4263 else
4264 cmodein &= ~ENABLE_MOUSE_INPUT;
4265#endif
4266 cmodein |= ENABLE_WINDOW_INPUT;
4267 SetConsoleMode(g_hConIn, cmodein);
4268
4269 redraw_later_clear();
4270 g_fTermcapMode = TRUE;
4271}
4272
4273
4274/*
4275 * End termcap mode
4276 */
4277 static void
4278termcap_mode_end(void)
4279{
4280 DWORD cmodein;
4281 ConsoleBuffer *cb;
4282 COORD coord;
4283 DWORD dwDummy;
4284
4285 if (!g_fTermcapMode)
4286 return;
4287
4288 SaveConsoleBuffer(&g_cbTermcap);
4289
4290 GetConsoleMode(g_hConIn, &cmodein);
4291 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4292 SetConsoleMode(g_hConIn, cmodein);
4293
4294#ifdef FEAT_RESTORE_ORIG_SCREEN
4295 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4296#else
4297 cb = &g_cbNonTermcap;
4298#endif
4299 RestoreConsoleBuffer(cb, p_rs);
4300 SetConsoleCursorInfo(g_hConOut, &g_cci);
4301
4302 if (p_rs || exiting)
4303 {
4304 /*
4305 * Clear anything that happens to be on the current line.
4306 */
4307 coord.X = 0;
4308 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4309 FillConsoleOutputCharacter(g_hConOut, ' ',
4310 cb->Info.dwSize.X, coord, &dwDummy);
4311 /*
4312 * The following is just for aesthetics. If we are exiting without
4313 * restoring the screen, then we want to have a prompt string
4314 * appear at the bottom line. However, the command interpreter
4315 * seems to always advance the cursor one line before displaying
4316 * the prompt string, which causes the screen to scroll. To
4317 * counter this, move the cursor up one line before exiting.
4318 */
4319 if (exiting && !p_rs)
4320 coord.Y--;
4321 /*
4322 * Position the cursor at the leftmost column of the desired row.
4323 */
4324 SetConsoleCursorPosition(g_hConOut, coord);
4325 }
4326
4327 g_fTermcapMode = FALSE;
4328}
4329#endif /* FEAT_GUI_W32 */
4330
4331
4332#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004333/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004334 void
4335mch_write(
4336 char_u *s,
4337 int len)
4338{
4339 /* never used */
4340}
4341
4342#else
4343
4344/*
4345 * clear `n' chars, starting from `coord'
4346 */
4347 static void
4348clear_chars(
4349 COORD coord,
4350 DWORD n)
4351{
4352 DWORD dwDummy;
4353
4354 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4355 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4356}
4357
4358
4359/*
4360 * Clear the screen
4361 */
4362 static void
4363clear_screen(void)
4364{
4365 g_coord.X = g_coord.Y = 0;
4366 clear_chars(g_coord, Rows * Columns);
4367}
4368
4369
4370/*
4371 * Clear to end of display
4372 */
4373 static void
4374clear_to_end_of_display(void)
4375{
4376 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4377 * Columns + (Columns - g_coord.X));
4378}
4379
4380
4381/*
4382 * Clear to end of line
4383 */
4384 static void
4385clear_to_end_of_line(void)
4386{
4387 clear_chars(g_coord, Columns - g_coord.X);
4388}
4389
4390
4391/*
4392 * Scroll the scroll region up by `cLines' lines
4393 */
4394 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004395scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396{
4397 COORD oldcoord = g_coord;
4398
4399 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4400 delete_lines(cLines);
4401
4402 g_coord = oldcoord;
4403}
4404
4405
4406/*
4407 * Set the scroll region
4408 */
4409 static void
4410set_scroll_region(
4411 unsigned left,
4412 unsigned top,
4413 unsigned right,
4414 unsigned bottom)
4415{
4416 if (left >= right
4417 || top >= bottom
4418 || right > (unsigned) Columns - 1
4419 || bottom > (unsigned) Rows - 1)
4420 return;
4421
4422 g_srScrollRegion.Left = left;
4423 g_srScrollRegion.Top = top;
4424 g_srScrollRegion.Right = right;
4425 g_srScrollRegion.Bottom = bottom;
4426}
4427
4428
4429/*
4430 * Insert `cLines' lines at the current cursor position
4431 */
4432 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004433insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434{
4435 SMALL_RECT source;
4436 COORD dest;
4437 CHAR_INFO fill;
4438
4439 dest.X = 0;
4440 dest.Y = g_coord.Y + cLines;
4441
4442 source.Left = 0;
4443 source.Top = g_coord.Y;
4444 source.Right = g_srScrollRegion.Right;
4445 source.Bottom = g_srScrollRegion.Bottom - cLines;
4446
4447 fill.Char.AsciiChar = ' ';
4448 fill.Attributes = g_attrCurrent;
4449
4450 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4451
4452 /* Here we have to deal with a win32 console flake: If the scroll
4453 * region looks like abc and we scroll c to a and fill with d we get
4454 * cbd... if we scroll block c one line at a time to a, we get cdd...
4455 * vim expects cdd consistently... So we have to deal with that
4456 * here... (this also occurs scrolling the same way in the other
4457 * direction). */
4458
4459 if (source.Bottom < dest.Y)
4460 {
4461 COORD coord;
4462
4463 coord.X = 0;
4464 coord.Y = source.Bottom;
4465 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4466 }
4467}
4468
4469
4470/*
4471 * Delete `cLines' lines at the current cursor position
4472 */
4473 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004474delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475{
4476 SMALL_RECT source;
4477 COORD dest;
4478 CHAR_INFO fill;
4479 int nb;
4480
4481 dest.X = 0;
4482 dest.Y = g_coord.Y;
4483
4484 source.Left = 0;
4485 source.Top = g_coord.Y + cLines;
4486 source.Right = g_srScrollRegion.Right;
4487 source.Bottom = g_srScrollRegion.Bottom;
4488
4489 fill.Char.AsciiChar = ' ';
4490 fill.Attributes = g_attrCurrent;
4491
4492 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4493
4494 /* Here we have to deal with a win32 console flake: If the scroll
4495 * region looks like abc and we scroll c to a and fill with d we get
4496 * cbd... if we scroll block c one line at a time to a, we get cdd...
4497 * vim expects cdd consistently... So we have to deal with that
4498 * here... (this also occurs scrolling the same way in the other
4499 * direction). */
4500
4501 nb = dest.Y + (source.Bottom - source.Top) + 1;
4502
4503 if (nb < source.Top)
4504 {
4505 COORD coord;
4506
4507 coord.X = 0;
4508 coord.Y = nb;
4509 clear_chars(coord, Columns * (source.Top - nb));
4510 }
4511}
4512
4513
4514/*
4515 * Set the cursor position
4516 */
4517 static void
4518gotoxy(
4519 unsigned x,
4520 unsigned y)
4521{
4522 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4523 return;
4524
4525 /* external cursor coords are 1-based; internal are 0-based */
4526 g_coord.X = x - 1;
4527 g_coord.Y = y - 1;
4528 SetConsoleCursorPosition(g_hConOut, g_coord);
4529}
4530
4531
4532/*
4533 * Set the current text attribute = (foreground | background)
4534 * See ../doc/os_win32.txt for the numbers.
4535 */
4536 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004537textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004538{
4539 g_attrCurrent = wAttr;
4540
4541 SetConsoleTextAttribute(g_hConOut, wAttr);
4542}
4543
4544
4545 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004546textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004547{
4548 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
4549
4550 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4551}
4552
4553
4554 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004555textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556{
4557 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
4558
4559 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4560}
4561
4562
4563/*
4564 * restore the default text attribute (whatever we started with)
4565 */
4566 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004567normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004568{
4569 textattr(g_attrDefault);
4570}
4571
4572
4573static WORD g_attrPreStandout = 0;
4574
4575/*
4576 * Make the text standout, by brightening it
4577 */
4578 static void
4579standout(void)
4580{
4581 g_attrPreStandout = g_attrCurrent;
4582 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
4583}
4584
4585
4586/*
4587 * Turn off standout mode
4588 */
4589 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004590standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004591{
4592 if (g_attrPreStandout)
4593 {
4594 textattr(g_attrPreStandout);
4595 g_attrPreStandout = 0;
4596 }
4597}
4598
4599
4600/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00004601 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004602 */
4603 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004604mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004605{
4606 char_u *p;
4607 int n;
4608
4609 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
4610 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
4611 if (T_ME[0] == ESC && T_ME[1] == '|')
4612 {
4613 p = T_ME + 2;
4614 n = getdigits(&p);
4615 if (*p == 'm' && n > 0)
4616 {
4617 cterm_normal_fg_color = (n & 0xf) + 1;
4618 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
4619 }
4620 }
4621}
4622
4623
4624/*
4625 * visual bell: flash the screen
4626 */
4627 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004628visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629{
4630 COORD coordOrigin = {0, 0};
4631 WORD attrFlash = ~g_attrCurrent & 0xff;
4632
4633 DWORD dwDummy;
4634 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
4635
4636 if (oldattrs == NULL)
4637 return;
4638 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4639 coordOrigin, &dwDummy);
4640 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
4641 coordOrigin, &dwDummy);
4642
4643 Sleep(15); /* wait for 15 msec */
4644 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4645 coordOrigin, &dwDummy);
4646 vim_free(oldattrs);
4647}
4648
4649
4650/*
4651 * Make the cursor visible or invisible
4652 */
4653 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004654cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004655{
4656 s_cursor_visible = fVisible;
4657#ifdef MCH_CURSOR_SHAPE
4658 mch_update_cursor();
4659#endif
4660}
4661
4662
4663/*
4664 * write `cchToWrite' characters in `pchBuf' to the screen
4665 * Returns the number of characters actually written (at least one).
4666 */
4667 static BOOL
4668write_chars(
4669 LPCSTR pchBuf,
4670 DWORD cchToWrite)
4671{
4672 COORD coord = g_coord;
4673 DWORD written;
4674
4675 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
4676 coord, &written);
4677 /* When writing fails or didn't write a single character, pretend one
4678 * character was written, otherwise we get stuck. */
4679 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
4680 coord, &written) == 0
4681 || written == 0)
4682 written = 1;
4683
4684 g_coord.X += (SHORT) written;
4685
4686 while (g_coord.X > g_srScrollRegion.Right)
4687 {
4688 g_coord.X -= (SHORT) Columns;
4689 if (g_coord.Y < g_srScrollRegion.Bottom)
4690 g_coord.Y++;
4691 }
4692
4693 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4694
4695 return written;
4696}
4697
4698
4699/*
4700 * mch_write(): write the output buffer to the screen, translating ESC
4701 * sequences into calls to console output routines.
4702 */
4703 void
4704mch_write(
4705 char_u *s,
4706 int len)
4707{
4708 s[len] = NUL;
4709
4710 if (!term_console)
4711 {
4712 write(1, s, (unsigned)len);
4713 return;
4714 }
4715
4716 /* translate ESC | sequences into faked bios calls */
4717 while (len--)
4718 {
4719 /* optimization: use one single write_chars for runs of text,
4720 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004721 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722
4723 if (p_wd)
4724 {
4725 WaitForChar(p_wd);
4726 if (prefix != 0)
4727 prefix = 1;
4728 }
4729
4730 if (prefix != 0)
4731 {
4732 DWORD nWritten;
4733
4734 nWritten = write_chars(s, prefix);
4735#ifdef MCH_WRITE_DUMP
4736 if (fdDump)
4737 {
4738 fputc('>', fdDump);
4739 fwrite(s, sizeof(char_u), nWritten, fdDump);
4740 fputs("<\n", fdDump);
4741 }
4742#endif
4743 len -= (nWritten - 1);
4744 s += nWritten;
4745 }
4746 else if (s[0] == '\n')
4747 {
4748 /* \n, newline: go to the beginning of the next line or scroll */
4749 if (g_coord.Y == g_srScrollRegion.Bottom)
4750 {
4751 scroll(1);
4752 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
4753 }
4754 else
4755 {
4756 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
4757 }
4758#ifdef MCH_WRITE_DUMP
4759 if (fdDump)
4760 fputs("\\n\n", fdDump);
4761#endif
4762 s++;
4763 }
4764 else if (s[0] == '\r')
4765 {
4766 /* \r, carriage return: go to beginning of line */
4767 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
4768#ifdef MCH_WRITE_DUMP
4769 if (fdDump)
4770 fputs("\\r\n", fdDump);
4771#endif
4772 s++;
4773 }
4774 else if (s[0] == '\b')
4775 {
4776 /* \b, backspace: move cursor one position left */
4777 if (g_coord.X > g_srScrollRegion.Left)
4778 g_coord.X--;
4779 else if (g_coord.Y > g_srScrollRegion.Top)
4780 {
4781 g_coord.X = g_srScrollRegion.Right;
4782 g_coord.Y--;
4783 }
4784 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4785#ifdef MCH_WRITE_DUMP
4786 if (fdDump)
4787 fputs("\\b\n", fdDump);
4788#endif
4789 s++;
4790 }
4791 else if (s[0] == '\a')
4792 {
4793 /* \a, bell */
4794 MessageBeep(0xFFFFFFFF);
4795#ifdef MCH_WRITE_DUMP
4796 if (fdDump)
4797 fputs("\\a\n", fdDump);
4798#endif
4799 s++;
4800 }
4801 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4802 {
4803#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004804 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004806 char_u *p;
4807 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004808
4809 switch (s[2])
4810 {
4811 /* one or two numeric arguments, separated by ';' */
4812
4813 case '0': case '1': case '2': case '3': case '4':
4814 case '5': case '6': case '7': case '8': case '9':
4815 p = s + 2;
4816 arg1 = getdigits(&p); /* no check for length! */
4817 if (p > s + len)
4818 break;
4819
4820 if (*p == ';')
4821 {
4822 ++p;
4823 arg2 = getdigits(&p); /* no check for length! */
4824 if (p > s + len)
4825 break;
4826
4827 if (*p == 'H')
4828 gotoxy(arg2, arg1);
4829 else if (*p == 'r')
4830 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4831 }
4832 else if (*p == 'A')
4833 {
4834 /* move cursor up arg1 lines in same column */
4835 gotoxy(g_coord.X + 1,
4836 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4837 }
4838 else if (*p == 'C')
4839 {
4840 /* move cursor right arg1 columns in same line */
4841 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4842 g_coord.Y + 1);
4843 }
4844 else if (*p == 'H')
4845 {
4846 gotoxy(1, arg1);
4847 }
4848 else if (*p == 'L')
4849 {
4850 insert_lines(arg1);
4851 }
4852 else if (*p == 'm')
4853 {
4854 if (arg1 == 0)
4855 normvideo();
4856 else
4857 textattr((WORD) arg1);
4858 }
4859 else if (*p == 'f')
4860 {
4861 textcolor((WORD) arg1);
4862 }
4863 else if (*p == 'b')
4864 {
4865 textbackground((WORD) arg1);
4866 }
4867 else if (*p == 'M')
4868 {
4869 delete_lines(arg1);
4870 }
4871
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004872 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 s = p + 1;
4874 break;
4875
4876
4877 /* Three-character escape sequences */
4878
4879 case 'A':
4880 /* move cursor up one line in same column */
4881 gotoxy(g_coord.X + 1,
4882 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4883 goto got3;
4884
4885 case 'B':
4886 visual_bell();
4887 goto got3;
4888
4889 case 'C':
4890 /* move cursor right one column in same line */
4891 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4892 g_coord.Y + 1);
4893 goto got3;
4894
4895 case 'E':
4896 termcap_mode_end();
4897 goto got3;
4898
4899 case 'F':
4900 standout();
4901 goto got3;
4902
4903 case 'f':
4904 standend();
4905 goto got3;
4906
4907 case 'H':
4908 gotoxy(1, 1);
4909 goto got3;
4910
4911 case 'j':
4912 clear_to_end_of_display();
4913 goto got3;
4914
4915 case 'J':
4916 clear_screen();
4917 goto got3;
4918
4919 case 'K':
4920 clear_to_end_of_line();
4921 goto got3;
4922
4923 case 'L':
4924 insert_lines(1);
4925 goto got3;
4926
4927 case 'M':
4928 delete_lines(1);
4929 goto got3;
4930
4931 case 'S':
4932 termcap_mode_start();
4933 goto got3;
4934
4935 case 'V':
4936 cursor_visible(TRUE);
4937 goto got3;
4938
4939 case 'v':
4940 cursor_visible(FALSE);
4941 goto got3;
4942
4943 got3:
4944 s += 3;
4945 len -= 2;
4946 }
4947
4948#ifdef MCH_WRITE_DUMP
4949 if (fdDump)
4950 {
4951 fputs("ESC | ", fdDump);
4952 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4953 fputc('\n', fdDump);
4954 }
4955#endif
4956 }
4957 else
4958 {
4959 /* Write a single character */
4960 DWORD nWritten;
4961
4962 nWritten = write_chars(s, 1);
4963#ifdef MCH_WRITE_DUMP
4964 if (fdDump)
4965 {
4966 fputc('>', fdDump);
4967 fwrite(s, sizeof(char_u), nWritten, fdDump);
4968 fputs("<\n", fdDump);
4969 }
4970#endif
4971
4972 len -= (nWritten - 1);
4973 s += nWritten;
4974 }
4975 }
4976
4977#ifdef MCH_WRITE_DUMP
4978 if (fdDump)
4979 fflush(fdDump);
4980#endif
4981}
4982
4983#endif /* FEAT_GUI_W32 */
4984
4985
4986/*
4987 * Delay for half a second.
4988 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004989/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004990 void
4991mch_delay(
4992 long msec,
4993 int ignoreinput)
4994{
4995#ifdef FEAT_GUI_W32
4996 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004997#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004998 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004999# ifdef FEAT_MZSCHEME
5000 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5001 {
5002 int towait = p_mzq;
5003
5004 /* if msec is large enough, wait by portions in p_mzq */
5005 while (msec > 0)
5006 {
5007 mzvim_check_threads();
5008 if (msec < towait)
5009 towait = msec;
5010 Sleep(towait);
5011 msec -= towait;
5012 }
5013 }
5014 else
5015# endif
5016 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017 else
5018 WaitForChar(msec);
5019#endif
5020}
5021
5022
5023/*
5024 * this version of remove is not scared by a readonly (backup) file
5025 * Return 0 for success, -1 for failure.
5026 */
5027 int
5028mch_remove(char_u *name)
5029{
5030#ifdef FEAT_MBYTE
5031 WCHAR *wn = NULL;
5032 int n;
5033
5034 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5035 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005036 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005037 if (wn != NULL)
5038 {
5039 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
5040 n = DeleteFileW(wn) ? 0 : -1;
5041 vim_free(wn);
5042 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5043 return n;
5044 /* Retry with non-wide function (for Windows 98). */
5045 }
5046 }
5047#endif
5048 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
5049 return DeleteFile(name) ? 0 : -1;
5050}
5051
5052
5053/*
5054 * check for an "interrupt signal": CTRL-break or CTRL-C
5055 */
5056 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005057mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005058{
5059#ifndef FEAT_GUI_W32 /* never used */
5060 if (g_fCtrlCPressed || g_fCBrkPressed)
5061 {
5062 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5063 got_int = TRUE;
5064 }
5065#endif
5066}
5067
5068
5069/*
Bram Moolenaar11b73d62012-06-29 15:51:30 +02005070 * How much memory is available in Kbyte?
Bram Moolenaar071d4272004-06-13 20:20:40 +00005071 * Return sum of available physical and page file memory.
5072 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005073/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005074 long_u
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005075mch_avail_mem(int special)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005076{
Bram Moolenaar1a0cee52012-07-19 11:37:26 +02005077#ifdef MEMORYSTATUSEX
5078 PlatformId();
5079 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5080 {
5081 MEMORYSTATUSEX ms;
5082
5083 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5084 * what fits in 32 bits. But it's not always available. */
5085 ms.dwLength = sizeof(MEMORYSTATUSEX);
5086 GlobalMemoryStatusEx(&ms);
5087 return (long_u)((ms.ullAvailPhys + ms.ullAvailPageFile) >> 10);
5088 }
5089 else
5090#endif
Bram Moolenaar11b73d62012-06-29 15:51:30 +02005091 {
5092 MEMORYSTATUS ms;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005093
Bram Moolenaar11b73d62012-06-29 15:51:30 +02005094 ms.dwLength = sizeof(MEMORYSTATUS);
5095 GlobalMemoryStatus(&ms);
5096 return (long_u)((ms.dwAvailPhys + ms.dwAvailPageFile) >> 10);
5097 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005098}
5099
5100#ifdef FEAT_MBYTE
5101/*
5102 * Same code as below, but with wide functions and no comments.
5103 * Return 0 for success, non-zero for failure.
5104 */
5105 int
5106mch_wrename(WCHAR *wold, WCHAR *wnew)
5107{
5108 WCHAR *p;
5109 int i;
5110 WCHAR szTempFile[_MAX_PATH + 1];
5111 WCHAR szNewPath[_MAX_PATH + 1];
5112 HANDLE hf;
5113
5114 if (!mch_windows95())
5115 {
5116 p = wold;
5117 for (i = 0; wold[i] != NUL; ++i)
5118 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5119 && wold[i + 1] != 0)
5120 p = wold + i + 1;
5121 if ((int)(wold + i - p) < 8 || p[6] != '~')
5122 return (MoveFileW(wold, wnew) == 0);
5123 }
5124
5125 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5126 return -1;
5127 *p = NUL;
5128
5129 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5130 return -2;
5131
5132 if (!DeleteFileW(szTempFile))
5133 return -3;
5134
5135 if (!MoveFileW(wold, szTempFile))
5136 return -4;
5137
5138 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5139 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5140 return -5;
5141 if (!CloseHandle(hf))
5142 return -6;
5143
5144 if (!MoveFileW(szTempFile, wnew))
5145 {
5146 (void)MoveFileW(szTempFile, wold);
5147 return -7;
5148 }
5149
5150 DeleteFileW(szTempFile);
5151
5152 if (!DeleteFileW(wold))
5153 return -8;
5154
5155 return 0;
5156}
5157#endif
5158
5159
5160/*
5161 * mch_rename() works around a bug in rename (aka MoveFile) in
5162 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5163 * file whose short file name is "FOO.BAR" (its long file name will
5164 * be correct: "foo.bar~"). Because a file can be accessed by
5165 * either its SFN or its LFN, "foo.bar" has effectively been
5166 * renamed to "foo.bar", which is not at all what was wanted. This
5167 * seems to happen only when renaming files with three-character
5168 * extensions by appending a suffix that does not include ".".
5169 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5170 *
5171 * There is another problem, which isn't really a bug but isn't right either:
5172 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5173 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5174 * service pack 6. Doesn't seem to happen on Windows 98.
5175 *
5176 * Like rename(), returns 0 upon success, non-zero upon failure.
5177 * Should probably set errno appropriately when errors occur.
5178 */
5179 int
5180mch_rename(
5181 const char *pszOldFile,
5182 const char *pszNewFile)
5183{
5184 char szTempFile[_MAX_PATH+1];
5185 char szNewPath[_MAX_PATH+1];
5186 char *pszFilePart;
5187 HANDLE hf;
5188#ifdef FEAT_MBYTE
5189 WCHAR *wold = NULL;
5190 WCHAR *wnew = NULL;
5191 int retval = -1;
5192
5193 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5194 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005195 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5196 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197 if (wold != NULL && wnew != NULL)
5198 retval = mch_wrename(wold, wnew);
5199 vim_free(wold);
5200 vim_free(wnew);
5201 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5202 return retval;
5203 /* Retry with non-wide function (for Windows 98). */
5204 }
5205#endif
5206
5207 /*
5208 * No need to play tricks if not running Windows 95, unless the file name
5209 * contains a "~" as the seventh character.
5210 */
5211 if (!mch_windows95())
5212 {
5213 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5214 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5215 return rename(pszOldFile, pszNewFile);
5216 }
5217
5218 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5219 * a directory, no error is returned and pszFilePart will be NULL. */
5220 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5221 || pszFilePart == NULL)
5222 return -1;
5223 *pszFilePart = NUL;
5224
5225 /* Get (and create) a unique temporary file name in directory of new file */
5226 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5227 return -2;
5228
5229 /* blow the temp file away */
5230 if (!DeleteFile(szTempFile))
5231 return -3;
5232
5233 /* rename old file to the temp file */
5234 if (!MoveFile(pszOldFile, szTempFile))
5235 return -4;
5236
5237 /* now create an empty file called pszOldFile; this prevents the operating
5238 * system using pszOldFile as an alias (SFN) if we're renaming within the
5239 * same directory. For example, we're editing a file called
5240 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5241 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5242 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005243 * cause all sorts of problems later in buf_write(). So, we create an
5244 * empty file called filena~1.txt and the system will have to find some
5245 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246 */
5247 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5248 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5249 return -5;
5250 if (!CloseHandle(hf))
5251 return -6;
5252
5253 /* rename the temp file to the new file */
5254 if (!MoveFile(szTempFile, pszNewFile))
5255 {
5256 /* Renaming failed. Rename the file back to its old name, so that it
5257 * looks like nothing happened. */
5258 (void)MoveFile(szTempFile, pszOldFile);
5259
5260 return -7;
5261 }
5262
5263 /* Seems to be left around on Novell filesystems */
5264 DeleteFile(szTempFile);
5265
5266 /* finally, remove the empty old file */
5267 if (!DeleteFile(pszOldFile))
5268 return -8;
5269
5270 return 0; /* success */
5271}
5272
5273/*
5274 * Get the default shell for the current hardware platform
5275 */
5276 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005277default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005278{
5279 char* psz = NULL;
5280
5281 PlatformId();
5282
5283 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5284 psz = "cmd.exe";
5285 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5286 psz = "command.com";
5287
5288 return psz;
5289}
5290
5291/*
5292 * mch_access() extends access() to do more detailed check on network drives.
5293 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5294 */
5295 int
5296mch_access(char *n, int p)
5297{
5298 HANDLE hFile;
5299 DWORD am;
5300 int retval = -1; /* default: fail */
5301#ifdef FEAT_MBYTE
5302 WCHAR *wn = NULL;
5303
5304 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005305 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005306#endif
5307
5308 if (mch_isdir(n))
5309 {
5310 char TempName[_MAX_PATH + 16] = "";
5311#ifdef FEAT_MBYTE
5312 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5313#endif
5314
5315 if (p & R_OK)
5316 {
5317 /* Read check is performed by seeing if we can do a find file on
5318 * the directory for any file. */
5319#ifdef FEAT_MBYTE
5320 if (wn != NULL)
5321 {
5322 int i;
5323 WIN32_FIND_DATAW d;
5324
5325 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5326 TempNameW[i] = wn[i];
5327 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5328 TempNameW[i++] = '\\';
5329 TempNameW[i++] = '*';
5330 TempNameW[i++] = 0;
5331
5332 hFile = FindFirstFileW(TempNameW, &d);
5333 if (hFile == INVALID_HANDLE_VALUE)
5334 {
5335 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5336 goto getout;
5337
5338 /* Retry with non-wide function (for Windows 98). */
5339 vim_free(wn);
5340 wn = NULL;
5341 }
5342 else
5343 (void)FindClose(hFile);
5344 }
5345 if (wn == NULL)
5346#endif
5347 {
5348 char *pch;
5349 WIN32_FIND_DATA d;
5350
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005351 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005352 pch = TempName + STRLEN(TempName) - 1;
5353 if (*pch != '\\' && *pch != '/')
5354 *++pch = '\\';
5355 *++pch = '*';
5356 *++pch = NUL;
5357
5358 hFile = FindFirstFile(TempName, &d);
5359 if (hFile == INVALID_HANDLE_VALUE)
5360 goto getout;
5361 (void)FindClose(hFile);
5362 }
5363 }
5364
5365 if (p & W_OK)
5366 {
5367 /* Trying to create a temporary file in the directory should catch
5368 * directories on read-only network shares. However, in
5369 * directories whose ACL allows writes but denies deletes will end
5370 * up keeping the temporary file :-(. */
5371#ifdef FEAT_MBYTE
5372 if (wn != NULL)
5373 {
5374 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5375 {
5376 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5377 goto getout;
5378
5379 /* Retry with non-wide function (for Windows 98). */
5380 vim_free(wn);
5381 wn = NULL;
5382 }
5383 else
5384 DeleteFileW(TempNameW);
5385 }
5386 if (wn == NULL)
5387#endif
5388 {
5389 if (!GetTempFileName(n, "VIM", 0, TempName))
5390 goto getout;
5391 mch_remove((char_u *)TempName);
5392 }
5393 }
5394 }
5395 else
5396 {
5397 /* Trying to open the file for the required access does ACL, read-only
5398 * network share, and file attribute checks. */
5399 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5400 | ((p & R_OK) ? GENERIC_READ : 0);
5401#ifdef FEAT_MBYTE
5402 if (wn != NULL)
5403 {
5404 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5405 if (hFile == INVALID_HANDLE_VALUE
5406 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5407 {
5408 /* Retry with non-wide function (for Windows 98). */
5409 vim_free(wn);
5410 wn = NULL;
5411 }
5412 }
5413 if (wn == NULL)
5414#endif
5415 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5416 if (hFile == INVALID_HANDLE_VALUE)
5417 goto getout;
5418 CloseHandle(hFile);
5419 }
5420
5421 retval = 0; /* success */
5422getout:
5423#ifdef FEAT_MBYTE
5424 vim_free(wn);
5425#endif
5426 return retval;
5427}
5428
5429#if defined(FEAT_MBYTE) || defined(PROTO)
5430/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005431 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005432 */
5433 int
5434mch_open(char *name, int flags, int mode)
5435{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005436 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5437# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005438 WCHAR *wn;
5439 int f;
5440
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005441 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005442 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005443 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005444 if (wn != NULL)
5445 {
5446 f = _wopen(wn, flags, mode);
5447 vim_free(wn);
5448 if (f >= 0)
5449 return f;
5450 /* Retry with non-wide function (for Windows 98). Can't use
5451 * GetLastError() here and it's unclear what errno gets set to if
5452 * the _wopen() fails for missing wide functions. */
5453 }
5454 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005455# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005456
5457 return open(name, flags, mode);
5458}
5459
5460/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005461 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005462 */
5463 FILE *
5464mch_fopen(char *name, char *mode)
5465{
5466 WCHAR *wn, *wm;
5467 FILE *f = NULL;
5468
5469 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5470# ifdef __BORLANDC__
5471 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5472 && g_PlatformId == VER_PLATFORM_WIN32_NT
5473# endif
5474 )
5475 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005476# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005477 /* Work around an annoying assertion in the Microsoft debug CRT
5478 * when mode's text/binary setting doesn't match _get_fmode(). */
5479 char newMode = mode[strlen(mode) - 1];
5480 int oldMode = 0;
5481
5482 _get_fmode(&oldMode);
5483 if (newMode == 't')
5484 _set_fmode(_O_TEXT);
5485 else if (newMode == 'b')
5486 _set_fmode(_O_BINARY);
5487# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005488 wn = enc_to_utf16(name, NULL);
5489 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490 if (wn != NULL && wm != NULL)
5491 f = _wfopen(wn, wm);
5492 vim_free(wn);
5493 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005494
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005495# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005496 _set_fmode(oldMode);
5497# endif
5498
Bram Moolenaar071d4272004-06-13 20:20:40 +00005499 if (f != NULL)
5500 return f;
5501 /* Retry with non-wide function (for Windows 98). Can't use
5502 * GetLastError() here and it's unclear what errno gets set to if
5503 * the _wfopen() fails for missing wide functions. */
5504 }
5505
5506 return fopen(name, mode);
5507}
5508#endif
5509
5510#ifdef FEAT_MBYTE
5511/*
5512 * SUB STREAM (aka info stream) handling:
5513 *
5514 * NTFS can have sub streams for each file. Normal contents of file is
5515 * stored in the main stream, and extra contents (author information and
5516 * title and so on) can be stored in sub stream. After Windows 2000, user
5517 * can access and store those informations in sub streams via explorer's
5518 * property menuitem in right click menu. Those informations in sub streams
5519 * were lost when copying only the main stream. So we have to copy sub
5520 * streams.
5521 *
5522 * Incomplete explanation:
5523 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5524 * More useful info and an example:
5525 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5526 */
5527
5528/*
5529 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5530 * and write to stream "substream" of file "to".
5531 * Errors are ignored.
5532 */
5533 static void
5534copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5535{
5536 HANDLE hTo;
5537 WCHAR *to_name;
5538
5539 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5540 wcscpy(to_name, to);
5541 wcscat(to_name, substream);
5542
5543 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5544 FILE_ATTRIBUTE_NORMAL, NULL);
5545 if (hTo != INVALID_HANDLE_VALUE)
5546 {
5547 long done;
5548 DWORD todo;
5549 DWORD readcnt, written;
5550 char buf[4096];
5551
5552 /* Copy block of bytes at a time. Abort when something goes wrong. */
5553 for (done = 0; done < len; done += written)
5554 {
5555 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005556 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5557 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5559 FALSE, FALSE, context)
5560 || readcnt != todo
5561 || !WriteFile(hTo, buf, todo, &written, NULL)
5562 || written != todo)
5563 break;
5564 }
5565 CloseHandle(hTo);
5566 }
5567
5568 free(to_name);
5569}
5570
5571/*
5572 * Copy info streams from file "from" to file "to".
5573 */
5574 static void
5575copy_infostreams(char_u *from, char_u *to)
5576{
5577 WCHAR *fromw;
5578 WCHAR *tow;
5579 HANDLE sh;
5580 WIN32_STREAM_ID sid;
5581 int headersize;
5582 WCHAR streamname[_MAX_PATH];
5583 DWORD readcount;
5584 void *context = NULL;
5585 DWORD lo, hi;
5586 int len;
5587
5588 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005589 fromw = enc_to_utf16(from, NULL);
5590 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591 if (fromw != NULL && tow != NULL)
5592 {
5593 /* Open the file for reading. */
5594 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
5595 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5596 if (sh != INVALID_HANDLE_VALUE)
5597 {
5598 /* Use BackupRead() to find the info streams. Repeat until we
5599 * have done them all.*/
5600 for (;;)
5601 {
5602 /* Get the header to find the length of the stream name. If
5603 * the "readcount" is zero we have done all info streams. */
5604 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005605 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005606 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
5607 &readcount, FALSE, FALSE, &context)
5608 || readcount == 0)
5609 break;
5610
5611 /* We only deal with streams that have a name. The normal
5612 * file data appears to be without a name, even though docs
5613 * suggest it is called "::$DATA". */
5614 if (sid.dwStreamNameSize > 0)
5615 {
5616 /* Read the stream name. */
5617 if (!BackupRead(sh, (LPBYTE)streamname,
5618 sid.dwStreamNameSize,
5619 &readcount, FALSE, FALSE, &context))
5620 break;
5621
5622 /* Copy an info stream with a name ":anything:$DATA".
5623 * Skip "::$DATA", it has no stream name (examples suggest
5624 * it might be used for the normal file contents).
5625 * Note that BackupRead() counts bytes, but the name is in
5626 * wide characters. */
5627 len = readcount / sizeof(WCHAR);
5628 streamname[len] = 0;
5629 if (len > 7 && wcsicmp(streamname + len - 6,
5630 L":$DATA") == 0)
5631 {
5632 streamname[len - 6] = 0;
5633 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00005634 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635 }
5636 }
5637
5638 /* Advance to the next stream. We might try seeking too far,
5639 * but BackupSeek() doesn't skip over stream borders, thus
5640 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005641 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 &lo, &hi, &context);
5643 }
5644
5645 /* Clear the context. */
5646 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
5647
5648 CloseHandle(sh);
5649 }
5650 }
5651 vim_free(fromw);
5652 vim_free(tow);
5653}
5654#endif
5655
5656/*
5657 * Copy file attributes from file "from" to file "to".
5658 * For Windows NT and later we copy info streams.
5659 * Always returns zero, errors are ignored.
5660 */
5661 int
5662mch_copy_file_attribute(char_u *from, char_u *to)
5663{
5664#ifdef FEAT_MBYTE
5665 /* File streams only work on Windows NT and later. */
5666 PlatformId();
5667 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5668 copy_infostreams(from, to);
5669#endif
5670 return 0;
5671}
5672
5673#if defined(MYRESETSTKOFLW) || defined(PROTO)
5674/*
5675 * Recreate a destroyed stack guard page in win32.
5676 * Written by Benjamin Peterson.
5677 */
5678
5679/* These magic numbers are from the MS header files */
5680#define MIN_STACK_WIN9X 17
5681#define MIN_STACK_WINNT 2
5682
5683/*
5684 * This function does the same thing as _resetstkoflw(), which is only
5685 * available in DevStudio .net and later.
5686 * Returns 0 for failure, 1 for success.
5687 */
5688 int
5689myresetstkoflw(void)
5690{
5691 BYTE *pStackPtr;
5692 BYTE *pGuardPage;
5693 BYTE *pStackBase;
5694 BYTE *pLowestPossiblePage;
5695 MEMORY_BASIC_INFORMATION mbi;
5696 SYSTEM_INFO si;
5697 DWORD nPageSize;
5698 DWORD dummy;
5699
5700 /* This code will not work on win32s. */
5701 PlatformId();
5702 if (g_PlatformId == VER_PLATFORM_WIN32s)
5703 return 0;
5704
5705 /* We need to know the system page size. */
5706 GetSystemInfo(&si);
5707 nPageSize = si.dwPageSize;
5708
5709 /* ...and the current stack pointer */
5710 pStackPtr = (BYTE*)_alloca(1);
5711
5712 /* ...and the base of the stack. */
5713 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
5714 return 0;
5715 pStackBase = (BYTE*)mbi.AllocationBase;
5716
5717 /* ...and the page thats min_stack_req pages away from stack base; this is
5718 * the lowest page we could use. */
5719 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
5720 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
5721
5722 /* On Win95, we want the next page down from the end of the stack. */
5723 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
5724 {
5725 /* Find the page that's only 1 page down from the page that the stack
5726 * ptr is in. */
5727 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
5728 / (DWORD)nPageSize) - 1));
5729 if (pGuardPage < pLowestPossiblePage)
5730 return 0;
5731
5732 /* Apply the noaccess attribute to the page -- there's no guard
5733 * attribute in win95-type OSes. */
5734 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
5735 return 0;
5736 }
5737 else
5738 {
5739 /* On NT, however, we want the first committed page in the stack Start
5740 * at the stack base and move forward through memory until we find a
5741 * committed block. */
5742 BYTE *pBlock = pStackBase;
5743
Bram Moolenaara466c992005-07-09 21:03:22 +00005744 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745 {
5746 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
5747 return 0;
5748
5749 pBlock += mbi.RegionSize;
5750
5751 if (mbi.State & MEM_COMMIT)
5752 break;
5753 }
5754
5755 /* mbi now describes the first committed block in the stack. */
5756 if (mbi.Protect & PAGE_GUARD)
5757 return 1;
5758
5759 /* decide where the guard page should start */
5760 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
5761 pGuardPage = pLowestPossiblePage;
5762 else
5763 pGuardPage = (BYTE*)mbi.BaseAddress;
5764
5765 /* allocate the guard page */
5766 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
5767 return 0;
5768
5769 /* apply the guard attribute to the page */
5770 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
5771 &dummy))
5772 return 0;
5773 }
5774
5775 return 1;
5776}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005777#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005778
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005779
5780#if defined(FEAT_MBYTE) || defined(PROTO)
5781/*
5782 * The command line arguments in UCS2
5783 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005784static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005785static LPWSTR *ArglistW = NULL;
5786static int global_argc = 0;
5787static char **global_argv;
5788
5789static int used_file_argc = 0; /* last argument in global_argv[] used
5790 for the argument list. */
5791static int *used_file_indexes = NULL; /* indexes in global_argv[] for
5792 command line arguments added to
5793 the argument list */
5794static int used_file_count = 0; /* nr of entries in used_file_indexes */
5795static int used_file_literal = FALSE; /* take file names literally */
5796static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005797static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005798static int used_alist_count = 0;
5799
5800
5801/*
5802 * Get the command line arguments. Unicode version.
5803 * Returns argc. Zero when something fails.
5804 */
5805 int
5806get_cmd_argsW(char ***argvp)
5807{
5808 char **argv = NULL;
5809 int argc = 0;
5810 int i;
5811
5812 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5813 if (ArglistW != NULL)
5814 {
5815 argv = malloc((nArgsW + 1) * sizeof(char *));
5816 if (argv != NULL)
5817 {
5818 argc = nArgsW;
5819 argv[argc] = NULL;
5820 for (i = 0; i < argc; ++i)
5821 {
5822 int len;
5823
5824 /* Convert each Unicode argument to the current codepage. */
5825 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005826 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005827 (LPSTR *)&argv[i], &len, 0, 0);
5828 if (argv[i] == NULL)
5829 {
5830 /* Out of memory, clear everything. */
5831 while (i > 0)
5832 free(argv[--i]);
5833 free(argv);
5834 argc = 0;
5835 }
5836 }
5837 }
5838 }
5839
5840 global_argc = argc;
5841 global_argv = argv;
5842 if (argc > 0)
5843 used_file_indexes = malloc(argc * sizeof(int));
5844
5845 if (argvp != NULL)
5846 *argvp = argv;
5847 return argc;
5848}
5849
5850 void
5851free_cmd_argsW(void)
5852{
5853 if (ArglistW != NULL)
5854 {
5855 GlobalFree(ArglistW);
5856 ArglistW = NULL;
5857 }
5858}
5859
5860/*
5861 * Remember "name" is an argument that was added to the argument list.
5862 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5863 * is called.
5864 */
5865 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005866used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005867{
5868 int i;
5869
5870 if (used_file_indexes == NULL)
5871 return;
5872 for (i = used_file_argc + 1; i < global_argc; ++i)
5873 if (STRCMP(global_argv[i], name) == 0)
5874 {
5875 used_file_argc = i;
5876 used_file_indexes[used_file_count++] = i;
5877 break;
5878 }
5879 used_file_literal = literal;
5880 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005881 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005882}
5883
5884/*
5885 * Remember the length of the argument list as it was. If it changes then we
5886 * leave it alone when 'encoding' is set.
5887 */
5888 void
5889set_alist_count(void)
5890{
5891 used_alist_count = GARGCOUNT;
5892}
5893
5894/*
5895 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5896 * has been changed while starting up. Use the UCS-2 command line arguments
5897 * and convert them to 'encoding'.
5898 */
5899 void
5900fix_arg_enc(void)
5901{
5902 int i;
5903 int idx;
5904 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005905 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005906
5907 /* Safety checks:
5908 * - if argument count differs between the wide and non-wide argument
5909 * list, something must be wrong.
5910 * - the file name arguments must have been located.
5911 * - the length of the argument list wasn't changed by the user.
5912 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005913 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005914 || ArglistW == NULL
5915 || used_file_indexes == NULL
5916 || used_file_count == 0
5917 || used_alist_count != GARGCOUNT)
5918 return;
5919
Bram Moolenaar86b68352004-12-27 21:59:20 +00005920 /* Remember the buffer numbers for the arguments. */
5921 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5922 if (fnum_list == NULL)
5923 return; /* out of memory */
5924 for (i = 0; i < GARGCOUNT; ++i)
5925 fnum_list[i] = GARGLIST[i].ae_fnum;
5926
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005927 /* Clear the argument list. Make room for the new arguments. */
5928 alist_clear(&global_alist);
5929 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005930 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005931
5932 for (i = 0; i < used_file_count; ++i)
5933 {
5934 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005935 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005936 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005937 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005938#ifdef FEAT_DIFF
5939 /* When using diff mode may need to concatenate file name to
5940 * directory name. Just like it's done in main(). */
5941 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5942 && !mch_isdir(alist_name(&GARGLIST[0])))
5943 {
5944 char_u *r;
5945
5946 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5947 if (r != NULL)
5948 {
5949 vim_free(str);
5950 str = r;
5951 }
5952 }
5953#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005954 /* Re-use the old buffer by renaming it. When not using literal
5955 * names it's done by alist_expand() below. */
5956 if (used_file_literal)
5957 buf_set_name(fnum_list[i], str);
5958
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005959 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005960 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005961 }
5962
5963 if (!used_file_literal)
5964 {
5965 /* Now expand wildcards in the arguments. */
5966 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5967 * filename characters but are excluded from 'isfname' to make
5968 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5969 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005970 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005971 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5972 }
5973
5974 /* If wildcard expansion failed, we are editing the first file of the
5975 * arglist and there is no file name: Edit the first argument now. */
5976 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5977 {
5978 do_cmdline_cmd((char_u *)":rewind");
5979 if (GARGCOUNT == 1 && used_file_full_path)
5980 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5981 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005982
5983 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005984}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005985#endif