blob: 30b725d4cfb43c3914b81e58f7a941c42403f08c [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
155#ifndef FEAT_GUI_W32
156/* Win32 Console handles for input and output */
157static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
158static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
159
160/* Win32 Screen buffer,coordinate,console I/O information */
161static SMALL_RECT g_srScrollRegion;
162static COORD g_coord; /* 0-based, but external coords are 1-based */
163
164/* The attribute of the screen when the editor was started */
165static WORD g_attrDefault = 7; /* lightgray text on black background */
166static WORD g_attrCurrent;
167
168static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
169static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
170static int g_fForceExit = FALSE; /* set when forcefully exiting */
171
172static void termcap_mode_start(void);
173static void termcap_mode_end(void);
174static void clear_chars(COORD coord, DWORD n);
175static void clear_screen(void);
176static void clear_to_end_of_display(void);
177static void clear_to_end_of_line(void);
178static void scroll(unsigned cLines);
179static void set_scroll_region(unsigned left, unsigned top,
180 unsigned right, unsigned bottom);
181static void insert_lines(unsigned cLines);
182static void delete_lines(unsigned cLines);
183static void gotoxy(unsigned x, unsigned y);
184static void normvideo(void);
185static void textattr(WORD wAttr);
186static void textcolor(WORD wAttr);
187static void textbackground(WORD wAttr);
188static void standout(void);
189static void standend(void);
190static void visual_bell(void);
191static void cursor_visible(BOOL fVisible);
192static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
193static char_u tgetch(int *pmodifiers, char_u *pch2);
194static void create_conin(void);
195static int s_cursor_visible = TRUE;
196static int did_create_conin = FALSE;
197#else
198static int s_dont_use_vimrun = TRUE;
199static int need_vimrun_warning = FALSE;
200static char *vimrun_path = "vimrun ";
201#endif
202
203#ifndef FEAT_GUI_W32
204static int suppress_winsize = 1; /* don't fiddle with console */
205#endif
206
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200207static char_u *exe_path = NULL;
208
Bram Moolenaar071d4272004-06-13 20:20:40 +0000209 static void
210get_exe_name(void)
211{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100212 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
213 * as the maximum length that works (plus a NUL byte). */
214#define MAX_ENV_PATH_LEN 8192
215 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200216 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000217
218 if (exe_name == NULL)
219 {
220 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100221 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000222 if (*temp != NUL)
223 exe_name = FullName_save((char_u *)temp, FALSE);
224 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000225
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200226 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000227 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200228 exe_path = vim_strnsave(exe_name,
229 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200230 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000231 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200232 /* Append our starting directory to $PATH, so that when doing
233 * "!xxd" it's found in our starting directory. Needed because
234 * SearchPath() also looks there. */
235 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100236 if (p == NULL
237 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200238 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100239 if (p == NULL || *p == NUL)
240 temp[0] = NUL;
241 else
242 {
243 STRCPY(temp, p);
244 STRCAT(temp, ";");
245 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200246 STRCAT(temp, exe_path);
247 vim_setenv((char_u *)"PATH", temp);
248 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000249 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000250 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000251}
252
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200253/*
254 * Load library "name".
255 */
256 HINSTANCE
257vimLoadLib(char *name)
258{
259 HINSTANCE dll = NULL;
260 char old_dir[MAXPATHL];
261
262 if (exe_path == NULL)
263 get_exe_name();
264 if (exe_path != NULL && mch_dirname(old_dir, MAXPATHL) == OK)
265 {
266 /* Change directory to where the executable is, both to make sure we
267 * find a .dll there and to avoid looking for a .dll in the current
268 * directory. */
269 mch_chdir(exe_path);
270 dll = LoadLibrary(name);
271 mch_chdir(old_dir);
272 }
273 return dll;
274}
275
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
277# ifndef GETTEXT_DLL
278# define GETTEXT_DLL "libintl.dll"
279# endif
280/* Dummy funcitons */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000281static char *null_libintl_gettext(const char *);
282static char *null_libintl_textdomain(const char *);
283static char *null_libintl_bindtextdomain(const char *, const char *);
284static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000285
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200286static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000287char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
288char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
289char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000290 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000291char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
292 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000293
294 int
295dyn_libintl_init(char *libname)
296{
297 int i;
298 static struct
299 {
300 char *name;
301 FARPROC *ptr;
302 } libintl_entry[] =
303 {
304 {"gettext", (FARPROC*)&dyn_libintl_gettext},
305 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
306 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
307 {NULL, NULL}
308 };
309
310 /* No need to initialize twice. */
311 if (hLibintlDLL)
312 return 1;
313 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200314 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000315 if (!hLibintlDLL)
316 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200317 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000318 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200319 verbose_enter();
320 EMSG2(_(e_loadlib), GETTEXT_DLL);
321 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000322 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200323 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324 }
325 for (i = 0; libintl_entry[i].name != NULL
326 && libintl_entry[i].ptr != NULL; ++i)
327 {
328 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
329 libintl_entry[i].name)) == NULL)
330 {
331 dyn_libintl_end();
332 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000333 {
334 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000335 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000336 verbose_leave();
337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000338 return 0;
339 }
340 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000341
342 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000343 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000344 "bind_textdomain_codeset");
345 if (dyn_libintl_bind_textdomain_codeset == NULL)
346 dyn_libintl_bind_textdomain_codeset =
347 null_libintl_bind_textdomain_codeset;
348
Bram Moolenaar071d4272004-06-13 20:20:40 +0000349 return 1;
350}
351
352 void
353dyn_libintl_end()
354{
355 if (hLibintlDLL)
356 FreeLibrary(hLibintlDLL);
357 hLibintlDLL = NULL;
358 dyn_libintl_gettext = null_libintl_gettext;
359 dyn_libintl_textdomain = null_libintl_textdomain;
360 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000361 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000362}
363
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000364/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000366null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367{
368 return (char*)msgid;
369}
370
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000371/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000372 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000373null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000374{
375 return NULL;
376}
377
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000378/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000379 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000380null_libintl_bind_textdomain_codeset(const char *domainname,
381 const char *codeset)
382{
383 return NULL;
384}
385
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000386/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000387 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000388null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389{
390 return NULL;
391}
392
393#endif /* DYNAMIC_GETTEXT */
394
395/* This symbol is not defined in older versions of the SDK or Visual C++ */
396
397#ifndef VER_PLATFORM_WIN32_WINDOWS
398# define VER_PLATFORM_WIN32_WINDOWS 1
399#endif
400
401DWORD g_PlatformId;
402
403#ifdef HAVE_ACL
404# include <aclapi.h>
405/*
406 * These are needed to dynamically load the ADVAPI DLL, which is not
407 * implemented under Windows 95 (and causes VIM to crash)
408 */
409typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
410 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
411typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
412 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
413 PSECURITY_DESCRIPTOR *);
414
415static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
416static PSNSECINFO pSetNamedSecurityInfo;
417static PGNSECINFO pGetNamedSecurityInfo;
418#endif
419
420/*
421 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
422 * VER_PLATFORM_WIN32_WINDOWS (Win95).
423 */
424 void
425PlatformId(void)
426{
427 static int done = FALSE;
428
429 if (!done)
430 {
431 OSVERSIONINFO ovi;
432
433 ovi.dwOSVersionInfoSize = sizeof(ovi);
434 GetVersionEx(&ovi);
435
436 g_PlatformId = ovi.dwPlatformId;
437
438#ifdef HAVE_ACL
439 /*
440 * Load the ADVAPI runtime if we are on anything
441 * other than Windows 95
442 */
443 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
444 {
445 /*
446 * do this load. Problems: Doesn't unload at end of run (this is
447 * theoretically okay, since Windows should unload it when VIM
448 * terminates). Should we be using the 'mch_libcall' routines?
449 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
450 * time we verify security...
451 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200452 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000453 if (advapi_lib != NULL)
454 {
455 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
456 "SetNamedSecurityInfoA");
457 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
458 "GetNamedSecurityInfoA");
459 if (pSetNamedSecurityInfo == NULL
460 || pGetNamedSecurityInfo == NULL)
461 {
462 /* If we can't get the function addresses, set advapi_lib
463 * to NULL so that we don't use them. */
464 FreeLibrary(advapi_lib);
465 advapi_lib = NULL;
466 }
467 }
468 }
469#endif
470 done = TRUE;
471 }
472}
473
474/*
475 * Return TRUE when running on Windows 95 (or 98 or ME).
476 * Only to be used after mch_init().
477 */
478 int
479mch_windows95(void)
480{
481 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
482}
483
484#ifdef FEAT_GUI_W32
485/*
486 * Used to work around the "can't do synchronous spawn"
487 * problem on Win32s, without resorting to Universal Thunk.
488 */
489static int old_num_windows;
490static int num_windows;
491
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000492/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 static BOOL CALLBACK
494win32ssynch_cb(HWND hwnd, LPARAM lparam)
495{
496 num_windows++;
497 return TRUE;
498}
499#endif
500
501#ifndef FEAT_GUI_W32
502
503#define SHIFT (SHIFT_PRESSED)
504#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
505#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
506#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
507
508
509/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
510 * We map function keys to their ANSI terminal equivalents, as produced
511 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
512 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
513 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
514 * combinations of function/arrow/etc keys.
515 */
516
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000517static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000518{
519 WORD wVirtKey;
520 BOOL fAnsiKey;
521 int chAlone;
522 int chShift;
523 int chCtrl;
524 int chAlt;
525} VirtKeyMap[] =
526{
527
528/* Key ANSI alone shift ctrl alt */
529 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
530
531 { VK_F1, TRUE, ';', 'T', '^', 'h', },
532 { VK_F2, TRUE, '<', 'U', '_', 'i', },
533 { VK_F3, TRUE, '=', 'V', '`', 'j', },
534 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
535 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
536 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
537 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
538 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
539 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
540 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
541 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
542 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
543
544 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
545 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
546 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
547 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
548 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
549 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
550 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
551 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
552 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
553 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
554
555 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
556
557#if 0
558 /* Most people don't have F13-F20, but what the hell... */
559 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
560 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
561 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
562 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
563 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
564 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
565 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
566 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
567#endif
568 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
569 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
570 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
571 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
572
573 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
574 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
575 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
576 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
577 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
578 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
579 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
580 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
581 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
582 /* Sorry, out of number space! <negri>*/
583 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
584
585};
586
587
588#ifdef _MSC_VER
589// The ToAscii bug destroys several registers. Need to turn off optimization
590// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000591# pragma warning(push)
592# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000593# pragma optimize("", off)
594#endif
595
596#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
597# define AChar AsciiChar
598#else
599# define AChar uChar.AsciiChar
600#endif
601
602/* The return code indicates key code size. */
603 static int
604#ifdef __BORLANDC__
605 __stdcall
606#endif
607win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000608 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609{
610 UINT uMods = pker->dwControlKeyState;
611 static int s_iIsDead = 0;
612 static WORD awAnsiCode[2];
613 static BYTE abKeystate[256];
614
615
616 if (s_iIsDead == 2)
617 {
618 pker->AChar = (CHAR) awAnsiCode[1];
619 s_iIsDead = 0;
620 return 1;
621 }
622
623 if (pker->AChar != 0)
624 return 1;
625
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200626 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000627
628 // Should only be non-NULL on NT 4.0
629 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
630 {
631 CHAR szKLID[KL_NAMELENGTH];
632
633 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
634 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
635 }
636
637 /* Clear any pending dead keys */
638 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
639
640 if (uMods & SHIFT_PRESSED)
641 abKeystate[VK_SHIFT] = 0x80;
642 if (uMods & CAPSLOCK_ON)
643 abKeystate[VK_CAPITAL] = 1;
644
645 if ((uMods & ALT_GR) == ALT_GR)
646 {
647 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
648 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
649 }
650
651 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
652 abKeystate, awAnsiCode, 0);
653
654 if (s_iIsDead > 0)
655 pker->AChar = (CHAR) awAnsiCode[0];
656
657 return s_iIsDead;
658}
659
660#ifdef _MSC_VER
661/* MUST switch optimization on again here, otherwise a call to
662 * decode_key_event() may crash (e.g. when hitting caps-lock) */
663# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000664# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665
666# if (_MSC_VER < 1100)
667/* MUST turn off global optimisation for this next function, or
668 * pressing ctrl-minus in insert mode crashes Vim when built with
669 * VC4.1. -- negri. */
670# pragma optimize("g", off)
671# endif
672#endif
673
674static BOOL g_fJustGotFocus = FALSE;
675
676/*
677 * Decode a KEY_EVENT into one or two keystrokes
678 */
679 static BOOL
680decode_key_event(
681 KEY_EVENT_RECORD *pker,
682 char_u *pch,
683 char_u *pch2,
684 int *pmodifiers,
685 BOOL fDoPost)
686{
687 int i;
688 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
689
690 *pch = *pch2 = NUL;
691 g_fJustGotFocus = FALSE;
692
693 /* ignore key up events */
694 if (!pker->bKeyDown)
695 return FALSE;
696
697 /* ignore some keystrokes */
698 switch (pker->wVirtualKeyCode)
699 {
700 /* modifiers */
701 case VK_SHIFT:
702 case VK_CONTROL:
703 case VK_MENU: /* Alt key */
704 return FALSE;
705
706 default:
707 break;
708 }
709
710 /* special cases */
711 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
712 {
713 /* Ctrl-6 is Ctrl-^ */
714 if (pker->wVirtualKeyCode == '6')
715 {
716 *pch = Ctrl_HAT;
717 return TRUE;
718 }
719 /* Ctrl-2 is Ctrl-@ */
720 else if (pker->wVirtualKeyCode == '2')
721 {
722 *pch = NUL;
723 return TRUE;
724 }
725 /* Ctrl-- is Ctrl-_ */
726 else if (pker->wVirtualKeyCode == 0xBD)
727 {
728 *pch = Ctrl__;
729 return TRUE;
730 }
731 }
732
733 /* Shift-TAB */
734 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
735 {
736 *pch = K_NUL;
737 *pch2 = '\017';
738 return TRUE;
739 }
740
741 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
742 {
743 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
744 {
745 if (nModifs == 0)
746 *pch = VirtKeyMap[i].chAlone;
747 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
748 *pch = VirtKeyMap[i].chShift;
749 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
750 *pch = VirtKeyMap[i].chCtrl;
751 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
752 *pch = VirtKeyMap[i].chAlt;
753
754 if (*pch != 0)
755 {
756 if (VirtKeyMap[i].fAnsiKey)
757 {
758 *pch2 = *pch;
759 *pch = K_NUL;
760 }
761
762 return TRUE;
763 }
764 }
765 }
766
767 i = win32_kbd_patch_key(pker);
768
769 if (i < 0)
770 *pch = NUL;
771 else
772 {
773 *pch = (i > 0) ? pker->AChar : NUL;
774
775 if (pmodifiers != NULL)
776 {
777 /* Pass on the ALT key as a modifier, but only when not combined
778 * with CTRL (which is ALTGR). */
779 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
780 *pmodifiers |= MOD_MASK_ALT;
781
782 /* Pass on SHIFT only for special keys, because we don't know when
783 * it's already included with the character. */
784 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
785 *pmodifiers |= MOD_MASK_SHIFT;
786
787 /* Pass on CTRL only for non-special keys, because we don't know
788 * when it's already included with the character. And not when
789 * combined with ALT (which is ALTGR). */
790 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
791 && *pch >= 0x20 && *pch < 0x80)
792 *pmodifiers |= MOD_MASK_CTRL;
793 }
794 }
795
796 return (*pch != NUL);
797}
798
799#ifdef _MSC_VER
800# pragma optimize("", on)
801#endif
802
803#endif /* FEAT_GUI_W32 */
804
805
806#ifdef FEAT_MOUSE
807
808/*
809 * For the GUI the mouse handling is in gui_w32.c.
810 */
811# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000812/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000814mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000815{
816}
817# else
818static int g_fMouseAvail = FALSE; /* mouse present */
819static int g_fMouseActive = FALSE; /* mouse enabled */
820static int g_nMouseClick = -1; /* mouse status */
821static int g_xMouse; /* mouse x coordinate */
822static int g_yMouse; /* mouse y coordinate */
823
824/*
825 * Enable or disable mouse input
826 */
827 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000828mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829{
830 DWORD cmodein;
831
832 if (!g_fMouseAvail)
833 return;
834
835 g_fMouseActive = on;
836 GetConsoleMode(g_hConIn, &cmodein);
837
838 if (g_fMouseActive)
839 cmodein |= ENABLE_MOUSE_INPUT;
840 else
841 cmodein &= ~ENABLE_MOUSE_INPUT;
842
843 SetConsoleMode(g_hConIn, cmodein);
844}
845
846
847/*
848 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
849 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
850 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
851 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
852 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
853 * and we return the mouse position in g_xMouse and g_yMouse.
854 *
855 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
856 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
857 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
858 *
859 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
860 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
861 *
862 * Windows will send us MOUSE_MOVED notifications whenever the mouse
863 * moves, even if it stays within the same character cell. We ignore
864 * all MOUSE_MOVED messages if the position hasn't really changed, and
865 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
866 * we're only interested in MOUSE_DRAG).
867 *
868 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
869 * 2-button mouses by pressing the left & right buttons simultaneously.
870 * In practice, it's almost impossible to click both at the same time,
871 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
872 * in such cases, if the user is clicking quickly.
873 */
874 static BOOL
875decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000876 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877{
878 static int s_nOldButton = -1;
879 static int s_nOldMouseClick = -1;
880 static int s_xOldMouse = -1;
881 static int s_yOldMouse = -1;
882 static linenr_T s_old_topline = 0;
883#ifdef FEAT_DIFF
884 static int s_old_topfill = 0;
885#endif
886 static int s_cClicks = 1;
887 static BOOL s_fReleased = TRUE;
888 static DWORD s_dwLastClickTime = 0;
889 static BOOL s_fNextIsMiddle = FALSE;
890
891 static DWORD cButtons = 0; /* number of buttons supported */
892
893 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
894 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
895 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
896 const DWORD LEFT_RIGHT = LEFT | RIGHT;
897
898 int nButton;
899
900 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
901 cButtons = 2;
902
903 if (!g_fMouseAvail || !g_fMouseActive)
904 {
905 g_nMouseClick = -1;
906 return FALSE;
907 }
908
909 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
910 if (g_fJustGotFocus)
911 {
912 g_fJustGotFocus = FALSE;
913 return FALSE;
914 }
915
916 /* unprocessed mouse click? */
917 if (g_nMouseClick != -1)
918 return TRUE;
919
920 nButton = -1;
921 g_xMouse = pmer->dwMousePosition.X;
922 g_yMouse = pmer->dwMousePosition.Y;
923
924 if (pmer->dwEventFlags == MOUSE_MOVED)
925 {
926 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
927 * events even when the mouse moves only within a char cell.) */
928 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
929 return FALSE;
930 }
931
932 /* If no buttons are pressed... */
933 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
934 {
935 /* If the last thing returned was MOUSE_RELEASE, ignore this */
936 if (s_fReleased)
937 return FALSE;
938
939 nButton = MOUSE_RELEASE;
940 s_fReleased = TRUE;
941 }
942 else /* one or more buttons pressed */
943 {
944 /* on a 2-button mouse, hold down left and right buttons
945 * simultaneously to get MIDDLE. */
946
947 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
948 {
949 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
950
951 /* if either left or right button only is pressed, see if the
952 * the next mouse event has both of them pressed */
953 if (dwLR == LEFT || dwLR == RIGHT)
954 {
955 for (;;)
956 {
957 /* wait a short time for next input event */
958 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
959 != WAIT_OBJECT_0)
960 break;
961 else
962 {
963 DWORD cRecords = 0;
964 INPUT_RECORD ir;
965 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
966
967 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
968
969 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
970 || !(pmer2->dwButtonState & LEFT_RIGHT))
971 break;
972 else
973 {
974 if (pmer2->dwEventFlags != MOUSE_MOVED)
975 {
976 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
977
978 return decode_mouse_event(pmer2);
979 }
980 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
981 s_yOldMouse == pmer2->dwMousePosition.Y)
982 {
983 /* throw away spurious mouse move */
984 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
985
986 /* are there any more mouse events in queue? */
987 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
988
989 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
990 break;
991 }
992 else
993 break;
994 }
995 }
996 }
997 }
998 }
999
1000 if (s_fNextIsMiddle)
1001 {
1002 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1003 ? MOUSE_DRAG : MOUSE_MIDDLE;
1004 s_fNextIsMiddle = FALSE;
1005 }
1006 else if (cButtons == 2 &&
1007 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1008 {
1009 nButton = MOUSE_MIDDLE;
1010
1011 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1012 {
1013 s_fNextIsMiddle = TRUE;
1014 nButton = MOUSE_RELEASE;
1015 }
1016 }
1017 else if ((pmer->dwButtonState & LEFT) == LEFT)
1018 nButton = MOUSE_LEFT;
1019 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1020 nButton = MOUSE_MIDDLE;
1021 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1022 nButton = MOUSE_RIGHT;
1023
1024 if (! s_fReleased && ! s_fNextIsMiddle
1025 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1026 return FALSE;
1027
1028 s_fReleased = s_fNextIsMiddle;
1029 }
1030
1031 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1032 {
1033 /* button pressed or released, without mouse moving */
1034 if (nButton != -1 && nButton != MOUSE_RELEASE)
1035 {
1036 DWORD dwCurrentTime = GetTickCount();
1037
1038 if (s_xOldMouse != g_xMouse
1039 || s_yOldMouse != g_yMouse
1040 || s_nOldButton != nButton
1041 || s_old_topline != curwin->w_topline
1042#ifdef FEAT_DIFF
1043 || s_old_topfill != curwin->w_topfill
1044#endif
1045 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1046 {
1047 s_cClicks = 1;
1048 }
1049 else if (++s_cClicks > 4)
1050 {
1051 s_cClicks = 1;
1052 }
1053
1054 s_dwLastClickTime = dwCurrentTime;
1055 }
1056 }
1057 else if (pmer->dwEventFlags == MOUSE_MOVED)
1058 {
1059 if (nButton != -1 && nButton != MOUSE_RELEASE)
1060 nButton = MOUSE_DRAG;
1061
1062 s_cClicks = 1;
1063 }
1064
1065 if (nButton == -1)
1066 return FALSE;
1067
1068 if (nButton != MOUSE_RELEASE)
1069 s_nOldButton = nButton;
1070
1071 g_nMouseClick = nButton;
1072
1073 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1074 g_nMouseClick |= MOUSE_SHIFT;
1075 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1076 g_nMouseClick |= MOUSE_CTRL;
1077 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1078 g_nMouseClick |= MOUSE_ALT;
1079
1080 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1081 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1082
1083 /* only pass on interesting (i.e., different) mouse events */
1084 if (s_xOldMouse == g_xMouse
1085 && s_yOldMouse == g_yMouse
1086 && s_nOldMouseClick == g_nMouseClick)
1087 {
1088 g_nMouseClick = -1;
1089 return FALSE;
1090 }
1091
1092 s_xOldMouse = g_xMouse;
1093 s_yOldMouse = g_yMouse;
1094 s_old_topline = curwin->w_topline;
1095#ifdef FEAT_DIFF
1096 s_old_topfill = curwin->w_topfill;
1097#endif
1098 s_nOldMouseClick = g_nMouseClick;
1099
1100 return TRUE;
1101}
1102
1103# endif /* FEAT_GUI_W32 */
1104#endif /* FEAT_MOUSE */
1105
1106
1107#ifdef MCH_CURSOR_SHAPE
1108/*
1109 * Set the shape of the cursor.
1110 * 'thickness' can be from 1 (thin) to 99 (block)
1111 */
1112 static void
1113mch_set_cursor_shape(int thickness)
1114{
1115 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1116 ConsoleCursorInfo.dwSize = thickness;
1117 ConsoleCursorInfo.bVisible = s_cursor_visible;
1118
1119 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1120 if (s_cursor_visible)
1121 SetConsoleCursorPosition(g_hConOut, g_coord);
1122}
1123
1124 void
1125mch_update_cursor(void)
1126{
1127 int idx;
1128 int thickness;
1129
1130 /*
1131 * How the cursor is drawn depends on the current mode.
1132 */
1133 idx = get_shape_idx(FALSE);
1134
1135 if (shape_table[idx].shape == SHAPE_BLOCK)
1136 thickness = 99; /* 100 doesn't work on W95 */
1137 else
1138 thickness = shape_table[idx].percentage;
1139 mch_set_cursor_shape(thickness);
1140}
1141#endif
1142
1143#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1144/*
1145 * Handle FOCUS_EVENT.
1146 */
1147 static void
1148handle_focus_event(INPUT_RECORD ir)
1149{
1150 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1151 ui_focus_change((int)g_fJustGotFocus);
1152}
1153
1154/*
1155 * Wait until console input from keyboard or mouse is available,
1156 * or the time is up.
1157 * Return TRUE if something is available FALSE if not.
1158 */
1159 static int
1160WaitForChar(long msec)
1161{
1162 DWORD dwNow = 0, dwEndTime = 0;
1163 INPUT_RECORD ir;
1164 DWORD cRecords;
1165 char_u ch, ch2;
1166
1167 if (msec > 0)
1168 /* Wait until the specified time has elapsed. */
1169 dwEndTime = GetTickCount() + msec;
1170 else if (msec < 0)
1171 /* Wait forever. */
1172 dwEndTime = INFINITE;
1173
1174 /* We need to loop until the end of the time period, because
1175 * we might get multiple unusable mouse events in that time.
1176 */
1177 for (;;)
1178 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001179#ifdef FEAT_MZSCHEME
1180 mzvim_check_threads();
1181#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001182#ifdef FEAT_CLIENTSERVER
1183 serverProcessPendingMessages();
1184#endif
1185 if (0
1186#ifdef FEAT_MOUSE
1187 || g_nMouseClick != -1
1188#endif
1189#ifdef FEAT_CLIENTSERVER
1190 || input_available()
1191#endif
1192 )
1193 return TRUE;
1194
1195 if (msec > 0)
1196 {
1197 /* If the specified wait time has passed, return. */
1198 dwNow = GetTickCount();
1199 if (dwNow >= dwEndTime)
1200 break;
1201 }
1202 if (msec != 0)
1203 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001204 DWORD dwWaitTime = dwEndTime - dwNow;
1205
1206#ifdef FEAT_MZSCHEME
1207 if (mzthreads_allowed() && p_mzq > 0
1208 && (msec < 0 || (long)dwWaitTime > p_mzq))
1209 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1210#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211#ifdef FEAT_CLIENTSERVER
1212 /* Wait for either an event on the console input or a message in
1213 * the client-server window. */
1214 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001215 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001217 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218#endif
1219 continue;
1220 }
1221
1222 cRecords = 0;
1223 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1224
1225#ifdef FEAT_MBYTE_IME
1226 if (State & CMDLINE && msg_row == Rows - 1)
1227 {
1228 CONSOLE_SCREEN_BUFFER_INFO csbi;
1229
1230 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1231 {
1232 if (csbi.dwCursorPosition.Y != msg_row)
1233 {
1234 /* The screen is now messed up, must redraw the
1235 * command line and later all the windows. */
1236 redraw_all_later(CLEAR);
1237 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1238 redrawcmd();
1239 }
1240 }
1241 }
1242#endif
1243
1244 if (cRecords > 0)
1245 {
1246 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1247 {
1248#ifdef FEAT_MBYTE_IME
1249 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1250 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1251 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1252 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1253 {
1254 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1255 continue;
1256 }
1257#endif
1258 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1259 NULL, FALSE))
1260 return TRUE;
1261 }
1262
1263 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1264
1265 if (ir.EventType == FOCUS_EVENT)
1266 handle_focus_event(ir);
1267 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1268 shell_resized();
1269#ifdef FEAT_MOUSE
1270 else if (ir.EventType == MOUSE_EVENT
1271 && decode_mouse_event(&ir.Event.MouseEvent))
1272 return TRUE;
1273#endif
1274 }
1275 else if (msec == 0)
1276 break;
1277 }
1278
1279#ifdef FEAT_CLIENTSERVER
1280 /* Something might have been received while we were waiting. */
1281 if (input_available())
1282 return TRUE;
1283#endif
1284 return FALSE;
1285}
1286
1287#ifndef FEAT_GUI_MSWIN
1288/*
1289 * return non-zero if a character is available
1290 */
1291 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001292mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001293{
1294 return WaitForChar(0L);
1295}
1296#endif
1297
1298/*
1299 * Create the console input. Used when reading stdin doesn't work.
1300 */
1301 static void
1302create_conin(void)
1303{
1304 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1305 FILE_SHARE_READ|FILE_SHARE_WRITE,
1306 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001307 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308 did_create_conin = TRUE;
1309}
1310
1311/*
1312 * Get a keystroke or a mouse event
1313 */
1314 static char_u
1315tgetch(int *pmodifiers, char_u *pch2)
1316{
1317 char_u ch;
1318
1319 for (;;)
1320 {
1321 INPUT_RECORD ir;
1322 DWORD cRecords = 0;
1323
1324#ifdef FEAT_CLIENTSERVER
1325 (void)WaitForChar(-1L);
1326 if (input_available())
1327 return 0;
1328# ifdef FEAT_MOUSE
1329 if (g_nMouseClick != -1)
1330 return 0;
1331# endif
1332#endif
1333 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1334 {
1335 if (did_create_conin)
1336 read_error_exit();
1337 create_conin();
1338 continue;
1339 }
1340
1341 if (ir.EventType == KEY_EVENT)
1342 {
1343 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1344 pmodifiers, TRUE))
1345 return ch;
1346 }
1347 else if (ir.EventType == FOCUS_EVENT)
1348 handle_focus_event(ir);
1349 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1350 shell_resized();
1351#ifdef FEAT_MOUSE
1352 else if (ir.EventType == MOUSE_EVENT)
1353 {
1354 if (decode_mouse_event(&ir.Event.MouseEvent))
1355 return 0;
1356 }
1357#endif
1358 }
1359}
1360#endif /* !FEAT_GUI_W32 */
1361
1362
1363/*
1364 * mch_inchar(): low-level input funcion.
1365 * Get one or more characters from the keyboard or the mouse.
1366 * If time == 0, do not wait for characters.
1367 * If time == n, wait a short time for characters.
1368 * If time == -1, wait forever for characters.
1369 * Returns the number of characters read into buf.
1370 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001371/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372 int
1373mch_inchar(
1374 char_u *buf,
1375 int maxlen,
1376 long time,
1377 int tb_change_cnt)
1378{
1379#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1380
1381 int len;
1382 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001383#define TYPEAHEADLEN 20
1384 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1385 static int typeaheadlen = 0;
1386
1387 /* First use any typeahead that was kept because "buf" was too small. */
1388 if (typeaheadlen > 0)
1389 goto theend;
1390
1391#ifdef FEAT_SNIFF
1392 if (want_sniff_request)
1393 {
1394 if (sniff_request_waiting)
1395 {
1396 /* return K_SNIFF */
1397 typeahead[typeaheadlen++] = CSI;
1398 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1399 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1400 sniff_request_waiting = 0;
1401 want_sniff_request = 0;
1402 goto theend;
1403 }
1404 else if (time < 0 || time > 250)
1405 {
1406 /* don't wait too long, a request might be pending */
1407 time = 250;
1408 }
1409 }
1410#endif
1411
1412 if (time >= 0)
1413 {
1414 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001415 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001416 }
1417 else /* time == -1, wait forever */
1418 {
1419 mch_set_winsize_now(); /* Allow winsize changes from now on */
1420
Bram Moolenaar3918c952005-03-15 22:34:55 +00001421 /*
1422 * If there is no character available within 2 seconds (default)
1423 * write the autoscript file to disk. Or cause the CursorHold event
1424 * to be triggered.
1425 */
1426 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427 {
1428#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001429 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001431 buf[0] = K_SPECIAL;
1432 buf[1] = KS_EXTRA;
1433 buf[2] = (int)KE_CURSORHOLD;
1434 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435 }
1436#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001437 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438 }
1439 }
1440
1441 /*
1442 * Try to read as many characters as there are, until the buffer is full.
1443 */
1444
1445 /* we will get at least one key. Get more if they are available. */
1446 g_fCBrkPressed = FALSE;
1447
1448#ifdef MCH_WRITE_DUMP
1449 if (fdDump)
1450 fputc('[', fdDump);
1451#endif
1452
1453 /* Keep looping until there is something in the typeahead buffer and more
1454 * to get and still room in the buffer (up to two bytes for a char and
1455 * three bytes for a modifier). */
1456 while ((typeaheadlen == 0 || WaitForChar(0L))
1457 && typeaheadlen + 5 <= TYPEAHEADLEN)
1458 {
1459 if (typebuf_changed(tb_change_cnt))
1460 {
1461 /* "buf" may be invalid now if a client put something in the
1462 * typeahead buffer and "buf" is in the typeahead buffer. */
1463 typeaheadlen = 0;
1464 break;
1465 }
1466#ifdef FEAT_MOUSE
1467 if (g_nMouseClick != -1)
1468 {
1469# ifdef MCH_WRITE_DUMP
1470 if (fdDump)
1471 fprintf(fdDump, "{%02x @ %d, %d}",
1472 g_nMouseClick, g_xMouse, g_yMouse);
1473# endif
1474 typeahead[typeaheadlen++] = ESC + 128;
1475 typeahead[typeaheadlen++] = 'M';
1476 typeahead[typeaheadlen++] = g_nMouseClick;
1477 typeahead[typeaheadlen++] = g_xMouse + '!';
1478 typeahead[typeaheadlen++] = g_yMouse + '!';
1479 g_nMouseClick = -1;
1480 }
1481 else
1482#endif
1483 {
1484 char_u ch2 = NUL;
1485 int modifiers = 0;
1486
1487 c = tgetch(&modifiers, &ch2);
1488
1489 if (typebuf_changed(tb_change_cnt))
1490 {
1491 /* "buf" may be invalid now if a client put something in the
1492 * typeahead buffer and "buf" is in the typeahead buffer. */
1493 typeaheadlen = 0;
1494 break;
1495 }
1496
1497 if (c == Ctrl_C && ctrl_c_interrupts)
1498 {
1499#if defined(FEAT_CLIENTSERVER)
1500 trash_input_buf();
1501#endif
1502 got_int = TRUE;
1503 }
1504
1505#ifdef FEAT_MOUSE
1506 if (g_nMouseClick == -1)
1507#endif
1508 {
1509 int n = 1;
1510
1511 /* A key may have one or two bytes. */
1512 typeahead[typeaheadlen] = c;
1513 if (ch2 != NUL)
1514 {
1515 typeahead[typeaheadlen + 1] = ch2;
1516 ++n;
1517 }
1518#ifdef FEAT_MBYTE
1519 /* Only convert normal characters, not special keys. Need to
1520 * convert before applying ALT, otherwise mapping <M-x> breaks
1521 * when 'tenc' is set. */
1522 if (input_conv.vc_type != CONV_NONE
1523 && (ch2 == NUL || c != K_NUL))
1524 n = convert_input(typeahead + typeaheadlen, n,
1525 TYPEAHEADLEN - typeaheadlen);
1526#endif
1527
1528 /* Use the ALT key to set the 8th bit of the character
1529 * when it's one byte, the 8th bit isn't set yet and not
1530 * using a double-byte encoding (would become a lead
1531 * byte). */
1532 if ((modifiers & MOD_MASK_ALT)
1533 && n == 1
1534 && (typeahead[typeaheadlen] & 0x80) == 0
1535#ifdef FEAT_MBYTE
1536 && !enc_dbcs
1537#endif
1538 )
1539 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001540#ifdef FEAT_MBYTE
1541 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1542 typeahead + typeaheadlen);
1543#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001545#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 modifiers &= ~MOD_MASK_ALT;
1547 }
1548
1549 if (modifiers != 0)
1550 {
1551 /* Prepend modifiers to the character. */
1552 mch_memmove(typeahead + typeaheadlen + 3,
1553 typeahead + typeaheadlen, n);
1554 typeahead[typeaheadlen++] = K_SPECIAL;
1555 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1556 typeahead[typeaheadlen++] = modifiers;
1557 }
1558
1559 typeaheadlen += n;
1560
1561#ifdef MCH_WRITE_DUMP
1562 if (fdDump)
1563 fputc(c, fdDump);
1564#endif
1565 }
1566 }
1567 }
1568
1569#ifdef MCH_WRITE_DUMP
1570 if (fdDump)
1571 {
1572 fputs("]\n", fdDump);
1573 fflush(fdDump);
1574 }
1575#endif
1576
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577theend:
1578 /* Move typeahead to "buf", as much as fits. */
1579 len = 0;
1580 while (len < maxlen && typeaheadlen > 0)
1581 {
1582 buf[len++] = typeahead[0];
1583 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1584 }
1585 return len;
1586
1587#else /* FEAT_GUI_W32 */
1588 return 0;
1589#endif /* FEAT_GUI_W32 */
1590}
1591
1592#ifndef __MINGW32__
1593# include <shellapi.h> /* required for FindExecutable() */
1594#endif
1595
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001596/*
1597 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001598 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001599 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600 static int
1601executable_exists(char *name)
1602{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001603 char *dum;
1604 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001606#ifdef FEAT_MBYTE
1607 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001609 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001610 WCHAR fnamew[_MAX_PATH];
1611 WCHAR *dumw;
1612 long n;
1613
1614 if (p != NULL)
1615 {
1616 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1617 vim_free(p);
1618 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1619 {
1620 if (n == 0)
1621 return FALSE;
1622 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1623 return FALSE;
1624 return TRUE;
1625 }
1626 /* Retry with non-wide function (for Windows 98). */
1627 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001629#endif
1630 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1631 return FALSE;
1632 if (mch_isdir(fname))
1633 return FALSE;
1634 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001635}
1636
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001637#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
1638 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
1639/*
1640 * Bad parameter handler.
1641 *
1642 * Certain MS CRT functions will intentionally crash when passed invalid
1643 * parameters to highlight possible security holes. Setting this function as
1644 * the bad parameter handler will prevent the crash.
1645 *
1646 * In debug builds the parameters contain CRT information that might help track
1647 * down the source of a problem, but in non-debug builds the arguments are all
1648 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1649 * worth allowing these to make debugging of issues easier.
1650 */
1651 static void
1652bad_param_handler(const wchar_t *expression,
1653 const wchar_t *function,
1654 const wchar_t *file,
1655 unsigned int line,
1656 uintptr_t pReserved)
1657{
1658}
1659
1660# define SET_INVALID_PARAM_HANDLER \
1661 ((void)_set_invalid_parameter_handler(bad_param_handler))
1662#else
1663# define SET_INVALID_PARAM_HANDLER
1664#endif
1665
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666#ifdef FEAT_GUI_W32
1667
1668/*
1669 * GUI version of mch_init().
1670 */
1671 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001672mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673{
1674#ifndef __MINGW32__
1675 extern int _fmode;
1676#endif
1677
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001678 /* Silently handle invalid parameters to CRT functions */
1679 SET_INVALID_PARAM_HANDLER;
1680
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681 /* Let critical errors result in a failure, not in a dialog box. Required
1682 * for the timestamp test to work on removed floppies. */
1683 SetErrorMode(SEM_FAILCRITICALERRORS);
1684
1685 _fmode = O_BINARY; /* we do our own CR-LF translation */
1686
1687 /* Specify window size. Is there a place to get the default from? */
1688 Rows = 25;
1689 Columns = 80;
1690
1691 /* Look for 'vimrun' */
1692 if (!gui_is_win32s())
1693 {
1694 char_u vimrun_location[_MAX_PATH + 4];
1695
1696 /* First try in same directory as gvim.exe */
1697 STRCPY(vimrun_location, exe_name);
1698 STRCPY(gettail(vimrun_location), "vimrun.exe");
1699 if (mch_getperm(vimrun_location) >= 0)
1700 {
1701 if (*skiptowhite(vimrun_location) != NUL)
1702 {
1703 /* Enclose path with white space in double quotes. */
1704 mch_memmove(vimrun_location + 1, vimrun_location,
1705 STRLEN(vimrun_location) + 1);
1706 *vimrun_location = '"';
1707 STRCPY(gettail(vimrun_location), "vimrun\" ");
1708 }
1709 else
1710 STRCPY(gettail(vimrun_location), "vimrun ");
1711
1712 vimrun_path = (char *)vim_strsave(vimrun_location);
1713 s_dont_use_vimrun = FALSE;
1714 }
1715 else if (executable_exists("vimrun.exe"))
1716 s_dont_use_vimrun = FALSE;
1717
1718 /* Don't give the warning for a missing vimrun.exe right now, but only
1719 * when vimrun was supposed to be used. Don't bother people that do
1720 * not need vimrun.exe. */
1721 if (s_dont_use_vimrun)
1722 need_vimrun_warning = TRUE;
1723 }
1724
1725 /*
1726 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1727 * Otherwise the default "findstr /n" is used.
1728 */
1729 if (!executable_exists("findstr.exe"))
1730 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1731
1732#ifdef FEAT_CLIPBOARD
1733 clip_init(TRUE);
1734
1735 /*
Bram Moolenaar7528dd62007-05-06 12:32:12 +00001736 * Vim's own clipboard format recognises whether the text is char, line,
1737 * or rectangular block. Only useful for copying between two Vims.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738 * "VimClipboard" was used for previous versions, using the first
1739 * character to specify MCHAR, MLINE or MBLOCK.
1740 */
1741 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1742 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1743#endif
1744}
1745
1746
1747#else /* FEAT_GUI_W32 */
1748
1749#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1750#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1751
1752/*
1753 * ClearConsoleBuffer()
1754 * Description:
1755 * Clears the entire contents of the console screen buffer, using the
1756 * specified attribute.
1757 * Returns:
1758 * TRUE on success
1759 */
1760 static BOOL
1761ClearConsoleBuffer(WORD wAttribute)
1762{
1763 CONSOLE_SCREEN_BUFFER_INFO csbi;
1764 COORD coord;
1765 DWORD NumCells, dummy;
1766
1767 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1768 return FALSE;
1769
1770 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1771 coord.X = 0;
1772 coord.Y = 0;
1773 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1774 coord, &dummy))
1775 {
1776 return FALSE;
1777 }
1778 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1779 coord, &dummy))
1780 {
1781 return FALSE;
1782 }
1783
1784 return TRUE;
1785}
1786
1787/*
1788 * FitConsoleWindow()
1789 * Description:
1790 * Checks if the console window will fit within given buffer dimensions.
1791 * Also, if requested, will shrink the window to fit.
1792 * Returns:
1793 * TRUE on success
1794 */
1795 static BOOL
1796FitConsoleWindow(
1797 COORD dwBufferSize,
1798 BOOL WantAdjust)
1799{
1800 CONSOLE_SCREEN_BUFFER_INFO csbi;
1801 COORD dwWindowSize;
1802 BOOL NeedAdjust = FALSE;
1803
1804 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1805 {
1806 /*
1807 * A buffer resize will fail if the current console window does
1808 * not lie completely within that buffer. To avoid this, we might
1809 * have to move and possibly shrink the window.
1810 */
1811 if (csbi.srWindow.Right >= dwBufferSize.X)
1812 {
1813 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1814 if (dwWindowSize.X > dwBufferSize.X)
1815 dwWindowSize.X = dwBufferSize.X;
1816 csbi.srWindow.Right = dwBufferSize.X - 1;
1817 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1818 NeedAdjust = TRUE;
1819 }
1820 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1821 {
1822 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1823 if (dwWindowSize.Y > dwBufferSize.Y)
1824 dwWindowSize.Y = dwBufferSize.Y;
1825 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1826 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1827 NeedAdjust = TRUE;
1828 }
1829 if (NeedAdjust && WantAdjust)
1830 {
1831 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1832 return FALSE;
1833 }
1834 return TRUE;
1835 }
1836
1837 return FALSE;
1838}
1839
1840typedef struct ConsoleBufferStruct
1841{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001842 BOOL IsValid;
1843 CONSOLE_SCREEN_BUFFER_INFO Info;
1844 PCHAR_INFO Buffer;
1845 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846} ConsoleBuffer;
1847
1848/*
1849 * SaveConsoleBuffer()
1850 * Description:
1851 * Saves important information about the console buffer, including the
1852 * actual buffer contents. The saved information is suitable for later
1853 * restoration by RestoreConsoleBuffer().
1854 * Returns:
1855 * TRUE if all information was saved; FALSE otherwise
1856 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1857 */
1858 static BOOL
1859SaveConsoleBuffer(
1860 ConsoleBuffer *cb)
1861{
1862 DWORD NumCells;
1863 COORD BufferCoord;
1864 SMALL_RECT ReadRegion;
1865 WORD Y, Y_incr;
1866
1867 if (cb == NULL)
1868 return FALSE;
1869
1870 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1871 {
1872 cb->IsValid = FALSE;
1873 return FALSE;
1874 }
1875 cb->IsValid = TRUE;
1876
1877 /*
1878 * Allocate a buffer large enough to hold the entire console screen
1879 * buffer. If this ConsoleBuffer structure has already been initialized
1880 * with a buffer of the correct size, then just use that one.
1881 */
1882 if (!cb->IsValid || cb->Buffer == NULL ||
1883 cb->BufferSize.X != cb->Info.dwSize.X ||
1884 cb->BufferSize.Y != cb->Info.dwSize.Y)
1885 {
1886 cb->BufferSize.X = cb->Info.dwSize.X;
1887 cb->BufferSize.Y = cb->Info.dwSize.Y;
1888 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
1889 if (cb->Buffer != NULL)
1890 vim_free(cb->Buffer);
1891 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
1892 if (cb->Buffer == NULL)
1893 return FALSE;
1894 }
1895
1896 /*
1897 * We will now copy the console screen buffer into our buffer.
1898 * ReadConsoleOutput() seems to be limited as far as how much you
1899 * can read at a time. Empirically, this number seems to be about
1900 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1901 * in chunks until it is all copied. The chunks will all have the
1902 * same horizontal characteristics, so initialize them now. The
1903 * height of each chunk will be (12000 / width).
1904 */
1905 BufferCoord.X = 0;
1906 ReadRegion.Left = 0;
1907 ReadRegion.Right = cb->Info.dwSize.X - 1;
1908 Y_incr = 12000 / cb->Info.dwSize.X;
1909 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
1910 {
1911 /*
1912 * Read into position (0, Y) in our buffer.
1913 */
1914 BufferCoord.Y = Y;
1915 /*
1916 * Read the region whose top left corner is (0, Y) and whose bottom
1917 * right corner is (width - 1, Y + Y_incr - 1). This should define
1918 * a region of size width by Y_incr. Don't worry if this region is
1919 * too large for the remaining buffer; it will be cropped.
1920 */
1921 ReadRegion.Top = Y;
1922 ReadRegion.Bottom = Y + Y_incr - 1;
1923 if (!ReadConsoleOutput(g_hConOut, /* output handle */
1924 cb->Buffer, /* our buffer */
1925 cb->BufferSize, /* dimensions of our buffer */
1926 BufferCoord, /* offset in our buffer */
1927 &ReadRegion)) /* region to save */
1928 {
1929 vim_free(cb->Buffer);
1930 cb->Buffer = NULL;
1931 return FALSE;
1932 }
1933 }
1934
1935 return TRUE;
1936}
1937
1938/*
1939 * RestoreConsoleBuffer()
1940 * Description:
1941 * Restores important information about the console buffer, including the
1942 * actual buffer contents, if desired. The information to restore is in
1943 * the same format used by SaveConsoleBuffer().
1944 * Returns:
1945 * TRUE on success
1946 */
1947 static BOOL
1948RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001949 ConsoleBuffer *cb,
1950 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001951{
1952 COORD BufferCoord;
1953 SMALL_RECT WriteRegion;
1954
1955 if (cb == NULL || !cb->IsValid)
1956 return FALSE;
1957
1958 /*
1959 * Before restoring the buffer contents, clear the current buffer, and
1960 * restore the cursor position and window information. Doing this now
1961 * prevents old buffer contents from "flashing" onto the screen.
1962 */
1963 if (RestoreScreen)
1964 ClearConsoleBuffer(cb->Info.wAttributes);
1965
1966 FitConsoleWindow(cb->Info.dwSize, TRUE);
1967 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
1968 return FALSE;
1969 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
1970 return FALSE;
1971
1972 if (!RestoreScreen)
1973 {
1974 /*
1975 * No need to restore the screen buffer contents, so we're done.
1976 */
1977 return TRUE;
1978 }
1979
1980 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
1981 return FALSE;
1982 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
1983 return FALSE;
1984
1985 /*
1986 * Restore the screen buffer contents.
1987 */
1988 if (cb->Buffer != NULL)
1989 {
1990 BufferCoord.X = 0;
1991 BufferCoord.Y = 0;
1992 WriteRegion.Left = 0;
1993 WriteRegion.Top = 0;
1994 WriteRegion.Right = cb->Info.dwSize.X - 1;
1995 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
1996 if (!WriteConsoleOutput(g_hConOut, /* output handle */
1997 cb->Buffer, /* our buffer */
1998 cb->BufferSize, /* dimensions of our buffer */
1999 BufferCoord, /* offset in our buffer */
2000 &WriteRegion)) /* region to restore */
2001 {
2002 return FALSE;
2003 }
2004 }
2005
2006 return TRUE;
2007}
2008
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002009#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010#ifdef FEAT_RESTORE_ORIG_SCREEN
2011static ConsoleBuffer g_cbOrig = { 0 };
2012#endif
2013static ConsoleBuffer g_cbNonTermcap = { 0 };
2014static ConsoleBuffer g_cbTermcap = { 0 };
2015
2016#ifdef FEAT_TITLE
2017#ifdef __BORLANDC__
2018typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2019#else
2020typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2021#endif
2022char g_szOrigTitle[256] = { 0 };
2023HWND g_hWnd = NULL; /* also used in os_mswin.c */
2024static HICON g_hOrigIconSmall = NULL;
2025static HICON g_hOrigIcon = NULL;
2026static HICON g_hVimIcon = NULL;
2027static BOOL g_fCanChangeIcon = FALSE;
2028
2029/* ICON* are not defined in VC++ 4.0 */
2030#ifndef ICON_SMALL
2031#define ICON_SMALL 0
2032#endif
2033#ifndef ICON_BIG
2034#define ICON_BIG 1
2035#endif
2036/*
2037 * GetConsoleIcon()
2038 * Description:
2039 * Attempts to retrieve the small icon and/or the big icon currently in
2040 * use by a given window.
2041 * Returns:
2042 * TRUE on success
2043 */
2044 static BOOL
2045GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002046 HWND hWnd,
2047 HICON *phIconSmall,
2048 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049{
2050 if (hWnd == NULL)
2051 return FALSE;
2052
2053 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002054 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2055 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002057 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2058 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 return TRUE;
2060}
2061
2062/*
2063 * SetConsoleIcon()
2064 * Description:
2065 * Attempts to change the small icon and/or the big icon currently in
2066 * use by a given window.
2067 * Returns:
2068 * TRUE on success
2069 */
2070 static BOOL
2071SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002072 HWND hWnd,
2073 HICON hIconSmall,
2074 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002076 HICON hPrevIconSmall;
2077 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078
2079 if (hWnd == NULL)
2080 return FALSE;
2081
2082 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002083 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2084 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002085 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002086 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2087 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002088 return TRUE;
2089}
2090
2091/*
2092 * SaveConsoleTitleAndIcon()
2093 * Description:
2094 * Saves the current console window title in g_szOrigTitle, for later
2095 * restoration. Also, attempts to obtain a handle to the console window,
2096 * and use it to save the small and big icons currently in use by the
2097 * console window. This is not always possible on some versions of Windows;
2098 * nor is it possible when running Vim remotely using Telnet (since the
2099 * console window the user sees is owned by a remote process).
2100 */
2101 static void
2102SaveConsoleTitleAndIcon(void)
2103{
2104 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2105
2106 /* Save the original title. */
2107 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2108 return;
2109
2110 /*
2111 * Obtain a handle to the console window using GetConsoleWindow() from
2112 * KERNEL32.DLL; we need to handle in order to change the window icon.
2113 * This function only exists on NT-based Windows, starting with Windows
2114 * 2000. On older operating systems, we can't change the window icon
2115 * anyway.
2116 */
2117 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2118 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2119 "GetConsoleWindow")) != NULL)
2120 {
2121 g_hWnd = (*GetConsoleWindowProc)();
2122 }
2123 if (g_hWnd == NULL)
2124 return;
2125
2126 /* Save the original console window icon. */
2127 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2128 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2129 return;
2130
2131 /* Extract the first icon contained in the Vim executable. */
2132 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2133 if (g_hVimIcon != NULL)
2134 g_fCanChangeIcon = TRUE;
2135}
2136#endif
2137
2138static int g_fWindInitCalled = FALSE;
2139static int g_fTermcapMode = FALSE;
2140static CONSOLE_CURSOR_INFO g_cci;
2141static DWORD g_cmodein = 0;
2142static DWORD g_cmodeout = 0;
2143
2144/*
2145 * non-GUI version of mch_init().
2146 */
2147 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002148mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149{
2150#ifndef FEAT_RESTORE_ORIG_SCREEN
2151 CONSOLE_SCREEN_BUFFER_INFO csbi;
2152#endif
2153#ifndef __MINGW32__
2154 extern int _fmode;
2155#endif
2156
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002157 /* Silently handle invalid parameters to CRT functions */
2158 SET_INVALID_PARAM_HANDLER;
2159
Bram Moolenaar071d4272004-06-13 20:20:40 +00002160 /* Let critical errors result in a failure, not in a dialog box. Required
2161 * for the timestamp test to work on removed floppies. */
2162 SetErrorMode(SEM_FAILCRITICALERRORS);
2163
2164 _fmode = O_BINARY; /* we do our own CR-LF translation */
2165 out_flush();
2166
2167 /* Obtain handles for the standard Console I/O devices */
2168 if (read_cmd_fd == 0)
2169 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2170 else
2171 create_conin();
2172 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2173
2174#ifdef FEAT_RESTORE_ORIG_SCREEN
2175 /* Save the initial console buffer for later restoration */
2176 SaveConsoleBuffer(&g_cbOrig);
2177 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2178#else
2179 /* Get current text attributes */
2180 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2181 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2182#endif
2183 if (cterm_normal_fg_color == 0)
2184 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2185 if (cterm_normal_bg_color == 0)
2186 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2187
2188 /* set termcap codes to current text attributes */
2189 update_tcap(g_attrCurrent);
2190
2191 GetConsoleCursorInfo(g_hConOut, &g_cci);
2192 GetConsoleMode(g_hConIn, &g_cmodein);
2193 GetConsoleMode(g_hConOut, &g_cmodeout);
2194
2195#ifdef FEAT_TITLE
2196 SaveConsoleTitleAndIcon();
2197 /*
2198 * Set both the small and big icons of the console window to Vim's icon.
2199 * Note that Vim presently only has one size of icon (32x32), but it
2200 * automatically gets scaled down to 16x16 when setting the small icon.
2201 */
2202 if (g_fCanChangeIcon)
2203 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2204#endif
2205
2206 ui_get_shellsize();
2207
2208#ifdef MCH_WRITE_DUMP
2209 fdDump = fopen("dump", "wt");
2210
2211 if (fdDump)
2212 {
2213 time_t t;
2214
2215 time(&t);
2216 fputs(ctime(&t), fdDump);
2217 fflush(fdDump);
2218 }
2219#endif
2220
2221 g_fWindInitCalled = TRUE;
2222
2223#ifdef FEAT_MOUSE
2224 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2225#endif
2226
2227#ifdef FEAT_CLIPBOARD
2228 clip_init(TRUE);
2229
2230 /*
2231 * Vim's own clipboard format recognises whether the text is char, line, or
2232 * rectangular block. Only useful for copying between two Vims.
2233 * "VimClipboard" was used for previous versions, using the first
2234 * character to specify MCHAR, MLINE or MBLOCK.
2235 */
2236 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2237 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2238#endif
2239
2240 /* This will be NULL on anything but NT 4.0 */
2241 s_pfnGetConsoleKeyboardLayoutName =
2242 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2243 "GetConsoleKeyboardLayoutNameA");
2244}
2245
2246/*
2247 * non-GUI version of mch_exit().
2248 * Shut down and exit with status `r'
2249 * Careful: mch_exit() may be called before mch_init()!
2250 */
2251 void
2252mch_exit(int r)
2253{
2254 stoptermcap();
2255
2256 if (g_fWindInitCalled)
2257 settmode(TMODE_COOK);
2258
2259 ml_close_all(TRUE); /* remove all memfiles */
2260
2261 if (g_fWindInitCalled)
2262 {
2263#ifdef FEAT_TITLE
2264 mch_restore_title(3);
2265 /*
2266 * Restore both the small and big icons of the console window to
2267 * what they were at startup. Don't do this when the window is
2268 * closed, Vim would hang here.
2269 */
2270 if (g_fCanChangeIcon && !g_fForceExit)
2271 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2272#endif
2273
2274#ifdef MCH_WRITE_DUMP
2275 if (fdDump)
2276 {
2277 time_t t;
2278
2279 time(&t);
2280 fputs(ctime(&t), fdDump);
2281 fclose(fdDump);
2282 }
2283 fdDump = NULL;
2284#endif
2285 }
2286
2287 SetConsoleCursorInfo(g_hConOut, &g_cci);
2288 SetConsoleMode(g_hConIn, g_cmodein);
2289 SetConsoleMode(g_hConOut, g_cmodeout);
2290
2291#ifdef DYNAMIC_GETTEXT
2292 dyn_libintl_end();
2293#endif
2294
2295 exit(r);
2296}
2297#endif /* !FEAT_GUI_W32 */
2298
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299/*
2300 * Do we have an interactive window?
2301 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002302/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303 int
2304mch_check_win(
2305 int argc,
2306 char **argv)
2307{
2308 get_exe_name();
2309
2310#ifdef FEAT_GUI_W32
2311 return OK; /* GUI always has a tty */
2312#else
2313 if (isatty(1))
2314 return OK;
2315 return FAIL;
2316#endif
2317}
2318
2319
2320/*
2321 * fname_case(): Set the case of the file name, if it already exists.
2322 * When "len" is > 0, also expand short to long filenames.
2323 */
2324 void
2325fname_case(
2326 char_u *name,
2327 int len)
2328{
2329 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002330 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 char *ptrue, *ptruePrev;
2332 char *porig, *porigPrev;
2333 int flen;
2334 WIN32_FIND_DATA fb;
2335 HANDLE hFind;
2336 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002337 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002339 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340 if (flen == 0 || flen > _MAX_PATH)
2341 return;
2342
2343 slash_adjust(name);
2344
2345 /* Build the new name in szTrueName[] one component at a time. */
2346 porig = name;
2347 ptrue = szTrueName;
2348
2349 if (isalpha(porig[0]) && porig[1] == ':')
2350 {
2351 /* copy leading drive letter */
2352 *ptrue++ = *porig++;
2353 *ptrue++ = *porig++;
2354 *ptrue = NUL; /* in case nothing follows */
2355 }
2356
2357 while (*porig != NUL)
2358 {
2359 /* copy \ characters */
2360 while (*porig == psepc)
2361 *ptrue++ = *porig++;
2362
2363 ptruePrev = ptrue;
2364 porigPrev = porig;
2365 while (*porig != NUL && *porig != psepc)
2366 {
2367#ifdef FEAT_MBYTE
2368 int l;
2369
2370 if (enc_dbcs)
2371 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002372 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 while (--l >= 0)
2374 *ptrue++ = *porig++;
2375 }
2376 else
2377#endif
2378 *ptrue++ = *porig++;
2379 }
2380 *ptrue = NUL;
2381
Bram Moolenaar464c9252010-10-13 20:37:41 +02002382 /* To avoid a slow failure append "\*" when searching a directory,
2383 * server or network share. */
2384 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002385 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002386 if (*porig == psepc && slen + 2 < _MAX_PATH)
2387 STRCPY(szTrueNameTemp + slen, "\\*");
2388
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389 /* Skip "", "." and "..". */
2390 if (ptrue > ptruePrev
2391 && (ptruePrev[0] != '.'
2392 || (ptruePrev[1] != NUL
2393 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002394 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395 != INVALID_HANDLE_VALUE)
2396 {
2397 c = *porig;
2398 *porig = NUL;
2399
2400 /* Only use the match when it's the same name (ignoring case) or
2401 * expansion is allowed and there is a match with the short name
2402 * and there is enough room. */
2403 if (_stricoll(porigPrev, fb.cFileName) == 0
2404 || (len > 0
2405 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2406 && (int)(ptruePrev - szTrueName)
2407 + (int)strlen(fb.cFileName) < len)))
2408 {
2409 STRCPY(ptruePrev, fb.cFileName);
2410
2411 /* Look for exact match and prefer it if found. Must be a
2412 * long name, otherwise there would be only one match. */
2413 while (FindNextFile(hFind, &fb))
2414 {
2415 if (*fb.cAlternateFileName != NUL
2416 && (strcoll(porigPrev, fb.cFileName) == 0
2417 || (len > 0
2418 && (_stricoll(porigPrev,
2419 fb.cAlternateFileName) == 0
2420 && (int)(ptruePrev - szTrueName)
2421 + (int)strlen(fb.cFileName) < len))))
2422 {
2423 STRCPY(ptruePrev, fb.cFileName);
2424 break;
2425 }
2426 }
2427 }
2428 FindClose(hFind);
2429 *porig = c;
2430 ptrue = ptruePrev + strlen(ptruePrev);
2431 }
2432 }
2433
2434 STRCPY(name, szTrueName);
2435}
2436
2437
2438/*
2439 * Insert user name in s[len].
2440 */
2441 int
2442mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002443 char_u *s,
2444 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002446 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447 DWORD cch = sizeof szUserName;
2448
2449 if (GetUserName(szUserName, &cch))
2450 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002451 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452 return OK;
2453 }
2454 s[0] = NUL;
2455 return FAIL;
2456}
2457
2458
2459/*
2460 * Insert host name in s[len].
2461 */
2462 void
2463mch_get_host_name(
2464 char_u *s,
2465 int len)
2466{
2467 DWORD cch = len;
2468
2469 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002470 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471}
2472
2473
2474/*
2475 * return process ID
2476 */
2477 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002478mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479{
2480 return (long)GetCurrentProcessId();
2481}
2482
2483
2484/*
2485 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2486 * Return OK for success, FAIL for failure.
2487 */
2488 int
2489mch_dirname(
2490 char_u *buf,
2491 int len)
2492{
2493 /*
2494 * Originally this was:
2495 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2496 * But the Win32s known bug list says that getcwd() doesn't work
2497 * so use the Win32 system call instead. <Negri>
2498 */
2499#ifdef FEAT_MBYTE
2500 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2501 {
2502 WCHAR wbuf[_MAX_PATH + 1];
2503
2504 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2505 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002506 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507
2508 if (p != NULL)
2509 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002510 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 vim_free(p);
2512 return OK;
2513 }
2514 }
2515 /* Retry with non-wide function (for Windows 98). */
2516 }
2517#endif
2518 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2519}
2520
2521/*
2522 * get file permissions for `name'
2523 * -1 : error
2524 * else FILE_ATTRIBUTE_* defined in winnt.h
2525 */
2526 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002527mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528{
2529#ifdef FEAT_MBYTE
2530 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2531 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002532 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002533 long n;
2534
2535 if (p != NULL)
2536 {
2537 n = (long)GetFileAttributesW(p);
2538 vim_free(p);
2539 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2540 return n;
2541 /* Retry with non-wide function (for Windows 98). */
2542 }
2543 }
2544#endif
2545 return (long)GetFileAttributes((char *)name);
2546}
2547
2548
2549/*
2550 * set file permission for `name' to `perm'
2551 */
2552 int
2553mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002554 char_u *name,
2555 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002556{
2557 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2558#ifdef FEAT_MBYTE
2559 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2560 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002561 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002562 long n;
2563
2564 if (p != NULL)
2565 {
2566 n = (long)SetFileAttributesW(p, perm);
2567 vim_free(p);
2568 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2569 return n ? OK : FAIL;
2570 /* Retry with non-wide function (for Windows 98). */
2571 }
2572 }
2573#endif
2574 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2575}
2576
2577/*
2578 * Set hidden flag for "name".
2579 */
2580 void
2581mch_hide(char_u *name)
2582{
2583 int perm;
2584#ifdef FEAT_MBYTE
2585 WCHAR *p = NULL;
2586
2587 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002588 p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589#endif
2590
2591#ifdef FEAT_MBYTE
2592 if (p != NULL)
2593 {
2594 perm = GetFileAttributesW(p);
2595 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2596 {
2597 /* Retry with non-wide function (for Windows 98). */
2598 vim_free(p);
2599 p = NULL;
2600 }
2601 }
2602 if (p == NULL)
2603#endif
2604 perm = GetFileAttributes((char *)name);
2605 if (perm >= 0)
2606 {
2607 perm |= FILE_ATTRIBUTE_HIDDEN;
2608#ifdef FEAT_MBYTE
2609 if (p != NULL)
2610 {
2611 if (SetFileAttributesW(p, perm) == 0
2612 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2613 {
2614 /* Retry with non-wide function (for Windows 98). */
2615 vim_free(p);
2616 p = NULL;
2617 }
2618 }
2619 if (p == NULL)
2620#endif
2621 SetFileAttributes((char *)name, perm);
2622 }
2623#ifdef FEAT_MBYTE
2624 vim_free(p);
2625#endif
2626}
2627
2628/*
2629 * return TRUE if "name" is a directory
2630 * return FALSE if "name" is not a directory or upon error
2631 */
2632 int
2633mch_isdir(char_u *name)
2634{
2635 int f = mch_getperm(name);
2636
2637 if (f == -1)
2638 return FALSE; /* file does not exist at all */
2639
2640 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2641}
2642
2643/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002644 * Return TRUE if file "fname" has more than one link.
2645 */
2646 int
2647mch_is_linked(char_u *fname)
2648{
2649 HANDLE hFile;
2650 int res = 0;
2651 BY_HANDLE_FILE_INFORMATION inf;
2652#ifdef FEAT_MBYTE
2653 WCHAR *wn = NULL;
2654
2655 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002656 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar03f48552006-02-28 23:52:23 +00002657 if (wn != NULL)
2658 {
2659 hFile = CreateFileW(wn, /* file name */
2660 GENERIC_READ, /* access mode */
2661 0, /* share mode */
2662 NULL, /* security descriptor */
2663 OPEN_EXISTING, /* creation disposition */
2664 0, /* file attributes */
2665 NULL); /* handle to template file */
2666 if (hFile == INVALID_HANDLE_VALUE
2667 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2668 {
2669 /* Retry with non-wide function (for Windows 98). */
2670 vim_free(wn);
2671 wn = NULL;
2672 }
2673 }
2674 if (wn == NULL)
2675#endif
2676 hFile = CreateFile(fname, /* file name */
2677 GENERIC_READ, /* access mode */
2678 0, /* share mode */
2679 NULL, /* security descriptor */
2680 OPEN_EXISTING, /* creation disposition */
2681 0, /* file attributes */
2682 NULL); /* handle to template file */
2683
2684 if (hFile != INVALID_HANDLE_VALUE)
2685 {
2686 if (GetFileInformationByHandle(hFile, &inf) != 0
2687 && inf.nNumberOfLinks > 1)
2688 res = 1;
2689 CloseHandle(hFile);
2690 }
2691
2692#ifdef FEAT_MBYTE
2693 vim_free(wn);
2694#endif
2695 return res;
2696}
2697
2698/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002699 * Return TRUE if file or directory "name" is writable (not readonly).
2700 * Strange semantics of Win32: a readonly directory is writable, but you can't
2701 * delete a file. Let's say this means it is writable.
2702 */
2703 int
2704mch_writable(char_u *name)
2705{
2706 int perm = mch_getperm(name);
2707
2708 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2709 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2710}
2711
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712/*
2713 * Return 1 if "name" can be executed, 0 if not.
2714 * Return -1 if unknown.
2715 */
2716 int
2717mch_can_exe(char_u *name)
2718{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002719 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002720 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002721 char_u *p;
2722
2723 if (len >= _MAX_PATH) /* safety check */
2724 return FALSE;
2725
2726 /* If there already is an extension try using the name directly. Also do
2727 * this with a Unix-shell like 'shell'. */
2728 if (vim_strchr(gettail(name), '.') != NULL
2729 || strstr((char *)gettail(p_sh), "sh") != NULL)
2730 if (executable_exists((char *)name))
2731 return TRUE;
2732
2733 /*
2734 * Loop over all extensions in $PATHEXT.
2735 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002736 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002737 p = mch_getenv("PATHEXT");
2738 if (p == NULL)
2739 p = (char_u *)".com;.exe;.bat;.cmd";
2740 while (*p)
2741 {
2742 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2743 {
2744 /* A single "." means no extension is added. */
2745 buf[len] = NUL;
2746 ++p;
2747 if (*p)
2748 ++p;
2749 }
2750 else
2751 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2752 if (executable_exists((char *)buf))
2753 return TRUE;
2754 }
2755 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002756}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757
2758/*
2759 * Check what "name" is:
2760 * NODE_NORMAL: file or directory (or doesn't exist)
2761 * NODE_WRITABLE: writable device, socket, fifo, etc.
2762 * NODE_OTHER: non-writable things
2763 */
2764 int
2765mch_nodetype(char_u *name)
2766{
2767 HANDLE hFile;
2768 int type;
2769
Bram Moolenaar043545e2006-10-10 16:44:07 +00002770 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2771 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2772 * here. */
2773 if (STRNCMP(name, "\\\\.\\", 4) == 0)
2774 return NODE_WRITABLE;
2775
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776 hFile = CreateFile(name, /* file name */
2777 GENERIC_WRITE, /* access mode */
2778 0, /* share mode */
2779 NULL, /* security descriptor */
2780 OPEN_EXISTING, /* creation disposition */
2781 0, /* file attributes */
2782 NULL); /* handle to template file */
2783
2784 if (hFile == INVALID_HANDLE_VALUE)
2785 return NODE_NORMAL;
2786
2787 type = GetFileType(hFile);
2788 CloseHandle(hFile);
2789 if (type == FILE_TYPE_CHAR)
2790 return NODE_WRITABLE;
2791 if (type == FILE_TYPE_DISK)
2792 return NODE_NORMAL;
2793 return NODE_OTHER;
2794}
2795
2796#ifdef HAVE_ACL
2797struct my_acl
2798{
2799 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2800 PSID pSidOwner;
2801 PSID pSidGroup;
2802 PACL pDacl;
2803 PACL pSacl;
2804};
2805#endif
2806
2807/*
2808 * Return a pointer to the ACL of file "fname" in allocated memory.
2809 * Return NULL if the ACL is not available for whatever reason.
2810 */
2811 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002812mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002813{
2814#ifndef HAVE_ACL
2815 return (vim_acl_T)NULL;
2816#else
2817 struct my_acl *p = NULL;
2818
2819 /* This only works on Windows NT and 2000. */
2820 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2821 {
2822 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2823 if (p != NULL)
2824 {
2825 if (pGetNamedSecurityInfo(
2826 (LPTSTR)fname, // Abstract filename
2827 SE_FILE_OBJECT, // File Object
2828 // Retrieve the entire security descriptor.
2829 OWNER_SECURITY_INFORMATION |
2830 GROUP_SECURITY_INFORMATION |
2831 DACL_SECURITY_INFORMATION |
2832 SACL_SECURITY_INFORMATION,
2833 &p->pSidOwner, // Ownership information.
2834 &p->pSidGroup, // Group membership.
2835 &p->pDacl, // Discretionary information.
2836 &p->pSacl, // For auditing purposes.
2837 &p->pSecurityDescriptor
2838 ) != ERROR_SUCCESS)
2839 {
2840 mch_free_acl((vim_acl_T)p);
2841 p = NULL;
2842 }
2843 }
2844 }
2845
2846 return (vim_acl_T)p;
2847#endif
2848}
2849
2850/*
2851 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2852 * Errors are ignored.
2853 * This must only be called with "acl" equal to what mch_get_acl() returned.
2854 */
2855 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002856mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857{
2858#ifdef HAVE_ACL
2859 struct my_acl *p = (struct my_acl *)acl;
2860
2861 if (p != NULL && advapi_lib != NULL)
2862 (void)pSetNamedSecurityInfo(
2863 (LPTSTR)fname, // Abstract filename
2864 SE_FILE_OBJECT, // File Object
2865 // Retrieve the entire security descriptor.
2866 OWNER_SECURITY_INFORMATION |
2867 GROUP_SECURITY_INFORMATION |
2868 DACL_SECURITY_INFORMATION |
2869 SACL_SECURITY_INFORMATION,
2870 p->pSidOwner, // Ownership information.
2871 p->pSidGroup, // Group membership.
2872 p->pDacl, // Discretionary information.
2873 p->pSacl // For auditing purposes.
2874 );
2875#endif
2876}
2877
2878 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002879mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880{
2881#ifdef HAVE_ACL
2882 struct my_acl *p = (struct my_acl *)acl;
2883
2884 if (p != NULL)
2885 {
2886 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2887 vim_free(p);
2888 }
2889#endif
2890}
2891
2892#ifndef FEAT_GUI_W32
2893
2894/*
2895 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2896 */
2897 static BOOL WINAPI
2898handler_routine(
2899 DWORD dwCtrlType)
2900{
2901 switch (dwCtrlType)
2902 {
2903 case CTRL_C_EVENT:
2904 if (ctrl_c_interrupts)
2905 g_fCtrlCPressed = TRUE;
2906 return TRUE;
2907
2908 case CTRL_BREAK_EVENT:
2909 g_fCBrkPressed = TRUE;
2910 return TRUE;
2911
2912 /* fatal events: shut down gracefully */
2913 case CTRL_CLOSE_EVENT:
2914 case CTRL_LOGOFF_EVENT:
2915 case CTRL_SHUTDOWN_EVENT:
2916 windgoto((int)Rows - 1, 0);
2917 g_fForceExit = TRUE;
2918
Bram Moolenaar0fde2902008-03-16 13:54:13 +00002919 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920 (dwCtrlType == CTRL_CLOSE_EVENT
2921 ? _("close")
2922 : dwCtrlType == CTRL_LOGOFF_EVENT
2923 ? _("logoff")
2924 : _("shutdown")));
2925#ifdef DEBUG
2926 OutputDebugString(IObuff);
2927#endif
2928
2929 preserve_exit(); /* output IObuff, preserve files and exit */
2930
2931 return TRUE; /* not reached */
2932
2933 default:
2934 return FALSE;
2935 }
2936}
2937
2938
2939/*
2940 * set the tty in (raw) ? "raw" : "cooked" mode
2941 */
2942 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002943mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944{
2945 DWORD cmodein;
2946 DWORD cmodeout;
2947 BOOL bEnableHandler;
2948
2949 GetConsoleMode(g_hConIn, &cmodein);
2950 GetConsoleMode(g_hConOut, &cmodeout);
2951 if (tmode == TMODE_RAW)
2952 {
2953 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2954 ENABLE_ECHO_INPUT);
2955#ifdef FEAT_MOUSE
2956 if (g_fMouseActive)
2957 cmodein |= ENABLE_MOUSE_INPUT;
2958#endif
2959 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2960 bEnableHandler = TRUE;
2961 }
2962 else /* cooked */
2963 {
2964 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2965 ENABLE_ECHO_INPUT);
2966 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2967 bEnableHandler = FALSE;
2968 }
2969 SetConsoleMode(g_hConIn, cmodein);
2970 SetConsoleMode(g_hConOut, cmodeout);
2971 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
2972
2973#ifdef MCH_WRITE_DUMP
2974 if (fdDump)
2975 {
2976 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
2977 tmode == TMODE_RAW ? "raw" :
2978 tmode == TMODE_COOK ? "cooked" : "normal",
2979 cmodein, cmodeout);
2980 fflush(fdDump);
2981 }
2982#endif
2983}
2984
2985
2986/*
2987 * Get the size of the current window in `Rows' and `Columns'
2988 * Return OK when size could be determined, FAIL otherwise.
2989 */
2990 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002991mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992{
2993 CONSOLE_SCREEN_BUFFER_INFO csbi;
2994
2995 if (!g_fTermcapMode && g_cbTermcap.IsValid)
2996 {
2997 /*
2998 * For some reason, we are trying to get the screen dimensions
2999 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3000 * variables are really intended to mean the size of Vim screen
3001 * while in termcap mode.
3002 */
3003 Rows = g_cbTermcap.Info.dwSize.Y;
3004 Columns = g_cbTermcap.Info.dwSize.X;
3005 }
3006 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3007 {
3008 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3009 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3010 }
3011 else
3012 {
3013 Rows = 25;
3014 Columns = 80;
3015 }
3016 return OK;
3017}
3018
3019/*
3020 * Set a console window to `xSize' * `ySize'
3021 */
3022 static void
3023ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003024 HANDLE hConsole,
3025 int xSize,
3026 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027{
3028 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3029 SMALL_RECT srWindowRect; /* hold the new console size */
3030 COORD coordScreen;
3031
3032#ifdef MCH_WRITE_DUMP
3033 if (fdDump)
3034 {
3035 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3036 fflush(fdDump);
3037 }
3038#endif
3039
3040 /* get the largest size we can size the console window to */
3041 coordScreen = GetLargestConsoleWindowSize(hConsole);
3042
3043 /* define the new console window size and scroll position */
3044 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3045 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3046 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3047
3048 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3049 {
3050 int sx, sy;
3051
3052 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3053 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3054 if (sy < ySize || sx < xSize)
3055 {
3056 /*
3057 * Increasing number of lines/columns, do buffer first.
3058 * Use the maximal size in x and y direction.
3059 */
3060 if (sy < ySize)
3061 coordScreen.Y = ySize;
3062 else
3063 coordScreen.Y = sy;
3064 if (sx < xSize)
3065 coordScreen.X = xSize;
3066 else
3067 coordScreen.X = sx;
3068 SetConsoleScreenBufferSize(hConsole, coordScreen);
3069 }
3070 }
3071
3072 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3073 {
3074#ifdef MCH_WRITE_DUMP
3075 if (fdDump)
3076 {
3077 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3078 GetLastError());
3079 fflush(fdDump);
3080 }
3081#endif
3082 }
3083
3084 /* define the new console buffer size */
3085 coordScreen.X = xSize;
3086 coordScreen.Y = ySize;
3087
3088 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3089 {
3090#ifdef MCH_WRITE_DUMP
3091 if (fdDump)
3092 {
3093 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3094 GetLastError());
3095 fflush(fdDump);
3096 }
3097#endif
3098 }
3099}
3100
3101
3102/*
3103 * Set the console window to `Rows' * `Columns'
3104 */
3105 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003106mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107{
3108 COORD coordScreen;
3109
3110 /* Don't change window size while still starting up */
3111 if (suppress_winsize != 0)
3112 {
3113 suppress_winsize = 2;
3114 return;
3115 }
3116
3117 if (term_console)
3118 {
3119 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3120
3121 /* Clamp Rows and Columns to reasonable values */
3122 if (Rows > coordScreen.Y)
3123 Rows = coordScreen.Y;
3124 if (Columns > coordScreen.X)
3125 Columns = coordScreen.X;
3126
3127 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3128 }
3129}
3130
3131/*
3132 * Rows and/or Columns has changed.
3133 */
3134 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003135mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136{
3137 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3138}
3139
3140
3141/*
3142 * Called when started up, to set the winsize that was delayed.
3143 */
3144 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003145mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146{
3147 if (suppress_winsize == 2)
3148 {
3149 suppress_winsize = 0;
3150 mch_set_shellsize();
3151 shell_resized();
3152 }
3153 suppress_winsize = 0;
3154}
3155#endif /* FEAT_GUI_W32 */
3156
3157
3158
3159#if defined(FEAT_GUI_W32) || defined(PROTO)
3160
3161/*
3162 * Specialised version of system() for Win32 GUI mode.
3163 * This version proceeds as follows:
3164 * 1. Create a console window for use by the subprocess
3165 * 2. Run the subprocess (it gets the allocated console by default)
3166 * 3. Wait for the subprocess to terminate and get its exit code
3167 * 4. Prompt the user to press a key to close the console window
3168 */
3169 static int
3170mch_system(char *cmd, int options)
3171{
3172 STARTUPINFO si;
3173 PROCESS_INFORMATION pi;
3174 DWORD ret = 0;
3175 HWND hwnd = GetFocus();
3176
3177 si.cb = sizeof(si);
3178 si.lpReserved = NULL;
3179 si.lpDesktop = NULL;
3180 si.lpTitle = NULL;
3181 si.dwFlags = STARTF_USESHOWWINDOW;
3182 /*
3183 * It's nicer to run a filter command in a minimized window, but in
3184 * Windows 95 this makes the command MUCH slower. We can't do it under
3185 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003186 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187 */
3188 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003189 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190 else
3191 si.wShowWindow = SW_SHOWNORMAL;
3192 si.cbReserved2 = 0;
3193 si.lpReserved2 = NULL;
3194
3195 /* There is a strange error on Windows 95 when using "c:\\command.com".
3196 * When the "c:\\" is left out it works OK...? */
3197 if (mch_windows95()
3198 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3199 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3200 cmd += 3;
3201
3202 /* Now, run the command */
3203 CreateProcess(NULL, /* Executable name */
3204 cmd, /* Command to execute */
3205 NULL, /* Process security attributes */
3206 NULL, /* Thread security attributes */
3207 FALSE, /* Inherit handles */
3208 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3209 CREATE_NEW_CONSOLE,
3210 NULL, /* Environment */
3211 NULL, /* Current directory */
3212 &si, /* Startup information */
3213 &pi); /* Process information */
3214
3215
3216 /* Wait for the command to terminate before continuing */
3217 if (g_PlatformId != VER_PLATFORM_WIN32s)
3218 {
3219#ifdef FEAT_GUI
3220 int delay = 1;
3221
3222 /* Keep updating the window while waiting for the shell to finish. */
3223 for (;;)
3224 {
3225 MSG msg;
3226
3227 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3228 {
3229 TranslateMessage(&msg);
3230 DispatchMessage(&msg);
3231 }
3232 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3233 break;
3234
3235 /* We start waiting for a very short time and then increase it, so
3236 * that we respond quickly when the process is quick, and don't
3237 * consume too much overhead when it's slow. */
3238 if (delay < 50)
3239 delay += 10;
3240 }
3241#else
3242 WaitForSingleObject(pi.hProcess, INFINITE);
3243#endif
3244
3245 /* Get the command exit code */
3246 GetExitCodeProcess(pi.hProcess, &ret);
3247 }
3248 else
3249 {
3250 /*
3251 * This ugly code is the only quick way of performing
3252 * a synchronous spawn under Win32s. Yuk.
3253 */
3254 num_windows = 0;
3255 EnumWindows(win32ssynch_cb, 0);
3256 old_num_windows = num_windows;
3257 do
3258 {
3259 Sleep(1000);
3260 num_windows = 0;
3261 EnumWindows(win32ssynch_cb, 0);
3262 } while (num_windows == old_num_windows);
3263 ret = 0;
3264 }
3265
3266 /* Close the handles to the subprocess, so that it goes away */
3267 CloseHandle(pi.hThread);
3268 CloseHandle(pi.hProcess);
3269
3270 /* Try to get input focus back. Doesn't always work though. */
3271 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3272
3273 return ret;
3274}
3275#else
3276
3277# define mch_system(c, o) system(c)
3278
3279#endif
3280
3281/*
3282 * Either execute a command by calling the shell or start a new shell
3283 */
3284 int
3285mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003286 char_u *cmd,
3287 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288{
3289 int x = 0;
3290 int tmode = cur_tmode;
3291#ifdef FEAT_TITLE
3292 char szShellTitle[512];
3293
3294 /* Change the title to reflect that we are in a subshell. */
3295 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3296 {
3297 if (cmd == NULL)
3298 strcat(szShellTitle, " :sh");
3299 else
3300 {
3301 strcat(szShellTitle, " - !");
3302 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3303 strcat(szShellTitle, cmd);
3304 }
3305 mch_settitle(szShellTitle, NULL);
3306 }
3307#endif
3308
3309 out_flush();
3310
3311#ifdef MCH_WRITE_DUMP
3312 if (fdDump)
3313 {
3314 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3315 fflush(fdDump);
3316 }
3317#endif
3318
3319 /*
3320 * Catch all deadly signals while running the external command, because a
3321 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3322 */
3323 signal(SIGINT, SIG_IGN);
3324#if defined(__GNUC__) && !defined(__MINGW32__)
3325 signal(SIGKILL, SIG_IGN);
3326#else
3327 signal(SIGBREAK, SIG_IGN);
3328#endif
3329 signal(SIGILL, SIG_IGN);
3330 signal(SIGFPE, SIG_IGN);
3331 signal(SIGSEGV, SIG_IGN);
3332 signal(SIGTERM, SIG_IGN);
3333 signal(SIGABRT, SIG_IGN);
3334
3335 if (options & SHELL_COOKED)
3336 settmode(TMODE_COOK); /* set to normal mode */
3337
3338 if (cmd == NULL)
3339 {
3340 x = mch_system(p_sh, options);
3341 }
3342 else
3343 {
3344 /* we use "command" or "cmd" to start the shell; slow but easy */
3345 char_u *newcmd;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003346 long_u cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00003347#ifdef FEAT_GUI_W32
3348 STRLEN(vimrun_path) +
3349#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003350 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
3351
3352 newcmd = lalloc(cmdlen, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353 if (newcmd != NULL)
3354 {
3355 char_u *cmdbase = (*cmd == '"' ? cmd + 1 : cmd);
3356
3357 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3358 {
3359 STARTUPINFO si;
3360 PROCESS_INFORMATION pi;
3361
3362 si.cb = sizeof(si);
3363 si.lpReserved = NULL;
3364 si.lpDesktop = NULL;
3365 si.lpTitle = NULL;
3366 si.dwFlags = 0;
3367 si.cbReserved2 = 0;
3368 si.lpReserved2 = NULL;
3369
3370 cmdbase = skipwhite(cmdbase + 5);
3371 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3372 && vim_iswhite(cmdbase[4]))
3373 {
3374 cmdbase = skipwhite(cmdbase + 4);
3375 si.dwFlags = STARTF_USESHOWWINDOW;
3376 si.wShowWindow = SW_SHOWMINNOACTIVE;
3377 }
3378
3379 /* When the command is in double quotes, but 'shellxquote' is
3380 * empty, keep the double quotes around the command.
3381 * Otherwise remove the double quotes, they aren't needed
3382 * here, because we don't use a shell to run the command. */
3383 if (*cmd == '"' && *p_sxq == NUL)
3384 {
3385 newcmd[0] = '"';
3386 STRCPY(newcmd + 1, cmdbase);
3387 }
3388 else
3389 {
3390 STRCPY(newcmd, cmdbase);
3391 if (*cmd == '"' && *newcmd != NUL)
3392 newcmd[STRLEN(newcmd) - 1] = NUL;
3393 }
3394
3395 /*
3396 * Now, start the command as a process, so that it doesn't
3397 * inherit our handles which causes unpleasant dangling swap
3398 * files if we exit before the spawned process
3399 */
3400 if (CreateProcess (NULL, // Executable name
3401 newcmd, // Command to execute
3402 NULL, // Process security attributes
3403 NULL, // Thread security attributes
3404 FALSE, // Inherit handles
3405 CREATE_NEW_CONSOLE, // Creation flags
3406 NULL, // Environment
3407 NULL, // Current directory
3408 &si, // Startup information
3409 &pi)) // Process information
3410 x = 0;
3411 else
3412 {
3413 x = -1;
3414#ifdef FEAT_GUI_W32
3415 EMSG(_("E371: Command not found"));
3416#endif
3417 }
3418 /* Close the handles to the subprocess, so that it goes away */
3419 CloseHandle(pi.hThread);
3420 CloseHandle(pi.hProcess);
3421 }
3422 else
3423 {
3424#if defined(FEAT_GUI_W32)
3425 if (need_vimrun_warning)
3426 {
3427 MessageBox(NULL,
3428 _("VIMRUN.EXE not found in your $PATH.\n"
3429 "External commands will not pause after completion.\n"
3430 "See :help win32-vimrun for more information."),
3431 _("Vim Warning"),
3432 MB_ICONWARNING);
3433 need_vimrun_warning = FALSE;
3434 }
3435 if (!s_dont_use_vimrun)
3436 /* Use vimrun to execute the command. It opens a console
3437 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02003438 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 vimrun_path,
3440 (msg_silent != 0 || (options & SHELL_DOOUT))
3441 ? "-s " : "",
3442 p_sh, p_shcf, cmd);
3443 else
3444#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02003445 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003446 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447 x = mch_system((char *)newcmd, options);
3448 }
3449 vim_free(newcmd);
3450 }
3451 }
3452
3453 if (tmode == TMODE_RAW)
3454 settmode(TMODE_RAW); /* set to raw mode */
3455
3456 /* Print the return value, unless "vimrun" was used. */
3457 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
3458#if defined(FEAT_GUI_W32)
3459 && ((options & SHELL_DOOUT) || s_dont_use_vimrun)
3460#endif
3461 )
3462 {
3463 smsg(_("shell returned %d"), x);
3464 msg_putchar('\n');
3465 }
3466#ifdef FEAT_TITLE
3467 resettitle();
3468#endif
3469
3470 signal(SIGINT, SIG_DFL);
3471#if defined(__GNUC__) && !defined(__MINGW32__)
3472 signal(SIGKILL, SIG_DFL);
3473#else
3474 signal(SIGBREAK, SIG_DFL);
3475#endif
3476 signal(SIGILL, SIG_DFL);
3477 signal(SIGFPE, SIG_DFL);
3478 signal(SIGSEGV, SIG_DFL);
3479 signal(SIGTERM, SIG_DFL);
3480 signal(SIGABRT, SIG_DFL);
3481
3482 return x;
3483}
3484
3485
3486#ifndef FEAT_GUI_W32
3487
3488/*
3489 * Start termcap mode
3490 */
3491 static void
3492termcap_mode_start(void)
3493{
3494 DWORD cmodein;
3495
3496 if (g_fTermcapMode)
3497 return;
3498
3499 SaveConsoleBuffer(&g_cbNonTermcap);
3500
3501 if (g_cbTermcap.IsValid)
3502 {
3503 /*
3504 * We've been in termcap mode before. Restore certain screen
3505 * characteristics, including the buffer size and the window
3506 * size. Since we will be redrawing the screen, we don't need
3507 * to restore the actual contents of the buffer.
3508 */
3509 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
3510 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
3511 Rows = g_cbTermcap.Info.dwSize.Y;
3512 Columns = g_cbTermcap.Info.dwSize.X;
3513 }
3514 else
3515 {
3516 /*
3517 * This is our first time entering termcap mode. Clear the console
3518 * screen buffer, and resize the buffer to match the current window
3519 * size. We will use this as the size of our editing environment.
3520 */
3521 ClearConsoleBuffer(g_attrCurrent);
3522 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3523 }
3524
3525#ifdef FEAT_TITLE
3526 resettitle();
3527#endif
3528
3529 GetConsoleMode(g_hConIn, &cmodein);
3530#ifdef FEAT_MOUSE
3531 if (g_fMouseActive)
3532 cmodein |= ENABLE_MOUSE_INPUT;
3533 else
3534 cmodein &= ~ENABLE_MOUSE_INPUT;
3535#endif
3536 cmodein |= ENABLE_WINDOW_INPUT;
3537 SetConsoleMode(g_hConIn, cmodein);
3538
3539 redraw_later_clear();
3540 g_fTermcapMode = TRUE;
3541}
3542
3543
3544/*
3545 * End termcap mode
3546 */
3547 static void
3548termcap_mode_end(void)
3549{
3550 DWORD cmodein;
3551 ConsoleBuffer *cb;
3552 COORD coord;
3553 DWORD dwDummy;
3554
3555 if (!g_fTermcapMode)
3556 return;
3557
3558 SaveConsoleBuffer(&g_cbTermcap);
3559
3560 GetConsoleMode(g_hConIn, &cmodein);
3561 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
3562 SetConsoleMode(g_hConIn, cmodein);
3563
3564#ifdef FEAT_RESTORE_ORIG_SCREEN
3565 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
3566#else
3567 cb = &g_cbNonTermcap;
3568#endif
3569 RestoreConsoleBuffer(cb, p_rs);
3570 SetConsoleCursorInfo(g_hConOut, &g_cci);
3571
3572 if (p_rs || exiting)
3573 {
3574 /*
3575 * Clear anything that happens to be on the current line.
3576 */
3577 coord.X = 0;
3578 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
3579 FillConsoleOutputCharacter(g_hConOut, ' ',
3580 cb->Info.dwSize.X, coord, &dwDummy);
3581 /*
3582 * The following is just for aesthetics. If we are exiting without
3583 * restoring the screen, then we want to have a prompt string
3584 * appear at the bottom line. However, the command interpreter
3585 * seems to always advance the cursor one line before displaying
3586 * the prompt string, which causes the screen to scroll. To
3587 * counter this, move the cursor up one line before exiting.
3588 */
3589 if (exiting && !p_rs)
3590 coord.Y--;
3591 /*
3592 * Position the cursor at the leftmost column of the desired row.
3593 */
3594 SetConsoleCursorPosition(g_hConOut, coord);
3595 }
3596
3597 g_fTermcapMode = FALSE;
3598}
3599#endif /* FEAT_GUI_W32 */
3600
3601
3602#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003603/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604 void
3605mch_write(
3606 char_u *s,
3607 int len)
3608{
3609 /* never used */
3610}
3611
3612#else
3613
3614/*
3615 * clear `n' chars, starting from `coord'
3616 */
3617 static void
3618clear_chars(
3619 COORD coord,
3620 DWORD n)
3621{
3622 DWORD dwDummy;
3623
3624 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
3625 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
3626}
3627
3628
3629/*
3630 * Clear the screen
3631 */
3632 static void
3633clear_screen(void)
3634{
3635 g_coord.X = g_coord.Y = 0;
3636 clear_chars(g_coord, Rows * Columns);
3637}
3638
3639
3640/*
3641 * Clear to end of display
3642 */
3643 static void
3644clear_to_end_of_display(void)
3645{
3646 clear_chars(g_coord, (Rows - g_coord.Y - 1)
3647 * Columns + (Columns - g_coord.X));
3648}
3649
3650
3651/*
3652 * Clear to end of line
3653 */
3654 static void
3655clear_to_end_of_line(void)
3656{
3657 clear_chars(g_coord, Columns - g_coord.X);
3658}
3659
3660
3661/*
3662 * Scroll the scroll region up by `cLines' lines
3663 */
3664 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003665scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003666{
3667 COORD oldcoord = g_coord;
3668
3669 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
3670 delete_lines(cLines);
3671
3672 g_coord = oldcoord;
3673}
3674
3675
3676/*
3677 * Set the scroll region
3678 */
3679 static void
3680set_scroll_region(
3681 unsigned left,
3682 unsigned top,
3683 unsigned right,
3684 unsigned bottom)
3685{
3686 if (left >= right
3687 || top >= bottom
3688 || right > (unsigned) Columns - 1
3689 || bottom > (unsigned) Rows - 1)
3690 return;
3691
3692 g_srScrollRegion.Left = left;
3693 g_srScrollRegion.Top = top;
3694 g_srScrollRegion.Right = right;
3695 g_srScrollRegion.Bottom = bottom;
3696}
3697
3698
3699/*
3700 * Insert `cLines' lines at the current cursor position
3701 */
3702 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003703insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704{
3705 SMALL_RECT source;
3706 COORD dest;
3707 CHAR_INFO fill;
3708
3709 dest.X = 0;
3710 dest.Y = g_coord.Y + cLines;
3711
3712 source.Left = 0;
3713 source.Top = g_coord.Y;
3714 source.Right = g_srScrollRegion.Right;
3715 source.Bottom = g_srScrollRegion.Bottom - cLines;
3716
3717 fill.Char.AsciiChar = ' ';
3718 fill.Attributes = g_attrCurrent;
3719
3720 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3721
3722 /* Here we have to deal with a win32 console flake: If the scroll
3723 * region looks like abc and we scroll c to a and fill with d we get
3724 * cbd... if we scroll block c one line at a time to a, we get cdd...
3725 * vim expects cdd consistently... So we have to deal with that
3726 * here... (this also occurs scrolling the same way in the other
3727 * direction). */
3728
3729 if (source.Bottom < dest.Y)
3730 {
3731 COORD coord;
3732
3733 coord.X = 0;
3734 coord.Y = source.Bottom;
3735 clear_chars(coord, Columns * (dest.Y - source.Bottom));
3736 }
3737}
3738
3739
3740/*
3741 * Delete `cLines' lines at the current cursor position
3742 */
3743 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003744delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745{
3746 SMALL_RECT source;
3747 COORD dest;
3748 CHAR_INFO fill;
3749 int nb;
3750
3751 dest.X = 0;
3752 dest.Y = g_coord.Y;
3753
3754 source.Left = 0;
3755 source.Top = g_coord.Y + cLines;
3756 source.Right = g_srScrollRegion.Right;
3757 source.Bottom = g_srScrollRegion.Bottom;
3758
3759 fill.Char.AsciiChar = ' ';
3760 fill.Attributes = g_attrCurrent;
3761
3762 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3763
3764 /* Here we have to deal with a win32 console flake: If the scroll
3765 * region looks like abc and we scroll c to a and fill with d we get
3766 * cbd... if we scroll block c one line at a time to a, we get cdd...
3767 * vim expects cdd consistently... So we have to deal with that
3768 * here... (this also occurs scrolling the same way in the other
3769 * direction). */
3770
3771 nb = dest.Y + (source.Bottom - source.Top) + 1;
3772
3773 if (nb < source.Top)
3774 {
3775 COORD coord;
3776
3777 coord.X = 0;
3778 coord.Y = nb;
3779 clear_chars(coord, Columns * (source.Top - nb));
3780 }
3781}
3782
3783
3784/*
3785 * Set the cursor position
3786 */
3787 static void
3788gotoxy(
3789 unsigned x,
3790 unsigned y)
3791{
3792 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
3793 return;
3794
3795 /* external cursor coords are 1-based; internal are 0-based */
3796 g_coord.X = x - 1;
3797 g_coord.Y = y - 1;
3798 SetConsoleCursorPosition(g_hConOut, g_coord);
3799}
3800
3801
3802/*
3803 * Set the current text attribute = (foreground | background)
3804 * See ../doc/os_win32.txt for the numbers.
3805 */
3806 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003807textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808{
3809 g_attrCurrent = wAttr;
3810
3811 SetConsoleTextAttribute(g_hConOut, wAttr);
3812}
3813
3814
3815 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003816textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817{
3818 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
3819
3820 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3821}
3822
3823
3824 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003825textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826{
3827 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
3828
3829 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3830}
3831
3832
3833/*
3834 * restore the default text attribute (whatever we started with)
3835 */
3836 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003837normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838{
3839 textattr(g_attrDefault);
3840}
3841
3842
3843static WORD g_attrPreStandout = 0;
3844
3845/*
3846 * Make the text standout, by brightening it
3847 */
3848 static void
3849standout(void)
3850{
3851 g_attrPreStandout = g_attrCurrent;
3852 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
3853}
3854
3855
3856/*
3857 * Turn off standout mode
3858 */
3859 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003860standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861{
3862 if (g_attrPreStandout)
3863 {
3864 textattr(g_attrPreStandout);
3865 g_attrPreStandout = 0;
3866 }
3867}
3868
3869
3870/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00003871 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003872 */
3873 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003874mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003875{
3876 char_u *p;
3877 int n;
3878
3879 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
3880 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
3881 if (T_ME[0] == ESC && T_ME[1] == '|')
3882 {
3883 p = T_ME + 2;
3884 n = getdigits(&p);
3885 if (*p == 'm' && n > 0)
3886 {
3887 cterm_normal_fg_color = (n & 0xf) + 1;
3888 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
3889 }
3890 }
3891}
3892
3893
3894/*
3895 * visual bell: flash the screen
3896 */
3897 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003898visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003899{
3900 COORD coordOrigin = {0, 0};
3901 WORD attrFlash = ~g_attrCurrent & 0xff;
3902
3903 DWORD dwDummy;
3904 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
3905
3906 if (oldattrs == NULL)
3907 return;
3908 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3909 coordOrigin, &dwDummy);
3910 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
3911 coordOrigin, &dwDummy);
3912
3913 Sleep(15); /* wait for 15 msec */
3914 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3915 coordOrigin, &dwDummy);
3916 vim_free(oldattrs);
3917}
3918
3919
3920/*
3921 * Make the cursor visible or invisible
3922 */
3923 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003924cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925{
3926 s_cursor_visible = fVisible;
3927#ifdef MCH_CURSOR_SHAPE
3928 mch_update_cursor();
3929#endif
3930}
3931
3932
3933/*
3934 * write `cchToWrite' characters in `pchBuf' to the screen
3935 * Returns the number of characters actually written (at least one).
3936 */
3937 static BOOL
3938write_chars(
3939 LPCSTR pchBuf,
3940 DWORD cchToWrite)
3941{
3942 COORD coord = g_coord;
3943 DWORD written;
3944
3945 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
3946 coord, &written);
3947 /* When writing fails or didn't write a single character, pretend one
3948 * character was written, otherwise we get stuck. */
3949 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
3950 coord, &written) == 0
3951 || written == 0)
3952 written = 1;
3953
3954 g_coord.X += (SHORT) written;
3955
3956 while (g_coord.X > g_srScrollRegion.Right)
3957 {
3958 g_coord.X -= (SHORT) Columns;
3959 if (g_coord.Y < g_srScrollRegion.Bottom)
3960 g_coord.Y++;
3961 }
3962
3963 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3964
3965 return written;
3966}
3967
3968
3969/*
3970 * mch_write(): write the output buffer to the screen, translating ESC
3971 * sequences into calls to console output routines.
3972 */
3973 void
3974mch_write(
3975 char_u *s,
3976 int len)
3977{
3978 s[len] = NUL;
3979
3980 if (!term_console)
3981 {
3982 write(1, s, (unsigned)len);
3983 return;
3984 }
3985
3986 /* translate ESC | sequences into faked bios calls */
3987 while (len--)
3988 {
3989 /* optimization: use one single write_chars for runs of text,
3990 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003991 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003992
3993 if (p_wd)
3994 {
3995 WaitForChar(p_wd);
3996 if (prefix != 0)
3997 prefix = 1;
3998 }
3999
4000 if (prefix != 0)
4001 {
4002 DWORD nWritten;
4003
4004 nWritten = write_chars(s, prefix);
4005#ifdef MCH_WRITE_DUMP
4006 if (fdDump)
4007 {
4008 fputc('>', fdDump);
4009 fwrite(s, sizeof(char_u), nWritten, fdDump);
4010 fputs("<\n", fdDump);
4011 }
4012#endif
4013 len -= (nWritten - 1);
4014 s += nWritten;
4015 }
4016 else if (s[0] == '\n')
4017 {
4018 /* \n, newline: go to the beginning of the next line or scroll */
4019 if (g_coord.Y == g_srScrollRegion.Bottom)
4020 {
4021 scroll(1);
4022 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
4023 }
4024 else
4025 {
4026 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
4027 }
4028#ifdef MCH_WRITE_DUMP
4029 if (fdDump)
4030 fputs("\\n\n", fdDump);
4031#endif
4032 s++;
4033 }
4034 else if (s[0] == '\r')
4035 {
4036 /* \r, carriage return: go to beginning of line */
4037 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
4038#ifdef MCH_WRITE_DUMP
4039 if (fdDump)
4040 fputs("\\r\n", fdDump);
4041#endif
4042 s++;
4043 }
4044 else if (s[0] == '\b')
4045 {
4046 /* \b, backspace: move cursor one position left */
4047 if (g_coord.X > g_srScrollRegion.Left)
4048 g_coord.X--;
4049 else if (g_coord.Y > g_srScrollRegion.Top)
4050 {
4051 g_coord.X = g_srScrollRegion.Right;
4052 g_coord.Y--;
4053 }
4054 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4055#ifdef MCH_WRITE_DUMP
4056 if (fdDump)
4057 fputs("\\b\n", fdDump);
4058#endif
4059 s++;
4060 }
4061 else if (s[0] == '\a')
4062 {
4063 /* \a, bell */
4064 MessageBeep(0xFFFFFFFF);
4065#ifdef MCH_WRITE_DUMP
4066 if (fdDump)
4067 fputs("\\a\n", fdDump);
4068#endif
4069 s++;
4070 }
4071 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4072 {
4073#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004074 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004075#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004076 char_u *p;
4077 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078
4079 switch (s[2])
4080 {
4081 /* one or two numeric arguments, separated by ';' */
4082
4083 case '0': case '1': case '2': case '3': case '4':
4084 case '5': case '6': case '7': case '8': case '9':
4085 p = s + 2;
4086 arg1 = getdigits(&p); /* no check for length! */
4087 if (p > s + len)
4088 break;
4089
4090 if (*p == ';')
4091 {
4092 ++p;
4093 arg2 = getdigits(&p); /* no check for length! */
4094 if (p > s + len)
4095 break;
4096
4097 if (*p == 'H')
4098 gotoxy(arg2, arg1);
4099 else if (*p == 'r')
4100 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4101 }
4102 else if (*p == 'A')
4103 {
4104 /* move cursor up arg1 lines in same column */
4105 gotoxy(g_coord.X + 1,
4106 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4107 }
4108 else if (*p == 'C')
4109 {
4110 /* move cursor right arg1 columns in same line */
4111 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4112 g_coord.Y + 1);
4113 }
4114 else if (*p == 'H')
4115 {
4116 gotoxy(1, arg1);
4117 }
4118 else if (*p == 'L')
4119 {
4120 insert_lines(arg1);
4121 }
4122 else if (*p == 'm')
4123 {
4124 if (arg1 == 0)
4125 normvideo();
4126 else
4127 textattr((WORD) arg1);
4128 }
4129 else if (*p == 'f')
4130 {
4131 textcolor((WORD) arg1);
4132 }
4133 else if (*p == 'b')
4134 {
4135 textbackground((WORD) arg1);
4136 }
4137 else if (*p == 'M')
4138 {
4139 delete_lines(arg1);
4140 }
4141
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004142 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 s = p + 1;
4144 break;
4145
4146
4147 /* Three-character escape sequences */
4148
4149 case 'A':
4150 /* move cursor up one line in same column */
4151 gotoxy(g_coord.X + 1,
4152 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4153 goto got3;
4154
4155 case 'B':
4156 visual_bell();
4157 goto got3;
4158
4159 case 'C':
4160 /* move cursor right one column in same line */
4161 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4162 g_coord.Y + 1);
4163 goto got3;
4164
4165 case 'E':
4166 termcap_mode_end();
4167 goto got3;
4168
4169 case 'F':
4170 standout();
4171 goto got3;
4172
4173 case 'f':
4174 standend();
4175 goto got3;
4176
4177 case 'H':
4178 gotoxy(1, 1);
4179 goto got3;
4180
4181 case 'j':
4182 clear_to_end_of_display();
4183 goto got3;
4184
4185 case 'J':
4186 clear_screen();
4187 goto got3;
4188
4189 case 'K':
4190 clear_to_end_of_line();
4191 goto got3;
4192
4193 case 'L':
4194 insert_lines(1);
4195 goto got3;
4196
4197 case 'M':
4198 delete_lines(1);
4199 goto got3;
4200
4201 case 'S':
4202 termcap_mode_start();
4203 goto got3;
4204
4205 case 'V':
4206 cursor_visible(TRUE);
4207 goto got3;
4208
4209 case 'v':
4210 cursor_visible(FALSE);
4211 goto got3;
4212
4213 got3:
4214 s += 3;
4215 len -= 2;
4216 }
4217
4218#ifdef MCH_WRITE_DUMP
4219 if (fdDump)
4220 {
4221 fputs("ESC | ", fdDump);
4222 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4223 fputc('\n', fdDump);
4224 }
4225#endif
4226 }
4227 else
4228 {
4229 /* Write a single character */
4230 DWORD nWritten;
4231
4232 nWritten = write_chars(s, 1);
4233#ifdef MCH_WRITE_DUMP
4234 if (fdDump)
4235 {
4236 fputc('>', fdDump);
4237 fwrite(s, sizeof(char_u), nWritten, fdDump);
4238 fputs("<\n", fdDump);
4239 }
4240#endif
4241
4242 len -= (nWritten - 1);
4243 s += nWritten;
4244 }
4245 }
4246
4247#ifdef MCH_WRITE_DUMP
4248 if (fdDump)
4249 fflush(fdDump);
4250#endif
4251}
4252
4253#endif /* FEAT_GUI_W32 */
4254
4255
4256/*
4257 * Delay for half a second.
4258 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004259/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004260 void
4261mch_delay(
4262 long msec,
4263 int ignoreinput)
4264{
4265#ifdef FEAT_GUI_W32
4266 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004267#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004268 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004269# ifdef FEAT_MZSCHEME
4270 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4271 {
4272 int towait = p_mzq;
4273
4274 /* if msec is large enough, wait by portions in p_mzq */
4275 while (msec > 0)
4276 {
4277 mzvim_check_threads();
4278 if (msec < towait)
4279 towait = msec;
4280 Sleep(towait);
4281 msec -= towait;
4282 }
4283 }
4284 else
4285# endif
4286 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287 else
4288 WaitForChar(msec);
4289#endif
4290}
4291
4292
4293/*
4294 * this version of remove is not scared by a readonly (backup) file
4295 * Return 0 for success, -1 for failure.
4296 */
4297 int
4298mch_remove(char_u *name)
4299{
4300#ifdef FEAT_MBYTE
4301 WCHAR *wn = NULL;
4302 int n;
4303
4304 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4305 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004306 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004307 if (wn != NULL)
4308 {
4309 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4310 n = DeleteFileW(wn) ? 0 : -1;
4311 vim_free(wn);
4312 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4313 return n;
4314 /* Retry with non-wide function (for Windows 98). */
4315 }
4316 }
4317#endif
4318 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4319 return DeleteFile(name) ? 0 : -1;
4320}
4321
4322
4323/*
4324 * check for an "interrupt signal": CTRL-break or CTRL-C
4325 */
4326 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004327mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328{
4329#ifndef FEAT_GUI_W32 /* never used */
4330 if (g_fCtrlCPressed || g_fCBrkPressed)
4331 {
4332 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4333 got_int = TRUE;
4334 }
4335#endif
4336}
4337
4338
4339/*
4340 * How much memory is available?
4341 * Return sum of available physical and page file memory.
4342 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004343/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344 long_u
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004345mch_avail_mem(int special)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004346{
4347 MEMORYSTATUS ms;
4348
4349 ms.dwLength = sizeof(MEMORYSTATUS);
4350 GlobalMemoryStatus(&ms);
4351 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
4352}
4353
4354#ifdef FEAT_MBYTE
4355/*
4356 * Same code as below, but with wide functions and no comments.
4357 * Return 0 for success, non-zero for failure.
4358 */
4359 int
4360mch_wrename(WCHAR *wold, WCHAR *wnew)
4361{
4362 WCHAR *p;
4363 int i;
4364 WCHAR szTempFile[_MAX_PATH + 1];
4365 WCHAR szNewPath[_MAX_PATH + 1];
4366 HANDLE hf;
4367
4368 if (!mch_windows95())
4369 {
4370 p = wold;
4371 for (i = 0; wold[i] != NUL; ++i)
4372 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
4373 && wold[i + 1] != 0)
4374 p = wold + i + 1;
4375 if ((int)(wold + i - p) < 8 || p[6] != '~')
4376 return (MoveFileW(wold, wnew) == 0);
4377 }
4378
4379 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
4380 return -1;
4381 *p = NUL;
4382
4383 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
4384 return -2;
4385
4386 if (!DeleteFileW(szTempFile))
4387 return -3;
4388
4389 if (!MoveFileW(wold, szTempFile))
4390 return -4;
4391
4392 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4393 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4394 return -5;
4395 if (!CloseHandle(hf))
4396 return -6;
4397
4398 if (!MoveFileW(szTempFile, wnew))
4399 {
4400 (void)MoveFileW(szTempFile, wold);
4401 return -7;
4402 }
4403
4404 DeleteFileW(szTempFile);
4405
4406 if (!DeleteFileW(wold))
4407 return -8;
4408
4409 return 0;
4410}
4411#endif
4412
4413
4414/*
4415 * mch_rename() works around a bug in rename (aka MoveFile) in
4416 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4417 * file whose short file name is "FOO.BAR" (its long file name will
4418 * be correct: "foo.bar~"). Because a file can be accessed by
4419 * either its SFN or its LFN, "foo.bar" has effectively been
4420 * renamed to "foo.bar", which is not at all what was wanted. This
4421 * seems to happen only when renaming files with three-character
4422 * extensions by appending a suffix that does not include ".".
4423 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4424 *
4425 * There is another problem, which isn't really a bug but isn't right either:
4426 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
4427 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
4428 * service pack 6. Doesn't seem to happen on Windows 98.
4429 *
4430 * Like rename(), returns 0 upon success, non-zero upon failure.
4431 * Should probably set errno appropriately when errors occur.
4432 */
4433 int
4434mch_rename(
4435 const char *pszOldFile,
4436 const char *pszNewFile)
4437{
4438 char szTempFile[_MAX_PATH+1];
4439 char szNewPath[_MAX_PATH+1];
4440 char *pszFilePart;
4441 HANDLE hf;
4442#ifdef FEAT_MBYTE
4443 WCHAR *wold = NULL;
4444 WCHAR *wnew = NULL;
4445 int retval = -1;
4446
4447 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4448 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004449 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
4450 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004451 if (wold != NULL && wnew != NULL)
4452 retval = mch_wrename(wold, wnew);
4453 vim_free(wold);
4454 vim_free(wnew);
4455 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4456 return retval;
4457 /* Retry with non-wide function (for Windows 98). */
4458 }
4459#endif
4460
4461 /*
4462 * No need to play tricks if not running Windows 95, unless the file name
4463 * contains a "~" as the seventh character.
4464 */
4465 if (!mch_windows95())
4466 {
4467 pszFilePart = (char *)gettail((char_u *)pszOldFile);
4468 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
4469 return rename(pszOldFile, pszNewFile);
4470 }
4471
4472 /* Get base path of new file name. Undocumented feature: If pszNewFile is
4473 * a directory, no error is returned and pszFilePart will be NULL. */
4474 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
4475 || pszFilePart == NULL)
4476 return -1;
4477 *pszFilePart = NUL;
4478
4479 /* Get (and create) a unique temporary file name in directory of new file */
4480 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
4481 return -2;
4482
4483 /* blow the temp file away */
4484 if (!DeleteFile(szTempFile))
4485 return -3;
4486
4487 /* rename old file to the temp file */
4488 if (!MoveFile(pszOldFile, szTempFile))
4489 return -4;
4490
4491 /* now create an empty file called pszOldFile; this prevents the operating
4492 * system using pszOldFile as an alias (SFN) if we're renaming within the
4493 * same directory. For example, we're editing a file called
4494 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
4495 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
4496 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004497 * cause all sorts of problems later in buf_write(). So, we create an
4498 * empty file called filena~1.txt and the system will have to find some
4499 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500 */
4501 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4502 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4503 return -5;
4504 if (!CloseHandle(hf))
4505 return -6;
4506
4507 /* rename the temp file to the new file */
4508 if (!MoveFile(szTempFile, pszNewFile))
4509 {
4510 /* Renaming failed. Rename the file back to its old name, so that it
4511 * looks like nothing happened. */
4512 (void)MoveFile(szTempFile, pszOldFile);
4513
4514 return -7;
4515 }
4516
4517 /* Seems to be left around on Novell filesystems */
4518 DeleteFile(szTempFile);
4519
4520 /* finally, remove the empty old file */
4521 if (!DeleteFile(pszOldFile))
4522 return -8;
4523
4524 return 0; /* success */
4525}
4526
4527/*
4528 * Get the default shell for the current hardware platform
4529 */
4530 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004531default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532{
4533 char* psz = NULL;
4534
4535 PlatformId();
4536
4537 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
4538 psz = "cmd.exe";
4539 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
4540 psz = "command.com";
4541
4542 return psz;
4543}
4544
4545/*
4546 * mch_access() extends access() to do more detailed check on network drives.
4547 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
4548 */
4549 int
4550mch_access(char *n, int p)
4551{
4552 HANDLE hFile;
4553 DWORD am;
4554 int retval = -1; /* default: fail */
4555#ifdef FEAT_MBYTE
4556 WCHAR *wn = NULL;
4557
4558 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004559 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560#endif
4561
4562 if (mch_isdir(n))
4563 {
4564 char TempName[_MAX_PATH + 16] = "";
4565#ifdef FEAT_MBYTE
4566 WCHAR TempNameW[_MAX_PATH + 16] = L"";
4567#endif
4568
4569 if (p & R_OK)
4570 {
4571 /* Read check is performed by seeing if we can do a find file on
4572 * the directory for any file. */
4573#ifdef FEAT_MBYTE
4574 if (wn != NULL)
4575 {
4576 int i;
4577 WIN32_FIND_DATAW d;
4578
4579 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
4580 TempNameW[i] = wn[i];
4581 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
4582 TempNameW[i++] = '\\';
4583 TempNameW[i++] = '*';
4584 TempNameW[i++] = 0;
4585
4586 hFile = FindFirstFileW(TempNameW, &d);
4587 if (hFile == INVALID_HANDLE_VALUE)
4588 {
4589 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4590 goto getout;
4591
4592 /* Retry with non-wide function (for Windows 98). */
4593 vim_free(wn);
4594 wn = NULL;
4595 }
4596 else
4597 (void)FindClose(hFile);
4598 }
4599 if (wn == NULL)
4600#endif
4601 {
4602 char *pch;
4603 WIN32_FIND_DATA d;
4604
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00004605 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004606 pch = TempName + STRLEN(TempName) - 1;
4607 if (*pch != '\\' && *pch != '/')
4608 *++pch = '\\';
4609 *++pch = '*';
4610 *++pch = NUL;
4611
4612 hFile = FindFirstFile(TempName, &d);
4613 if (hFile == INVALID_HANDLE_VALUE)
4614 goto getout;
4615 (void)FindClose(hFile);
4616 }
4617 }
4618
4619 if (p & W_OK)
4620 {
4621 /* Trying to create a temporary file in the directory should catch
4622 * directories on read-only network shares. However, in
4623 * directories whose ACL allows writes but denies deletes will end
4624 * up keeping the temporary file :-(. */
4625#ifdef FEAT_MBYTE
4626 if (wn != NULL)
4627 {
4628 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
4629 {
4630 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4631 goto getout;
4632
4633 /* Retry with non-wide function (for Windows 98). */
4634 vim_free(wn);
4635 wn = NULL;
4636 }
4637 else
4638 DeleteFileW(TempNameW);
4639 }
4640 if (wn == NULL)
4641#endif
4642 {
4643 if (!GetTempFileName(n, "VIM", 0, TempName))
4644 goto getout;
4645 mch_remove((char_u *)TempName);
4646 }
4647 }
4648 }
4649 else
4650 {
4651 /* Trying to open the file for the required access does ACL, read-only
4652 * network share, and file attribute checks. */
4653 am = ((p & W_OK) ? GENERIC_WRITE : 0)
4654 | ((p & R_OK) ? GENERIC_READ : 0);
4655#ifdef FEAT_MBYTE
4656 if (wn != NULL)
4657 {
4658 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4659 if (hFile == INVALID_HANDLE_VALUE
4660 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4661 {
4662 /* Retry with non-wide function (for Windows 98). */
4663 vim_free(wn);
4664 wn = NULL;
4665 }
4666 }
4667 if (wn == NULL)
4668#endif
4669 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4670 if (hFile == INVALID_HANDLE_VALUE)
4671 goto getout;
4672 CloseHandle(hFile);
4673 }
4674
4675 retval = 0; /* success */
4676getout:
4677#ifdef FEAT_MBYTE
4678 vim_free(wn);
4679#endif
4680 return retval;
4681}
4682
4683#if defined(FEAT_MBYTE) || defined(PROTO)
4684/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004685 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004686 */
4687 int
4688mch_open(char *name, int flags, int mode)
4689{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004690 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
4691# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692 WCHAR *wn;
4693 int f;
4694
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004695 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004696 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004697 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004698 if (wn != NULL)
4699 {
4700 f = _wopen(wn, flags, mode);
4701 vim_free(wn);
4702 if (f >= 0)
4703 return f;
4704 /* Retry with non-wide function (for Windows 98). Can't use
4705 * GetLastError() here and it's unclear what errno gets set to if
4706 * the _wopen() fails for missing wide functions. */
4707 }
4708 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004709# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710
4711 return open(name, flags, mode);
4712}
4713
4714/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004715 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 */
4717 FILE *
4718mch_fopen(char *name, char *mode)
4719{
4720 WCHAR *wn, *wm;
4721 FILE *f = NULL;
4722
4723 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
4724# ifdef __BORLANDC__
4725 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4726 && g_PlatformId == VER_PLATFORM_WIN32_NT
4727# endif
4728 )
4729 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00004730# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004731 /* Work around an annoying assertion in the Microsoft debug CRT
4732 * when mode's text/binary setting doesn't match _get_fmode(). */
4733 char newMode = mode[strlen(mode) - 1];
4734 int oldMode = 0;
4735
4736 _get_fmode(&oldMode);
4737 if (newMode == 't')
4738 _set_fmode(_O_TEXT);
4739 else if (newMode == 'b')
4740 _set_fmode(_O_BINARY);
4741# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004742 wn = enc_to_utf16(name, NULL);
4743 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744 if (wn != NULL && wm != NULL)
4745 f = _wfopen(wn, wm);
4746 vim_free(wn);
4747 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004748
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00004749# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004750 _set_fmode(oldMode);
4751# endif
4752
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753 if (f != NULL)
4754 return f;
4755 /* Retry with non-wide function (for Windows 98). Can't use
4756 * GetLastError() here and it's unclear what errno gets set to if
4757 * the _wfopen() fails for missing wide functions. */
4758 }
4759
4760 return fopen(name, mode);
4761}
4762#endif
4763
4764#ifdef FEAT_MBYTE
4765/*
4766 * SUB STREAM (aka info stream) handling:
4767 *
4768 * NTFS can have sub streams for each file. Normal contents of file is
4769 * stored in the main stream, and extra contents (author information and
4770 * title and so on) can be stored in sub stream. After Windows 2000, user
4771 * can access and store those informations in sub streams via explorer's
4772 * property menuitem in right click menu. Those informations in sub streams
4773 * were lost when copying only the main stream. So we have to copy sub
4774 * streams.
4775 *
4776 * Incomplete explanation:
4777 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
4778 * More useful info and an example:
4779 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
4780 */
4781
4782/*
4783 * Copy info stream data "substream". Read from the file with BackupRead(sh)
4784 * and write to stream "substream" of file "to".
4785 * Errors are ignored.
4786 */
4787 static void
4788copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
4789{
4790 HANDLE hTo;
4791 WCHAR *to_name;
4792
4793 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
4794 wcscpy(to_name, to);
4795 wcscat(to_name, substream);
4796
4797 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
4798 FILE_ATTRIBUTE_NORMAL, NULL);
4799 if (hTo != INVALID_HANDLE_VALUE)
4800 {
4801 long done;
4802 DWORD todo;
4803 DWORD readcnt, written;
4804 char buf[4096];
4805
4806 /* Copy block of bytes at a time. Abort when something goes wrong. */
4807 for (done = 0; done < len; done += written)
4808 {
4809 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004810 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
4811 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
4813 FALSE, FALSE, context)
4814 || readcnt != todo
4815 || !WriteFile(hTo, buf, todo, &written, NULL)
4816 || written != todo)
4817 break;
4818 }
4819 CloseHandle(hTo);
4820 }
4821
4822 free(to_name);
4823}
4824
4825/*
4826 * Copy info streams from file "from" to file "to".
4827 */
4828 static void
4829copy_infostreams(char_u *from, char_u *to)
4830{
4831 WCHAR *fromw;
4832 WCHAR *tow;
4833 HANDLE sh;
4834 WIN32_STREAM_ID sid;
4835 int headersize;
4836 WCHAR streamname[_MAX_PATH];
4837 DWORD readcount;
4838 void *context = NULL;
4839 DWORD lo, hi;
4840 int len;
4841
4842 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004843 fromw = enc_to_utf16(from, NULL);
4844 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004845 if (fromw != NULL && tow != NULL)
4846 {
4847 /* Open the file for reading. */
4848 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
4849 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4850 if (sh != INVALID_HANDLE_VALUE)
4851 {
4852 /* Use BackupRead() to find the info streams. Repeat until we
4853 * have done them all.*/
4854 for (;;)
4855 {
4856 /* Get the header to find the length of the stream name. If
4857 * the "readcount" is zero we have done all info streams. */
4858 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004859 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
4861 &readcount, FALSE, FALSE, &context)
4862 || readcount == 0)
4863 break;
4864
4865 /* We only deal with streams that have a name. The normal
4866 * file data appears to be without a name, even though docs
4867 * suggest it is called "::$DATA". */
4868 if (sid.dwStreamNameSize > 0)
4869 {
4870 /* Read the stream name. */
4871 if (!BackupRead(sh, (LPBYTE)streamname,
4872 sid.dwStreamNameSize,
4873 &readcount, FALSE, FALSE, &context))
4874 break;
4875
4876 /* Copy an info stream with a name ":anything:$DATA".
4877 * Skip "::$DATA", it has no stream name (examples suggest
4878 * it might be used for the normal file contents).
4879 * Note that BackupRead() counts bytes, but the name is in
4880 * wide characters. */
4881 len = readcount / sizeof(WCHAR);
4882 streamname[len] = 0;
4883 if (len > 7 && wcsicmp(streamname + len - 6,
4884 L":$DATA") == 0)
4885 {
4886 streamname[len - 6] = 0;
4887 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004888 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 }
4890 }
4891
4892 /* Advance to the next stream. We might try seeking too far,
4893 * but BackupSeek() doesn't skip over stream borders, thus
4894 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004895 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004896 &lo, &hi, &context);
4897 }
4898
4899 /* Clear the context. */
4900 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
4901
4902 CloseHandle(sh);
4903 }
4904 }
4905 vim_free(fromw);
4906 vim_free(tow);
4907}
4908#endif
4909
4910/*
4911 * Copy file attributes from file "from" to file "to".
4912 * For Windows NT and later we copy info streams.
4913 * Always returns zero, errors are ignored.
4914 */
4915 int
4916mch_copy_file_attribute(char_u *from, char_u *to)
4917{
4918#ifdef FEAT_MBYTE
4919 /* File streams only work on Windows NT and later. */
4920 PlatformId();
4921 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
4922 copy_infostreams(from, to);
4923#endif
4924 return 0;
4925}
4926
4927#if defined(MYRESETSTKOFLW) || defined(PROTO)
4928/*
4929 * Recreate a destroyed stack guard page in win32.
4930 * Written by Benjamin Peterson.
4931 */
4932
4933/* These magic numbers are from the MS header files */
4934#define MIN_STACK_WIN9X 17
4935#define MIN_STACK_WINNT 2
4936
4937/*
4938 * This function does the same thing as _resetstkoflw(), which is only
4939 * available in DevStudio .net and later.
4940 * Returns 0 for failure, 1 for success.
4941 */
4942 int
4943myresetstkoflw(void)
4944{
4945 BYTE *pStackPtr;
4946 BYTE *pGuardPage;
4947 BYTE *pStackBase;
4948 BYTE *pLowestPossiblePage;
4949 MEMORY_BASIC_INFORMATION mbi;
4950 SYSTEM_INFO si;
4951 DWORD nPageSize;
4952 DWORD dummy;
4953
4954 /* This code will not work on win32s. */
4955 PlatformId();
4956 if (g_PlatformId == VER_PLATFORM_WIN32s)
4957 return 0;
4958
4959 /* We need to know the system page size. */
4960 GetSystemInfo(&si);
4961 nPageSize = si.dwPageSize;
4962
4963 /* ...and the current stack pointer */
4964 pStackPtr = (BYTE*)_alloca(1);
4965
4966 /* ...and the base of the stack. */
4967 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
4968 return 0;
4969 pStackBase = (BYTE*)mbi.AllocationBase;
4970
4971 /* ...and the page thats min_stack_req pages away from stack base; this is
4972 * the lowest page we could use. */
4973 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
4974 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
4975
4976 /* On Win95, we want the next page down from the end of the stack. */
4977 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
4978 {
4979 /* Find the page that's only 1 page down from the page that the stack
4980 * ptr is in. */
4981 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
4982 / (DWORD)nPageSize) - 1));
4983 if (pGuardPage < pLowestPossiblePage)
4984 return 0;
4985
4986 /* Apply the noaccess attribute to the page -- there's no guard
4987 * attribute in win95-type OSes. */
4988 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
4989 return 0;
4990 }
4991 else
4992 {
4993 /* On NT, however, we want the first committed page in the stack Start
4994 * at the stack base and move forward through memory until we find a
4995 * committed block. */
4996 BYTE *pBlock = pStackBase;
4997
Bram Moolenaara466c992005-07-09 21:03:22 +00004998 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999 {
5000 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
5001 return 0;
5002
5003 pBlock += mbi.RegionSize;
5004
5005 if (mbi.State & MEM_COMMIT)
5006 break;
5007 }
5008
5009 /* mbi now describes the first committed block in the stack. */
5010 if (mbi.Protect & PAGE_GUARD)
5011 return 1;
5012
5013 /* decide where the guard page should start */
5014 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
5015 pGuardPage = pLowestPossiblePage;
5016 else
5017 pGuardPage = (BYTE*)mbi.BaseAddress;
5018
5019 /* allocate the guard page */
5020 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
5021 return 0;
5022
5023 /* apply the guard attribute to the page */
5024 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
5025 &dummy))
5026 return 0;
5027 }
5028
5029 return 1;
5030}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005031#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005033
5034#if defined(FEAT_MBYTE) || defined(PROTO)
5035/*
5036 * The command line arguments in UCS2
5037 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005038static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005039static LPWSTR *ArglistW = NULL;
5040static int global_argc = 0;
5041static char **global_argv;
5042
5043static int used_file_argc = 0; /* last argument in global_argv[] used
5044 for the argument list. */
5045static int *used_file_indexes = NULL; /* indexes in global_argv[] for
5046 command line arguments added to
5047 the argument list */
5048static int used_file_count = 0; /* nr of entries in used_file_indexes */
5049static int used_file_literal = FALSE; /* take file names literally */
5050static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005051static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005052static int used_alist_count = 0;
5053
5054
5055/*
5056 * Get the command line arguments. Unicode version.
5057 * Returns argc. Zero when something fails.
5058 */
5059 int
5060get_cmd_argsW(char ***argvp)
5061{
5062 char **argv = NULL;
5063 int argc = 0;
5064 int i;
5065
5066 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5067 if (ArglistW != NULL)
5068 {
5069 argv = malloc((nArgsW + 1) * sizeof(char *));
5070 if (argv != NULL)
5071 {
5072 argc = nArgsW;
5073 argv[argc] = NULL;
5074 for (i = 0; i < argc; ++i)
5075 {
5076 int len;
5077
5078 /* Convert each Unicode argument to the current codepage. */
5079 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005080 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005081 (LPSTR *)&argv[i], &len, 0, 0);
5082 if (argv[i] == NULL)
5083 {
5084 /* Out of memory, clear everything. */
5085 while (i > 0)
5086 free(argv[--i]);
5087 free(argv);
5088 argc = 0;
5089 }
5090 }
5091 }
5092 }
5093
5094 global_argc = argc;
5095 global_argv = argv;
5096 if (argc > 0)
5097 used_file_indexes = malloc(argc * sizeof(int));
5098
5099 if (argvp != NULL)
5100 *argvp = argv;
5101 return argc;
5102}
5103
5104 void
5105free_cmd_argsW(void)
5106{
5107 if (ArglistW != NULL)
5108 {
5109 GlobalFree(ArglistW);
5110 ArglistW = NULL;
5111 }
5112}
5113
5114/*
5115 * Remember "name" is an argument that was added to the argument list.
5116 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5117 * is called.
5118 */
5119 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005120used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005121{
5122 int i;
5123
5124 if (used_file_indexes == NULL)
5125 return;
5126 for (i = used_file_argc + 1; i < global_argc; ++i)
5127 if (STRCMP(global_argv[i], name) == 0)
5128 {
5129 used_file_argc = i;
5130 used_file_indexes[used_file_count++] = i;
5131 break;
5132 }
5133 used_file_literal = literal;
5134 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005135 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005136}
5137
5138/*
5139 * Remember the length of the argument list as it was. If it changes then we
5140 * leave it alone when 'encoding' is set.
5141 */
5142 void
5143set_alist_count(void)
5144{
5145 used_alist_count = GARGCOUNT;
5146}
5147
5148/*
5149 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5150 * has been changed while starting up. Use the UCS-2 command line arguments
5151 * and convert them to 'encoding'.
5152 */
5153 void
5154fix_arg_enc(void)
5155{
5156 int i;
5157 int idx;
5158 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005159 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005160
5161 /* Safety checks:
5162 * - if argument count differs between the wide and non-wide argument
5163 * list, something must be wrong.
5164 * - the file name arguments must have been located.
5165 * - the length of the argument list wasn't changed by the user.
5166 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005167 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005168 || ArglistW == NULL
5169 || used_file_indexes == NULL
5170 || used_file_count == 0
5171 || used_alist_count != GARGCOUNT)
5172 return;
5173
Bram Moolenaar86b68352004-12-27 21:59:20 +00005174 /* Remember the buffer numbers for the arguments. */
5175 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5176 if (fnum_list == NULL)
5177 return; /* out of memory */
5178 for (i = 0; i < GARGCOUNT; ++i)
5179 fnum_list[i] = GARGLIST[i].ae_fnum;
5180
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005181 /* Clear the argument list. Make room for the new arguments. */
5182 alist_clear(&global_alist);
5183 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005184 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005185
5186 for (i = 0; i < used_file_count; ++i)
5187 {
5188 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005189 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005190 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005191 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005192#ifdef FEAT_DIFF
5193 /* When using diff mode may need to concatenate file name to
5194 * directory name. Just like it's done in main(). */
5195 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5196 && !mch_isdir(alist_name(&GARGLIST[0])))
5197 {
5198 char_u *r;
5199
5200 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5201 if (r != NULL)
5202 {
5203 vim_free(str);
5204 str = r;
5205 }
5206 }
5207#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005208 /* Re-use the old buffer by renaming it. When not using literal
5209 * names it's done by alist_expand() below. */
5210 if (used_file_literal)
5211 buf_set_name(fnum_list[i], str);
5212
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005213 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005214 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005215 }
5216
5217 if (!used_file_literal)
5218 {
5219 /* Now expand wildcards in the arguments. */
5220 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5221 * filename characters but are excluded from 'isfname' to make
5222 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5223 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005224 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005225 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5226 }
5227
5228 /* If wildcard expansion failed, we are editing the first file of the
5229 * arglist and there is no file name: Edit the first argument now. */
5230 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5231 {
5232 do_cmdline_cmd((char_u *)":rewind");
5233 if (GARGCOUNT == 1 && used_file_full_path)
5234 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5235 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005236
5237 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005238}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005239#endif