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