blob: 520a09544d5860ffe0449a6839da26feccd5b440 [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>
32#include <process.h>
33
34#undef chdir
35#ifdef __GNUC__
36# ifndef __MINGW32__
37# include <dirent.h>
38# endif
39#else
40# include <direct.h>
41#endif
42
43#if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
44# include <shellapi.h>
45#endif
46
47#ifdef __MINGW32__
48# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
49# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
50# endif
51# ifndef RIGHTMOST_BUTTON_PRESSED
52# define RIGHTMOST_BUTTON_PRESSED 0x0002
53# endif
54# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
55# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
56# endif
57# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
58# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
59# endif
60# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
61# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
62# endif
63
64/*
65 * EventFlags
66 */
67# ifndef MOUSE_MOVED
68# define MOUSE_MOVED 0x0001
69# endif
70# ifndef DOUBLE_CLICK
71# define DOUBLE_CLICK 0x0002
72# endif
73#endif
74
75/* Record all output and all keyboard & mouse input */
76/* #define MCH_WRITE_DUMP */
77
78#ifdef MCH_WRITE_DUMP
79FILE* fdDump = NULL;
80#endif
81
82/*
83 * When generating prototypes for Win32 on Unix, these lines make the syntax
84 * errors disappear. They do not need to be correct.
85 */
86#ifdef PROTO
87#define WINAPI
88#define WINBASEAPI
89typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000090typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000091typedef int ACCESS_MASK;
92typedef int BOOL;
93typedef int COLORREF;
94typedef int CONSOLE_CURSOR_INFO;
95typedef int COORD;
96typedef int DWORD;
97typedef int HANDLE;
98typedef int HDC;
99typedef int HFONT;
100typedef int HICON;
101typedef int HINSTANCE;
102typedef int HWND;
103typedef int INPUT_RECORD;
104typedef int KEY_EVENT_RECORD;
105typedef int LOGFONT;
106typedef int LPBOOL;
107typedef int LPCTSTR;
108typedef int LPDWORD;
109typedef int LPSTR;
110typedef int LPTSTR;
111typedef int LPVOID;
112typedef int MOUSE_EVENT_RECORD;
113typedef int PACL;
114typedef int PDWORD;
115typedef int PHANDLE;
116typedef int PRINTDLG;
117typedef int PSECURITY_DESCRIPTOR;
118typedef int PSID;
119typedef int SECURITY_INFORMATION;
120typedef int SHORT;
121typedef int SMALL_RECT;
122typedef int TEXTMETRIC;
123typedef int TOKEN_INFORMATION_CLASS;
124typedef int TRUSTEE;
125typedef int WORD;
126typedef int WCHAR;
127typedef void VOID;
128#endif
129
130#ifndef FEAT_GUI_W32
131/* Undocumented API in kernel32.dll needed to work around dead key bug in
132 * console-mode applications in NT 4.0. If you switch keyboard layouts
133 * in a console app to a layout that includes dead keys and then hit a
134 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
135 * and Michael Dietrich for helping me figure out this workaround.
136 */
137
138/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
139#ifndef WINBASEAPI
140# define WINBASEAPI __stdcall
141#endif
142#if defined(__BORLANDC__)
143typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
144#else
145typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
146#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000147static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
150#if defined(__BORLANDC__)
151/* Strangely Borland uses a non-standard name. */
152# define wcsicmp(a, b) wcscmpi((a), (b))
153#endif
154
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200155/* Enable common dialogs input unicode from IME if posible. */
156#ifdef FEAT_MBYTE
157LRESULT (WINAPI *pDispatchMessage)(LPMSG) = DispatchMessage;
158BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
159BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
160BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
161#endif
162
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163#ifndef FEAT_GUI_W32
164/* Win32 Console handles for input and output */
165static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
166static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
167
168/* Win32 Screen buffer,coordinate,console I/O information */
169static SMALL_RECT g_srScrollRegion;
170static COORD g_coord; /* 0-based, but external coords are 1-based */
171
172/* The attribute of the screen when the editor was started */
173static WORD g_attrDefault = 7; /* lightgray text on black background */
174static WORD g_attrCurrent;
175
176static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
177static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
178static int g_fForceExit = FALSE; /* set when forcefully exiting */
179
180static void termcap_mode_start(void);
181static void termcap_mode_end(void);
182static void clear_chars(COORD coord, DWORD n);
183static void clear_screen(void);
184static void clear_to_end_of_display(void);
185static void clear_to_end_of_line(void);
186static void scroll(unsigned cLines);
187static void set_scroll_region(unsigned left, unsigned top,
188 unsigned right, unsigned bottom);
189static void insert_lines(unsigned cLines);
190static void delete_lines(unsigned cLines);
191static void gotoxy(unsigned x, unsigned y);
192static void normvideo(void);
193static void textattr(WORD wAttr);
194static void textcolor(WORD wAttr);
195static void textbackground(WORD wAttr);
196static void standout(void);
197static void standend(void);
198static void visual_bell(void);
199static void cursor_visible(BOOL fVisible);
200static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
201static char_u tgetch(int *pmodifiers, char_u *pch2);
202static void create_conin(void);
203static int s_cursor_visible = TRUE;
204static int did_create_conin = FALSE;
205#else
206static int s_dont_use_vimrun = TRUE;
207static int need_vimrun_warning = FALSE;
208static char *vimrun_path = "vimrun ";
209#endif
210
211#ifndef FEAT_GUI_W32
212static int suppress_winsize = 1; /* don't fiddle with console */
213#endif
214
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200215static char_u *exe_path = NULL;
216
Bram Moolenaar071d4272004-06-13 20:20:40 +0000217 static void
218get_exe_name(void)
219{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100220 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
221 * as the maximum length that works (plus a NUL byte). */
222#define MAX_ENV_PATH_LEN 8192
223 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200224 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000225
226 if (exe_name == NULL)
227 {
228 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100229 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000230 if (*temp != NUL)
231 exe_name = FullName_save((char_u *)temp, FALSE);
232 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000233
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200234 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000235 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200236 exe_path = vim_strnsave(exe_name,
237 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200238 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000239 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200240 /* Append our starting directory to $PATH, so that when doing
241 * "!xxd" it's found in our starting directory. Needed because
242 * SearchPath() also looks there. */
243 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100244 if (p == NULL
245 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200246 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100247 if (p == NULL || *p == NUL)
248 temp[0] = NUL;
249 else
250 {
251 STRCPY(temp, p);
252 STRCAT(temp, ";");
253 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200254 STRCAT(temp, exe_path);
255 vim_setenv((char_u *)"PATH", temp);
256 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000257 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000258 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000259}
260
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200261/*
262 * Load library "name".
263 */
264 HINSTANCE
265vimLoadLib(char *name)
266{
267 HINSTANCE dll = NULL;
268 char old_dir[MAXPATHL];
269
270 if (exe_path == NULL)
271 get_exe_name();
272 if (exe_path != NULL && mch_dirname(old_dir, MAXPATHL) == OK)
273 {
274 /* Change directory to where the executable is, both to make sure we
275 * find a .dll there and to avoid looking for a .dll in the current
276 * directory. */
277 mch_chdir(exe_path);
278 dll = LoadLibrary(name);
279 mch_chdir(old_dir);
280 }
281 return dll;
282}
283
Bram Moolenaar071d4272004-06-13 20:20:40 +0000284#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
285# ifndef GETTEXT_DLL
286# define GETTEXT_DLL "libintl.dll"
287# endif
288/* Dummy funcitons */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000289static char *null_libintl_gettext(const char *);
290static char *null_libintl_textdomain(const char *);
291static char *null_libintl_bindtextdomain(const char *, const char *);
292static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000293
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200294static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000295char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
296char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
297char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000298 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000299char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
300 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000301
302 int
303dyn_libintl_init(char *libname)
304{
305 int i;
306 static struct
307 {
308 char *name;
309 FARPROC *ptr;
310 } libintl_entry[] =
311 {
312 {"gettext", (FARPROC*)&dyn_libintl_gettext},
313 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
314 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
315 {NULL, NULL}
316 };
317
318 /* No need to initialize twice. */
319 if (hLibintlDLL)
320 return 1;
321 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200322 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000323 if (!hLibintlDLL)
324 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200325 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000326 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200327 verbose_enter();
328 EMSG2(_(e_loadlib), GETTEXT_DLL);
329 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000330 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200331 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000332 }
333 for (i = 0; libintl_entry[i].name != NULL
334 && libintl_entry[i].ptr != NULL; ++i)
335 {
336 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
337 libintl_entry[i].name)) == NULL)
338 {
339 dyn_libintl_end();
340 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000341 {
342 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000343 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000344 verbose_leave();
345 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346 return 0;
347 }
348 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000349
350 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000351 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000352 "bind_textdomain_codeset");
353 if (dyn_libintl_bind_textdomain_codeset == NULL)
354 dyn_libintl_bind_textdomain_codeset =
355 null_libintl_bind_textdomain_codeset;
356
Bram Moolenaar071d4272004-06-13 20:20:40 +0000357 return 1;
358}
359
360 void
361dyn_libintl_end()
362{
363 if (hLibintlDLL)
364 FreeLibrary(hLibintlDLL);
365 hLibintlDLL = NULL;
366 dyn_libintl_gettext = null_libintl_gettext;
367 dyn_libintl_textdomain = null_libintl_textdomain;
368 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000369 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000370}
371
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000372/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000374null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000375{
376 return (char*)msgid;
377}
378
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000379/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000380 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000381null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000382{
383 return NULL;
384}
385
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000386/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000387 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000388null_libintl_bind_textdomain_codeset(const char *domainname,
389 const char *codeset)
390{
391 return NULL;
392}
393
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000394/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000395 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000396null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397{
398 return NULL;
399}
400
401#endif /* DYNAMIC_GETTEXT */
402
403/* This symbol is not defined in older versions of the SDK or Visual C++ */
404
405#ifndef VER_PLATFORM_WIN32_WINDOWS
406# define VER_PLATFORM_WIN32_WINDOWS 1
407#endif
408
409DWORD g_PlatformId;
410
411#ifdef HAVE_ACL
412# include <aclapi.h>
413/*
414 * These are needed to dynamically load the ADVAPI DLL, which is not
415 * implemented under Windows 95 (and causes VIM to crash)
416 */
417typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
418 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
419typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
420 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
421 PSECURITY_DESCRIPTOR *);
422
423static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
424static PSNSECINFO pSetNamedSecurityInfo;
425static PGNSECINFO pGetNamedSecurityInfo;
426#endif
427
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200428typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
429
430static BOOL allowPiping = FALSE;
431static PSETHANDLEINFORMATION pSetHandleInformation;
432
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433/*
434 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
435 * VER_PLATFORM_WIN32_WINDOWS (Win95).
436 */
437 void
438PlatformId(void)
439{
440 static int done = FALSE;
441
442 if (!done)
443 {
444 OSVERSIONINFO ovi;
445
446 ovi.dwOSVersionInfoSize = sizeof(ovi);
447 GetVersionEx(&ovi);
448
449 g_PlatformId = ovi.dwPlatformId;
450
451#ifdef HAVE_ACL
452 /*
453 * Load the ADVAPI runtime if we are on anything
454 * other than Windows 95
455 */
456 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
457 {
458 /*
459 * do this load. Problems: Doesn't unload at end of run (this is
460 * theoretically okay, since Windows should unload it when VIM
461 * terminates). Should we be using the 'mch_libcall' routines?
462 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
463 * time we verify security...
464 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200465 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000466 if (advapi_lib != NULL)
467 {
468 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
469 "SetNamedSecurityInfoA");
470 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
471 "GetNamedSecurityInfoA");
472 if (pSetNamedSecurityInfo == NULL
473 || pGetNamedSecurityInfo == NULL)
474 {
475 /* If we can't get the function addresses, set advapi_lib
476 * to NULL so that we don't use them. */
477 FreeLibrary(advapi_lib);
478 advapi_lib = NULL;
479 }
480 }
481 }
482#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200483 /*
484 * If we are on windows NT, try to load the pipe functions, only
485 * available from Win2K.
486 */
487 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
488 {
489 HANDLE kernel32 = GetModuleHandle("kernel32");
490 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
491 kernel32, "SetHandleInformation");
492
493 allowPiping = pSetHandleInformation != NULL;
494 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495 done = TRUE;
496 }
497}
498
499/*
500 * Return TRUE when running on Windows 95 (or 98 or ME).
501 * Only to be used after mch_init().
502 */
503 int
504mch_windows95(void)
505{
506 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
507}
508
509#ifdef FEAT_GUI_W32
510/*
511 * Used to work around the "can't do synchronous spawn"
512 * problem on Win32s, without resorting to Universal Thunk.
513 */
514static int old_num_windows;
515static int num_windows;
516
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000517/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000518 static BOOL CALLBACK
519win32ssynch_cb(HWND hwnd, LPARAM lparam)
520{
521 num_windows++;
522 return TRUE;
523}
524#endif
525
526#ifndef FEAT_GUI_W32
527
528#define SHIFT (SHIFT_PRESSED)
529#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
530#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
531#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
532
533
534/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
535 * We map function keys to their ANSI terminal equivalents, as produced
536 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
537 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
538 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
539 * combinations of function/arrow/etc keys.
540 */
541
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000542static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000543{
544 WORD wVirtKey;
545 BOOL fAnsiKey;
546 int chAlone;
547 int chShift;
548 int chCtrl;
549 int chAlt;
550} VirtKeyMap[] =
551{
552
553/* Key ANSI alone shift ctrl alt */
554 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
555
556 { VK_F1, TRUE, ';', 'T', '^', 'h', },
557 { VK_F2, TRUE, '<', 'U', '_', 'i', },
558 { VK_F3, TRUE, '=', 'V', '`', 'j', },
559 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
560 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
561 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
562 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
563 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
564 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
565 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
566 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
567 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
568
569 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
570 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
571 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
572 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
573 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
574 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
575 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
576 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
577 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
578 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
579
580 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
581
582#if 0
583 /* Most people don't have F13-F20, but what the hell... */
584 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
585 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
586 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
587 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
588 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
589 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
590 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
591 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
592#endif
593 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
594 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
595 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
596 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
597
598 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
599 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
600 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
601 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
602 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
603 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
604 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
605 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
606 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
607 /* Sorry, out of number space! <negri>*/
608 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
609
610};
611
612
613#ifdef _MSC_VER
614// The ToAscii bug destroys several registers. Need to turn off optimization
615// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000616# pragma warning(push)
617# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618# pragma optimize("", off)
619#endif
620
621#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
622# define AChar AsciiChar
623#else
624# define AChar uChar.AsciiChar
625#endif
626
627/* The return code indicates key code size. */
628 static int
629#ifdef __BORLANDC__
630 __stdcall
631#endif
632win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000633 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634{
635 UINT uMods = pker->dwControlKeyState;
636 static int s_iIsDead = 0;
637 static WORD awAnsiCode[2];
638 static BYTE abKeystate[256];
639
640
641 if (s_iIsDead == 2)
642 {
643 pker->AChar = (CHAR) awAnsiCode[1];
644 s_iIsDead = 0;
645 return 1;
646 }
647
648 if (pker->AChar != 0)
649 return 1;
650
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200651 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652
653 // Should only be non-NULL on NT 4.0
654 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
655 {
656 CHAR szKLID[KL_NAMELENGTH];
657
658 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
659 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
660 }
661
662 /* Clear any pending dead keys */
663 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
664
665 if (uMods & SHIFT_PRESSED)
666 abKeystate[VK_SHIFT] = 0x80;
667 if (uMods & CAPSLOCK_ON)
668 abKeystate[VK_CAPITAL] = 1;
669
670 if ((uMods & ALT_GR) == ALT_GR)
671 {
672 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
673 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
674 }
675
676 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
677 abKeystate, awAnsiCode, 0);
678
679 if (s_iIsDead > 0)
680 pker->AChar = (CHAR) awAnsiCode[0];
681
682 return s_iIsDead;
683}
684
685#ifdef _MSC_VER
686/* MUST switch optimization on again here, otherwise a call to
687 * decode_key_event() may crash (e.g. when hitting caps-lock) */
688# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000689# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690
691# if (_MSC_VER < 1100)
692/* MUST turn off global optimisation for this next function, or
693 * pressing ctrl-minus in insert mode crashes Vim when built with
694 * VC4.1. -- negri. */
695# pragma optimize("g", off)
696# endif
697#endif
698
699static BOOL g_fJustGotFocus = FALSE;
700
701/*
702 * Decode a KEY_EVENT into one or two keystrokes
703 */
704 static BOOL
705decode_key_event(
706 KEY_EVENT_RECORD *pker,
707 char_u *pch,
708 char_u *pch2,
709 int *pmodifiers,
710 BOOL fDoPost)
711{
712 int i;
713 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
714
715 *pch = *pch2 = NUL;
716 g_fJustGotFocus = FALSE;
717
718 /* ignore key up events */
719 if (!pker->bKeyDown)
720 return FALSE;
721
722 /* ignore some keystrokes */
723 switch (pker->wVirtualKeyCode)
724 {
725 /* modifiers */
726 case VK_SHIFT:
727 case VK_CONTROL:
728 case VK_MENU: /* Alt key */
729 return FALSE;
730
731 default:
732 break;
733 }
734
735 /* special cases */
736 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
737 {
738 /* Ctrl-6 is Ctrl-^ */
739 if (pker->wVirtualKeyCode == '6')
740 {
741 *pch = Ctrl_HAT;
742 return TRUE;
743 }
744 /* Ctrl-2 is Ctrl-@ */
745 else if (pker->wVirtualKeyCode == '2')
746 {
747 *pch = NUL;
748 return TRUE;
749 }
750 /* Ctrl-- is Ctrl-_ */
751 else if (pker->wVirtualKeyCode == 0xBD)
752 {
753 *pch = Ctrl__;
754 return TRUE;
755 }
756 }
757
758 /* Shift-TAB */
759 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
760 {
761 *pch = K_NUL;
762 *pch2 = '\017';
763 return TRUE;
764 }
765
766 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
767 {
768 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
769 {
770 if (nModifs == 0)
771 *pch = VirtKeyMap[i].chAlone;
772 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
773 *pch = VirtKeyMap[i].chShift;
774 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
775 *pch = VirtKeyMap[i].chCtrl;
776 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
777 *pch = VirtKeyMap[i].chAlt;
778
779 if (*pch != 0)
780 {
781 if (VirtKeyMap[i].fAnsiKey)
782 {
783 *pch2 = *pch;
784 *pch = K_NUL;
785 }
786
787 return TRUE;
788 }
789 }
790 }
791
792 i = win32_kbd_patch_key(pker);
793
794 if (i < 0)
795 *pch = NUL;
796 else
797 {
798 *pch = (i > 0) ? pker->AChar : NUL;
799
800 if (pmodifiers != NULL)
801 {
802 /* Pass on the ALT key as a modifier, but only when not combined
803 * with CTRL (which is ALTGR). */
804 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
805 *pmodifiers |= MOD_MASK_ALT;
806
807 /* Pass on SHIFT only for special keys, because we don't know when
808 * it's already included with the character. */
809 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
810 *pmodifiers |= MOD_MASK_SHIFT;
811
812 /* Pass on CTRL only for non-special keys, because we don't know
813 * when it's already included with the character. And not when
814 * combined with ALT (which is ALTGR). */
815 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
816 && *pch >= 0x20 && *pch < 0x80)
817 *pmodifiers |= MOD_MASK_CTRL;
818 }
819 }
820
821 return (*pch != NUL);
822}
823
824#ifdef _MSC_VER
825# pragma optimize("", on)
826#endif
827
828#endif /* FEAT_GUI_W32 */
829
830
831#ifdef FEAT_MOUSE
832
833/*
834 * For the GUI the mouse handling is in gui_w32.c.
835 */
836# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000837/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000839mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840{
841}
842# else
843static int g_fMouseAvail = FALSE; /* mouse present */
844static int g_fMouseActive = FALSE; /* mouse enabled */
845static int g_nMouseClick = -1; /* mouse status */
846static int g_xMouse; /* mouse x coordinate */
847static int g_yMouse; /* mouse y coordinate */
848
849/*
850 * Enable or disable mouse input
851 */
852 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000853mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854{
855 DWORD cmodein;
856
857 if (!g_fMouseAvail)
858 return;
859
860 g_fMouseActive = on;
861 GetConsoleMode(g_hConIn, &cmodein);
862
863 if (g_fMouseActive)
864 cmodein |= ENABLE_MOUSE_INPUT;
865 else
866 cmodein &= ~ENABLE_MOUSE_INPUT;
867
868 SetConsoleMode(g_hConIn, cmodein);
869}
870
871
872/*
873 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
874 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
875 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
876 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
877 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
878 * and we return the mouse position in g_xMouse and g_yMouse.
879 *
880 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
881 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
882 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
883 *
884 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
885 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
886 *
887 * Windows will send us MOUSE_MOVED notifications whenever the mouse
888 * moves, even if it stays within the same character cell. We ignore
889 * all MOUSE_MOVED messages if the position hasn't really changed, and
890 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
891 * we're only interested in MOUSE_DRAG).
892 *
893 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
894 * 2-button mouses by pressing the left & right buttons simultaneously.
895 * In practice, it's almost impossible to click both at the same time,
896 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
897 * in such cases, if the user is clicking quickly.
898 */
899 static BOOL
900decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000901 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902{
903 static int s_nOldButton = -1;
904 static int s_nOldMouseClick = -1;
905 static int s_xOldMouse = -1;
906 static int s_yOldMouse = -1;
907 static linenr_T s_old_topline = 0;
908#ifdef FEAT_DIFF
909 static int s_old_topfill = 0;
910#endif
911 static int s_cClicks = 1;
912 static BOOL s_fReleased = TRUE;
913 static DWORD s_dwLastClickTime = 0;
914 static BOOL s_fNextIsMiddle = FALSE;
915
916 static DWORD cButtons = 0; /* number of buttons supported */
917
918 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
919 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
920 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
921 const DWORD LEFT_RIGHT = LEFT | RIGHT;
922
923 int nButton;
924
925 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
926 cButtons = 2;
927
928 if (!g_fMouseAvail || !g_fMouseActive)
929 {
930 g_nMouseClick = -1;
931 return FALSE;
932 }
933
934 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
935 if (g_fJustGotFocus)
936 {
937 g_fJustGotFocus = FALSE;
938 return FALSE;
939 }
940
941 /* unprocessed mouse click? */
942 if (g_nMouseClick != -1)
943 return TRUE;
944
945 nButton = -1;
946 g_xMouse = pmer->dwMousePosition.X;
947 g_yMouse = pmer->dwMousePosition.Y;
948
949 if (pmer->dwEventFlags == MOUSE_MOVED)
950 {
951 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
952 * events even when the mouse moves only within a char cell.) */
953 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
954 return FALSE;
955 }
956
957 /* If no buttons are pressed... */
958 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
959 {
960 /* If the last thing returned was MOUSE_RELEASE, ignore this */
961 if (s_fReleased)
962 return FALSE;
963
964 nButton = MOUSE_RELEASE;
965 s_fReleased = TRUE;
966 }
967 else /* one or more buttons pressed */
968 {
969 /* on a 2-button mouse, hold down left and right buttons
970 * simultaneously to get MIDDLE. */
971
972 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
973 {
974 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
975
976 /* if either left or right button only is pressed, see if the
977 * the next mouse event has both of them pressed */
978 if (dwLR == LEFT || dwLR == RIGHT)
979 {
980 for (;;)
981 {
982 /* wait a short time for next input event */
983 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
984 != WAIT_OBJECT_0)
985 break;
986 else
987 {
988 DWORD cRecords = 0;
989 INPUT_RECORD ir;
990 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
991
992 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
993
994 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
995 || !(pmer2->dwButtonState & LEFT_RIGHT))
996 break;
997 else
998 {
999 if (pmer2->dwEventFlags != MOUSE_MOVED)
1000 {
1001 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1002
1003 return decode_mouse_event(pmer2);
1004 }
1005 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1006 s_yOldMouse == pmer2->dwMousePosition.Y)
1007 {
1008 /* throw away spurious mouse move */
1009 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1010
1011 /* are there any more mouse events in queue? */
1012 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1013
1014 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1015 break;
1016 }
1017 else
1018 break;
1019 }
1020 }
1021 }
1022 }
1023 }
1024
1025 if (s_fNextIsMiddle)
1026 {
1027 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1028 ? MOUSE_DRAG : MOUSE_MIDDLE;
1029 s_fNextIsMiddle = FALSE;
1030 }
1031 else if (cButtons == 2 &&
1032 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1033 {
1034 nButton = MOUSE_MIDDLE;
1035
1036 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1037 {
1038 s_fNextIsMiddle = TRUE;
1039 nButton = MOUSE_RELEASE;
1040 }
1041 }
1042 else if ((pmer->dwButtonState & LEFT) == LEFT)
1043 nButton = MOUSE_LEFT;
1044 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1045 nButton = MOUSE_MIDDLE;
1046 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1047 nButton = MOUSE_RIGHT;
1048
1049 if (! s_fReleased && ! s_fNextIsMiddle
1050 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1051 return FALSE;
1052
1053 s_fReleased = s_fNextIsMiddle;
1054 }
1055
1056 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1057 {
1058 /* button pressed or released, without mouse moving */
1059 if (nButton != -1 && nButton != MOUSE_RELEASE)
1060 {
1061 DWORD dwCurrentTime = GetTickCount();
1062
1063 if (s_xOldMouse != g_xMouse
1064 || s_yOldMouse != g_yMouse
1065 || s_nOldButton != nButton
1066 || s_old_topline != curwin->w_topline
1067#ifdef FEAT_DIFF
1068 || s_old_topfill != curwin->w_topfill
1069#endif
1070 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1071 {
1072 s_cClicks = 1;
1073 }
1074 else if (++s_cClicks > 4)
1075 {
1076 s_cClicks = 1;
1077 }
1078
1079 s_dwLastClickTime = dwCurrentTime;
1080 }
1081 }
1082 else if (pmer->dwEventFlags == MOUSE_MOVED)
1083 {
1084 if (nButton != -1 && nButton != MOUSE_RELEASE)
1085 nButton = MOUSE_DRAG;
1086
1087 s_cClicks = 1;
1088 }
1089
1090 if (nButton == -1)
1091 return FALSE;
1092
1093 if (nButton != MOUSE_RELEASE)
1094 s_nOldButton = nButton;
1095
1096 g_nMouseClick = nButton;
1097
1098 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1099 g_nMouseClick |= MOUSE_SHIFT;
1100 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1101 g_nMouseClick |= MOUSE_CTRL;
1102 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1103 g_nMouseClick |= MOUSE_ALT;
1104
1105 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1106 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1107
1108 /* only pass on interesting (i.e., different) mouse events */
1109 if (s_xOldMouse == g_xMouse
1110 && s_yOldMouse == g_yMouse
1111 && s_nOldMouseClick == g_nMouseClick)
1112 {
1113 g_nMouseClick = -1;
1114 return FALSE;
1115 }
1116
1117 s_xOldMouse = g_xMouse;
1118 s_yOldMouse = g_yMouse;
1119 s_old_topline = curwin->w_topline;
1120#ifdef FEAT_DIFF
1121 s_old_topfill = curwin->w_topfill;
1122#endif
1123 s_nOldMouseClick = g_nMouseClick;
1124
1125 return TRUE;
1126}
1127
1128# endif /* FEAT_GUI_W32 */
1129#endif /* FEAT_MOUSE */
1130
1131
1132#ifdef MCH_CURSOR_SHAPE
1133/*
1134 * Set the shape of the cursor.
1135 * 'thickness' can be from 1 (thin) to 99 (block)
1136 */
1137 static void
1138mch_set_cursor_shape(int thickness)
1139{
1140 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1141 ConsoleCursorInfo.dwSize = thickness;
1142 ConsoleCursorInfo.bVisible = s_cursor_visible;
1143
1144 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1145 if (s_cursor_visible)
1146 SetConsoleCursorPosition(g_hConOut, g_coord);
1147}
1148
1149 void
1150mch_update_cursor(void)
1151{
1152 int idx;
1153 int thickness;
1154
1155 /*
1156 * How the cursor is drawn depends on the current mode.
1157 */
1158 idx = get_shape_idx(FALSE);
1159
1160 if (shape_table[idx].shape == SHAPE_BLOCK)
1161 thickness = 99; /* 100 doesn't work on W95 */
1162 else
1163 thickness = shape_table[idx].percentage;
1164 mch_set_cursor_shape(thickness);
1165}
1166#endif
1167
1168#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1169/*
1170 * Handle FOCUS_EVENT.
1171 */
1172 static void
1173handle_focus_event(INPUT_RECORD ir)
1174{
1175 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1176 ui_focus_change((int)g_fJustGotFocus);
1177}
1178
1179/*
1180 * Wait until console input from keyboard or mouse is available,
1181 * or the time is up.
1182 * Return TRUE if something is available FALSE if not.
1183 */
1184 static int
1185WaitForChar(long msec)
1186{
1187 DWORD dwNow = 0, dwEndTime = 0;
1188 INPUT_RECORD ir;
1189 DWORD cRecords;
1190 char_u ch, ch2;
1191
1192 if (msec > 0)
1193 /* Wait until the specified time has elapsed. */
1194 dwEndTime = GetTickCount() + msec;
1195 else if (msec < 0)
1196 /* Wait forever. */
1197 dwEndTime = INFINITE;
1198
1199 /* We need to loop until the end of the time period, because
1200 * we might get multiple unusable mouse events in that time.
1201 */
1202 for (;;)
1203 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001204#ifdef FEAT_MZSCHEME
1205 mzvim_check_threads();
1206#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207#ifdef FEAT_CLIENTSERVER
1208 serverProcessPendingMessages();
1209#endif
1210 if (0
1211#ifdef FEAT_MOUSE
1212 || g_nMouseClick != -1
1213#endif
1214#ifdef FEAT_CLIENTSERVER
1215 || input_available()
1216#endif
1217 )
1218 return TRUE;
1219
1220 if (msec > 0)
1221 {
1222 /* If the specified wait time has passed, return. */
1223 dwNow = GetTickCount();
1224 if (dwNow >= dwEndTime)
1225 break;
1226 }
1227 if (msec != 0)
1228 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001229 DWORD dwWaitTime = dwEndTime - dwNow;
1230
1231#ifdef FEAT_MZSCHEME
1232 if (mzthreads_allowed() && p_mzq > 0
1233 && (msec < 0 || (long)dwWaitTime > p_mzq))
1234 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1235#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236#ifdef FEAT_CLIENTSERVER
1237 /* Wait for either an event on the console input or a message in
1238 * the client-server window. */
1239 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001240 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001242 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001243#endif
1244 continue;
1245 }
1246
1247 cRecords = 0;
1248 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1249
1250#ifdef FEAT_MBYTE_IME
1251 if (State & CMDLINE && msg_row == Rows - 1)
1252 {
1253 CONSOLE_SCREEN_BUFFER_INFO csbi;
1254
1255 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1256 {
1257 if (csbi.dwCursorPosition.Y != msg_row)
1258 {
1259 /* The screen is now messed up, must redraw the
1260 * command line and later all the windows. */
1261 redraw_all_later(CLEAR);
1262 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1263 redrawcmd();
1264 }
1265 }
1266 }
1267#endif
1268
1269 if (cRecords > 0)
1270 {
1271 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1272 {
1273#ifdef FEAT_MBYTE_IME
1274 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1275 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1276 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1277 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1278 {
1279 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1280 continue;
1281 }
1282#endif
1283 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1284 NULL, FALSE))
1285 return TRUE;
1286 }
1287
1288 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1289
1290 if (ir.EventType == FOCUS_EVENT)
1291 handle_focus_event(ir);
1292 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1293 shell_resized();
1294#ifdef FEAT_MOUSE
1295 else if (ir.EventType == MOUSE_EVENT
1296 && decode_mouse_event(&ir.Event.MouseEvent))
1297 return TRUE;
1298#endif
1299 }
1300 else if (msec == 0)
1301 break;
1302 }
1303
1304#ifdef FEAT_CLIENTSERVER
1305 /* Something might have been received while we were waiting. */
1306 if (input_available())
1307 return TRUE;
1308#endif
1309 return FALSE;
1310}
1311
1312#ifndef FEAT_GUI_MSWIN
1313/*
1314 * return non-zero if a character is available
1315 */
1316 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001317mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318{
1319 return WaitForChar(0L);
1320}
1321#endif
1322
1323/*
1324 * Create the console input. Used when reading stdin doesn't work.
1325 */
1326 static void
1327create_conin(void)
1328{
1329 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1330 FILE_SHARE_READ|FILE_SHARE_WRITE,
1331 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001332 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001333 did_create_conin = TRUE;
1334}
1335
1336/*
1337 * Get a keystroke or a mouse event
1338 */
1339 static char_u
1340tgetch(int *pmodifiers, char_u *pch2)
1341{
1342 char_u ch;
1343
1344 for (;;)
1345 {
1346 INPUT_RECORD ir;
1347 DWORD cRecords = 0;
1348
1349#ifdef FEAT_CLIENTSERVER
1350 (void)WaitForChar(-1L);
1351 if (input_available())
1352 return 0;
1353# ifdef FEAT_MOUSE
1354 if (g_nMouseClick != -1)
1355 return 0;
1356# endif
1357#endif
1358 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1359 {
1360 if (did_create_conin)
1361 read_error_exit();
1362 create_conin();
1363 continue;
1364 }
1365
1366 if (ir.EventType == KEY_EVENT)
1367 {
1368 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1369 pmodifiers, TRUE))
1370 return ch;
1371 }
1372 else if (ir.EventType == FOCUS_EVENT)
1373 handle_focus_event(ir);
1374 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1375 shell_resized();
1376#ifdef FEAT_MOUSE
1377 else if (ir.EventType == MOUSE_EVENT)
1378 {
1379 if (decode_mouse_event(&ir.Event.MouseEvent))
1380 return 0;
1381 }
1382#endif
1383 }
1384}
1385#endif /* !FEAT_GUI_W32 */
1386
1387
1388/*
1389 * mch_inchar(): low-level input funcion.
1390 * Get one or more characters from the keyboard or the mouse.
1391 * If time == 0, do not wait for characters.
1392 * If time == n, wait a short time for characters.
1393 * If time == -1, wait forever for characters.
1394 * Returns the number of characters read into buf.
1395 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001396/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001397 int
1398mch_inchar(
1399 char_u *buf,
1400 int maxlen,
1401 long time,
1402 int tb_change_cnt)
1403{
1404#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1405
1406 int len;
1407 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408#define TYPEAHEADLEN 20
1409 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1410 static int typeaheadlen = 0;
1411
1412 /* First use any typeahead that was kept because "buf" was too small. */
1413 if (typeaheadlen > 0)
1414 goto theend;
1415
1416#ifdef FEAT_SNIFF
1417 if (want_sniff_request)
1418 {
1419 if (sniff_request_waiting)
1420 {
1421 /* return K_SNIFF */
1422 typeahead[typeaheadlen++] = CSI;
1423 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1424 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1425 sniff_request_waiting = 0;
1426 want_sniff_request = 0;
1427 goto theend;
1428 }
1429 else if (time < 0 || time > 250)
1430 {
1431 /* don't wait too long, a request might be pending */
1432 time = 250;
1433 }
1434 }
1435#endif
1436
1437 if (time >= 0)
1438 {
1439 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001441 }
1442 else /* time == -1, wait forever */
1443 {
1444 mch_set_winsize_now(); /* Allow winsize changes from now on */
1445
Bram Moolenaar3918c952005-03-15 22:34:55 +00001446 /*
1447 * If there is no character available within 2 seconds (default)
1448 * write the autoscript file to disk. Or cause the CursorHold event
1449 * to be triggered.
1450 */
1451 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452 {
1453#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001454 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001456 buf[0] = K_SPECIAL;
1457 buf[1] = KS_EXTRA;
1458 buf[2] = (int)KE_CURSORHOLD;
1459 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460 }
1461#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001462 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001463 }
1464 }
1465
1466 /*
1467 * Try to read as many characters as there are, until the buffer is full.
1468 */
1469
1470 /* we will get at least one key. Get more if they are available. */
1471 g_fCBrkPressed = FALSE;
1472
1473#ifdef MCH_WRITE_DUMP
1474 if (fdDump)
1475 fputc('[', fdDump);
1476#endif
1477
1478 /* Keep looping until there is something in the typeahead buffer and more
1479 * to get and still room in the buffer (up to two bytes for a char and
1480 * three bytes for a modifier). */
1481 while ((typeaheadlen == 0 || WaitForChar(0L))
1482 && typeaheadlen + 5 <= TYPEAHEADLEN)
1483 {
1484 if (typebuf_changed(tb_change_cnt))
1485 {
1486 /* "buf" may be invalid now if a client put something in the
1487 * typeahead buffer and "buf" is in the typeahead buffer. */
1488 typeaheadlen = 0;
1489 break;
1490 }
1491#ifdef FEAT_MOUSE
1492 if (g_nMouseClick != -1)
1493 {
1494# ifdef MCH_WRITE_DUMP
1495 if (fdDump)
1496 fprintf(fdDump, "{%02x @ %d, %d}",
1497 g_nMouseClick, g_xMouse, g_yMouse);
1498# endif
1499 typeahead[typeaheadlen++] = ESC + 128;
1500 typeahead[typeaheadlen++] = 'M';
1501 typeahead[typeaheadlen++] = g_nMouseClick;
1502 typeahead[typeaheadlen++] = g_xMouse + '!';
1503 typeahead[typeaheadlen++] = g_yMouse + '!';
1504 g_nMouseClick = -1;
1505 }
1506 else
1507#endif
1508 {
1509 char_u ch2 = NUL;
1510 int modifiers = 0;
1511
1512 c = tgetch(&modifiers, &ch2);
1513
1514 if (typebuf_changed(tb_change_cnt))
1515 {
1516 /* "buf" may be invalid now if a client put something in the
1517 * typeahead buffer and "buf" is in the typeahead buffer. */
1518 typeaheadlen = 0;
1519 break;
1520 }
1521
1522 if (c == Ctrl_C && ctrl_c_interrupts)
1523 {
1524#if defined(FEAT_CLIENTSERVER)
1525 trash_input_buf();
1526#endif
1527 got_int = TRUE;
1528 }
1529
1530#ifdef FEAT_MOUSE
1531 if (g_nMouseClick == -1)
1532#endif
1533 {
1534 int n = 1;
1535
1536 /* A key may have one or two bytes. */
1537 typeahead[typeaheadlen] = c;
1538 if (ch2 != NUL)
1539 {
1540 typeahead[typeaheadlen + 1] = ch2;
1541 ++n;
1542 }
1543#ifdef FEAT_MBYTE
1544 /* Only convert normal characters, not special keys. Need to
1545 * convert before applying ALT, otherwise mapping <M-x> breaks
1546 * when 'tenc' is set. */
1547 if (input_conv.vc_type != CONV_NONE
1548 && (ch2 == NUL || c != K_NUL))
1549 n = convert_input(typeahead + typeaheadlen, n,
1550 TYPEAHEADLEN - typeaheadlen);
1551#endif
1552
1553 /* Use the ALT key to set the 8th bit of the character
1554 * when it's one byte, the 8th bit isn't set yet and not
1555 * using a double-byte encoding (would become a lead
1556 * byte). */
1557 if ((modifiers & MOD_MASK_ALT)
1558 && n == 1
1559 && (typeahead[typeaheadlen] & 0x80) == 0
1560#ifdef FEAT_MBYTE
1561 && !enc_dbcs
1562#endif
1563 )
1564 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001565#ifdef FEAT_MBYTE
1566 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1567 typeahead + typeaheadlen);
1568#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001570#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571 modifiers &= ~MOD_MASK_ALT;
1572 }
1573
1574 if (modifiers != 0)
1575 {
1576 /* Prepend modifiers to the character. */
1577 mch_memmove(typeahead + typeaheadlen + 3,
1578 typeahead + typeaheadlen, n);
1579 typeahead[typeaheadlen++] = K_SPECIAL;
1580 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1581 typeahead[typeaheadlen++] = modifiers;
1582 }
1583
1584 typeaheadlen += n;
1585
1586#ifdef MCH_WRITE_DUMP
1587 if (fdDump)
1588 fputc(c, fdDump);
1589#endif
1590 }
1591 }
1592 }
1593
1594#ifdef MCH_WRITE_DUMP
1595 if (fdDump)
1596 {
1597 fputs("]\n", fdDump);
1598 fflush(fdDump);
1599 }
1600#endif
1601
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602theend:
1603 /* Move typeahead to "buf", as much as fits. */
1604 len = 0;
1605 while (len < maxlen && typeaheadlen > 0)
1606 {
1607 buf[len++] = typeahead[0];
1608 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1609 }
1610 return len;
1611
1612#else /* FEAT_GUI_W32 */
1613 return 0;
1614#endif /* FEAT_GUI_W32 */
1615}
1616
1617#ifndef __MINGW32__
1618# include <shellapi.h> /* required for FindExecutable() */
1619#endif
1620
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001621/*
1622 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001623 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001624 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 static int
1626executable_exists(char *name)
1627{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001628 char *dum;
1629 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001631#ifdef FEAT_MBYTE
1632 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001634 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001635 WCHAR fnamew[_MAX_PATH];
1636 WCHAR *dumw;
1637 long n;
1638
1639 if (p != NULL)
1640 {
1641 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1642 vim_free(p);
1643 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1644 {
1645 if (n == 0)
1646 return FALSE;
1647 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1648 return FALSE;
1649 return TRUE;
1650 }
1651 /* Retry with non-wide function (for Windows 98). */
1652 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001654#endif
1655 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1656 return FALSE;
1657 if (mch_isdir(fname))
1658 return FALSE;
1659 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660}
1661
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001662#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001663 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001664/*
1665 * Bad parameter handler.
1666 *
1667 * Certain MS CRT functions will intentionally crash when passed invalid
1668 * parameters to highlight possible security holes. Setting this function as
1669 * the bad parameter handler will prevent the crash.
1670 *
1671 * In debug builds the parameters contain CRT information that might help track
1672 * down the source of a problem, but in non-debug builds the arguments are all
1673 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1674 * worth allowing these to make debugging of issues easier.
1675 */
1676 static void
1677bad_param_handler(const wchar_t *expression,
1678 const wchar_t *function,
1679 const wchar_t *file,
1680 unsigned int line,
1681 uintptr_t pReserved)
1682{
1683}
1684
1685# define SET_INVALID_PARAM_HANDLER \
1686 ((void)_set_invalid_parameter_handler(bad_param_handler))
1687#else
1688# define SET_INVALID_PARAM_HANDLER
1689#endif
1690
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691#ifdef FEAT_GUI_W32
1692
1693/*
1694 * GUI version of mch_init().
1695 */
1696 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001697mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698{
1699#ifndef __MINGW32__
1700 extern int _fmode;
1701#endif
1702
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001703 /* Silently handle invalid parameters to CRT functions */
1704 SET_INVALID_PARAM_HANDLER;
1705
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 /* Let critical errors result in a failure, not in a dialog box. Required
1707 * for the timestamp test to work on removed floppies. */
1708 SetErrorMode(SEM_FAILCRITICALERRORS);
1709
1710 _fmode = O_BINARY; /* we do our own CR-LF translation */
1711
1712 /* Specify window size. Is there a place to get the default from? */
1713 Rows = 25;
1714 Columns = 80;
1715
1716 /* Look for 'vimrun' */
1717 if (!gui_is_win32s())
1718 {
1719 char_u vimrun_location[_MAX_PATH + 4];
1720
1721 /* First try in same directory as gvim.exe */
1722 STRCPY(vimrun_location, exe_name);
1723 STRCPY(gettail(vimrun_location), "vimrun.exe");
1724 if (mch_getperm(vimrun_location) >= 0)
1725 {
1726 if (*skiptowhite(vimrun_location) != NUL)
1727 {
1728 /* Enclose path with white space in double quotes. */
1729 mch_memmove(vimrun_location + 1, vimrun_location,
1730 STRLEN(vimrun_location) + 1);
1731 *vimrun_location = '"';
1732 STRCPY(gettail(vimrun_location), "vimrun\" ");
1733 }
1734 else
1735 STRCPY(gettail(vimrun_location), "vimrun ");
1736
1737 vimrun_path = (char *)vim_strsave(vimrun_location);
1738 s_dont_use_vimrun = FALSE;
1739 }
1740 else if (executable_exists("vimrun.exe"))
1741 s_dont_use_vimrun = FALSE;
1742
1743 /* Don't give the warning for a missing vimrun.exe right now, but only
1744 * when vimrun was supposed to be used. Don't bother people that do
1745 * not need vimrun.exe. */
1746 if (s_dont_use_vimrun)
1747 need_vimrun_warning = TRUE;
1748 }
1749
1750 /*
1751 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1752 * Otherwise the default "findstr /n" is used.
1753 */
1754 if (!executable_exists("findstr.exe"))
1755 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1756
1757#ifdef FEAT_CLIPBOARD
1758 clip_init(TRUE);
1759
1760 /*
Bram Moolenaar7528dd62007-05-06 12:32:12 +00001761 * Vim's own clipboard format recognises whether the text is char, line,
1762 * or rectangular block. Only useful for copying between two Vims.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763 * "VimClipboard" was used for previous versions, using the first
1764 * character to specify MCHAR, MLINE or MBLOCK.
1765 */
1766 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1767 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1768#endif
1769}
1770
1771
1772#else /* FEAT_GUI_W32 */
1773
1774#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1775#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1776
1777/*
1778 * ClearConsoleBuffer()
1779 * Description:
1780 * Clears the entire contents of the console screen buffer, using the
1781 * specified attribute.
1782 * Returns:
1783 * TRUE on success
1784 */
1785 static BOOL
1786ClearConsoleBuffer(WORD wAttribute)
1787{
1788 CONSOLE_SCREEN_BUFFER_INFO csbi;
1789 COORD coord;
1790 DWORD NumCells, dummy;
1791
1792 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1793 return FALSE;
1794
1795 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1796 coord.X = 0;
1797 coord.Y = 0;
1798 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1799 coord, &dummy))
1800 {
1801 return FALSE;
1802 }
1803 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1804 coord, &dummy))
1805 {
1806 return FALSE;
1807 }
1808
1809 return TRUE;
1810}
1811
1812/*
1813 * FitConsoleWindow()
1814 * Description:
1815 * Checks if the console window will fit within given buffer dimensions.
1816 * Also, if requested, will shrink the window to fit.
1817 * Returns:
1818 * TRUE on success
1819 */
1820 static BOOL
1821FitConsoleWindow(
1822 COORD dwBufferSize,
1823 BOOL WantAdjust)
1824{
1825 CONSOLE_SCREEN_BUFFER_INFO csbi;
1826 COORD dwWindowSize;
1827 BOOL NeedAdjust = FALSE;
1828
1829 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1830 {
1831 /*
1832 * A buffer resize will fail if the current console window does
1833 * not lie completely within that buffer. To avoid this, we might
1834 * have to move and possibly shrink the window.
1835 */
1836 if (csbi.srWindow.Right >= dwBufferSize.X)
1837 {
1838 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1839 if (dwWindowSize.X > dwBufferSize.X)
1840 dwWindowSize.X = dwBufferSize.X;
1841 csbi.srWindow.Right = dwBufferSize.X - 1;
1842 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1843 NeedAdjust = TRUE;
1844 }
1845 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1846 {
1847 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1848 if (dwWindowSize.Y > dwBufferSize.Y)
1849 dwWindowSize.Y = dwBufferSize.Y;
1850 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1851 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1852 NeedAdjust = TRUE;
1853 }
1854 if (NeedAdjust && WantAdjust)
1855 {
1856 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1857 return FALSE;
1858 }
1859 return TRUE;
1860 }
1861
1862 return FALSE;
1863}
1864
1865typedef struct ConsoleBufferStruct
1866{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001867 BOOL IsValid;
1868 CONSOLE_SCREEN_BUFFER_INFO Info;
1869 PCHAR_INFO Buffer;
1870 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871} ConsoleBuffer;
1872
1873/*
1874 * SaveConsoleBuffer()
1875 * Description:
1876 * Saves important information about the console buffer, including the
1877 * actual buffer contents. The saved information is suitable for later
1878 * restoration by RestoreConsoleBuffer().
1879 * Returns:
1880 * TRUE if all information was saved; FALSE otherwise
1881 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1882 */
1883 static BOOL
1884SaveConsoleBuffer(
1885 ConsoleBuffer *cb)
1886{
1887 DWORD NumCells;
1888 COORD BufferCoord;
1889 SMALL_RECT ReadRegion;
1890 WORD Y, Y_incr;
1891
1892 if (cb == NULL)
1893 return FALSE;
1894
1895 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1896 {
1897 cb->IsValid = FALSE;
1898 return FALSE;
1899 }
1900 cb->IsValid = TRUE;
1901
1902 /*
1903 * Allocate a buffer large enough to hold the entire console screen
1904 * buffer. If this ConsoleBuffer structure has already been initialized
1905 * with a buffer of the correct size, then just use that one.
1906 */
1907 if (!cb->IsValid || cb->Buffer == NULL ||
1908 cb->BufferSize.X != cb->Info.dwSize.X ||
1909 cb->BufferSize.Y != cb->Info.dwSize.Y)
1910 {
1911 cb->BufferSize.X = cb->Info.dwSize.X;
1912 cb->BufferSize.Y = cb->Info.dwSize.Y;
1913 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01001914 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
1916 if (cb->Buffer == NULL)
1917 return FALSE;
1918 }
1919
1920 /*
1921 * We will now copy the console screen buffer into our buffer.
1922 * ReadConsoleOutput() seems to be limited as far as how much you
1923 * can read at a time. Empirically, this number seems to be about
1924 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1925 * in chunks until it is all copied. The chunks will all have the
1926 * same horizontal characteristics, so initialize them now. The
1927 * height of each chunk will be (12000 / width).
1928 */
1929 BufferCoord.X = 0;
1930 ReadRegion.Left = 0;
1931 ReadRegion.Right = cb->Info.dwSize.X - 1;
1932 Y_incr = 12000 / cb->Info.dwSize.X;
1933 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
1934 {
1935 /*
1936 * Read into position (0, Y) in our buffer.
1937 */
1938 BufferCoord.Y = Y;
1939 /*
1940 * Read the region whose top left corner is (0, Y) and whose bottom
1941 * right corner is (width - 1, Y + Y_incr - 1). This should define
1942 * a region of size width by Y_incr. Don't worry if this region is
1943 * too large for the remaining buffer; it will be cropped.
1944 */
1945 ReadRegion.Top = Y;
1946 ReadRegion.Bottom = Y + Y_incr - 1;
1947 if (!ReadConsoleOutput(g_hConOut, /* output handle */
1948 cb->Buffer, /* our buffer */
1949 cb->BufferSize, /* dimensions of our buffer */
1950 BufferCoord, /* offset in our buffer */
1951 &ReadRegion)) /* region to save */
1952 {
1953 vim_free(cb->Buffer);
1954 cb->Buffer = NULL;
1955 return FALSE;
1956 }
1957 }
1958
1959 return TRUE;
1960}
1961
1962/*
1963 * RestoreConsoleBuffer()
1964 * Description:
1965 * Restores important information about the console buffer, including the
1966 * actual buffer contents, if desired. The information to restore is in
1967 * the same format used by SaveConsoleBuffer().
1968 * Returns:
1969 * TRUE on success
1970 */
1971 static BOOL
1972RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001973 ConsoleBuffer *cb,
1974 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975{
1976 COORD BufferCoord;
1977 SMALL_RECT WriteRegion;
1978
1979 if (cb == NULL || !cb->IsValid)
1980 return FALSE;
1981
1982 /*
1983 * Before restoring the buffer contents, clear the current buffer, and
1984 * restore the cursor position and window information. Doing this now
1985 * prevents old buffer contents from "flashing" onto the screen.
1986 */
1987 if (RestoreScreen)
1988 ClearConsoleBuffer(cb->Info.wAttributes);
1989
1990 FitConsoleWindow(cb->Info.dwSize, TRUE);
1991 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
1992 return FALSE;
1993 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
1994 return FALSE;
1995
1996 if (!RestoreScreen)
1997 {
1998 /*
1999 * No need to restore the screen buffer contents, so we're done.
2000 */
2001 return TRUE;
2002 }
2003
2004 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2005 return FALSE;
2006 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2007 return FALSE;
2008
2009 /*
2010 * Restore the screen buffer contents.
2011 */
2012 if (cb->Buffer != NULL)
2013 {
2014 BufferCoord.X = 0;
2015 BufferCoord.Y = 0;
2016 WriteRegion.Left = 0;
2017 WriteRegion.Top = 0;
2018 WriteRegion.Right = cb->Info.dwSize.X - 1;
2019 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2020 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2021 cb->Buffer, /* our buffer */
2022 cb->BufferSize, /* dimensions of our buffer */
2023 BufferCoord, /* offset in our buffer */
2024 &WriteRegion)) /* region to restore */
2025 {
2026 return FALSE;
2027 }
2028 }
2029
2030 return TRUE;
2031}
2032
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002033#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034#ifdef FEAT_RESTORE_ORIG_SCREEN
2035static ConsoleBuffer g_cbOrig = { 0 };
2036#endif
2037static ConsoleBuffer g_cbNonTermcap = { 0 };
2038static ConsoleBuffer g_cbTermcap = { 0 };
2039
2040#ifdef FEAT_TITLE
2041#ifdef __BORLANDC__
2042typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2043#else
2044typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2045#endif
2046char g_szOrigTitle[256] = { 0 };
2047HWND g_hWnd = NULL; /* also used in os_mswin.c */
2048static HICON g_hOrigIconSmall = NULL;
2049static HICON g_hOrigIcon = NULL;
2050static HICON g_hVimIcon = NULL;
2051static BOOL g_fCanChangeIcon = FALSE;
2052
2053/* ICON* are not defined in VC++ 4.0 */
2054#ifndef ICON_SMALL
2055#define ICON_SMALL 0
2056#endif
2057#ifndef ICON_BIG
2058#define ICON_BIG 1
2059#endif
2060/*
2061 * GetConsoleIcon()
2062 * Description:
2063 * Attempts to retrieve the small icon and/or the big icon currently in
2064 * use by a given window.
2065 * Returns:
2066 * TRUE on success
2067 */
2068 static BOOL
2069GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002070 HWND hWnd,
2071 HICON *phIconSmall,
2072 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073{
2074 if (hWnd == NULL)
2075 return FALSE;
2076
2077 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002078 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2079 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002081 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2082 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 return TRUE;
2084}
2085
2086/*
2087 * SetConsoleIcon()
2088 * Description:
2089 * Attempts to change the small icon and/or the big icon currently in
2090 * use by a given window.
2091 * Returns:
2092 * TRUE on success
2093 */
2094 static BOOL
2095SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002096 HWND hWnd,
2097 HICON hIconSmall,
2098 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002100 HICON hPrevIconSmall;
2101 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002102
2103 if (hWnd == NULL)
2104 return FALSE;
2105
2106 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002107 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2108 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002110 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2111 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 return TRUE;
2113}
2114
2115/*
2116 * SaveConsoleTitleAndIcon()
2117 * Description:
2118 * Saves the current console window title in g_szOrigTitle, for later
2119 * restoration. Also, attempts to obtain a handle to the console window,
2120 * and use it to save the small and big icons currently in use by the
2121 * console window. This is not always possible on some versions of Windows;
2122 * nor is it possible when running Vim remotely using Telnet (since the
2123 * console window the user sees is owned by a remote process).
2124 */
2125 static void
2126SaveConsoleTitleAndIcon(void)
2127{
2128 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2129
2130 /* Save the original title. */
2131 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2132 return;
2133
2134 /*
2135 * Obtain a handle to the console window using GetConsoleWindow() from
2136 * KERNEL32.DLL; we need to handle in order to change the window icon.
2137 * This function only exists on NT-based Windows, starting with Windows
2138 * 2000. On older operating systems, we can't change the window icon
2139 * anyway.
2140 */
2141 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2142 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2143 "GetConsoleWindow")) != NULL)
2144 {
2145 g_hWnd = (*GetConsoleWindowProc)();
2146 }
2147 if (g_hWnd == NULL)
2148 return;
2149
2150 /* Save the original console window icon. */
2151 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2152 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2153 return;
2154
2155 /* Extract the first icon contained in the Vim executable. */
2156 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2157 if (g_hVimIcon != NULL)
2158 g_fCanChangeIcon = TRUE;
2159}
2160#endif
2161
2162static int g_fWindInitCalled = FALSE;
2163static int g_fTermcapMode = FALSE;
2164static CONSOLE_CURSOR_INFO g_cci;
2165static DWORD g_cmodein = 0;
2166static DWORD g_cmodeout = 0;
2167
2168/*
2169 * non-GUI version of mch_init().
2170 */
2171 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002172mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173{
2174#ifndef FEAT_RESTORE_ORIG_SCREEN
2175 CONSOLE_SCREEN_BUFFER_INFO csbi;
2176#endif
2177#ifndef __MINGW32__
2178 extern int _fmode;
2179#endif
2180
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002181 /* Silently handle invalid parameters to CRT functions */
2182 SET_INVALID_PARAM_HANDLER;
2183
Bram Moolenaar071d4272004-06-13 20:20:40 +00002184 /* Let critical errors result in a failure, not in a dialog box. Required
2185 * for the timestamp test to work on removed floppies. */
2186 SetErrorMode(SEM_FAILCRITICALERRORS);
2187
2188 _fmode = O_BINARY; /* we do our own CR-LF translation */
2189 out_flush();
2190
2191 /* Obtain handles for the standard Console I/O devices */
2192 if (read_cmd_fd == 0)
2193 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2194 else
2195 create_conin();
2196 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2197
2198#ifdef FEAT_RESTORE_ORIG_SCREEN
2199 /* Save the initial console buffer for later restoration */
2200 SaveConsoleBuffer(&g_cbOrig);
2201 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2202#else
2203 /* Get current text attributes */
2204 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2205 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2206#endif
2207 if (cterm_normal_fg_color == 0)
2208 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2209 if (cterm_normal_bg_color == 0)
2210 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2211
2212 /* set termcap codes to current text attributes */
2213 update_tcap(g_attrCurrent);
2214
2215 GetConsoleCursorInfo(g_hConOut, &g_cci);
2216 GetConsoleMode(g_hConIn, &g_cmodein);
2217 GetConsoleMode(g_hConOut, &g_cmodeout);
2218
2219#ifdef FEAT_TITLE
2220 SaveConsoleTitleAndIcon();
2221 /*
2222 * Set both the small and big icons of the console window to Vim's icon.
2223 * Note that Vim presently only has one size of icon (32x32), but it
2224 * automatically gets scaled down to 16x16 when setting the small icon.
2225 */
2226 if (g_fCanChangeIcon)
2227 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2228#endif
2229
2230 ui_get_shellsize();
2231
2232#ifdef MCH_WRITE_DUMP
2233 fdDump = fopen("dump", "wt");
2234
2235 if (fdDump)
2236 {
2237 time_t t;
2238
2239 time(&t);
2240 fputs(ctime(&t), fdDump);
2241 fflush(fdDump);
2242 }
2243#endif
2244
2245 g_fWindInitCalled = TRUE;
2246
2247#ifdef FEAT_MOUSE
2248 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2249#endif
2250
2251#ifdef FEAT_CLIPBOARD
2252 clip_init(TRUE);
2253
2254 /*
2255 * Vim's own clipboard format recognises whether the text is char, line, or
2256 * rectangular block. Only useful for copying between two Vims.
2257 * "VimClipboard" was used for previous versions, using the first
2258 * character to specify MCHAR, MLINE or MBLOCK.
2259 */
2260 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2261 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2262#endif
2263
2264 /* This will be NULL on anything but NT 4.0 */
2265 s_pfnGetConsoleKeyboardLayoutName =
2266 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2267 "GetConsoleKeyboardLayoutNameA");
2268}
2269
2270/*
2271 * non-GUI version of mch_exit().
2272 * Shut down and exit with status `r'
2273 * Careful: mch_exit() may be called before mch_init()!
2274 */
2275 void
2276mch_exit(int r)
2277{
2278 stoptermcap();
2279
2280 if (g_fWindInitCalled)
2281 settmode(TMODE_COOK);
2282
2283 ml_close_all(TRUE); /* remove all memfiles */
2284
2285 if (g_fWindInitCalled)
2286 {
2287#ifdef FEAT_TITLE
2288 mch_restore_title(3);
2289 /*
2290 * Restore both the small and big icons of the console window to
2291 * what they were at startup. Don't do this when the window is
2292 * closed, Vim would hang here.
2293 */
2294 if (g_fCanChangeIcon && !g_fForceExit)
2295 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2296#endif
2297
2298#ifdef MCH_WRITE_DUMP
2299 if (fdDump)
2300 {
2301 time_t t;
2302
2303 time(&t);
2304 fputs(ctime(&t), fdDump);
2305 fclose(fdDump);
2306 }
2307 fdDump = NULL;
2308#endif
2309 }
2310
2311 SetConsoleCursorInfo(g_hConOut, &g_cci);
2312 SetConsoleMode(g_hConIn, g_cmodein);
2313 SetConsoleMode(g_hConOut, g_cmodeout);
2314
2315#ifdef DYNAMIC_GETTEXT
2316 dyn_libintl_end();
2317#endif
2318
2319 exit(r);
2320}
2321#endif /* !FEAT_GUI_W32 */
2322
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323/*
2324 * Do we have an interactive window?
2325 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002326/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327 int
2328mch_check_win(
2329 int argc,
2330 char **argv)
2331{
2332 get_exe_name();
2333
2334#ifdef FEAT_GUI_W32
2335 return OK; /* GUI always has a tty */
2336#else
2337 if (isatty(1))
2338 return OK;
2339 return FAIL;
2340#endif
2341}
2342
2343
2344/*
2345 * fname_case(): Set the case of the file name, if it already exists.
2346 * When "len" is > 0, also expand short to long filenames.
2347 */
2348 void
2349fname_case(
2350 char_u *name,
2351 int len)
2352{
2353 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002354 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 char *ptrue, *ptruePrev;
2356 char *porig, *porigPrev;
2357 int flen;
2358 WIN32_FIND_DATA fb;
2359 HANDLE hFind;
2360 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002361 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002363 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002364 if (flen == 0 || flen > _MAX_PATH)
2365 return;
2366
2367 slash_adjust(name);
2368
2369 /* Build the new name in szTrueName[] one component at a time. */
2370 porig = name;
2371 ptrue = szTrueName;
2372
2373 if (isalpha(porig[0]) && porig[1] == ':')
2374 {
2375 /* copy leading drive letter */
2376 *ptrue++ = *porig++;
2377 *ptrue++ = *porig++;
2378 *ptrue = NUL; /* in case nothing follows */
2379 }
2380
2381 while (*porig != NUL)
2382 {
2383 /* copy \ characters */
2384 while (*porig == psepc)
2385 *ptrue++ = *porig++;
2386
2387 ptruePrev = ptrue;
2388 porigPrev = porig;
2389 while (*porig != NUL && *porig != psepc)
2390 {
2391#ifdef FEAT_MBYTE
2392 int l;
2393
2394 if (enc_dbcs)
2395 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002396 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397 while (--l >= 0)
2398 *ptrue++ = *porig++;
2399 }
2400 else
2401#endif
2402 *ptrue++ = *porig++;
2403 }
2404 *ptrue = NUL;
2405
Bram Moolenaar464c9252010-10-13 20:37:41 +02002406 /* To avoid a slow failure append "\*" when searching a directory,
2407 * server or network share. */
2408 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002409 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002410 if (*porig == psepc && slen + 2 < _MAX_PATH)
2411 STRCPY(szTrueNameTemp + slen, "\\*");
2412
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413 /* Skip "", "." and "..". */
2414 if (ptrue > ptruePrev
2415 && (ptruePrev[0] != '.'
2416 || (ptruePrev[1] != NUL
2417 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002418 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 != INVALID_HANDLE_VALUE)
2420 {
2421 c = *porig;
2422 *porig = NUL;
2423
2424 /* Only use the match when it's the same name (ignoring case) or
2425 * expansion is allowed and there is a match with the short name
2426 * and there is enough room. */
2427 if (_stricoll(porigPrev, fb.cFileName) == 0
2428 || (len > 0
2429 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2430 && (int)(ptruePrev - szTrueName)
2431 + (int)strlen(fb.cFileName) < len)))
2432 {
2433 STRCPY(ptruePrev, fb.cFileName);
2434
2435 /* Look for exact match and prefer it if found. Must be a
2436 * long name, otherwise there would be only one match. */
2437 while (FindNextFile(hFind, &fb))
2438 {
2439 if (*fb.cAlternateFileName != NUL
2440 && (strcoll(porigPrev, fb.cFileName) == 0
2441 || (len > 0
2442 && (_stricoll(porigPrev,
2443 fb.cAlternateFileName) == 0
2444 && (int)(ptruePrev - szTrueName)
2445 + (int)strlen(fb.cFileName) < len))))
2446 {
2447 STRCPY(ptruePrev, fb.cFileName);
2448 break;
2449 }
2450 }
2451 }
2452 FindClose(hFind);
2453 *porig = c;
2454 ptrue = ptruePrev + strlen(ptruePrev);
2455 }
2456 }
2457
2458 STRCPY(name, szTrueName);
2459}
2460
2461
2462/*
2463 * Insert user name in s[len].
2464 */
2465 int
2466mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002467 char_u *s,
2468 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002470 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471 DWORD cch = sizeof szUserName;
2472
2473 if (GetUserName(szUserName, &cch))
2474 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002475 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002476 return OK;
2477 }
2478 s[0] = NUL;
2479 return FAIL;
2480}
2481
2482
2483/*
2484 * Insert host name in s[len].
2485 */
2486 void
2487mch_get_host_name(
2488 char_u *s,
2489 int len)
2490{
2491 DWORD cch = len;
2492
2493 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002494 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495}
2496
2497
2498/*
2499 * return process ID
2500 */
2501 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002502mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503{
2504 return (long)GetCurrentProcessId();
2505}
2506
2507
2508/*
2509 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2510 * Return OK for success, FAIL for failure.
2511 */
2512 int
2513mch_dirname(
2514 char_u *buf,
2515 int len)
2516{
2517 /*
2518 * Originally this was:
2519 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2520 * But the Win32s known bug list says that getcwd() doesn't work
2521 * so use the Win32 system call instead. <Negri>
2522 */
2523#ifdef FEAT_MBYTE
2524 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2525 {
2526 WCHAR wbuf[_MAX_PATH + 1];
2527
2528 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2529 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002530 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531
2532 if (p != NULL)
2533 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002534 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 vim_free(p);
2536 return OK;
2537 }
2538 }
2539 /* Retry with non-wide function (for Windows 98). */
2540 }
2541#endif
2542 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2543}
2544
2545/*
2546 * get file permissions for `name'
2547 * -1 : error
2548 * else FILE_ATTRIBUTE_* defined in winnt.h
2549 */
2550 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002551mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552{
2553#ifdef FEAT_MBYTE
2554 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2555 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002556 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557 long n;
2558
2559 if (p != NULL)
2560 {
2561 n = (long)GetFileAttributesW(p);
2562 vim_free(p);
2563 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2564 return n;
2565 /* Retry with non-wide function (for Windows 98). */
2566 }
2567 }
2568#endif
2569 return (long)GetFileAttributes((char *)name);
2570}
2571
2572
2573/*
2574 * set file permission for `name' to `perm'
2575 */
2576 int
2577mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002578 char_u *name,
2579 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580{
2581 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2582#ifdef FEAT_MBYTE
2583 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2584 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002585 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586 long n;
2587
2588 if (p != NULL)
2589 {
2590 n = (long)SetFileAttributesW(p, perm);
2591 vim_free(p);
2592 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2593 return n ? OK : FAIL;
2594 /* Retry with non-wide function (for Windows 98). */
2595 }
2596 }
2597#endif
2598 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2599}
2600
2601/*
2602 * Set hidden flag for "name".
2603 */
2604 void
2605mch_hide(char_u *name)
2606{
2607 int perm;
2608#ifdef FEAT_MBYTE
2609 WCHAR *p = NULL;
2610
2611 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002612 p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002613#endif
2614
2615#ifdef FEAT_MBYTE
2616 if (p != NULL)
2617 {
2618 perm = GetFileAttributesW(p);
2619 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2620 {
2621 /* Retry with non-wide function (for Windows 98). */
2622 vim_free(p);
2623 p = NULL;
2624 }
2625 }
2626 if (p == NULL)
2627#endif
2628 perm = GetFileAttributes((char *)name);
2629 if (perm >= 0)
2630 {
2631 perm |= FILE_ATTRIBUTE_HIDDEN;
2632#ifdef FEAT_MBYTE
2633 if (p != NULL)
2634 {
2635 if (SetFileAttributesW(p, perm) == 0
2636 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2637 {
2638 /* Retry with non-wide function (for Windows 98). */
2639 vim_free(p);
2640 p = NULL;
2641 }
2642 }
2643 if (p == NULL)
2644#endif
2645 SetFileAttributes((char *)name, perm);
2646 }
2647#ifdef FEAT_MBYTE
2648 vim_free(p);
2649#endif
2650}
2651
2652/*
2653 * return TRUE if "name" is a directory
2654 * return FALSE if "name" is not a directory or upon error
2655 */
2656 int
2657mch_isdir(char_u *name)
2658{
2659 int f = mch_getperm(name);
2660
2661 if (f == -1)
2662 return FALSE; /* file does not exist at all */
2663
2664 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2665}
2666
2667/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002668 * Create directory "name".
2669 * Return 0 on success, -1 on error.
2670 */
2671 int
2672mch_mkdir(char_u *name)
2673{
2674#ifdef FEAT_MBYTE
2675 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2676 {
2677 WCHAR *p;
2678 int retval;
2679
2680 p = enc_to_utf16(name, NULL);
2681 if (p == NULL)
2682 return -1;
2683 retval = _wmkdir(p);
2684 vim_free(p);
2685 return retval;
2686 }
2687#endif
2688 return _mkdir(name);
2689}
2690
2691/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002692 * Return TRUE if file "fname" has more than one link.
2693 */
2694 int
2695mch_is_linked(char_u *fname)
2696{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002697 BY_HANDLE_FILE_INFORMATION info;
2698
2699 return win32_fileinfo(fname, &info) == FILEINFO_OK
2700 && info.nNumberOfLinks > 1;
2701}
2702
2703/*
2704 * Get the by-handle-file-information for "fname".
2705 * Returns FILEINFO_OK when OK.
2706 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
2707 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
2708 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
2709 */
2710 int
2711win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
2712{
Bram Moolenaar03f48552006-02-28 23:52:23 +00002713 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002714 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002715#ifdef FEAT_MBYTE
2716 WCHAR *wn = NULL;
2717
2718 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002719 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002720 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002721 if (wn == NULL)
2722 res = FILEINFO_ENC_FAIL;
2723 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00002724 if (wn != NULL)
2725 {
2726 hFile = CreateFileW(wn, /* file name */
2727 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002728 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002729 NULL, /* security descriptor */
2730 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002731 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002732 NULL); /* handle to template file */
2733 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002734 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002735 {
2736 /* Retry with non-wide function (for Windows 98). */
2737 vim_free(wn);
2738 wn = NULL;
2739 }
2740 }
2741 if (wn == NULL)
2742#endif
2743 hFile = CreateFile(fname, /* file name */
2744 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002745 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002746 NULL, /* security descriptor */
2747 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002748 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002749 NULL); /* handle to template file */
2750
2751 if (hFile != INVALID_HANDLE_VALUE)
2752 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002753 if (GetFileInformationByHandle(hFile, info) != 0)
2754 res = FILEINFO_OK;
2755 else
2756 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002757 CloseHandle(hFile);
2758 }
2759
2760#ifdef FEAT_MBYTE
2761 vim_free(wn);
2762#endif
2763 return res;
2764}
2765
2766/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767 * Return TRUE if file or directory "name" is writable (not readonly).
2768 * Strange semantics of Win32: a readonly directory is writable, but you can't
2769 * delete a file. Let's say this means it is writable.
2770 */
2771 int
2772mch_writable(char_u *name)
2773{
2774 int perm = mch_getperm(name);
2775
2776 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2777 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2778}
2779
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780/*
2781 * Return 1 if "name" can be executed, 0 if not.
2782 * Return -1 if unknown.
2783 */
2784 int
2785mch_can_exe(char_u *name)
2786{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002787 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002788 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002789 char_u *p;
2790
2791 if (len >= _MAX_PATH) /* safety check */
2792 return FALSE;
2793
2794 /* If there already is an extension try using the name directly. Also do
2795 * this with a Unix-shell like 'shell'. */
2796 if (vim_strchr(gettail(name), '.') != NULL
2797 || strstr((char *)gettail(p_sh), "sh") != NULL)
2798 if (executable_exists((char *)name))
2799 return TRUE;
2800
2801 /*
2802 * Loop over all extensions in $PATHEXT.
2803 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002804 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002805 p = mch_getenv("PATHEXT");
2806 if (p == NULL)
2807 p = (char_u *)".com;.exe;.bat;.cmd";
2808 while (*p)
2809 {
2810 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2811 {
2812 /* A single "." means no extension is added. */
2813 buf[len] = NUL;
2814 ++p;
2815 if (*p)
2816 ++p;
2817 }
2818 else
2819 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2820 if (executable_exists((char *)buf))
2821 return TRUE;
2822 }
2823 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825
2826/*
2827 * Check what "name" is:
2828 * NODE_NORMAL: file or directory (or doesn't exist)
2829 * NODE_WRITABLE: writable device, socket, fifo, etc.
2830 * NODE_OTHER: non-writable things
2831 */
2832 int
2833mch_nodetype(char_u *name)
2834{
2835 HANDLE hFile;
2836 int type;
2837
Bram Moolenaar043545e2006-10-10 16:44:07 +00002838 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2839 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2840 * here. */
2841 if (STRNCMP(name, "\\\\.\\", 4) == 0)
2842 return NODE_WRITABLE;
2843
Bram Moolenaar071d4272004-06-13 20:20:40 +00002844 hFile = CreateFile(name, /* file name */
2845 GENERIC_WRITE, /* access mode */
2846 0, /* share mode */
2847 NULL, /* security descriptor */
2848 OPEN_EXISTING, /* creation disposition */
2849 0, /* file attributes */
2850 NULL); /* handle to template file */
2851
2852 if (hFile == INVALID_HANDLE_VALUE)
2853 return NODE_NORMAL;
2854
2855 type = GetFileType(hFile);
2856 CloseHandle(hFile);
2857 if (type == FILE_TYPE_CHAR)
2858 return NODE_WRITABLE;
2859 if (type == FILE_TYPE_DISK)
2860 return NODE_NORMAL;
2861 return NODE_OTHER;
2862}
2863
2864#ifdef HAVE_ACL
2865struct my_acl
2866{
2867 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2868 PSID pSidOwner;
2869 PSID pSidGroup;
2870 PACL pDacl;
2871 PACL pSacl;
2872};
2873#endif
2874
2875/*
2876 * Return a pointer to the ACL of file "fname" in allocated memory.
2877 * Return NULL if the ACL is not available for whatever reason.
2878 */
2879 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002880mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881{
2882#ifndef HAVE_ACL
2883 return (vim_acl_T)NULL;
2884#else
2885 struct my_acl *p = NULL;
2886
2887 /* This only works on Windows NT and 2000. */
2888 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2889 {
2890 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2891 if (p != NULL)
2892 {
2893 if (pGetNamedSecurityInfo(
2894 (LPTSTR)fname, // Abstract filename
2895 SE_FILE_OBJECT, // File Object
2896 // Retrieve the entire security descriptor.
2897 OWNER_SECURITY_INFORMATION |
2898 GROUP_SECURITY_INFORMATION |
2899 DACL_SECURITY_INFORMATION |
2900 SACL_SECURITY_INFORMATION,
2901 &p->pSidOwner, // Ownership information.
2902 &p->pSidGroup, // Group membership.
2903 &p->pDacl, // Discretionary information.
2904 &p->pSacl, // For auditing purposes.
2905 &p->pSecurityDescriptor
2906 ) != ERROR_SUCCESS)
2907 {
2908 mch_free_acl((vim_acl_T)p);
2909 p = NULL;
2910 }
2911 }
2912 }
2913
2914 return (vim_acl_T)p;
2915#endif
2916}
2917
2918/*
2919 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2920 * Errors are ignored.
2921 * This must only be called with "acl" equal to what mch_get_acl() returned.
2922 */
2923 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002924mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925{
2926#ifdef HAVE_ACL
2927 struct my_acl *p = (struct my_acl *)acl;
2928
2929 if (p != NULL && advapi_lib != NULL)
2930 (void)pSetNamedSecurityInfo(
2931 (LPTSTR)fname, // Abstract filename
2932 SE_FILE_OBJECT, // File Object
2933 // Retrieve the entire security descriptor.
2934 OWNER_SECURITY_INFORMATION |
2935 GROUP_SECURITY_INFORMATION |
2936 DACL_SECURITY_INFORMATION |
2937 SACL_SECURITY_INFORMATION,
2938 p->pSidOwner, // Ownership information.
2939 p->pSidGroup, // Group membership.
2940 p->pDacl, // Discretionary information.
2941 p->pSacl // For auditing purposes.
2942 );
2943#endif
2944}
2945
2946 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002947mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948{
2949#ifdef HAVE_ACL
2950 struct my_acl *p = (struct my_acl *)acl;
2951
2952 if (p != NULL)
2953 {
2954 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2955 vim_free(p);
2956 }
2957#endif
2958}
2959
2960#ifndef FEAT_GUI_W32
2961
2962/*
2963 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2964 */
2965 static BOOL WINAPI
2966handler_routine(
2967 DWORD dwCtrlType)
2968{
2969 switch (dwCtrlType)
2970 {
2971 case CTRL_C_EVENT:
2972 if (ctrl_c_interrupts)
2973 g_fCtrlCPressed = TRUE;
2974 return TRUE;
2975
2976 case CTRL_BREAK_EVENT:
2977 g_fCBrkPressed = TRUE;
2978 return TRUE;
2979
2980 /* fatal events: shut down gracefully */
2981 case CTRL_CLOSE_EVENT:
2982 case CTRL_LOGOFF_EVENT:
2983 case CTRL_SHUTDOWN_EVENT:
2984 windgoto((int)Rows - 1, 0);
2985 g_fForceExit = TRUE;
2986
Bram Moolenaar0fde2902008-03-16 13:54:13 +00002987 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988 (dwCtrlType == CTRL_CLOSE_EVENT
2989 ? _("close")
2990 : dwCtrlType == CTRL_LOGOFF_EVENT
2991 ? _("logoff")
2992 : _("shutdown")));
2993#ifdef DEBUG
2994 OutputDebugString(IObuff);
2995#endif
2996
2997 preserve_exit(); /* output IObuff, preserve files and exit */
2998
2999 return TRUE; /* not reached */
3000
3001 default:
3002 return FALSE;
3003 }
3004}
3005
3006
3007/*
3008 * set the tty in (raw) ? "raw" : "cooked" mode
3009 */
3010 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003011mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012{
3013 DWORD cmodein;
3014 DWORD cmodeout;
3015 BOOL bEnableHandler;
3016
3017 GetConsoleMode(g_hConIn, &cmodein);
3018 GetConsoleMode(g_hConOut, &cmodeout);
3019 if (tmode == TMODE_RAW)
3020 {
3021 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3022 ENABLE_ECHO_INPUT);
3023#ifdef FEAT_MOUSE
3024 if (g_fMouseActive)
3025 cmodein |= ENABLE_MOUSE_INPUT;
3026#endif
3027 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3028 bEnableHandler = TRUE;
3029 }
3030 else /* cooked */
3031 {
3032 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3033 ENABLE_ECHO_INPUT);
3034 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3035 bEnableHandler = FALSE;
3036 }
3037 SetConsoleMode(g_hConIn, cmodein);
3038 SetConsoleMode(g_hConOut, cmodeout);
3039 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3040
3041#ifdef MCH_WRITE_DUMP
3042 if (fdDump)
3043 {
3044 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3045 tmode == TMODE_RAW ? "raw" :
3046 tmode == TMODE_COOK ? "cooked" : "normal",
3047 cmodein, cmodeout);
3048 fflush(fdDump);
3049 }
3050#endif
3051}
3052
3053
3054/*
3055 * Get the size of the current window in `Rows' and `Columns'
3056 * Return OK when size could be determined, FAIL otherwise.
3057 */
3058 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003059mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060{
3061 CONSOLE_SCREEN_BUFFER_INFO csbi;
3062
3063 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3064 {
3065 /*
3066 * For some reason, we are trying to get the screen dimensions
3067 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3068 * variables are really intended to mean the size of Vim screen
3069 * while in termcap mode.
3070 */
3071 Rows = g_cbTermcap.Info.dwSize.Y;
3072 Columns = g_cbTermcap.Info.dwSize.X;
3073 }
3074 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3075 {
3076 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3077 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3078 }
3079 else
3080 {
3081 Rows = 25;
3082 Columns = 80;
3083 }
3084 return OK;
3085}
3086
3087/*
3088 * Set a console window to `xSize' * `ySize'
3089 */
3090 static void
3091ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003092 HANDLE hConsole,
3093 int xSize,
3094 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095{
3096 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3097 SMALL_RECT srWindowRect; /* hold the new console size */
3098 COORD coordScreen;
3099
3100#ifdef MCH_WRITE_DUMP
3101 if (fdDump)
3102 {
3103 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3104 fflush(fdDump);
3105 }
3106#endif
3107
3108 /* get the largest size we can size the console window to */
3109 coordScreen = GetLargestConsoleWindowSize(hConsole);
3110
3111 /* define the new console window size and scroll position */
3112 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3113 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3114 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3115
3116 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3117 {
3118 int sx, sy;
3119
3120 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3121 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3122 if (sy < ySize || sx < xSize)
3123 {
3124 /*
3125 * Increasing number of lines/columns, do buffer first.
3126 * Use the maximal size in x and y direction.
3127 */
3128 if (sy < ySize)
3129 coordScreen.Y = ySize;
3130 else
3131 coordScreen.Y = sy;
3132 if (sx < xSize)
3133 coordScreen.X = xSize;
3134 else
3135 coordScreen.X = sx;
3136 SetConsoleScreenBufferSize(hConsole, coordScreen);
3137 }
3138 }
3139
3140 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3141 {
3142#ifdef MCH_WRITE_DUMP
3143 if (fdDump)
3144 {
3145 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3146 GetLastError());
3147 fflush(fdDump);
3148 }
3149#endif
3150 }
3151
3152 /* define the new console buffer size */
3153 coordScreen.X = xSize;
3154 coordScreen.Y = ySize;
3155
3156 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3157 {
3158#ifdef MCH_WRITE_DUMP
3159 if (fdDump)
3160 {
3161 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3162 GetLastError());
3163 fflush(fdDump);
3164 }
3165#endif
3166 }
3167}
3168
3169
3170/*
3171 * Set the console window to `Rows' * `Columns'
3172 */
3173 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003174mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175{
3176 COORD coordScreen;
3177
3178 /* Don't change window size while still starting up */
3179 if (suppress_winsize != 0)
3180 {
3181 suppress_winsize = 2;
3182 return;
3183 }
3184
3185 if (term_console)
3186 {
3187 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3188
3189 /* Clamp Rows and Columns to reasonable values */
3190 if (Rows > coordScreen.Y)
3191 Rows = coordScreen.Y;
3192 if (Columns > coordScreen.X)
3193 Columns = coordScreen.X;
3194
3195 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3196 }
3197}
3198
3199/*
3200 * Rows and/or Columns has changed.
3201 */
3202 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003203mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204{
3205 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3206}
3207
3208
3209/*
3210 * Called when started up, to set the winsize that was delayed.
3211 */
3212 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003213mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214{
3215 if (suppress_winsize == 2)
3216 {
3217 suppress_winsize = 0;
3218 mch_set_shellsize();
3219 shell_resized();
3220 }
3221 suppress_winsize = 0;
3222}
3223#endif /* FEAT_GUI_W32 */
3224
3225
3226
3227#if defined(FEAT_GUI_W32) || defined(PROTO)
3228
3229/*
3230 * Specialised version of system() for Win32 GUI mode.
3231 * This version proceeds as follows:
3232 * 1. Create a console window for use by the subprocess
3233 * 2. Run the subprocess (it gets the allocated console by default)
3234 * 3. Wait for the subprocess to terminate and get its exit code
3235 * 4. Prompt the user to press a key to close the console window
3236 */
3237 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003238mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003239{
3240 STARTUPINFO si;
3241 PROCESS_INFORMATION pi;
3242 DWORD ret = 0;
3243 HWND hwnd = GetFocus();
3244
3245 si.cb = sizeof(si);
3246 si.lpReserved = NULL;
3247 si.lpDesktop = NULL;
3248 si.lpTitle = NULL;
3249 si.dwFlags = STARTF_USESHOWWINDOW;
3250 /*
3251 * It's nicer to run a filter command in a minimized window, but in
3252 * Windows 95 this makes the command MUCH slower. We can't do it under
3253 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003254 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255 */
3256 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003257 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258 else
3259 si.wShowWindow = SW_SHOWNORMAL;
3260 si.cbReserved2 = 0;
3261 si.lpReserved2 = NULL;
3262
3263 /* There is a strange error on Windows 95 when using "c:\\command.com".
3264 * When the "c:\\" is left out it works OK...? */
3265 if (mch_windows95()
3266 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3267 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3268 cmd += 3;
3269
3270 /* Now, run the command */
3271 CreateProcess(NULL, /* Executable name */
3272 cmd, /* Command to execute */
3273 NULL, /* Process security attributes */
3274 NULL, /* Thread security attributes */
3275 FALSE, /* Inherit handles */
3276 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3277 CREATE_NEW_CONSOLE,
3278 NULL, /* Environment */
3279 NULL, /* Current directory */
3280 &si, /* Startup information */
3281 &pi); /* Process information */
3282
3283
3284 /* Wait for the command to terminate before continuing */
3285 if (g_PlatformId != VER_PLATFORM_WIN32s)
3286 {
3287#ifdef FEAT_GUI
3288 int delay = 1;
3289
3290 /* Keep updating the window while waiting for the shell to finish. */
3291 for (;;)
3292 {
3293 MSG msg;
3294
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003295 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003296 {
3297 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003298 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299 }
3300 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3301 break;
3302
3303 /* We start waiting for a very short time and then increase it, so
3304 * that we respond quickly when the process is quick, and don't
3305 * consume too much overhead when it's slow. */
3306 if (delay < 50)
3307 delay += 10;
3308 }
3309#else
3310 WaitForSingleObject(pi.hProcess, INFINITE);
3311#endif
3312
3313 /* Get the command exit code */
3314 GetExitCodeProcess(pi.hProcess, &ret);
3315 }
3316 else
3317 {
3318 /*
3319 * This ugly code is the only quick way of performing
3320 * a synchronous spawn under Win32s. Yuk.
3321 */
3322 num_windows = 0;
3323 EnumWindows(win32ssynch_cb, 0);
3324 old_num_windows = num_windows;
3325 do
3326 {
3327 Sleep(1000);
3328 num_windows = 0;
3329 EnumWindows(win32ssynch_cb, 0);
3330 } while (num_windows == old_num_windows);
3331 ret = 0;
3332 }
3333
3334 /* Close the handles to the subprocess, so that it goes away */
3335 CloseHandle(pi.hThread);
3336 CloseHandle(pi.hProcess);
3337
3338 /* Try to get input focus back. Doesn't always work though. */
3339 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3340
3341 return ret;
3342}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003343
3344/*
3345 * Thread launched by the gui to send the current buffer data to the
3346 * process. This way avoid to hang up vim totally if the children
3347 * process take a long time to process the lines.
3348 */
3349 static DWORD WINAPI
3350sub_process_writer(LPVOID param)
3351{
3352 HANDLE g_hChildStd_IN_Wr = param;
3353 linenr_T lnum = curbuf->b_op_start.lnum;
3354 DWORD len = 0;
3355 DWORD l;
3356 char_u *lp = ml_get(lnum);
3357 char_u *s;
3358 int written = 0;
3359
3360 for (;;)
3361 {
3362 l = (DWORD)STRLEN(lp + written);
3363 if (l == 0)
3364 len = 0;
3365 else if (lp[written] == NL)
3366 {
3367 /* NL -> NUL translation */
3368 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3369 }
3370 else
3371 {
3372 s = vim_strchr(lp + written, NL);
3373 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3374 s == NULL ? l : (DWORD)(s - (lp + written)),
3375 &len, NULL);
3376 }
3377 if (len == (int)l)
3378 {
3379 /* Finished a line, add a NL, unless this line should not have
3380 * one. */
3381 if (lnum != curbuf->b_op_end.lnum
3382 || !curbuf->b_p_bin
3383 || (lnum != curbuf->b_no_eol_lnum
3384 && (lnum != curbuf->b_ml.ml_line_count
3385 || curbuf->b_p_eol)))
3386 {
3387 WriteFile(g_hChildStd_IN_Wr, "\n", 1, &ignored, NULL);
3388 }
3389
3390 ++lnum;
3391 if (lnum > curbuf->b_op_end.lnum)
3392 break;
3393
3394 lp = ml_get(lnum);
3395 written = 0;
3396 }
3397 else if (len > 0)
3398 written += len;
3399 }
3400
3401 /* finished all the lines, close pipe */
3402 CloseHandle(g_hChildStd_IN_Wr);
3403 ExitThread(0);
3404}
3405
3406
3407# define BUFLEN 100 /* length for buffer, stolen from unix version */
3408
3409/*
3410 * This function read from the children's stdout and write the
3411 * data on screen or in the buffer accordingly.
3412 */
3413 static void
3414dump_pipe(int options,
3415 HANDLE g_hChildStd_OUT_Rd,
3416 garray_T *ga,
3417 char_u buffer[],
3418 DWORD *buffer_off)
3419{
3420 DWORD availableBytes = 0;
3421 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003422 int ret;
3423 DWORD len;
3424 DWORD toRead;
3425 int repeatCount;
3426
3427 /* we query the pipe to see if there is any data to read
3428 * to avoid to perform a blocking read */
3429 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3430 NULL, /* optional buffer */
3431 0, /* buffe size */
3432 NULL, /* number of read bytes */
3433 &availableBytes, /* available bytes total */
3434 NULL); /* byteLeft */
3435
3436 repeatCount = 0;
3437 /* We got real data in the pipe, read it */
3438 while (ret != 0 && availableBytes > 0 && availableBytes > 0)
3439 {
3440 repeatCount++;
3441 toRead =
3442# ifdef FEAT_MBYTE
3443 (DWORD)(BUFLEN - *buffer_off);
3444# else
3445 (DWORD)BUFLEN;
3446# endif
3447 toRead = availableBytes < toRead ? availableBytes : toRead;
3448 ReadFile(g_hChildStd_OUT_Rd, buffer
3449# ifdef FEAT_MBYTE
3450 + *buffer_off, toRead
3451# else
3452 , toRead
3453# endif
3454 , &len, NULL);
3455
3456 /* If we haven't read anything, there is a problem */
3457 if (len == 0)
3458 break;
3459
3460 availableBytes -= len;
3461
3462 if (options & SHELL_READ)
3463 {
3464 /* Do NUL -> NL translation, append NL separated
3465 * lines to the current buffer. */
3466 for (i = 0; i < len; ++i)
3467 {
3468 if (buffer[i] == NL)
3469 append_ga_line(ga);
3470 else if (buffer[i] == NUL)
3471 ga_append(ga, NL);
3472 else
3473 ga_append(ga, buffer[i]);
3474 }
3475 }
3476# ifdef FEAT_MBYTE
3477 else if (has_mbyte)
3478 {
3479 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003480 int c;
3481 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003482
3483 len += *buffer_off;
3484 buffer[len] = NUL;
3485
3486 /* Check if the last character in buffer[] is
3487 * incomplete, keep these bytes for the next
3488 * round. */
3489 for (p = buffer; p < buffer + len; p += l)
3490 {
3491 l = mb_cptr2len(p);
3492 if (l == 0)
3493 l = 1; /* NUL byte? */
3494 else if (MB_BYTE2LEN(*p) != l)
3495 break;
3496 }
3497 if (p == buffer) /* no complete character */
3498 {
3499 /* avoid getting stuck at an illegal byte */
3500 if (len >= 12)
3501 ++p;
3502 else
3503 {
3504 *buffer_off = len;
3505 return;
3506 }
3507 }
3508 c = *p;
3509 *p = NUL;
3510 msg_puts(buffer);
3511 if (p < buffer + len)
3512 {
3513 *p = c;
3514 *buffer_off = (DWORD)((buffer + len) - p);
3515 mch_memmove(buffer, p, *buffer_off);
3516 return;
3517 }
3518 *buffer_off = 0;
3519 }
3520# endif /* FEAT_MBYTE */
3521 else
3522 {
3523 buffer[len] = NUL;
3524 msg_puts(buffer);
3525 }
3526
3527 windgoto(msg_row, msg_col);
3528 cursor_on();
3529 out_flush();
3530 }
3531}
3532
3533/*
3534 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
3535 * for communication and doesn't open any new window.
3536 */
3537 static int
3538mch_system_piped(char *cmd, int options)
3539{
3540 STARTUPINFO si;
3541 PROCESS_INFORMATION pi;
3542 DWORD ret = 0;
3543
3544 HANDLE g_hChildStd_IN_Rd = NULL;
3545 HANDLE g_hChildStd_IN_Wr = NULL;
3546 HANDLE g_hChildStd_OUT_Rd = NULL;
3547 HANDLE g_hChildStd_OUT_Wr = NULL;
3548
3549 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
3550 DWORD len;
3551
3552 /* buffer used to receive keys */
3553 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3554 int ta_len = 0; /* valid bytes in ta_buf[] */
3555
3556 DWORD i;
3557 int c;
3558 int noread_cnt = 0;
3559 garray_T ga;
3560 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003561 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003562
3563 SECURITY_ATTRIBUTES saAttr;
3564
3565 /* Set the bInheritHandle flag so pipe handles are inherited. */
3566 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
3567 saAttr.bInheritHandle = TRUE;
3568 saAttr.lpSecurityDescriptor = NULL;
3569
3570 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
3571 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
3572 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
3573 /* Create a pipe for the child process's STDIN. */
3574 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
3575 /* Ensure the write handle to the pipe for STDIN is not inherited. */
3576 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
3577 {
3578 CloseHandle(g_hChildStd_IN_Rd);
3579 CloseHandle(g_hChildStd_IN_Wr);
3580 CloseHandle(g_hChildStd_OUT_Rd);
3581 CloseHandle(g_hChildStd_OUT_Wr);
3582 MSG_PUTS(_("\nCannot create pipes\n"));
3583 }
3584
3585 si.cb = sizeof(si);
3586 si.lpReserved = NULL;
3587 si.lpDesktop = NULL;
3588 si.lpTitle = NULL;
3589 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
3590
3591 /* set-up our file redirection */
3592 si.hStdError = g_hChildStd_OUT_Wr;
3593 si.hStdOutput = g_hChildStd_OUT_Wr;
3594 si.hStdInput = g_hChildStd_IN_Rd;
3595 si.wShowWindow = SW_HIDE;
3596 si.cbReserved2 = 0;
3597 si.lpReserved2 = NULL;
3598
3599 if (options & SHELL_READ)
3600 ga_init2(&ga, 1, BUFLEN);
3601
3602 /* Now, run the command */
3603 CreateProcess(NULL, /* Executable name */
3604 cmd, /* Command to execute */
3605 NULL, /* Process security attributes */
3606 NULL, /* Thread security attributes */
3607
3608 // this command can be litigeous, handle inheritence was
3609 // deactivated for pending temp file, but, if we deactivate
3610 // it, the pipes don't work for some reason.
3611 TRUE, /* Inherit handles, first deactivated,
3612 * but needed */
3613 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
3614 NULL, /* Environment */
3615 NULL, /* Current directory */
3616 &si, /* Startup information */
3617 &pi); /* Process information */
3618
3619
3620 /* Close our unused side of the pipes */
3621 CloseHandle(g_hChildStd_IN_Rd);
3622 CloseHandle(g_hChildStd_OUT_Wr);
3623
3624 if (options & SHELL_WRITE)
3625 {
3626 HANDLE thread =
3627 CreateThread(NULL, /* security attributes */
3628 0, /* default stack size */
3629 sub_process_writer, /* function to be executed */
3630 g_hChildStd_IN_Wr, /* parameter */
3631 0, /* creation flag, start immediately */
3632 NULL); /* we don't care about thread id */
3633 CloseHandle(thread);
3634 g_hChildStd_IN_Wr = NULL;
3635 }
3636
3637 /* Keep updating the window while waiting for the shell to finish. */
3638 for (;;)
3639 {
3640 MSG msg;
3641
3642 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3643 {
3644 TranslateMessage(&msg);
3645 DispatchMessage(&msg);
3646 }
3647
3648 /* write pipe information in the window */
3649 if ((options & (SHELL_READ|SHELL_WRITE))
3650# ifdef FEAT_GUI
3651 || gui.in_use
3652# endif
3653 )
3654 {
3655 len = 0;
3656 if (!(options & SHELL_EXPAND)
3657 && ((options &
3658 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
3659 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
3660# ifdef FEAT_GUI
3661 || gui.in_use
3662# endif
3663 )
3664 && (ta_len > 0 || noread_cnt > 4))
3665 {
3666 if (ta_len == 0)
3667 {
3668 /* Get extra characters when we don't have any. Reset the
3669 * counter and timer. */
3670 noread_cnt = 0;
3671# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
3672 gettimeofday(&start_tv, NULL);
3673# endif
3674 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
3675 }
3676 if (ta_len > 0 || len > 0)
3677 {
3678 /*
3679 * For pipes: Check for CTRL-C: send interrupt signal to
3680 * child. Check for CTRL-D: EOF, close pipe to child.
3681 */
3682 if (len == 1 && cmd != NULL)
3683 {
3684 if (ta_buf[ta_len] == Ctrl_C)
3685 {
3686 /* Learn what exit code is expected, for
3687 * now put 9 as SIGKILL */
3688 TerminateProcess(pi.hProcess, 9);
3689 }
3690 if (ta_buf[ta_len] == Ctrl_D)
3691 {
3692 CloseHandle(g_hChildStd_IN_Wr);
3693 g_hChildStd_IN_Wr = NULL;
3694 }
3695 }
3696
3697 /* replace K_BS by <BS> and K_DEL by <DEL> */
3698 for (i = ta_len; i < ta_len + len; ++i)
3699 {
3700 if (ta_buf[i] == CSI && len - i > 2)
3701 {
3702 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
3703 if (c == K_DEL || c == K_KDEL || c == K_BS)
3704 {
3705 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
3706 (size_t)(len - i - 2));
3707 if (c == K_DEL || c == K_KDEL)
3708 ta_buf[i] = DEL;
3709 else
3710 ta_buf[i] = Ctrl_H;
3711 len -= 2;
3712 }
3713 }
3714 else if (ta_buf[i] == '\r')
3715 ta_buf[i] = '\n';
3716# ifdef FEAT_MBYTE
3717 if (has_mbyte)
3718 i += (*mb_ptr2len_len)(ta_buf + i,
3719 ta_len + len - i) - 1;
3720# endif
3721 }
3722
3723 /*
3724 * For pipes: echo the typed characters. For a pty this
3725 * does not seem to work.
3726 */
3727 for (i = ta_len; i < ta_len + len; ++i)
3728 {
3729 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
3730 msg_putchar(ta_buf[i]);
3731# ifdef FEAT_MBYTE
3732 else if (has_mbyte)
3733 {
3734 int l = (*mb_ptr2len)(ta_buf + i);
3735
3736 msg_outtrans_len(ta_buf + i, l);
3737 i += l - 1;
3738 }
3739# endif
3740 else
3741 msg_outtrans_len(ta_buf + i, 1);
3742 }
3743 windgoto(msg_row, msg_col);
3744 out_flush();
3745
3746 ta_len += len;
3747
3748 /*
3749 * Write the characters to the child, unless EOF has been
3750 * typed for pipes. Write one character at a time, to
3751 * avoid losing too much typeahead. When writing buffer
3752 * lines, drop the typed characters (only check for
3753 * CTRL-C).
3754 */
3755 if (options & SHELL_WRITE)
3756 ta_len = 0;
3757 else if (g_hChildStd_IN_Wr != NULL)
3758 {
3759 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
3760 1, &len, NULL);
3761 // if we are typing in, we want to keep things reactive
3762 delay = 1;
3763 if (len > 0)
3764 {
3765 ta_len -= len;
3766 mch_memmove(ta_buf, ta_buf + len, ta_len);
3767 }
3768 }
3769 }
3770 }
3771 }
3772
3773 if (ta_len)
3774 ui_inchar_undo(ta_buf, ta_len);
3775
3776 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3777 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003778 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003779 break;
3780 }
3781
3782 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003783 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003784
3785 /* We start waiting for a very short time and then increase it, so
3786 * that we respond quickly when the process is quick, and don't
3787 * consume too much overhead when it's slow. */
3788 if (delay < 50)
3789 delay += 10;
3790 }
3791
3792 /* Close the pipe */
3793 CloseHandle(g_hChildStd_OUT_Rd);
3794 if (g_hChildStd_IN_Wr != NULL)
3795 CloseHandle(g_hChildStd_IN_Wr);
3796
3797 WaitForSingleObject(pi.hProcess, INFINITE);
3798
3799 /* Get the command exit code */
3800 GetExitCodeProcess(pi.hProcess, &ret);
3801
3802 if (options & SHELL_READ)
3803 {
3804 if (ga.ga_len > 0)
3805 {
3806 append_ga_line(&ga);
3807 /* remember that the NL was missing */
3808 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
3809 }
3810 else
3811 curbuf->b_no_eol_lnum = 0;
3812 ga_clear(&ga);
3813 }
3814
3815 /* Close the handles to the subprocess, so that it goes away */
3816 CloseHandle(pi.hThread);
3817 CloseHandle(pi.hProcess);
3818
3819 return ret;
3820}
3821
3822 static int
3823mch_system(char *cmd, int options)
3824{
3825 /* if we can pipe and the shelltemp option is off */
3826 if (allowPiping && !p_stmp)
3827 return mch_system_piped(cmd, options);
3828 else
3829 return mch_system_classic(cmd, options);
3830}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831#else
3832
3833# define mch_system(c, o) system(c)
3834
3835#endif
3836
3837/*
3838 * Either execute a command by calling the shell or start a new shell
3839 */
3840 int
3841mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003842 char_u *cmd,
3843 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003844{
3845 int x = 0;
3846 int tmode = cur_tmode;
3847#ifdef FEAT_TITLE
3848 char szShellTitle[512];
3849
3850 /* Change the title to reflect that we are in a subshell. */
3851 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3852 {
3853 if (cmd == NULL)
3854 strcat(szShellTitle, " :sh");
3855 else
3856 {
3857 strcat(szShellTitle, " - !");
3858 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3859 strcat(szShellTitle, cmd);
3860 }
3861 mch_settitle(szShellTitle, NULL);
3862 }
3863#endif
3864
3865 out_flush();
3866
3867#ifdef MCH_WRITE_DUMP
3868 if (fdDump)
3869 {
3870 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3871 fflush(fdDump);
3872 }
3873#endif
3874
3875 /*
3876 * Catch all deadly signals while running the external command, because a
3877 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3878 */
3879 signal(SIGINT, SIG_IGN);
3880#if defined(__GNUC__) && !defined(__MINGW32__)
3881 signal(SIGKILL, SIG_IGN);
3882#else
3883 signal(SIGBREAK, SIG_IGN);
3884#endif
3885 signal(SIGILL, SIG_IGN);
3886 signal(SIGFPE, SIG_IGN);
3887 signal(SIGSEGV, SIG_IGN);
3888 signal(SIGTERM, SIG_IGN);
3889 signal(SIGABRT, SIG_IGN);
3890
3891 if (options & SHELL_COOKED)
3892 settmode(TMODE_COOK); /* set to normal mode */
3893
3894 if (cmd == NULL)
3895 {
3896 x = mch_system(p_sh, options);
3897 }
3898 else
3899 {
3900 /* we use "command" or "cmd" to start the shell; slow but easy */
3901 char_u *newcmd;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003902 long_u cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003904 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003906 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
3907
3908 newcmd = lalloc(cmdlen, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 if (newcmd != NULL)
3910 {
Bram Moolenaar034b1152012-02-19 18:19:30 +01003911 char_u *cmdbase = cmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912
Bram Moolenaar034b1152012-02-19 18:19:30 +01003913 /* Skip a leading ", ( and "(. */
3914 if (*cmdbase == '"' )
3915 ++cmdbase;
3916 if (*cmdbase == '(')
3917 ++cmdbase;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3919 {
3920 STARTUPINFO si;
3921 PROCESS_INFORMATION pi;
Bram Moolenaarbd8608d2011-05-25 17:06:22 +02003922 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923
3924 si.cb = sizeof(si);
3925 si.lpReserved = NULL;
3926 si.lpDesktop = NULL;
3927 si.lpTitle = NULL;
3928 si.dwFlags = 0;
3929 si.cbReserved2 = 0;
3930 si.lpReserved2 = NULL;
3931
3932 cmdbase = skipwhite(cmdbase + 5);
3933 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3934 && vim_iswhite(cmdbase[4]))
3935 {
3936 cmdbase = skipwhite(cmdbase + 4);
3937 si.dwFlags = STARTF_USESHOWWINDOW;
3938 si.wShowWindow = SW_SHOWMINNOACTIVE;
3939 }
Bram Moolenaarbd8608d2011-05-25 17:06:22 +02003940 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
3941 && vim_iswhite(cmdbase[2]))
3942 {
3943 cmdbase = skipwhite(cmdbase + 2);
3944 flags = CREATE_NO_WINDOW;
3945 si.dwFlags = STARTF_USESTDHANDLES;
3946 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
3947 GENERIC_READ, // Access flags
3948 0, // Share flags
3949 NULL, // Security att.
3950 OPEN_EXISTING, // Open flags
3951 FILE_ATTRIBUTE_NORMAL, // File att.
3952 NULL); // Temp file
3953 si.hStdOutput = si.hStdInput;
3954 si.hStdError = si.hStdInput;
3955 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956
3957 /* When the command is in double quotes, but 'shellxquote' is
3958 * empty, keep the double quotes around the command.
3959 * Otherwise remove the double quotes, they aren't needed
3960 * here, because we don't use a shell to run the command. */
Bram Moolenaar034b1152012-02-19 18:19:30 +01003961 if (cmdbase > cmd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962 {
Bram Moolenaar034b1152012-02-19 18:19:30 +01003963 if (STRNCMP(cmd, p_sxq, cmd - cmdbase) != 0)
3964 {
3965 STRCPY(newcmd, cmd);
3966 }
3967 else
3968 {
3969 char_u *p;
3970
3971 STRCPY(newcmd, cmdbase);
3972 /* Remove a trailing ", ) and )" if they have a match
3973 * at the start of the command. */
3974 p = newcmd + STRLEN(newcmd);
3975 if (p > newcmd && p[-1] == '"' && *cmd == '"')
3976 *--p = NUL;
3977 if (p > newcmd && p[-1] == ')'
3978 && (*cmd =='(' || cmd[1] == '('))
3979 *--p = NUL;
3980 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003981 }
3982
3983 /*
3984 * Now, start the command as a process, so that it doesn't
3985 * inherit our handles which causes unpleasant dangling swap
3986 * files if we exit before the spawned process
3987 */
Bram Moolenaar034b1152012-02-19 18:19:30 +01003988 if (CreateProcess(NULL, // Executable name
Bram Moolenaar071d4272004-06-13 20:20:40 +00003989 newcmd, // Command to execute
3990 NULL, // Process security attributes
3991 NULL, // Thread security attributes
3992 FALSE, // Inherit handles
Bram Moolenaarbd8608d2011-05-25 17:06:22 +02003993 flags, // Creation flags
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994 NULL, // Environment
3995 NULL, // Current directory
3996 &si, // Startup information
3997 &pi)) // Process information
3998 x = 0;
3999 else
4000 {
4001 x = -1;
4002#ifdef FEAT_GUI_W32
4003 EMSG(_("E371: Command not found"));
4004#endif
4005 }
Bram Moolenaarbd8608d2011-05-25 17:06:22 +02004006 if (si.hStdInput != NULL)
4007 {
4008 /* Close the handle to \\.\NUL */
4009 CloseHandle(si.hStdInput);
4010 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004011 /* Close the handles to the subprocess, so that it goes away */
4012 CloseHandle(pi.hThread);
4013 CloseHandle(pi.hProcess);
4014 }
4015 else
4016 {
4017#if defined(FEAT_GUI_W32)
4018 if (need_vimrun_warning)
4019 {
4020 MessageBox(NULL,
4021 _("VIMRUN.EXE not found in your $PATH.\n"
4022 "External commands will not pause after completion.\n"
4023 "See :help win32-vimrun for more information."),
4024 _("Vim Warning"),
4025 MB_ICONWARNING);
4026 need_vimrun_warning = FALSE;
4027 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004028 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004029 /* Use vimrun to execute the command. It opens a console
4030 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004031 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032 vimrun_path,
4033 (msg_silent != 0 || (options & SHELL_DOOUT))
4034 ? "-s " : "",
4035 p_sh, p_shcf, cmd);
4036 else
4037#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004038 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004039 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004040 x = mch_system((char *)newcmd, options);
4041 }
4042 vim_free(newcmd);
4043 }
4044 }
4045
4046 if (tmode == TMODE_RAW)
4047 settmode(TMODE_RAW); /* set to raw mode */
4048
4049 /* Print the return value, unless "vimrun" was used. */
4050 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4051#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004052 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4053 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054#endif
4055 )
4056 {
4057 smsg(_("shell returned %d"), x);
4058 msg_putchar('\n');
4059 }
4060#ifdef FEAT_TITLE
4061 resettitle();
4062#endif
4063
4064 signal(SIGINT, SIG_DFL);
4065#if defined(__GNUC__) && !defined(__MINGW32__)
4066 signal(SIGKILL, SIG_DFL);
4067#else
4068 signal(SIGBREAK, SIG_DFL);
4069#endif
4070 signal(SIGILL, SIG_DFL);
4071 signal(SIGFPE, SIG_DFL);
4072 signal(SIGSEGV, SIG_DFL);
4073 signal(SIGTERM, SIG_DFL);
4074 signal(SIGABRT, SIG_DFL);
4075
4076 return x;
4077}
4078
4079
4080#ifndef FEAT_GUI_W32
4081
4082/*
4083 * Start termcap mode
4084 */
4085 static void
4086termcap_mode_start(void)
4087{
4088 DWORD cmodein;
4089
4090 if (g_fTermcapMode)
4091 return;
4092
4093 SaveConsoleBuffer(&g_cbNonTermcap);
4094
4095 if (g_cbTermcap.IsValid)
4096 {
4097 /*
4098 * We've been in termcap mode before. Restore certain screen
4099 * characteristics, including the buffer size and the window
4100 * size. Since we will be redrawing the screen, we don't need
4101 * to restore the actual contents of the buffer.
4102 */
4103 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4104 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4105 Rows = g_cbTermcap.Info.dwSize.Y;
4106 Columns = g_cbTermcap.Info.dwSize.X;
4107 }
4108 else
4109 {
4110 /*
4111 * This is our first time entering termcap mode. Clear the console
4112 * screen buffer, and resize the buffer to match the current window
4113 * size. We will use this as the size of our editing environment.
4114 */
4115 ClearConsoleBuffer(g_attrCurrent);
4116 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4117 }
4118
4119#ifdef FEAT_TITLE
4120 resettitle();
4121#endif
4122
4123 GetConsoleMode(g_hConIn, &cmodein);
4124#ifdef FEAT_MOUSE
4125 if (g_fMouseActive)
4126 cmodein |= ENABLE_MOUSE_INPUT;
4127 else
4128 cmodein &= ~ENABLE_MOUSE_INPUT;
4129#endif
4130 cmodein |= ENABLE_WINDOW_INPUT;
4131 SetConsoleMode(g_hConIn, cmodein);
4132
4133 redraw_later_clear();
4134 g_fTermcapMode = TRUE;
4135}
4136
4137
4138/*
4139 * End termcap mode
4140 */
4141 static void
4142termcap_mode_end(void)
4143{
4144 DWORD cmodein;
4145 ConsoleBuffer *cb;
4146 COORD coord;
4147 DWORD dwDummy;
4148
4149 if (!g_fTermcapMode)
4150 return;
4151
4152 SaveConsoleBuffer(&g_cbTermcap);
4153
4154 GetConsoleMode(g_hConIn, &cmodein);
4155 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4156 SetConsoleMode(g_hConIn, cmodein);
4157
4158#ifdef FEAT_RESTORE_ORIG_SCREEN
4159 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4160#else
4161 cb = &g_cbNonTermcap;
4162#endif
4163 RestoreConsoleBuffer(cb, p_rs);
4164 SetConsoleCursorInfo(g_hConOut, &g_cci);
4165
4166 if (p_rs || exiting)
4167 {
4168 /*
4169 * Clear anything that happens to be on the current line.
4170 */
4171 coord.X = 0;
4172 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4173 FillConsoleOutputCharacter(g_hConOut, ' ',
4174 cb->Info.dwSize.X, coord, &dwDummy);
4175 /*
4176 * The following is just for aesthetics. If we are exiting without
4177 * restoring the screen, then we want to have a prompt string
4178 * appear at the bottom line. However, the command interpreter
4179 * seems to always advance the cursor one line before displaying
4180 * the prompt string, which causes the screen to scroll. To
4181 * counter this, move the cursor up one line before exiting.
4182 */
4183 if (exiting && !p_rs)
4184 coord.Y--;
4185 /*
4186 * Position the cursor at the leftmost column of the desired row.
4187 */
4188 SetConsoleCursorPosition(g_hConOut, coord);
4189 }
4190
4191 g_fTermcapMode = FALSE;
4192}
4193#endif /* FEAT_GUI_W32 */
4194
4195
4196#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004197/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198 void
4199mch_write(
4200 char_u *s,
4201 int len)
4202{
4203 /* never used */
4204}
4205
4206#else
4207
4208/*
4209 * clear `n' chars, starting from `coord'
4210 */
4211 static void
4212clear_chars(
4213 COORD coord,
4214 DWORD n)
4215{
4216 DWORD dwDummy;
4217
4218 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4219 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4220}
4221
4222
4223/*
4224 * Clear the screen
4225 */
4226 static void
4227clear_screen(void)
4228{
4229 g_coord.X = g_coord.Y = 0;
4230 clear_chars(g_coord, Rows * Columns);
4231}
4232
4233
4234/*
4235 * Clear to end of display
4236 */
4237 static void
4238clear_to_end_of_display(void)
4239{
4240 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4241 * Columns + (Columns - g_coord.X));
4242}
4243
4244
4245/*
4246 * Clear to end of line
4247 */
4248 static void
4249clear_to_end_of_line(void)
4250{
4251 clear_chars(g_coord, Columns - g_coord.X);
4252}
4253
4254
4255/*
4256 * Scroll the scroll region up by `cLines' lines
4257 */
4258 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004259scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004260{
4261 COORD oldcoord = g_coord;
4262
4263 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4264 delete_lines(cLines);
4265
4266 g_coord = oldcoord;
4267}
4268
4269
4270/*
4271 * Set the scroll region
4272 */
4273 static void
4274set_scroll_region(
4275 unsigned left,
4276 unsigned top,
4277 unsigned right,
4278 unsigned bottom)
4279{
4280 if (left >= right
4281 || top >= bottom
4282 || right > (unsigned) Columns - 1
4283 || bottom > (unsigned) Rows - 1)
4284 return;
4285
4286 g_srScrollRegion.Left = left;
4287 g_srScrollRegion.Top = top;
4288 g_srScrollRegion.Right = right;
4289 g_srScrollRegion.Bottom = bottom;
4290}
4291
4292
4293/*
4294 * Insert `cLines' lines at the current cursor position
4295 */
4296 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004297insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298{
4299 SMALL_RECT source;
4300 COORD dest;
4301 CHAR_INFO fill;
4302
4303 dest.X = 0;
4304 dest.Y = g_coord.Y + cLines;
4305
4306 source.Left = 0;
4307 source.Top = g_coord.Y;
4308 source.Right = g_srScrollRegion.Right;
4309 source.Bottom = g_srScrollRegion.Bottom - cLines;
4310
4311 fill.Char.AsciiChar = ' ';
4312 fill.Attributes = g_attrCurrent;
4313
4314 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4315
4316 /* Here we have to deal with a win32 console flake: If the scroll
4317 * region looks like abc and we scroll c to a and fill with d we get
4318 * cbd... if we scroll block c one line at a time to a, we get cdd...
4319 * vim expects cdd consistently... So we have to deal with that
4320 * here... (this also occurs scrolling the same way in the other
4321 * direction). */
4322
4323 if (source.Bottom < dest.Y)
4324 {
4325 COORD coord;
4326
4327 coord.X = 0;
4328 coord.Y = source.Bottom;
4329 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4330 }
4331}
4332
4333
4334/*
4335 * Delete `cLines' lines at the current cursor position
4336 */
4337 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004338delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004339{
4340 SMALL_RECT source;
4341 COORD dest;
4342 CHAR_INFO fill;
4343 int nb;
4344
4345 dest.X = 0;
4346 dest.Y = g_coord.Y;
4347
4348 source.Left = 0;
4349 source.Top = g_coord.Y + cLines;
4350 source.Right = g_srScrollRegion.Right;
4351 source.Bottom = g_srScrollRegion.Bottom;
4352
4353 fill.Char.AsciiChar = ' ';
4354 fill.Attributes = g_attrCurrent;
4355
4356 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4357
4358 /* Here we have to deal with a win32 console flake: If the scroll
4359 * region looks like abc and we scroll c to a and fill with d we get
4360 * cbd... if we scroll block c one line at a time to a, we get cdd...
4361 * vim expects cdd consistently... So we have to deal with that
4362 * here... (this also occurs scrolling the same way in the other
4363 * direction). */
4364
4365 nb = dest.Y + (source.Bottom - source.Top) + 1;
4366
4367 if (nb < source.Top)
4368 {
4369 COORD coord;
4370
4371 coord.X = 0;
4372 coord.Y = nb;
4373 clear_chars(coord, Columns * (source.Top - nb));
4374 }
4375}
4376
4377
4378/*
4379 * Set the cursor position
4380 */
4381 static void
4382gotoxy(
4383 unsigned x,
4384 unsigned y)
4385{
4386 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4387 return;
4388
4389 /* external cursor coords are 1-based; internal are 0-based */
4390 g_coord.X = x - 1;
4391 g_coord.Y = y - 1;
4392 SetConsoleCursorPosition(g_hConOut, g_coord);
4393}
4394
4395
4396/*
4397 * Set the current text attribute = (foreground | background)
4398 * See ../doc/os_win32.txt for the numbers.
4399 */
4400 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004401textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004402{
4403 g_attrCurrent = wAttr;
4404
4405 SetConsoleTextAttribute(g_hConOut, wAttr);
4406}
4407
4408
4409 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004410textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411{
4412 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
4413
4414 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4415}
4416
4417
4418 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004419textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004420{
4421 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
4422
4423 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4424}
4425
4426
4427/*
4428 * restore the default text attribute (whatever we started with)
4429 */
4430 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004431normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432{
4433 textattr(g_attrDefault);
4434}
4435
4436
4437static WORD g_attrPreStandout = 0;
4438
4439/*
4440 * Make the text standout, by brightening it
4441 */
4442 static void
4443standout(void)
4444{
4445 g_attrPreStandout = g_attrCurrent;
4446 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
4447}
4448
4449
4450/*
4451 * Turn off standout mode
4452 */
4453 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004454standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455{
4456 if (g_attrPreStandout)
4457 {
4458 textattr(g_attrPreStandout);
4459 g_attrPreStandout = 0;
4460 }
4461}
4462
4463
4464/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00004465 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004466 */
4467 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004468mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004469{
4470 char_u *p;
4471 int n;
4472
4473 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
4474 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
4475 if (T_ME[0] == ESC && T_ME[1] == '|')
4476 {
4477 p = T_ME + 2;
4478 n = getdigits(&p);
4479 if (*p == 'm' && n > 0)
4480 {
4481 cterm_normal_fg_color = (n & 0xf) + 1;
4482 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
4483 }
4484 }
4485}
4486
4487
4488/*
4489 * visual bell: flash the screen
4490 */
4491 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004492visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493{
4494 COORD coordOrigin = {0, 0};
4495 WORD attrFlash = ~g_attrCurrent & 0xff;
4496
4497 DWORD dwDummy;
4498 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
4499
4500 if (oldattrs == NULL)
4501 return;
4502 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4503 coordOrigin, &dwDummy);
4504 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
4505 coordOrigin, &dwDummy);
4506
4507 Sleep(15); /* wait for 15 msec */
4508 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4509 coordOrigin, &dwDummy);
4510 vim_free(oldattrs);
4511}
4512
4513
4514/*
4515 * Make the cursor visible or invisible
4516 */
4517 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004518cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519{
4520 s_cursor_visible = fVisible;
4521#ifdef MCH_CURSOR_SHAPE
4522 mch_update_cursor();
4523#endif
4524}
4525
4526
4527/*
4528 * write `cchToWrite' characters in `pchBuf' to the screen
4529 * Returns the number of characters actually written (at least one).
4530 */
4531 static BOOL
4532write_chars(
4533 LPCSTR pchBuf,
4534 DWORD cchToWrite)
4535{
4536 COORD coord = g_coord;
4537 DWORD written;
4538
4539 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
4540 coord, &written);
4541 /* When writing fails or didn't write a single character, pretend one
4542 * character was written, otherwise we get stuck. */
4543 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
4544 coord, &written) == 0
4545 || written == 0)
4546 written = 1;
4547
4548 g_coord.X += (SHORT) written;
4549
4550 while (g_coord.X > g_srScrollRegion.Right)
4551 {
4552 g_coord.X -= (SHORT) Columns;
4553 if (g_coord.Y < g_srScrollRegion.Bottom)
4554 g_coord.Y++;
4555 }
4556
4557 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4558
4559 return written;
4560}
4561
4562
4563/*
4564 * mch_write(): write the output buffer to the screen, translating ESC
4565 * sequences into calls to console output routines.
4566 */
4567 void
4568mch_write(
4569 char_u *s,
4570 int len)
4571{
4572 s[len] = NUL;
4573
4574 if (!term_console)
4575 {
4576 write(1, s, (unsigned)len);
4577 return;
4578 }
4579
4580 /* translate ESC | sequences into faked bios calls */
4581 while (len--)
4582 {
4583 /* optimization: use one single write_chars for runs of text,
4584 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004585 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004586
4587 if (p_wd)
4588 {
4589 WaitForChar(p_wd);
4590 if (prefix != 0)
4591 prefix = 1;
4592 }
4593
4594 if (prefix != 0)
4595 {
4596 DWORD nWritten;
4597
4598 nWritten = write_chars(s, prefix);
4599#ifdef MCH_WRITE_DUMP
4600 if (fdDump)
4601 {
4602 fputc('>', fdDump);
4603 fwrite(s, sizeof(char_u), nWritten, fdDump);
4604 fputs("<\n", fdDump);
4605 }
4606#endif
4607 len -= (nWritten - 1);
4608 s += nWritten;
4609 }
4610 else if (s[0] == '\n')
4611 {
4612 /* \n, newline: go to the beginning of the next line or scroll */
4613 if (g_coord.Y == g_srScrollRegion.Bottom)
4614 {
4615 scroll(1);
4616 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
4617 }
4618 else
4619 {
4620 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
4621 }
4622#ifdef MCH_WRITE_DUMP
4623 if (fdDump)
4624 fputs("\\n\n", fdDump);
4625#endif
4626 s++;
4627 }
4628 else if (s[0] == '\r')
4629 {
4630 /* \r, carriage return: go to beginning of line */
4631 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
4632#ifdef MCH_WRITE_DUMP
4633 if (fdDump)
4634 fputs("\\r\n", fdDump);
4635#endif
4636 s++;
4637 }
4638 else if (s[0] == '\b')
4639 {
4640 /* \b, backspace: move cursor one position left */
4641 if (g_coord.X > g_srScrollRegion.Left)
4642 g_coord.X--;
4643 else if (g_coord.Y > g_srScrollRegion.Top)
4644 {
4645 g_coord.X = g_srScrollRegion.Right;
4646 g_coord.Y--;
4647 }
4648 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4649#ifdef MCH_WRITE_DUMP
4650 if (fdDump)
4651 fputs("\\b\n", fdDump);
4652#endif
4653 s++;
4654 }
4655 else if (s[0] == '\a')
4656 {
4657 /* \a, bell */
4658 MessageBeep(0xFFFFFFFF);
4659#ifdef MCH_WRITE_DUMP
4660 if (fdDump)
4661 fputs("\\a\n", fdDump);
4662#endif
4663 s++;
4664 }
4665 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4666 {
4667#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004668 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004669#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004670 char_u *p;
4671 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672
4673 switch (s[2])
4674 {
4675 /* one or two numeric arguments, separated by ';' */
4676
4677 case '0': case '1': case '2': case '3': case '4':
4678 case '5': case '6': case '7': case '8': case '9':
4679 p = s + 2;
4680 arg1 = getdigits(&p); /* no check for length! */
4681 if (p > s + len)
4682 break;
4683
4684 if (*p == ';')
4685 {
4686 ++p;
4687 arg2 = getdigits(&p); /* no check for length! */
4688 if (p > s + len)
4689 break;
4690
4691 if (*p == 'H')
4692 gotoxy(arg2, arg1);
4693 else if (*p == 'r')
4694 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4695 }
4696 else if (*p == 'A')
4697 {
4698 /* move cursor up arg1 lines in same column */
4699 gotoxy(g_coord.X + 1,
4700 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4701 }
4702 else if (*p == 'C')
4703 {
4704 /* move cursor right arg1 columns in same line */
4705 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4706 g_coord.Y + 1);
4707 }
4708 else if (*p == 'H')
4709 {
4710 gotoxy(1, arg1);
4711 }
4712 else if (*p == 'L')
4713 {
4714 insert_lines(arg1);
4715 }
4716 else if (*p == 'm')
4717 {
4718 if (arg1 == 0)
4719 normvideo();
4720 else
4721 textattr((WORD) arg1);
4722 }
4723 else if (*p == 'f')
4724 {
4725 textcolor((WORD) arg1);
4726 }
4727 else if (*p == 'b')
4728 {
4729 textbackground((WORD) arg1);
4730 }
4731 else if (*p == 'M')
4732 {
4733 delete_lines(arg1);
4734 }
4735
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004736 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737 s = p + 1;
4738 break;
4739
4740
4741 /* Three-character escape sequences */
4742
4743 case 'A':
4744 /* move cursor up one line in same column */
4745 gotoxy(g_coord.X + 1,
4746 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4747 goto got3;
4748
4749 case 'B':
4750 visual_bell();
4751 goto got3;
4752
4753 case 'C':
4754 /* move cursor right one column in same line */
4755 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4756 g_coord.Y + 1);
4757 goto got3;
4758
4759 case 'E':
4760 termcap_mode_end();
4761 goto got3;
4762
4763 case 'F':
4764 standout();
4765 goto got3;
4766
4767 case 'f':
4768 standend();
4769 goto got3;
4770
4771 case 'H':
4772 gotoxy(1, 1);
4773 goto got3;
4774
4775 case 'j':
4776 clear_to_end_of_display();
4777 goto got3;
4778
4779 case 'J':
4780 clear_screen();
4781 goto got3;
4782
4783 case 'K':
4784 clear_to_end_of_line();
4785 goto got3;
4786
4787 case 'L':
4788 insert_lines(1);
4789 goto got3;
4790
4791 case 'M':
4792 delete_lines(1);
4793 goto got3;
4794
4795 case 'S':
4796 termcap_mode_start();
4797 goto got3;
4798
4799 case 'V':
4800 cursor_visible(TRUE);
4801 goto got3;
4802
4803 case 'v':
4804 cursor_visible(FALSE);
4805 goto got3;
4806
4807 got3:
4808 s += 3;
4809 len -= 2;
4810 }
4811
4812#ifdef MCH_WRITE_DUMP
4813 if (fdDump)
4814 {
4815 fputs("ESC | ", fdDump);
4816 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4817 fputc('\n', fdDump);
4818 }
4819#endif
4820 }
4821 else
4822 {
4823 /* Write a single character */
4824 DWORD nWritten;
4825
4826 nWritten = write_chars(s, 1);
4827#ifdef MCH_WRITE_DUMP
4828 if (fdDump)
4829 {
4830 fputc('>', fdDump);
4831 fwrite(s, sizeof(char_u), nWritten, fdDump);
4832 fputs("<\n", fdDump);
4833 }
4834#endif
4835
4836 len -= (nWritten - 1);
4837 s += nWritten;
4838 }
4839 }
4840
4841#ifdef MCH_WRITE_DUMP
4842 if (fdDump)
4843 fflush(fdDump);
4844#endif
4845}
4846
4847#endif /* FEAT_GUI_W32 */
4848
4849
4850/*
4851 * Delay for half a second.
4852 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004853/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004854 void
4855mch_delay(
4856 long msec,
4857 int ignoreinput)
4858{
4859#ifdef FEAT_GUI_W32
4860 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004861#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004863# ifdef FEAT_MZSCHEME
4864 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4865 {
4866 int towait = p_mzq;
4867
4868 /* if msec is large enough, wait by portions in p_mzq */
4869 while (msec > 0)
4870 {
4871 mzvim_check_threads();
4872 if (msec < towait)
4873 towait = msec;
4874 Sleep(towait);
4875 msec -= towait;
4876 }
4877 }
4878 else
4879# endif
4880 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004881 else
4882 WaitForChar(msec);
4883#endif
4884}
4885
4886
4887/*
4888 * this version of remove is not scared by a readonly (backup) file
4889 * Return 0 for success, -1 for failure.
4890 */
4891 int
4892mch_remove(char_u *name)
4893{
4894#ifdef FEAT_MBYTE
4895 WCHAR *wn = NULL;
4896 int n;
4897
4898 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4899 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004900 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901 if (wn != NULL)
4902 {
4903 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4904 n = DeleteFileW(wn) ? 0 : -1;
4905 vim_free(wn);
4906 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4907 return n;
4908 /* Retry with non-wide function (for Windows 98). */
4909 }
4910 }
4911#endif
4912 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4913 return DeleteFile(name) ? 0 : -1;
4914}
4915
4916
4917/*
4918 * check for an "interrupt signal": CTRL-break or CTRL-C
4919 */
4920 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004921mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004922{
4923#ifndef FEAT_GUI_W32 /* never used */
4924 if (g_fCtrlCPressed || g_fCBrkPressed)
4925 {
4926 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4927 got_int = TRUE;
4928 }
4929#endif
4930}
4931
4932
4933/*
4934 * How much memory is available?
4935 * Return sum of available physical and page file memory.
4936 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004937/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938 long_u
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004939mch_avail_mem(int special)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940{
4941 MEMORYSTATUS ms;
4942
4943 ms.dwLength = sizeof(MEMORYSTATUS);
4944 GlobalMemoryStatus(&ms);
4945 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
4946}
4947
4948#ifdef FEAT_MBYTE
4949/*
4950 * Same code as below, but with wide functions and no comments.
4951 * Return 0 for success, non-zero for failure.
4952 */
4953 int
4954mch_wrename(WCHAR *wold, WCHAR *wnew)
4955{
4956 WCHAR *p;
4957 int i;
4958 WCHAR szTempFile[_MAX_PATH + 1];
4959 WCHAR szNewPath[_MAX_PATH + 1];
4960 HANDLE hf;
4961
4962 if (!mch_windows95())
4963 {
4964 p = wold;
4965 for (i = 0; wold[i] != NUL; ++i)
4966 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
4967 && wold[i + 1] != 0)
4968 p = wold + i + 1;
4969 if ((int)(wold + i - p) < 8 || p[6] != '~')
4970 return (MoveFileW(wold, wnew) == 0);
4971 }
4972
4973 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
4974 return -1;
4975 *p = NUL;
4976
4977 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
4978 return -2;
4979
4980 if (!DeleteFileW(szTempFile))
4981 return -3;
4982
4983 if (!MoveFileW(wold, szTempFile))
4984 return -4;
4985
4986 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4987 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4988 return -5;
4989 if (!CloseHandle(hf))
4990 return -6;
4991
4992 if (!MoveFileW(szTempFile, wnew))
4993 {
4994 (void)MoveFileW(szTempFile, wold);
4995 return -7;
4996 }
4997
4998 DeleteFileW(szTempFile);
4999
5000 if (!DeleteFileW(wold))
5001 return -8;
5002
5003 return 0;
5004}
5005#endif
5006
5007
5008/*
5009 * mch_rename() works around a bug in rename (aka MoveFile) in
5010 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5011 * file whose short file name is "FOO.BAR" (its long file name will
5012 * be correct: "foo.bar~"). Because a file can be accessed by
5013 * either its SFN or its LFN, "foo.bar" has effectively been
5014 * renamed to "foo.bar", which is not at all what was wanted. This
5015 * seems to happen only when renaming files with three-character
5016 * extensions by appending a suffix that does not include ".".
5017 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5018 *
5019 * There is another problem, which isn't really a bug but isn't right either:
5020 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5021 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5022 * service pack 6. Doesn't seem to happen on Windows 98.
5023 *
5024 * Like rename(), returns 0 upon success, non-zero upon failure.
5025 * Should probably set errno appropriately when errors occur.
5026 */
5027 int
5028mch_rename(
5029 const char *pszOldFile,
5030 const char *pszNewFile)
5031{
5032 char szTempFile[_MAX_PATH+1];
5033 char szNewPath[_MAX_PATH+1];
5034 char *pszFilePart;
5035 HANDLE hf;
5036#ifdef FEAT_MBYTE
5037 WCHAR *wold = NULL;
5038 WCHAR *wnew = NULL;
5039 int retval = -1;
5040
5041 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5042 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005043 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5044 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045 if (wold != NULL && wnew != NULL)
5046 retval = mch_wrename(wold, wnew);
5047 vim_free(wold);
5048 vim_free(wnew);
5049 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5050 return retval;
5051 /* Retry with non-wide function (for Windows 98). */
5052 }
5053#endif
5054
5055 /*
5056 * No need to play tricks if not running Windows 95, unless the file name
5057 * contains a "~" as the seventh character.
5058 */
5059 if (!mch_windows95())
5060 {
5061 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5062 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5063 return rename(pszOldFile, pszNewFile);
5064 }
5065
5066 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5067 * a directory, no error is returned and pszFilePart will be NULL. */
5068 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5069 || pszFilePart == NULL)
5070 return -1;
5071 *pszFilePart = NUL;
5072
5073 /* Get (and create) a unique temporary file name in directory of new file */
5074 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5075 return -2;
5076
5077 /* blow the temp file away */
5078 if (!DeleteFile(szTempFile))
5079 return -3;
5080
5081 /* rename old file to the temp file */
5082 if (!MoveFile(pszOldFile, szTempFile))
5083 return -4;
5084
5085 /* now create an empty file called pszOldFile; this prevents the operating
5086 * system using pszOldFile as an alias (SFN) if we're renaming within the
5087 * same directory. For example, we're editing a file called
5088 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5089 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5090 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005091 * cause all sorts of problems later in buf_write(). So, we create an
5092 * empty file called filena~1.txt and the system will have to find some
5093 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005094 */
5095 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5096 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5097 return -5;
5098 if (!CloseHandle(hf))
5099 return -6;
5100
5101 /* rename the temp file to the new file */
5102 if (!MoveFile(szTempFile, pszNewFile))
5103 {
5104 /* Renaming failed. Rename the file back to its old name, so that it
5105 * looks like nothing happened. */
5106 (void)MoveFile(szTempFile, pszOldFile);
5107
5108 return -7;
5109 }
5110
5111 /* Seems to be left around on Novell filesystems */
5112 DeleteFile(szTempFile);
5113
5114 /* finally, remove the empty old file */
5115 if (!DeleteFile(pszOldFile))
5116 return -8;
5117
5118 return 0; /* success */
5119}
5120
5121/*
5122 * Get the default shell for the current hardware platform
5123 */
5124 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005125default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005126{
5127 char* psz = NULL;
5128
5129 PlatformId();
5130
5131 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5132 psz = "cmd.exe";
5133 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5134 psz = "command.com";
5135
5136 return psz;
5137}
5138
5139/*
5140 * mch_access() extends access() to do more detailed check on network drives.
5141 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5142 */
5143 int
5144mch_access(char *n, int p)
5145{
5146 HANDLE hFile;
5147 DWORD am;
5148 int retval = -1; /* default: fail */
5149#ifdef FEAT_MBYTE
5150 WCHAR *wn = NULL;
5151
5152 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005153 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005154#endif
5155
5156 if (mch_isdir(n))
5157 {
5158 char TempName[_MAX_PATH + 16] = "";
5159#ifdef FEAT_MBYTE
5160 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5161#endif
5162
5163 if (p & R_OK)
5164 {
5165 /* Read check is performed by seeing if we can do a find file on
5166 * the directory for any file. */
5167#ifdef FEAT_MBYTE
5168 if (wn != NULL)
5169 {
5170 int i;
5171 WIN32_FIND_DATAW d;
5172
5173 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5174 TempNameW[i] = wn[i];
5175 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5176 TempNameW[i++] = '\\';
5177 TempNameW[i++] = '*';
5178 TempNameW[i++] = 0;
5179
5180 hFile = FindFirstFileW(TempNameW, &d);
5181 if (hFile == INVALID_HANDLE_VALUE)
5182 {
5183 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5184 goto getout;
5185
5186 /* Retry with non-wide function (for Windows 98). */
5187 vim_free(wn);
5188 wn = NULL;
5189 }
5190 else
5191 (void)FindClose(hFile);
5192 }
5193 if (wn == NULL)
5194#endif
5195 {
5196 char *pch;
5197 WIN32_FIND_DATA d;
5198
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005199 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005200 pch = TempName + STRLEN(TempName) - 1;
5201 if (*pch != '\\' && *pch != '/')
5202 *++pch = '\\';
5203 *++pch = '*';
5204 *++pch = NUL;
5205
5206 hFile = FindFirstFile(TempName, &d);
5207 if (hFile == INVALID_HANDLE_VALUE)
5208 goto getout;
5209 (void)FindClose(hFile);
5210 }
5211 }
5212
5213 if (p & W_OK)
5214 {
5215 /* Trying to create a temporary file in the directory should catch
5216 * directories on read-only network shares. However, in
5217 * directories whose ACL allows writes but denies deletes will end
5218 * up keeping the temporary file :-(. */
5219#ifdef FEAT_MBYTE
5220 if (wn != NULL)
5221 {
5222 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5223 {
5224 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5225 goto getout;
5226
5227 /* Retry with non-wide function (for Windows 98). */
5228 vim_free(wn);
5229 wn = NULL;
5230 }
5231 else
5232 DeleteFileW(TempNameW);
5233 }
5234 if (wn == NULL)
5235#endif
5236 {
5237 if (!GetTempFileName(n, "VIM", 0, TempName))
5238 goto getout;
5239 mch_remove((char_u *)TempName);
5240 }
5241 }
5242 }
5243 else
5244 {
5245 /* Trying to open the file for the required access does ACL, read-only
5246 * network share, and file attribute checks. */
5247 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5248 | ((p & R_OK) ? GENERIC_READ : 0);
5249#ifdef FEAT_MBYTE
5250 if (wn != NULL)
5251 {
5252 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5253 if (hFile == INVALID_HANDLE_VALUE
5254 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5255 {
5256 /* Retry with non-wide function (for Windows 98). */
5257 vim_free(wn);
5258 wn = NULL;
5259 }
5260 }
5261 if (wn == NULL)
5262#endif
5263 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5264 if (hFile == INVALID_HANDLE_VALUE)
5265 goto getout;
5266 CloseHandle(hFile);
5267 }
5268
5269 retval = 0; /* success */
5270getout:
5271#ifdef FEAT_MBYTE
5272 vim_free(wn);
5273#endif
5274 return retval;
5275}
5276
5277#if defined(FEAT_MBYTE) || defined(PROTO)
5278/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005279 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005280 */
5281 int
5282mch_open(char *name, int flags, int mode)
5283{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005284 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5285# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005286 WCHAR *wn;
5287 int f;
5288
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005289 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005290 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005291 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005292 if (wn != NULL)
5293 {
5294 f = _wopen(wn, flags, mode);
5295 vim_free(wn);
5296 if (f >= 0)
5297 return f;
5298 /* Retry with non-wide function (for Windows 98). Can't use
5299 * GetLastError() here and it's unclear what errno gets set to if
5300 * the _wopen() fails for missing wide functions. */
5301 }
5302 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005303# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005304
5305 return open(name, flags, mode);
5306}
5307
5308/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005309 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310 */
5311 FILE *
5312mch_fopen(char *name, char *mode)
5313{
5314 WCHAR *wn, *wm;
5315 FILE *f = NULL;
5316
5317 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5318# ifdef __BORLANDC__
5319 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5320 && g_PlatformId == VER_PLATFORM_WIN32_NT
5321# endif
5322 )
5323 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005324# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005325 /* Work around an annoying assertion in the Microsoft debug CRT
5326 * when mode's text/binary setting doesn't match _get_fmode(). */
5327 char newMode = mode[strlen(mode) - 1];
5328 int oldMode = 0;
5329
5330 _get_fmode(&oldMode);
5331 if (newMode == 't')
5332 _set_fmode(_O_TEXT);
5333 else if (newMode == 'b')
5334 _set_fmode(_O_BINARY);
5335# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005336 wn = enc_to_utf16(name, NULL);
5337 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005338 if (wn != NULL && wm != NULL)
5339 f = _wfopen(wn, wm);
5340 vim_free(wn);
5341 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005342
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005343# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005344 _set_fmode(oldMode);
5345# endif
5346
Bram Moolenaar071d4272004-06-13 20:20:40 +00005347 if (f != NULL)
5348 return f;
5349 /* Retry with non-wide function (for Windows 98). Can't use
5350 * GetLastError() here and it's unclear what errno gets set to if
5351 * the _wfopen() fails for missing wide functions. */
5352 }
5353
5354 return fopen(name, mode);
5355}
5356#endif
5357
5358#ifdef FEAT_MBYTE
5359/*
5360 * SUB STREAM (aka info stream) handling:
5361 *
5362 * NTFS can have sub streams for each file. Normal contents of file is
5363 * stored in the main stream, and extra contents (author information and
5364 * title and so on) can be stored in sub stream. After Windows 2000, user
5365 * can access and store those informations in sub streams via explorer's
5366 * property menuitem in right click menu. Those informations in sub streams
5367 * were lost when copying only the main stream. So we have to copy sub
5368 * streams.
5369 *
5370 * Incomplete explanation:
5371 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5372 * More useful info and an example:
5373 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5374 */
5375
5376/*
5377 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5378 * and write to stream "substream" of file "to".
5379 * Errors are ignored.
5380 */
5381 static void
5382copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5383{
5384 HANDLE hTo;
5385 WCHAR *to_name;
5386
5387 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5388 wcscpy(to_name, to);
5389 wcscat(to_name, substream);
5390
5391 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5392 FILE_ATTRIBUTE_NORMAL, NULL);
5393 if (hTo != INVALID_HANDLE_VALUE)
5394 {
5395 long done;
5396 DWORD todo;
5397 DWORD readcnt, written;
5398 char buf[4096];
5399
5400 /* Copy block of bytes at a time. Abort when something goes wrong. */
5401 for (done = 0; done < len; done += written)
5402 {
5403 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005404 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5405 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005406 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5407 FALSE, FALSE, context)
5408 || readcnt != todo
5409 || !WriteFile(hTo, buf, todo, &written, NULL)
5410 || written != todo)
5411 break;
5412 }
5413 CloseHandle(hTo);
5414 }
5415
5416 free(to_name);
5417}
5418
5419/*
5420 * Copy info streams from file "from" to file "to".
5421 */
5422 static void
5423copy_infostreams(char_u *from, char_u *to)
5424{
5425 WCHAR *fromw;
5426 WCHAR *tow;
5427 HANDLE sh;
5428 WIN32_STREAM_ID sid;
5429 int headersize;
5430 WCHAR streamname[_MAX_PATH];
5431 DWORD readcount;
5432 void *context = NULL;
5433 DWORD lo, hi;
5434 int len;
5435
5436 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005437 fromw = enc_to_utf16(from, NULL);
5438 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005439 if (fromw != NULL && tow != NULL)
5440 {
5441 /* Open the file for reading. */
5442 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
5443 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5444 if (sh != INVALID_HANDLE_VALUE)
5445 {
5446 /* Use BackupRead() to find the info streams. Repeat until we
5447 * have done them all.*/
5448 for (;;)
5449 {
5450 /* Get the header to find the length of the stream name. If
5451 * the "readcount" is zero we have done all info streams. */
5452 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005453 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
5455 &readcount, FALSE, FALSE, &context)
5456 || readcount == 0)
5457 break;
5458
5459 /* We only deal with streams that have a name. The normal
5460 * file data appears to be without a name, even though docs
5461 * suggest it is called "::$DATA". */
5462 if (sid.dwStreamNameSize > 0)
5463 {
5464 /* Read the stream name. */
5465 if (!BackupRead(sh, (LPBYTE)streamname,
5466 sid.dwStreamNameSize,
5467 &readcount, FALSE, FALSE, &context))
5468 break;
5469
5470 /* Copy an info stream with a name ":anything:$DATA".
5471 * Skip "::$DATA", it has no stream name (examples suggest
5472 * it might be used for the normal file contents).
5473 * Note that BackupRead() counts bytes, but the name is in
5474 * wide characters. */
5475 len = readcount / sizeof(WCHAR);
5476 streamname[len] = 0;
5477 if (len > 7 && wcsicmp(streamname + len - 6,
5478 L":$DATA") == 0)
5479 {
5480 streamname[len - 6] = 0;
5481 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00005482 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005483 }
5484 }
5485
5486 /* Advance to the next stream. We might try seeking too far,
5487 * but BackupSeek() doesn't skip over stream borders, thus
5488 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005489 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490 &lo, &hi, &context);
5491 }
5492
5493 /* Clear the context. */
5494 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
5495
5496 CloseHandle(sh);
5497 }
5498 }
5499 vim_free(fromw);
5500 vim_free(tow);
5501}
5502#endif
5503
5504/*
5505 * Copy file attributes from file "from" to file "to".
5506 * For Windows NT and later we copy info streams.
5507 * Always returns zero, errors are ignored.
5508 */
5509 int
5510mch_copy_file_attribute(char_u *from, char_u *to)
5511{
5512#ifdef FEAT_MBYTE
5513 /* File streams only work on Windows NT and later. */
5514 PlatformId();
5515 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5516 copy_infostreams(from, to);
5517#endif
5518 return 0;
5519}
5520
5521#if defined(MYRESETSTKOFLW) || defined(PROTO)
5522/*
5523 * Recreate a destroyed stack guard page in win32.
5524 * Written by Benjamin Peterson.
5525 */
5526
5527/* These magic numbers are from the MS header files */
5528#define MIN_STACK_WIN9X 17
5529#define MIN_STACK_WINNT 2
5530
5531/*
5532 * This function does the same thing as _resetstkoflw(), which is only
5533 * available in DevStudio .net and later.
5534 * Returns 0 for failure, 1 for success.
5535 */
5536 int
5537myresetstkoflw(void)
5538{
5539 BYTE *pStackPtr;
5540 BYTE *pGuardPage;
5541 BYTE *pStackBase;
5542 BYTE *pLowestPossiblePage;
5543 MEMORY_BASIC_INFORMATION mbi;
5544 SYSTEM_INFO si;
5545 DWORD nPageSize;
5546 DWORD dummy;
5547
5548 /* This code will not work on win32s. */
5549 PlatformId();
5550 if (g_PlatformId == VER_PLATFORM_WIN32s)
5551 return 0;
5552
5553 /* We need to know the system page size. */
5554 GetSystemInfo(&si);
5555 nPageSize = si.dwPageSize;
5556
5557 /* ...and the current stack pointer */
5558 pStackPtr = (BYTE*)_alloca(1);
5559
5560 /* ...and the base of the stack. */
5561 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
5562 return 0;
5563 pStackBase = (BYTE*)mbi.AllocationBase;
5564
5565 /* ...and the page thats min_stack_req pages away from stack base; this is
5566 * the lowest page we could use. */
5567 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
5568 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
5569
5570 /* On Win95, we want the next page down from the end of the stack. */
5571 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
5572 {
5573 /* Find the page that's only 1 page down from the page that the stack
5574 * ptr is in. */
5575 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
5576 / (DWORD)nPageSize) - 1));
5577 if (pGuardPage < pLowestPossiblePage)
5578 return 0;
5579
5580 /* Apply the noaccess attribute to the page -- there's no guard
5581 * attribute in win95-type OSes. */
5582 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
5583 return 0;
5584 }
5585 else
5586 {
5587 /* On NT, however, we want the first committed page in the stack Start
5588 * at the stack base and move forward through memory until we find a
5589 * committed block. */
5590 BYTE *pBlock = pStackBase;
5591
Bram Moolenaara466c992005-07-09 21:03:22 +00005592 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 {
5594 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
5595 return 0;
5596
5597 pBlock += mbi.RegionSize;
5598
5599 if (mbi.State & MEM_COMMIT)
5600 break;
5601 }
5602
5603 /* mbi now describes the first committed block in the stack. */
5604 if (mbi.Protect & PAGE_GUARD)
5605 return 1;
5606
5607 /* decide where the guard page should start */
5608 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
5609 pGuardPage = pLowestPossiblePage;
5610 else
5611 pGuardPage = (BYTE*)mbi.BaseAddress;
5612
5613 /* allocate the guard page */
5614 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
5615 return 0;
5616
5617 /* apply the guard attribute to the page */
5618 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
5619 &dummy))
5620 return 0;
5621 }
5622
5623 return 1;
5624}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005625#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005627
5628#if defined(FEAT_MBYTE) || defined(PROTO)
5629/*
5630 * The command line arguments in UCS2
5631 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005632static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005633static LPWSTR *ArglistW = NULL;
5634static int global_argc = 0;
5635static char **global_argv;
5636
5637static int used_file_argc = 0; /* last argument in global_argv[] used
5638 for the argument list. */
5639static int *used_file_indexes = NULL; /* indexes in global_argv[] for
5640 command line arguments added to
5641 the argument list */
5642static int used_file_count = 0; /* nr of entries in used_file_indexes */
5643static int used_file_literal = FALSE; /* take file names literally */
5644static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005645static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005646static int used_alist_count = 0;
5647
5648
5649/*
5650 * Get the command line arguments. Unicode version.
5651 * Returns argc. Zero when something fails.
5652 */
5653 int
5654get_cmd_argsW(char ***argvp)
5655{
5656 char **argv = NULL;
5657 int argc = 0;
5658 int i;
5659
5660 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5661 if (ArglistW != NULL)
5662 {
5663 argv = malloc((nArgsW + 1) * sizeof(char *));
5664 if (argv != NULL)
5665 {
5666 argc = nArgsW;
5667 argv[argc] = NULL;
5668 for (i = 0; i < argc; ++i)
5669 {
5670 int len;
5671
5672 /* Convert each Unicode argument to the current codepage. */
5673 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005674 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005675 (LPSTR *)&argv[i], &len, 0, 0);
5676 if (argv[i] == NULL)
5677 {
5678 /* Out of memory, clear everything. */
5679 while (i > 0)
5680 free(argv[--i]);
5681 free(argv);
5682 argc = 0;
5683 }
5684 }
5685 }
5686 }
5687
5688 global_argc = argc;
5689 global_argv = argv;
5690 if (argc > 0)
5691 used_file_indexes = malloc(argc * sizeof(int));
5692
5693 if (argvp != NULL)
5694 *argvp = argv;
5695 return argc;
5696}
5697
5698 void
5699free_cmd_argsW(void)
5700{
5701 if (ArglistW != NULL)
5702 {
5703 GlobalFree(ArglistW);
5704 ArglistW = NULL;
5705 }
5706}
5707
5708/*
5709 * Remember "name" is an argument that was added to the argument list.
5710 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5711 * is called.
5712 */
5713 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005714used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005715{
5716 int i;
5717
5718 if (used_file_indexes == NULL)
5719 return;
5720 for (i = used_file_argc + 1; i < global_argc; ++i)
5721 if (STRCMP(global_argv[i], name) == 0)
5722 {
5723 used_file_argc = i;
5724 used_file_indexes[used_file_count++] = i;
5725 break;
5726 }
5727 used_file_literal = literal;
5728 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005729 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005730}
5731
5732/*
5733 * Remember the length of the argument list as it was. If it changes then we
5734 * leave it alone when 'encoding' is set.
5735 */
5736 void
5737set_alist_count(void)
5738{
5739 used_alist_count = GARGCOUNT;
5740}
5741
5742/*
5743 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5744 * has been changed while starting up. Use the UCS-2 command line arguments
5745 * and convert them to 'encoding'.
5746 */
5747 void
5748fix_arg_enc(void)
5749{
5750 int i;
5751 int idx;
5752 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005753 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005754
5755 /* Safety checks:
5756 * - if argument count differs between the wide and non-wide argument
5757 * list, something must be wrong.
5758 * - the file name arguments must have been located.
5759 * - the length of the argument list wasn't changed by the user.
5760 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005761 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005762 || ArglistW == NULL
5763 || used_file_indexes == NULL
5764 || used_file_count == 0
5765 || used_alist_count != GARGCOUNT)
5766 return;
5767
Bram Moolenaar86b68352004-12-27 21:59:20 +00005768 /* Remember the buffer numbers for the arguments. */
5769 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5770 if (fnum_list == NULL)
5771 return; /* out of memory */
5772 for (i = 0; i < GARGCOUNT; ++i)
5773 fnum_list[i] = GARGLIST[i].ae_fnum;
5774
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005775 /* Clear the argument list. Make room for the new arguments. */
5776 alist_clear(&global_alist);
5777 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005778 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005779
5780 for (i = 0; i < used_file_count; ++i)
5781 {
5782 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005783 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005784 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005785 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005786#ifdef FEAT_DIFF
5787 /* When using diff mode may need to concatenate file name to
5788 * directory name. Just like it's done in main(). */
5789 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5790 && !mch_isdir(alist_name(&GARGLIST[0])))
5791 {
5792 char_u *r;
5793
5794 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5795 if (r != NULL)
5796 {
5797 vim_free(str);
5798 str = r;
5799 }
5800 }
5801#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005802 /* Re-use the old buffer by renaming it. When not using literal
5803 * names it's done by alist_expand() below. */
5804 if (used_file_literal)
5805 buf_set_name(fnum_list[i], str);
5806
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005807 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005808 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005809 }
5810
5811 if (!used_file_literal)
5812 {
5813 /* Now expand wildcards in the arguments. */
5814 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5815 * filename characters but are excluded from 'isfname' to make
5816 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5817 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005818 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005819 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5820 }
5821
5822 /* If wildcard expansion failed, we are editing the first file of the
5823 * arglist and there is no file name: Edit the first argument now. */
5824 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5825 {
5826 do_cmdline_cmd((char_u *)":rewind");
5827 if (GARGCOUNT == 1 && used_file_full_path)
5828 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5829 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005830
5831 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005832}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005833#endif