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