Merge branch 'vim-with-runtime' into feat/code-check
[vim_extended.git] / src / os_win32.c
blob3d0ba7ddfda74a6cda520c0ea9058d4e065eaa98
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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
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".
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.
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.
23 #include "vimio.h"
24 #include "vim.h"
26 #ifdef FEAT_MZSCHEME
27 # include "if_mzsch.h"
28 #endif
30 #include <sys/types.h>
31 #include <errno.h>
32 #include <signal.h>
33 #include <limits.h>
34 #include <process.h>
36 #undef chdir
37 #ifdef __GNUC__
38 # ifndef __MINGW32__
39 # include <dirent.h>
40 # endif
41 #else
42 # include <direct.h>
43 #endif
45 #if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
46 # include <shellapi.h>
47 #endif
49 #ifdef __MINGW32__
50 # ifndef FROM_LEFT_1ST_BUTTON_PRESSED
51 # define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
52 # endif
53 # ifndef RIGHTMOST_BUTTON_PRESSED
54 # define RIGHTMOST_BUTTON_PRESSED 0x0002
55 # endif
56 # ifndef FROM_LEFT_2ND_BUTTON_PRESSED
57 # define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
58 # endif
59 # ifndef FROM_LEFT_3RD_BUTTON_PRESSED
60 # define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
61 # endif
62 # ifndef FROM_LEFT_4TH_BUTTON_PRESSED
63 # define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
64 # endif
67 * EventFlags
69 # ifndef MOUSE_MOVED
70 # define MOUSE_MOVED 0x0001
71 # endif
72 # ifndef DOUBLE_CLICK
73 # define DOUBLE_CLICK 0x0002
74 # endif
75 #endif
77 /* Record all output and all keyboard & mouse input */
78 /* #define MCH_WRITE_DUMP */
80 #ifdef MCH_WRITE_DUMP
81 FILE* fdDump = NULL;
82 #endif
85 * When generating prototypes for Win32 on Unix, these lines make the syntax
86 * errors disappear. They do not need to be correct.
88 #ifdef PROTO
89 #define WINAPI
90 #define WINBASEAPI
91 typedef char * LPCSTR;
92 typedef char * LPWSTR;
93 typedef int ACCESS_MASK;
94 typedef int BOOL;
95 typedef int COLORREF;
96 typedef int CONSOLE_CURSOR_INFO;
97 typedef int COORD;
98 typedef int DWORD;
99 typedef int HANDLE;
100 typedef int HDC;
101 typedef int HFONT;
102 typedef int HICON;
103 typedef int HINSTANCE;
104 typedef int HWND;
105 typedef int INPUT_RECORD;
106 typedef int KEY_EVENT_RECORD;
107 typedef int LOGFONT;
108 typedef int LPBOOL;
109 typedef int LPCTSTR;
110 typedef int LPDWORD;
111 typedef int LPSTR;
112 typedef int LPTSTR;
113 typedef int LPVOID;
114 typedef int MOUSE_EVENT_RECORD;
115 typedef int PACL;
116 typedef int PDWORD;
117 typedef int PHANDLE;
118 typedef int PRINTDLG;
119 typedef int PSECURITY_DESCRIPTOR;
120 typedef int PSID;
121 typedef int SECURITY_INFORMATION;
122 typedef int SHORT;
123 typedef int SMALL_RECT;
124 typedef int TEXTMETRIC;
125 typedef int TOKEN_INFORMATION_CLASS;
126 typedef int TRUSTEE;
127 typedef int WORD;
128 typedef int WCHAR;
129 typedef void VOID;
130 #endif
132 #ifndef FEAT_GUI_W32
133 /* Undocumented API in kernel32.dll needed to work around dead key bug in
134 * console-mode applications in NT 4.0. If you switch keyboard layouts
135 * in a console app to a layout that includes dead keys and then hit a
136 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
137 * and Michael Dietrich for helping me figure out this workaround.
140 /* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
141 #ifndef WINBASEAPI
142 # define WINBASEAPI __stdcall
143 #endif
144 #if defined(__BORLANDC__)
145 typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
146 #else
147 typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
148 #endif
149 static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
150 #endif
152 #if defined(__BORLANDC__)
153 /* Strangely Borland uses a non-standard name. */
154 # define wcsicmp(a, b) wcscmpi((a), (b))
155 #endif
157 #ifndef FEAT_GUI_W32
158 /* Win32 Console handles for input and output */
159 static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
160 static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
162 /* Win32 Screen buffer,coordinate,console I/O information */
163 static SMALL_RECT g_srScrollRegion;
164 static COORD g_coord; /* 0-based, but external coords are 1-based */
166 /* The attribute of the screen when the editor was started */
167 static WORD g_attrDefault = 7; /* lightgray text on black background */
168 static WORD g_attrCurrent;
170 static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
171 static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
172 static int g_fForceExit = FALSE; /* set when forcefully exiting */
174 static void termcap_mode_start(void);
175 static void termcap_mode_end(void);
176 static void clear_chars(COORD coord, DWORD n);
177 static void clear_screen(void);
178 static void clear_to_end_of_display(void);
179 static void clear_to_end_of_line(void);
180 static void scroll(unsigned cLines);
181 static void set_scroll_region(unsigned left, unsigned top,
182 unsigned right, unsigned bottom);
183 static void insert_lines(unsigned cLines);
184 static void delete_lines(unsigned cLines);
185 static void gotoxy(unsigned x, unsigned y);
186 static void normvideo(void);
187 static void textattr(WORD wAttr);
188 static void textcolor(WORD wAttr);
189 static void textbackground(WORD wAttr);
190 static void standout(void);
191 static void standend(void);
192 static void visual_bell(void);
193 static void cursor_visible(BOOL fVisible);
194 static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
195 static char_u tgetch(int *pmodifiers, char_u *pch2);
196 static void create_conin(void);
197 static int s_cursor_visible = TRUE;
198 static int did_create_conin = FALSE;
199 #else
200 static int s_dont_use_vimrun = TRUE;
201 static int need_vimrun_warning = FALSE;
202 static char *vimrun_path = "vimrun ";
203 #endif
205 #ifndef FEAT_GUI_W32
206 static int suppress_winsize = 1; /* don't fiddle with console */
207 #endif
209 static void
210 get_exe_name(void)
212 char temp[256];
213 static int did_set_PATH = FALSE;
215 if (exe_name == NULL)
217 /* store the name of the executable, may be used for $VIM */
218 GetModuleFileName(NULL, temp, 255);
219 if (*temp != NUL)
220 exe_name = FullName_save((char_u *)temp, FALSE);
223 if (!did_set_PATH && exe_name != NULL)
225 char_u *p;
226 char_u *newpath;
228 /* Append our starting directory to $PATH, so that when doing "!xxd"
229 * it's found in our starting directory. Needed because SearchPath()
230 * also looks there. */
231 p = mch_getenv("PATH");
232 newpath = alloc((unsigned)(STRLEN(p) + STRLEN(exe_name) + 2));
233 if (newpath != NULL)
235 STRCPY(newpath, p);
236 STRCAT(newpath, ";");
237 vim_strncpy(newpath + STRLEN(newpath), exe_name,
238 gettail_sep(exe_name) - exe_name);
239 vim_setenv((char_u *)"PATH", newpath);
240 vim_free(newpath);
243 did_set_PATH = TRUE;
247 #if defined(DYNAMIC_GETTEXT) || defined(PROTO)
248 # ifndef GETTEXT_DLL
249 # define GETTEXT_DLL "libintl.dll"
250 # endif
251 /* Dummy funcitons */
252 static char *null_libintl_gettext(const char *);
253 static char *null_libintl_textdomain(const char *);
254 static char *null_libintl_bindtextdomain(const char *, const char *);
255 static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
257 static HINSTANCE hLibintlDLL = 0;
258 char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
259 char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
260 char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
261 = null_libintl_bindtextdomain;
262 char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
263 = null_libintl_bind_textdomain_codeset;
266 dyn_libintl_init(char *libname)
268 int i;
269 static struct
271 char *name;
272 FARPROC *ptr;
273 } libintl_entry[] =
275 {"gettext", (FARPROC*)&dyn_libintl_gettext},
276 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
277 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
278 {NULL, NULL}
281 /* No need to initialize twice. */
282 if (hLibintlDLL)
283 return 1;
284 /* Load gettext library (libintl.dll) */
285 hLibintlDLL = LoadLibrary(libname != NULL ? libname : GETTEXT_DLL);
286 if (!hLibintlDLL)
288 char_u dirname[_MAX_PATH];
290 /* Try using the path from gvim.exe to find the .dll there. */
291 get_exe_name();
292 STRCPY(dirname, exe_name);
293 STRCPY(gettail(dirname), GETTEXT_DLL);
294 hLibintlDLL = LoadLibrary((char *)dirname);
295 if (!hLibintlDLL)
297 if (p_verbose > 0)
299 verbose_enter();
300 EMSG2(_(e_loadlib), GETTEXT_DLL);
301 verbose_leave();
303 return 0;
306 for (i = 0; libintl_entry[i].name != NULL
307 && libintl_entry[i].ptr != NULL; ++i)
309 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
310 libintl_entry[i].name)) == NULL)
312 dyn_libintl_end();
313 if (p_verbose > 0)
315 verbose_enter();
316 EMSG2(_(e_loadfunc), libintl_entry[i].name);
317 verbose_leave();
319 return 0;
323 /* The bind_textdomain_codeset() function is optional. */
324 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
325 "bind_textdomain_codeset");
326 if (dyn_libintl_bind_textdomain_codeset == NULL)
327 dyn_libintl_bind_textdomain_codeset =
328 null_libintl_bind_textdomain_codeset;
330 return 1;
333 void
334 dyn_libintl_end()
336 if (hLibintlDLL)
337 FreeLibrary(hLibintlDLL);
338 hLibintlDLL = NULL;
339 dyn_libintl_gettext = null_libintl_gettext;
340 dyn_libintl_textdomain = null_libintl_textdomain;
341 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
342 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
345 /*ARGSUSED*/
346 static char *
347 null_libintl_gettext(const char *msgid)
349 return (char*)msgid;
352 /*ARGSUSED*/
353 static char *
354 null_libintl_bindtextdomain(const char *domainname, const char *dirname)
356 return NULL;
359 /*ARGSUSED*/
360 static char *
361 null_libintl_bind_textdomain_codeset(const char *domainname,
362 const char *codeset)
364 return NULL;
367 /*ARGSUSED*/
368 static char *
369 null_libintl_textdomain(const char *domainname)
371 return NULL;
374 #endif /* DYNAMIC_GETTEXT */
376 /* This symbol is not defined in older versions of the SDK or Visual C++ */
378 #ifndef VER_PLATFORM_WIN32_WINDOWS
379 # define VER_PLATFORM_WIN32_WINDOWS 1
380 #endif
382 DWORD g_PlatformId;
384 #ifdef HAVE_ACL
385 # include <aclapi.h>
387 * These are needed to dynamically load the ADVAPI DLL, which is not
388 * implemented under Windows 95 (and causes VIM to crash)
390 typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
391 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
392 typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
393 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
394 PSECURITY_DESCRIPTOR *);
396 static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
397 static PSNSECINFO pSetNamedSecurityInfo;
398 static PGNSECINFO pGetNamedSecurityInfo;
399 #endif
402 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
403 * VER_PLATFORM_WIN32_WINDOWS (Win95).
405 void
406 PlatformId(void)
408 static int done = FALSE;
410 if (!done)
412 OSVERSIONINFO ovi;
414 ovi.dwOSVersionInfoSize = sizeof(ovi);
415 GetVersionEx(&ovi);
417 g_PlatformId = ovi.dwPlatformId;
419 #ifdef HAVE_ACL
421 * Load the ADVAPI runtime if we are on anything
422 * other than Windows 95
424 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
427 * do this load. Problems: Doesn't unload at end of run (this is
428 * theoretically okay, since Windows should unload it when VIM
429 * terminates). Should we be using the 'mch_libcall' routines?
430 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
431 * time we verify security...
433 advapi_lib = LoadLibrary("ADVAPI32.DLL");
434 if (advapi_lib != NULL)
436 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
437 "SetNamedSecurityInfoA");
438 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
439 "GetNamedSecurityInfoA");
440 if (pSetNamedSecurityInfo == NULL
441 || pGetNamedSecurityInfo == NULL)
443 /* If we can't get the function addresses, set advapi_lib
444 * to NULL so that we don't use them. */
445 FreeLibrary(advapi_lib);
446 advapi_lib = NULL;
450 #endif
451 done = TRUE;
456 * Return TRUE when running on Windows 95 (or 98 or ME).
457 * Only to be used after mch_init().
460 mch_windows95(void)
462 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
465 #ifdef FEAT_GUI_W32
467 * Used to work around the "can't do synchronous spawn"
468 * problem on Win32s, without resorting to Universal Thunk.
470 static int old_num_windows;
471 static int num_windows;
473 /*ARGSUSED*/
474 static BOOL CALLBACK
475 win32ssynch_cb(HWND hwnd, LPARAM lparam)
477 num_windows++;
478 return TRUE;
480 #endif
482 #ifndef FEAT_GUI_W32
484 #define SHIFT (SHIFT_PRESSED)
485 #define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
486 #define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
487 #define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
490 /* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
491 * We map function keys to their ANSI terminal equivalents, as produced
492 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
493 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
494 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
495 * combinations of function/arrow/etc keys.
498 static const struct
500 WORD wVirtKey;
501 BOOL fAnsiKey;
502 int chAlone;
503 int chShift;
504 int chCtrl;
505 int chAlt;
506 } VirtKeyMap[] =
509 /* Key ANSI alone shift ctrl alt */
510 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
512 { VK_F1, TRUE, ';', 'T', '^', 'h', },
513 { VK_F2, TRUE, '<', 'U', '_', 'i', },
514 { VK_F3, TRUE, '=', 'V', '`', 'j', },
515 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
516 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
517 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
518 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
519 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
520 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
521 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
522 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
523 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
525 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
526 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
527 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
528 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
529 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
530 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
531 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
532 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
533 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
534 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
536 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
538 #if 0
539 /* Most people don't have F13-F20, but what the hell... */
540 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
541 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
542 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
543 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
544 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
545 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
546 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
547 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
548 #endif
549 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
550 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
551 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
552 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
554 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
555 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
556 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
557 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
558 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
559 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
560 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
561 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
562 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
563 /* Sorry, out of number space! <negri>*/
564 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
569 #ifdef _MSC_VER
570 // The ToAscii bug destroys several registers. Need to turn off optimization
571 // or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
572 # pragma warning(push)
573 # pragma warning(disable: 4748)
574 # pragma optimize("", off)
575 #endif
577 #if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
578 # define AChar AsciiChar
579 #else
580 # define AChar uChar.AsciiChar
581 #endif
583 /* The return code indicates key code size. */
584 static int
585 #ifdef __BORLANDC__
586 __stdcall
587 #endif
588 win32_kbd_patch_key(
589 KEY_EVENT_RECORD *pker)
591 UINT uMods = pker->dwControlKeyState;
592 static int s_iIsDead = 0;
593 static WORD awAnsiCode[2];
594 static BYTE abKeystate[256];
597 if (s_iIsDead == 2)
599 pker->AChar = (CHAR) awAnsiCode[1];
600 s_iIsDead = 0;
601 return 1;
604 if (pker->AChar != 0)
605 return 1;
607 memset(abKeystate, 0, sizeof (abKeystate));
609 // Should only be non-NULL on NT 4.0
610 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
612 CHAR szKLID[KL_NAMELENGTH];
614 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
615 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
618 /* Clear any pending dead keys */
619 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
621 if (uMods & SHIFT_PRESSED)
622 abKeystate[VK_SHIFT] = 0x80;
623 if (uMods & CAPSLOCK_ON)
624 abKeystate[VK_CAPITAL] = 1;
626 if ((uMods & ALT_GR) == ALT_GR)
628 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
629 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
632 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
633 abKeystate, awAnsiCode, 0);
635 if (s_iIsDead > 0)
636 pker->AChar = (CHAR) awAnsiCode[0];
638 return s_iIsDead;
641 #ifdef _MSC_VER
642 /* MUST switch optimization on again here, otherwise a call to
643 * decode_key_event() may crash (e.g. when hitting caps-lock) */
644 # pragma optimize("", on)
645 # pragma warning(pop)
647 # if (_MSC_VER < 1100)
648 /* MUST turn off global optimisation for this next function, or
649 * pressing ctrl-minus in insert mode crashes Vim when built with
650 * VC4.1. -- negri. */
651 # pragma optimize("g", off)
652 # endif
653 #endif
655 static BOOL g_fJustGotFocus = FALSE;
658 * Decode a KEY_EVENT into one or two keystrokes
660 static BOOL
661 decode_key_event(
662 KEY_EVENT_RECORD *pker,
663 char_u *pch,
664 char_u *pch2,
665 int *pmodifiers,
666 BOOL fDoPost)
668 int i;
669 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
671 *pch = *pch2 = NUL;
672 g_fJustGotFocus = FALSE;
674 /* ignore key up events */
675 if (!pker->bKeyDown)
676 return FALSE;
678 /* ignore some keystrokes */
679 switch (pker->wVirtualKeyCode)
681 /* modifiers */
682 case VK_SHIFT:
683 case VK_CONTROL:
684 case VK_MENU: /* Alt key */
685 return FALSE;
687 default:
688 break;
691 /* special cases */
692 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
694 /* Ctrl-6 is Ctrl-^ */
695 if (pker->wVirtualKeyCode == '6')
697 *pch = Ctrl_HAT;
698 return TRUE;
700 /* Ctrl-2 is Ctrl-@ */
701 else if (pker->wVirtualKeyCode == '2')
703 *pch = NUL;
704 return TRUE;
706 /* Ctrl-- is Ctrl-_ */
707 else if (pker->wVirtualKeyCode == 0xBD)
709 *pch = Ctrl__;
710 return TRUE;
714 /* Shift-TAB */
715 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
717 *pch = K_NUL;
718 *pch2 = '\017';
719 return TRUE;
722 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
724 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
726 if (nModifs == 0)
727 *pch = VirtKeyMap[i].chAlone;
728 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
729 *pch = VirtKeyMap[i].chShift;
730 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
731 *pch = VirtKeyMap[i].chCtrl;
732 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
733 *pch = VirtKeyMap[i].chAlt;
735 if (*pch != 0)
737 if (VirtKeyMap[i].fAnsiKey)
739 *pch2 = *pch;
740 *pch = K_NUL;
743 return TRUE;
748 i = win32_kbd_patch_key(pker);
750 if (i < 0)
751 *pch = NUL;
752 else
754 *pch = (i > 0) ? pker->AChar : NUL;
756 if (pmodifiers != NULL)
758 /* Pass on the ALT key as a modifier, but only when not combined
759 * with CTRL (which is ALTGR). */
760 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
761 *pmodifiers |= MOD_MASK_ALT;
763 /* Pass on SHIFT only for special keys, because we don't know when
764 * it's already included with the character. */
765 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
766 *pmodifiers |= MOD_MASK_SHIFT;
768 /* Pass on CTRL only for non-special keys, because we don't know
769 * when it's already included with the character. And not when
770 * combined with ALT (which is ALTGR). */
771 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
772 && *pch >= 0x20 && *pch < 0x80)
773 *pmodifiers |= MOD_MASK_CTRL;
777 return (*pch != NUL);
780 #ifdef _MSC_VER
781 # pragma optimize("", on)
782 #endif
784 #endif /* FEAT_GUI_W32 */
787 #ifdef FEAT_MOUSE
790 * For the GUI the mouse handling is in gui_w32.c.
792 # ifdef FEAT_GUI_W32
793 /*ARGSUSED*/
794 void
795 mch_setmouse(int on)
798 # else
799 static int g_fMouseAvail = FALSE; /* mouse present */
800 static int g_fMouseActive = FALSE; /* mouse enabled */
801 static int g_nMouseClick = -1; /* mouse status */
802 static int g_xMouse; /* mouse x coordinate */
803 static int g_yMouse; /* mouse y coordinate */
806 * Enable or disable mouse input
808 void
809 mch_setmouse(int on)
811 DWORD cmodein;
813 if (!g_fMouseAvail)
814 return;
816 g_fMouseActive = on;
817 GetConsoleMode(g_hConIn, &cmodein);
819 if (g_fMouseActive)
820 cmodein |= ENABLE_MOUSE_INPUT;
821 else
822 cmodein &= ~ENABLE_MOUSE_INPUT;
824 SetConsoleMode(g_hConIn, cmodein);
829 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
830 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
831 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
832 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
833 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
834 * and we return the mouse position in g_xMouse and g_yMouse.
836 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
837 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
838 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
840 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
841 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
843 * Windows will send us MOUSE_MOVED notifications whenever the mouse
844 * moves, even if it stays within the same character cell. We ignore
845 * all MOUSE_MOVED messages if the position hasn't really changed, and
846 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
847 * we're only interested in MOUSE_DRAG).
849 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
850 * 2-button mouses by pressing the left & right buttons simultaneously.
851 * In practice, it's almost impossible to click both at the same time,
852 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
853 * in such cases, if the user is clicking quickly.
855 static BOOL
856 decode_mouse_event(
857 MOUSE_EVENT_RECORD *pmer)
859 static int s_nOldButton = -1;
860 static int s_nOldMouseClick = -1;
861 static int s_xOldMouse = -1;
862 static int s_yOldMouse = -1;
863 static linenr_T s_old_topline = 0;
864 #ifdef FEAT_DIFF
865 static int s_old_topfill = 0;
866 #endif
867 static int s_cClicks = 1;
868 static BOOL s_fReleased = TRUE;
869 static DWORD s_dwLastClickTime = 0;
870 static BOOL s_fNextIsMiddle = FALSE;
872 static DWORD cButtons = 0; /* number of buttons supported */
874 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
875 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
876 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
877 const DWORD LEFT_RIGHT = LEFT | RIGHT;
879 int nButton;
881 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
882 cButtons = 2;
884 if (!g_fMouseAvail || !g_fMouseActive)
886 g_nMouseClick = -1;
887 return FALSE;
890 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
891 if (g_fJustGotFocus)
893 g_fJustGotFocus = FALSE;
894 return FALSE;
897 /* unprocessed mouse click? */
898 if (g_nMouseClick != -1)
899 return TRUE;
901 nButton = -1;
902 g_xMouse = pmer->dwMousePosition.X;
903 g_yMouse = pmer->dwMousePosition.Y;
905 if (pmer->dwEventFlags == MOUSE_MOVED)
907 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
908 * events even when the mouse moves only within a char cell.) */
909 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
910 return FALSE;
913 /* If no buttons are pressed... */
914 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
916 /* If the last thing returned was MOUSE_RELEASE, ignore this */
917 if (s_fReleased)
918 return FALSE;
920 nButton = MOUSE_RELEASE;
921 s_fReleased = TRUE;
923 else /* one or more buttons pressed */
925 /* on a 2-button mouse, hold down left and right buttons
926 * simultaneously to get MIDDLE. */
928 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
930 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
932 /* if either left or right button only is pressed, see if the
933 * the next mouse event has both of them pressed */
934 if (dwLR == LEFT || dwLR == RIGHT)
936 for (;;)
938 /* wait a short time for next input event */
939 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
940 != WAIT_OBJECT_0)
941 break;
942 else
944 DWORD cRecords = 0;
945 INPUT_RECORD ir;
946 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
948 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
950 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
951 || !(pmer2->dwButtonState & LEFT_RIGHT))
952 break;
953 else
955 if (pmer2->dwEventFlags != MOUSE_MOVED)
957 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
959 return decode_mouse_event(pmer2);
961 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
962 s_yOldMouse == pmer2->dwMousePosition.Y)
964 /* throw away spurious mouse move */
965 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
967 /* are there any more mouse events in queue? */
968 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
970 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
971 break;
973 else
974 break;
981 if (s_fNextIsMiddle)
983 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
984 ? MOUSE_DRAG : MOUSE_MIDDLE;
985 s_fNextIsMiddle = FALSE;
987 else if (cButtons == 2 &&
988 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
990 nButton = MOUSE_MIDDLE;
992 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
994 s_fNextIsMiddle = TRUE;
995 nButton = MOUSE_RELEASE;
998 else if ((pmer->dwButtonState & LEFT) == LEFT)
999 nButton = MOUSE_LEFT;
1000 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1001 nButton = MOUSE_MIDDLE;
1002 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1003 nButton = MOUSE_RIGHT;
1005 if (! s_fReleased && ! s_fNextIsMiddle
1006 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1007 return FALSE;
1009 s_fReleased = s_fNextIsMiddle;
1012 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1014 /* button pressed or released, without mouse moving */
1015 if (nButton != -1 && nButton != MOUSE_RELEASE)
1017 DWORD dwCurrentTime = GetTickCount();
1019 if (s_xOldMouse != g_xMouse
1020 || s_yOldMouse != g_yMouse
1021 || s_nOldButton != nButton
1022 || s_old_topline != curwin->w_topline
1023 #ifdef FEAT_DIFF
1024 || s_old_topfill != curwin->w_topfill
1025 #endif
1026 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1028 s_cClicks = 1;
1030 else if (++s_cClicks > 4)
1032 s_cClicks = 1;
1035 s_dwLastClickTime = dwCurrentTime;
1038 else if (pmer->dwEventFlags == MOUSE_MOVED)
1040 if (nButton != -1 && nButton != MOUSE_RELEASE)
1041 nButton = MOUSE_DRAG;
1043 s_cClicks = 1;
1046 if (nButton == -1)
1047 return FALSE;
1049 if (nButton != MOUSE_RELEASE)
1050 s_nOldButton = nButton;
1052 g_nMouseClick = nButton;
1054 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1055 g_nMouseClick |= MOUSE_SHIFT;
1056 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1057 g_nMouseClick |= MOUSE_CTRL;
1058 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1059 g_nMouseClick |= MOUSE_ALT;
1061 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1062 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1064 /* only pass on interesting (i.e., different) mouse events */
1065 if (s_xOldMouse == g_xMouse
1066 && s_yOldMouse == g_yMouse
1067 && s_nOldMouseClick == g_nMouseClick)
1069 g_nMouseClick = -1;
1070 return FALSE;
1073 s_xOldMouse = g_xMouse;
1074 s_yOldMouse = g_yMouse;
1075 s_old_topline = curwin->w_topline;
1076 #ifdef FEAT_DIFF
1077 s_old_topfill = curwin->w_topfill;
1078 #endif
1079 s_nOldMouseClick = g_nMouseClick;
1081 return TRUE;
1084 # endif /* FEAT_GUI_W32 */
1085 #endif /* FEAT_MOUSE */
1088 #ifdef MCH_CURSOR_SHAPE
1090 * Set the shape of the cursor.
1091 * 'thickness' can be from 1 (thin) to 99 (block)
1093 static void
1094 mch_set_cursor_shape(int thickness)
1096 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1097 ConsoleCursorInfo.dwSize = thickness;
1098 ConsoleCursorInfo.bVisible = s_cursor_visible;
1100 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1101 if (s_cursor_visible)
1102 SetConsoleCursorPosition(g_hConOut, g_coord);
1105 void
1106 mch_update_cursor(void)
1108 int idx;
1109 int thickness;
1112 * How the cursor is drawn depends on the current mode.
1114 idx = get_shape_idx(FALSE);
1116 if (shape_table[idx].shape == SHAPE_BLOCK)
1117 thickness = 99; /* 100 doesn't work on W95 */
1118 else
1119 thickness = shape_table[idx].percentage;
1120 mch_set_cursor_shape(thickness);
1122 #endif
1124 #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1126 * Handle FOCUS_EVENT.
1128 static void
1129 handle_focus_event(INPUT_RECORD ir)
1131 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1132 ui_focus_change((int)g_fJustGotFocus);
1136 * Wait until console input from keyboard or mouse is available,
1137 * or the time is up.
1138 * Return TRUE if something is available FALSE if not.
1140 static int
1141 WaitForChar(long msec)
1143 DWORD dwNow = 0, dwEndTime = 0;
1144 INPUT_RECORD ir;
1145 DWORD cRecords;
1146 char_u ch, ch2;
1148 if (msec > 0)
1149 /* Wait until the specified time has elapsed. */
1150 dwEndTime = GetTickCount() + msec;
1151 else if (msec < 0)
1152 /* Wait forever. */
1153 dwEndTime = INFINITE;
1155 /* We need to loop until the end of the time period, because
1156 * we might get multiple unusable mouse events in that time.
1158 for (;;)
1160 #ifdef FEAT_MZSCHEME
1161 mzvim_check_threads();
1162 #endif
1163 #ifdef FEAT_CLIENTSERVER
1164 serverProcessPendingMessages();
1165 #endif
1166 if (0
1167 #ifdef FEAT_MOUSE
1168 || g_nMouseClick != -1
1169 #endif
1170 #ifdef FEAT_CLIENTSERVER
1171 || input_available()
1172 #endif
1174 return TRUE;
1176 if (msec > 0)
1178 /* If the specified wait time has passed, return. */
1179 dwNow = GetTickCount();
1180 if (dwNow >= dwEndTime)
1181 break;
1183 if (msec != 0)
1185 DWORD dwWaitTime = dwEndTime - dwNow;
1187 #ifdef FEAT_MZSCHEME
1188 if (mzthreads_allowed() && p_mzq > 0
1189 && (msec < 0 || (long)dwWaitTime > p_mzq))
1190 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1191 #endif
1192 #ifdef FEAT_CLIENTSERVER
1193 /* Wait for either an event on the console input or a message in
1194 * the client-server window. */
1195 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
1196 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
1197 #else
1198 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
1199 #endif
1200 continue;
1203 cRecords = 0;
1204 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1206 #ifdef FEAT_MBYTE_IME
1207 if (State & CMDLINE && msg_row == Rows - 1)
1209 CONSOLE_SCREEN_BUFFER_INFO csbi;
1211 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1213 if (csbi.dwCursorPosition.Y != msg_row)
1215 /* The screen is now messed up, must redraw the
1216 * command line and later all the windows. */
1217 redraw_all_later(CLEAR);
1218 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1219 redrawcmd();
1223 #endif
1225 if (cRecords > 0)
1227 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1229 #ifdef FEAT_MBYTE_IME
1230 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1231 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1232 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1233 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1235 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1236 continue;
1238 #endif
1239 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1240 NULL, FALSE))
1241 return TRUE;
1244 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1246 if (ir.EventType == FOCUS_EVENT)
1247 handle_focus_event(ir);
1248 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1249 shell_resized();
1250 #ifdef FEAT_MOUSE
1251 else if (ir.EventType == MOUSE_EVENT
1252 && decode_mouse_event(&ir.Event.MouseEvent))
1253 return TRUE;
1254 #endif
1256 else if (msec == 0)
1257 break;
1260 #ifdef FEAT_CLIENTSERVER
1261 /* Something might have been received while we were waiting. */
1262 if (input_available())
1263 return TRUE;
1264 #endif
1265 return FALSE;
1268 #ifndef FEAT_GUI_MSWIN
1270 * return non-zero if a character is available
1273 mch_char_avail(void)
1275 return WaitForChar(0L);
1277 #endif
1280 * Create the console input. Used when reading stdin doesn't work.
1282 static void
1283 create_conin(void)
1285 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1286 FILE_SHARE_READ|FILE_SHARE_WRITE,
1287 (LPSECURITY_ATTRIBUTES) NULL,
1288 OPEN_EXISTING, 0, (HANDLE)NULL);
1289 did_create_conin = TRUE;
1293 * Get a keystroke or a mouse event
1295 static char_u
1296 tgetch(int *pmodifiers, char_u *pch2)
1298 char_u ch;
1300 for (;;)
1302 INPUT_RECORD ir;
1303 DWORD cRecords = 0;
1305 #ifdef FEAT_CLIENTSERVER
1306 (void)WaitForChar(-1L);
1307 if (input_available())
1308 return 0;
1309 # ifdef FEAT_MOUSE
1310 if (g_nMouseClick != -1)
1311 return 0;
1312 # endif
1313 #endif
1314 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1316 if (did_create_conin)
1317 read_error_exit();
1318 create_conin();
1319 continue;
1322 if (ir.EventType == KEY_EVENT)
1324 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1325 pmodifiers, TRUE))
1326 return ch;
1328 else if (ir.EventType == FOCUS_EVENT)
1329 handle_focus_event(ir);
1330 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1331 shell_resized();
1332 #ifdef FEAT_MOUSE
1333 else if (ir.EventType == MOUSE_EVENT)
1335 if (decode_mouse_event(&ir.Event.MouseEvent))
1336 return 0;
1338 #endif
1341 #endif /* !FEAT_GUI_W32 */
1345 * mch_inchar(): low-level input funcion.
1346 * Get one or more characters from the keyboard or the mouse.
1347 * If time == 0, do not wait for characters.
1348 * If time == n, wait a short time for characters.
1349 * If time == -1, wait forever for characters.
1350 * Returns the number of characters read into buf.
1352 /*ARGSUSED*/
1354 mch_inchar(
1355 char_u *buf,
1356 int maxlen,
1357 long time,
1358 int tb_change_cnt)
1360 #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1362 int len;
1363 int c;
1364 #define TYPEAHEADLEN 20
1365 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1366 static int typeaheadlen = 0;
1368 /* First use any typeahead that was kept because "buf" was too small. */
1369 if (typeaheadlen > 0)
1370 goto theend;
1372 #ifdef FEAT_SNIFF
1373 if (want_sniff_request)
1375 if (sniff_request_waiting)
1377 /* return K_SNIFF */
1378 typeahead[typeaheadlen++] = CSI;
1379 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1380 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1381 sniff_request_waiting = 0;
1382 want_sniff_request = 0;
1383 goto theend;
1385 else if (time < 0 || time > 250)
1387 /* don't wait too long, a request might be pending */
1388 time = 250;
1391 #endif
1393 if (time >= 0)
1395 if (!WaitForChar(time)) /* no character available */
1396 return 0;
1398 else /* time == -1, wait forever */
1400 mch_set_winsize_now(); /* Allow winsize changes from now on */
1403 * If there is no character available within 2 seconds (default)
1404 * write the autoscript file to disk. Or cause the CursorHold event
1405 * to be triggered.
1407 if (!WaitForChar(p_ut))
1409 #ifdef FEAT_AUTOCMD
1410 if (trigger_cursorhold() && maxlen >= 3)
1412 buf[0] = K_SPECIAL;
1413 buf[1] = KS_EXTRA;
1414 buf[2] = (int)KE_CURSORHOLD;
1415 return 3;
1417 #endif
1418 before_blocking();
1423 * Try to read as many characters as there are, until the buffer is full.
1426 /* we will get at least one key. Get more if they are available. */
1427 g_fCBrkPressed = FALSE;
1429 #ifdef MCH_WRITE_DUMP
1430 if (fdDump)
1431 fputc('[', fdDump);
1432 #endif
1434 /* Keep looping until there is something in the typeahead buffer and more
1435 * to get and still room in the buffer (up to two bytes for a char and
1436 * three bytes for a modifier). */
1437 while ((typeaheadlen == 0 || WaitForChar(0L))
1438 && typeaheadlen + 5 <= TYPEAHEADLEN)
1440 if (typebuf_changed(tb_change_cnt))
1442 /* "buf" may be invalid now if a client put something in the
1443 * typeahead buffer and "buf" is in the typeahead buffer. */
1444 typeaheadlen = 0;
1445 break;
1447 #ifdef FEAT_MOUSE
1448 if (g_nMouseClick != -1)
1450 # ifdef MCH_WRITE_DUMP
1451 if (fdDump)
1452 fprintf(fdDump, "{%02x @ %d, %d}",
1453 g_nMouseClick, g_xMouse, g_yMouse);
1454 # endif
1455 typeahead[typeaheadlen++] = ESC + 128;
1456 typeahead[typeaheadlen++] = 'M';
1457 typeahead[typeaheadlen++] = g_nMouseClick;
1458 typeahead[typeaheadlen++] = g_xMouse + '!';
1459 typeahead[typeaheadlen++] = g_yMouse + '!';
1460 g_nMouseClick = -1;
1462 else
1463 #endif
1465 char_u ch2 = NUL;
1466 int modifiers = 0;
1468 c = tgetch(&modifiers, &ch2);
1470 if (typebuf_changed(tb_change_cnt))
1472 /* "buf" may be invalid now if a client put something in the
1473 * typeahead buffer and "buf" is in the typeahead buffer. */
1474 typeaheadlen = 0;
1475 break;
1478 if (c == Ctrl_C && ctrl_c_interrupts)
1480 #if defined(FEAT_CLIENTSERVER)
1481 trash_input_buf();
1482 #endif
1483 got_int = TRUE;
1486 #ifdef FEAT_MOUSE
1487 if (g_nMouseClick == -1)
1488 #endif
1490 int n = 1;
1492 /* A key may have one or two bytes. */
1493 typeahead[typeaheadlen] = c;
1494 if (ch2 != NUL)
1496 typeahead[typeaheadlen + 1] = ch2;
1497 ++n;
1499 #ifdef FEAT_MBYTE
1500 /* Only convert normal characters, not special keys. Need to
1501 * convert before applying ALT, otherwise mapping <M-x> breaks
1502 * when 'tenc' is set. */
1503 if (input_conv.vc_type != CONV_NONE
1504 && (ch2 == NUL || c != K_NUL))
1505 n = convert_input(typeahead + typeaheadlen, n,
1506 TYPEAHEADLEN - typeaheadlen);
1507 #endif
1509 /* Use the ALT key to set the 8th bit of the character
1510 * when it's one byte, the 8th bit isn't set yet and not
1511 * using a double-byte encoding (would become a lead
1512 * byte). */
1513 if ((modifiers & MOD_MASK_ALT)
1514 && n == 1
1515 && (typeahead[typeaheadlen] & 0x80) == 0
1516 #ifdef FEAT_MBYTE
1517 && !enc_dbcs
1518 #endif
1521 #ifdef FEAT_MBYTE
1522 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1523 typeahead + typeaheadlen);
1524 #else
1525 typeahead[typeaheadlen] |= 0x80;
1526 #endif
1527 modifiers &= ~MOD_MASK_ALT;
1530 if (modifiers != 0)
1532 /* Prepend modifiers to the character. */
1533 mch_memmove(typeahead + typeaheadlen + 3,
1534 typeahead + typeaheadlen, n);
1535 typeahead[typeaheadlen++] = K_SPECIAL;
1536 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1537 typeahead[typeaheadlen++] = modifiers;
1540 typeaheadlen += n;
1542 #ifdef MCH_WRITE_DUMP
1543 if (fdDump)
1544 fputc(c, fdDump);
1545 #endif
1550 #ifdef MCH_WRITE_DUMP
1551 if (fdDump)
1553 fputs("]\n", fdDump);
1554 fflush(fdDump);
1556 #endif
1558 theend:
1559 /* Move typeahead to "buf", as much as fits. */
1560 len = 0;
1561 while (len < maxlen && typeaheadlen > 0)
1563 buf[len++] = typeahead[0];
1564 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1566 return len;
1568 #else /* FEAT_GUI_W32 */
1569 return 0;
1570 #endif /* FEAT_GUI_W32 */
1573 #ifndef __MINGW32__
1574 # include <shellapi.h> /* required for FindExecutable() */
1575 #endif
1578 * Return TRUE if "name" is in $PATH.
1579 * TODO: Should somehow check if it's really executable.
1581 static int
1582 executable_exists(char *name)
1584 char *dum;
1585 char fname[_MAX_PATH];
1587 #ifdef FEAT_MBYTE
1588 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1590 WCHAR *p = enc_to_utf16(name, NULL);
1591 WCHAR fnamew[_MAX_PATH];
1592 WCHAR *dumw;
1593 long n;
1595 if (p != NULL)
1597 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1598 vim_free(p);
1599 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1601 if (n == 0)
1602 return FALSE;
1603 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1604 return FALSE;
1605 return TRUE;
1607 /* Retry with non-wide function (for Windows 98). */
1610 #endif
1611 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1612 return FALSE;
1613 if (mch_isdir(fname))
1614 return FALSE;
1615 return TRUE;
1618 #ifdef FEAT_GUI_W32
1621 * GUI version of mch_init().
1623 void
1624 mch_init(void)
1626 #ifndef __MINGW32__
1627 extern int _fmode;
1628 #endif
1630 /* Let critical errors result in a failure, not in a dialog box. Required
1631 * for the timestamp test to work on removed floppies. */
1632 SetErrorMode(SEM_FAILCRITICALERRORS);
1634 _fmode = O_BINARY; /* we do our own CR-LF translation */
1636 /* Specify window size. Is there a place to get the default from? */
1637 Rows = 25;
1638 Columns = 80;
1640 /* Look for 'vimrun' */
1641 if (!gui_is_win32s())
1643 char_u vimrun_location[_MAX_PATH + 4];
1645 /* First try in same directory as gvim.exe */
1646 STRCPY(vimrun_location, exe_name);
1647 STRCPY(gettail(vimrun_location), "vimrun.exe");
1648 if (mch_getperm(vimrun_location) >= 0)
1650 if (*skiptowhite(vimrun_location) != NUL)
1652 /* Enclose path with white space in double quotes. */
1653 mch_memmove(vimrun_location + 1, vimrun_location,
1654 STRLEN(vimrun_location) + 1);
1655 *vimrun_location = '"';
1656 STRCPY(gettail(vimrun_location), "vimrun\" ");
1658 else
1659 STRCPY(gettail(vimrun_location), "vimrun ");
1661 vimrun_path = (char *)vim_strsave(vimrun_location);
1662 s_dont_use_vimrun = FALSE;
1664 else if (executable_exists("vimrun.exe"))
1665 s_dont_use_vimrun = FALSE;
1667 /* Don't give the warning for a missing vimrun.exe right now, but only
1668 * when vimrun was supposed to be used. Don't bother people that do
1669 * not need vimrun.exe. */
1670 if (s_dont_use_vimrun)
1671 need_vimrun_warning = TRUE;
1675 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1676 * Otherwise the default "findstr /n" is used.
1678 if (!executable_exists("findstr.exe"))
1679 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1681 #ifdef FEAT_CLIPBOARD
1682 clip_init(TRUE);
1685 * Vim's own clipboard format recognises whether the text is char, line,
1686 * or rectangular block. Only useful for copying between two Vims.
1687 * "VimClipboard" was used for previous versions, using the first
1688 * character to specify MCHAR, MLINE or MBLOCK.
1690 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1691 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1692 #endif
1696 #else /* FEAT_GUI_W32 */
1698 #define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1699 #define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1702 * ClearConsoleBuffer()
1703 * Description:
1704 * Clears the entire contents of the console screen buffer, using the
1705 * specified attribute.
1706 * Returns:
1707 * TRUE on success
1709 static BOOL
1710 ClearConsoleBuffer(WORD wAttribute)
1712 CONSOLE_SCREEN_BUFFER_INFO csbi;
1713 COORD coord;
1714 DWORD NumCells, dummy;
1716 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1717 return FALSE;
1719 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1720 coord.X = 0;
1721 coord.Y = 0;
1722 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1723 coord, &dummy))
1725 return FALSE;
1727 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1728 coord, &dummy))
1730 return FALSE;
1733 return TRUE;
1737 * FitConsoleWindow()
1738 * Description:
1739 * Checks if the console window will fit within given buffer dimensions.
1740 * Also, if requested, will shrink the window to fit.
1741 * Returns:
1742 * TRUE on success
1744 static BOOL
1745 FitConsoleWindow(
1746 COORD dwBufferSize,
1747 BOOL WantAdjust)
1749 CONSOLE_SCREEN_BUFFER_INFO csbi;
1750 COORD dwWindowSize;
1751 BOOL NeedAdjust = FALSE;
1753 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1756 * A buffer resize will fail if the current console window does
1757 * not lie completely within that buffer. To avoid this, we might
1758 * have to move and possibly shrink the window.
1760 if (csbi.srWindow.Right >= dwBufferSize.X)
1762 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1763 if (dwWindowSize.X > dwBufferSize.X)
1764 dwWindowSize.X = dwBufferSize.X;
1765 csbi.srWindow.Right = dwBufferSize.X - 1;
1766 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1767 NeedAdjust = TRUE;
1769 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1771 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1772 if (dwWindowSize.Y > dwBufferSize.Y)
1773 dwWindowSize.Y = dwBufferSize.Y;
1774 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1775 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1776 NeedAdjust = TRUE;
1778 if (NeedAdjust && WantAdjust)
1780 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1781 return FALSE;
1783 return TRUE;
1786 return FALSE;
1789 typedef struct ConsoleBufferStruct
1791 BOOL IsValid;
1792 CONSOLE_SCREEN_BUFFER_INFO Info;
1793 PCHAR_INFO Buffer;
1794 COORD BufferSize;
1795 } ConsoleBuffer;
1798 * SaveConsoleBuffer()
1799 * Description:
1800 * Saves important information about the console buffer, including the
1801 * actual buffer contents. The saved information is suitable for later
1802 * restoration by RestoreConsoleBuffer().
1803 * Returns:
1804 * TRUE if all information was saved; FALSE otherwise
1805 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1807 static BOOL
1808 SaveConsoleBuffer(
1809 ConsoleBuffer *cb)
1811 DWORD NumCells;
1812 COORD BufferCoord;
1813 SMALL_RECT ReadRegion;
1814 WORD Y, Y_incr;
1816 if (cb == NULL)
1817 return FALSE;
1819 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1821 cb->IsValid = FALSE;
1822 return FALSE;
1824 cb->IsValid = TRUE;
1827 * Allocate a buffer large enough to hold the entire console screen
1828 * buffer. If this ConsoleBuffer structure has already been initialized
1829 * with a buffer of the correct size, then just use that one.
1831 if (!cb->IsValid || cb->Buffer == NULL ||
1832 cb->BufferSize.X != cb->Info.dwSize.X ||
1833 cb->BufferSize.Y != cb->Info.dwSize.Y)
1835 cb->BufferSize.X = cb->Info.dwSize.X;
1836 cb->BufferSize.Y = cb->Info.dwSize.Y;
1837 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
1838 if (cb->Buffer != NULL)
1839 vim_free(cb->Buffer);
1840 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
1841 if (cb->Buffer == NULL)
1842 return FALSE;
1846 * We will now copy the console screen buffer into our buffer.
1847 * ReadConsoleOutput() seems to be limited as far as how much you
1848 * can read at a time. Empirically, this number seems to be about
1849 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1850 * in chunks until it is all copied. The chunks will all have the
1851 * same horizontal characteristics, so initialize them now. The
1852 * height of each chunk will be (12000 / width).
1854 BufferCoord.X = 0;
1855 ReadRegion.Left = 0;
1856 ReadRegion.Right = cb->Info.dwSize.X - 1;
1857 Y_incr = 12000 / cb->Info.dwSize.X;
1858 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
1861 * Read into position (0, Y) in our buffer.
1863 BufferCoord.Y = Y;
1865 * Read the region whose top left corner is (0, Y) and whose bottom
1866 * right corner is (width - 1, Y + Y_incr - 1). This should define
1867 * a region of size width by Y_incr. Don't worry if this region is
1868 * too large for the remaining buffer; it will be cropped.
1870 ReadRegion.Top = Y;
1871 ReadRegion.Bottom = Y + Y_incr - 1;
1872 if (!ReadConsoleOutput(g_hConOut, /* output handle */
1873 cb->Buffer, /* our buffer */
1874 cb->BufferSize, /* dimensions of our buffer */
1875 BufferCoord, /* offset in our buffer */
1876 &ReadRegion)) /* region to save */
1878 vim_free(cb->Buffer);
1879 cb->Buffer = NULL;
1880 return FALSE;
1884 return TRUE;
1888 * RestoreConsoleBuffer()
1889 * Description:
1890 * Restores important information about the console buffer, including the
1891 * actual buffer contents, if desired. The information to restore is in
1892 * the same format used by SaveConsoleBuffer().
1893 * Returns:
1894 * TRUE on success
1896 static BOOL
1897 RestoreConsoleBuffer(
1898 ConsoleBuffer *cb,
1899 BOOL RestoreScreen)
1901 COORD BufferCoord;
1902 SMALL_RECT WriteRegion;
1904 if (cb == NULL || !cb->IsValid)
1905 return FALSE;
1908 * Before restoring the buffer contents, clear the current buffer, and
1909 * restore the cursor position and window information. Doing this now
1910 * prevents old buffer contents from "flashing" onto the screen.
1912 if (RestoreScreen)
1913 ClearConsoleBuffer(cb->Info.wAttributes);
1915 FitConsoleWindow(cb->Info.dwSize, TRUE);
1916 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
1917 return FALSE;
1918 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
1919 return FALSE;
1921 if (!RestoreScreen)
1924 * No need to restore the screen buffer contents, so we're done.
1926 return TRUE;
1929 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
1930 return FALSE;
1931 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
1932 return FALSE;
1935 * Restore the screen buffer contents.
1937 if (cb->Buffer != NULL)
1939 BufferCoord.X = 0;
1940 BufferCoord.Y = 0;
1941 WriteRegion.Left = 0;
1942 WriteRegion.Top = 0;
1943 WriteRegion.Right = cb->Info.dwSize.X - 1;
1944 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
1945 if (!WriteConsoleOutput(g_hConOut, /* output handle */
1946 cb->Buffer, /* our buffer */
1947 cb->BufferSize, /* dimensions of our buffer */
1948 BufferCoord, /* offset in our buffer */
1949 &WriteRegion)) /* region to restore */
1951 return FALSE;
1955 return TRUE;
1958 #define FEAT_RESTORE_ORIG_SCREEN
1959 #ifdef FEAT_RESTORE_ORIG_SCREEN
1960 static ConsoleBuffer g_cbOrig = { 0 };
1961 #endif
1962 static ConsoleBuffer g_cbNonTermcap = { 0 };
1963 static ConsoleBuffer g_cbTermcap = { 0 };
1965 #ifdef FEAT_TITLE
1966 #ifdef __BORLANDC__
1967 typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
1968 #else
1969 typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
1970 #endif
1971 char g_szOrigTitle[256] = { 0 };
1972 HWND g_hWnd = NULL; /* also used in os_mswin.c */
1973 static HICON g_hOrigIconSmall = NULL;
1974 static HICON g_hOrigIcon = NULL;
1975 static HICON g_hVimIcon = NULL;
1976 static BOOL g_fCanChangeIcon = FALSE;
1978 /* ICON* are not defined in VC++ 4.0 */
1979 #ifndef ICON_SMALL
1980 #define ICON_SMALL 0
1981 #endif
1982 #ifndef ICON_BIG
1983 #define ICON_BIG 1
1984 #endif
1986 * GetConsoleIcon()
1987 * Description:
1988 * Attempts to retrieve the small icon and/or the big icon currently in
1989 * use by a given window.
1990 * Returns:
1991 * TRUE on success
1993 static BOOL
1994 GetConsoleIcon(
1995 HWND hWnd,
1996 HICON *phIconSmall,
1997 HICON *phIcon)
1999 if (hWnd == NULL)
2000 return FALSE;
2002 if (phIconSmall != NULL)
2003 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2004 (WPARAM)ICON_SMALL, (LPARAM)0);
2005 if (phIcon != NULL)
2006 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2007 (WPARAM)ICON_BIG, (LPARAM)0);
2008 return TRUE;
2012 * SetConsoleIcon()
2013 * Description:
2014 * Attempts to change the small icon and/or the big icon currently in
2015 * use by a given window.
2016 * Returns:
2017 * TRUE on success
2019 static BOOL
2020 SetConsoleIcon(
2021 HWND hWnd,
2022 HICON hIconSmall,
2023 HICON hIcon)
2025 HICON hPrevIconSmall;
2026 HICON hPrevIcon;
2028 if (hWnd == NULL)
2029 return FALSE;
2031 if (hIconSmall != NULL)
2032 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2033 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
2034 if (hIcon != NULL)
2035 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2036 (WPARAM)ICON_BIG,(LPARAM) hIcon);
2037 return TRUE;
2041 * SaveConsoleTitleAndIcon()
2042 * Description:
2043 * Saves the current console window title in g_szOrigTitle, for later
2044 * restoration. Also, attempts to obtain a handle to the console window,
2045 * and use it to save the small and big icons currently in use by the
2046 * console window. This is not always possible on some versions of Windows;
2047 * nor is it possible when running Vim remotely using Telnet (since the
2048 * console window the user sees is owned by a remote process).
2050 static void
2051 SaveConsoleTitleAndIcon(void)
2053 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2055 /* Save the original title. */
2056 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2057 return;
2060 * Obtain a handle to the console window using GetConsoleWindow() from
2061 * KERNEL32.DLL; we need to handle in order to change the window icon.
2062 * This function only exists on NT-based Windows, starting with Windows
2063 * 2000. On older operating systems, we can't change the window icon
2064 * anyway.
2066 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2067 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2068 "GetConsoleWindow")) != NULL)
2070 g_hWnd = (*GetConsoleWindowProc)();
2072 if (g_hWnd == NULL)
2073 return;
2075 /* Save the original console window icon. */
2076 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2077 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2078 return;
2080 /* Extract the first icon contained in the Vim executable. */
2081 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2082 if (g_hVimIcon != NULL)
2083 g_fCanChangeIcon = TRUE;
2085 #endif
2087 static int g_fWindInitCalled = FALSE;
2088 static int g_fTermcapMode = FALSE;
2089 static CONSOLE_CURSOR_INFO g_cci;
2090 static DWORD g_cmodein = 0;
2091 static DWORD g_cmodeout = 0;
2094 * non-GUI version of mch_init().
2096 void
2097 mch_init(void)
2099 #ifndef FEAT_RESTORE_ORIG_SCREEN
2100 CONSOLE_SCREEN_BUFFER_INFO csbi;
2101 #endif
2102 #ifndef __MINGW32__
2103 extern int _fmode;
2104 #endif
2106 /* Let critical errors result in a failure, not in a dialog box. Required
2107 * for the timestamp test to work on removed floppies. */
2108 SetErrorMode(SEM_FAILCRITICALERRORS);
2110 _fmode = O_BINARY; /* we do our own CR-LF translation */
2111 out_flush();
2113 /* Obtain handles for the standard Console I/O devices */
2114 if (read_cmd_fd == 0)
2115 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2116 else
2117 create_conin();
2118 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2120 #ifdef FEAT_RESTORE_ORIG_SCREEN
2121 /* Save the initial console buffer for later restoration */
2122 SaveConsoleBuffer(&g_cbOrig);
2123 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2124 #else
2125 /* Get current text attributes */
2126 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2127 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2128 #endif
2129 if (cterm_normal_fg_color == 0)
2130 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2131 if (cterm_normal_bg_color == 0)
2132 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2134 /* set termcap codes to current text attributes */
2135 update_tcap(g_attrCurrent);
2137 GetConsoleCursorInfo(g_hConOut, &g_cci);
2138 GetConsoleMode(g_hConIn, &g_cmodein);
2139 GetConsoleMode(g_hConOut, &g_cmodeout);
2141 #ifdef FEAT_TITLE
2142 SaveConsoleTitleAndIcon();
2144 * Set both the small and big icons of the console window to Vim's icon.
2145 * Note that Vim presently only has one size of icon (32x32), but it
2146 * automatically gets scaled down to 16x16 when setting the small icon.
2148 if (g_fCanChangeIcon)
2149 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2150 #endif
2152 ui_get_shellsize();
2154 #ifdef MCH_WRITE_DUMP
2155 fdDump = fopen("dump", "wt");
2157 if (fdDump)
2159 time_t t;
2161 time(&t);
2162 fputs(ctime(&t), fdDump);
2163 fflush(fdDump);
2165 #endif
2167 g_fWindInitCalled = TRUE;
2169 #ifdef FEAT_MOUSE
2170 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2171 #endif
2173 #ifdef FEAT_CLIPBOARD
2174 clip_init(TRUE);
2177 * Vim's own clipboard format recognises whether the text is char, line, or
2178 * rectangular block. Only useful for copying between two Vims.
2179 * "VimClipboard" was used for previous versions, using the first
2180 * character to specify MCHAR, MLINE or MBLOCK.
2182 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2183 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2184 #endif
2186 /* This will be NULL on anything but NT 4.0 */
2187 s_pfnGetConsoleKeyboardLayoutName =
2188 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2189 "GetConsoleKeyboardLayoutNameA");
2193 * non-GUI version of mch_exit().
2194 * Shut down and exit with status `r'
2195 * Careful: mch_exit() may be called before mch_init()!
2197 void
2198 mch_exit(int r)
2200 stoptermcap();
2202 if (g_fWindInitCalled)
2203 settmode(TMODE_COOK);
2205 ml_close_all(TRUE); /* remove all memfiles */
2207 if (g_fWindInitCalled)
2209 #ifdef FEAT_TITLE
2210 mch_restore_title(3);
2212 * Restore both the small and big icons of the console window to
2213 * what they were at startup. Don't do this when the window is
2214 * closed, Vim would hang here.
2216 if (g_fCanChangeIcon && !g_fForceExit)
2217 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2218 #endif
2220 #ifdef MCH_WRITE_DUMP
2221 if (fdDump)
2223 time_t t;
2225 time(&t);
2226 fputs(ctime(&t), fdDump);
2227 fclose(fdDump);
2229 fdDump = NULL;
2230 #endif
2233 SetConsoleCursorInfo(g_hConOut, &g_cci);
2234 SetConsoleMode(g_hConIn, g_cmodein);
2235 SetConsoleMode(g_hConOut, g_cmodeout);
2237 #ifdef DYNAMIC_GETTEXT
2238 dyn_libintl_end();
2239 #endif
2241 exit(r);
2243 #endif /* !FEAT_GUI_W32 */
2246 * Do we have an interactive window?
2248 /*ARGSUSED*/
2250 mch_check_win(
2251 int argc,
2252 char **argv)
2254 get_exe_name();
2256 #ifdef FEAT_GUI_W32
2257 return OK; /* GUI always has a tty */
2258 #else
2259 if (isatty(1))
2260 return OK;
2261 return FAIL;
2262 #endif
2267 * fname_case(): Set the case of the file name, if it already exists.
2268 * When "len" is > 0, also expand short to long filenames.
2270 void
2271 fname_case(
2272 char_u *name,
2273 int len)
2275 char szTrueName[_MAX_PATH + 2];
2276 char *ptrue, *ptruePrev;
2277 char *porig, *porigPrev;
2278 int flen;
2279 WIN32_FIND_DATA fb;
2280 HANDLE hFind;
2281 int c;
2283 flen = (int)STRLEN(name);
2284 if (flen == 0 || flen > _MAX_PATH)
2285 return;
2287 slash_adjust(name);
2289 /* Build the new name in szTrueName[] one component at a time. */
2290 porig = name;
2291 ptrue = szTrueName;
2293 if (isalpha(porig[0]) && porig[1] == ':')
2295 /* copy leading drive letter */
2296 *ptrue++ = *porig++;
2297 *ptrue++ = *porig++;
2298 *ptrue = NUL; /* in case nothing follows */
2301 while (*porig != NUL)
2303 /* copy \ characters */
2304 while (*porig == psepc)
2305 *ptrue++ = *porig++;
2307 ptruePrev = ptrue;
2308 porigPrev = porig;
2309 while (*porig != NUL && *porig != psepc)
2311 #ifdef FEAT_MBYTE
2312 int l;
2314 if (enc_dbcs)
2316 l = (*mb_ptr2len)(porig);
2317 while (--l >= 0)
2318 *ptrue++ = *porig++;
2320 else
2321 #endif
2322 *ptrue++ = *porig++;
2324 *ptrue = NUL;
2326 /* Skip "", "." and "..". */
2327 if (ptrue > ptruePrev
2328 && (ptruePrev[0] != '.'
2329 || (ptruePrev[1] != NUL
2330 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
2331 && (hFind = FindFirstFile(szTrueName, &fb))
2332 != INVALID_HANDLE_VALUE)
2334 c = *porig;
2335 *porig = NUL;
2337 /* Only use the match when it's the same name (ignoring case) or
2338 * expansion is allowed and there is a match with the short name
2339 * and there is enough room. */
2340 if (_stricoll(porigPrev, fb.cFileName) == 0
2341 || (len > 0
2342 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2343 && (int)(ptruePrev - szTrueName)
2344 + (int)strlen(fb.cFileName) < len)))
2346 STRCPY(ptruePrev, fb.cFileName);
2348 /* Look for exact match and prefer it if found. Must be a
2349 * long name, otherwise there would be only one match. */
2350 while (FindNextFile(hFind, &fb))
2352 if (*fb.cAlternateFileName != NUL
2353 && (strcoll(porigPrev, fb.cFileName) == 0
2354 || (len > 0
2355 && (_stricoll(porigPrev,
2356 fb.cAlternateFileName) == 0
2357 && (int)(ptruePrev - szTrueName)
2358 + (int)strlen(fb.cFileName) < len))))
2360 STRCPY(ptruePrev, fb.cFileName);
2361 break;
2365 FindClose(hFind);
2366 *porig = c;
2367 ptrue = ptruePrev + strlen(ptruePrev);
2371 STRCPY(name, szTrueName);
2376 * Insert user name in s[len].
2379 mch_get_user_name(
2380 char_u *s,
2381 int len)
2383 char szUserName[256 + 1]; /* UNLEN is 256 */
2384 DWORD cch = sizeof szUserName;
2386 if (GetUserName(szUserName, &cch))
2388 vim_strncpy(s, szUserName, len - 1);
2389 return OK;
2391 s[0] = NUL;
2392 return FAIL;
2397 * Insert host name in s[len].
2399 void
2400 mch_get_host_name(
2401 char_u *s,
2402 int len)
2404 DWORD cch = len;
2406 if (!GetComputerName(s, &cch))
2407 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
2412 * return process ID
2414 long
2415 mch_get_pid(void)
2417 return (long)GetCurrentProcessId();
2422 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2423 * Return OK for success, FAIL for failure.
2426 mch_dirname(
2427 char_u *buf,
2428 int len)
2431 * Originally this was:
2432 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2433 * But the Win32s known bug list says that getcwd() doesn't work
2434 * so use the Win32 system call instead. <Negri>
2436 #ifdef FEAT_MBYTE
2437 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2439 WCHAR wbuf[_MAX_PATH + 1];
2441 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2443 char_u *p = utf16_to_enc(wbuf, NULL);
2445 if (p != NULL)
2447 vim_strncpy(buf, p, len - 1);
2448 vim_free(p);
2449 return OK;
2452 /* Retry with non-wide function (for Windows 98). */
2454 #endif
2455 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2459 * get file permissions for `name'
2460 * -1 : error
2461 * else FILE_ATTRIBUTE_* defined in winnt.h
2463 long
2464 mch_getperm(char_u *name)
2466 #ifdef FEAT_MBYTE
2467 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2469 WCHAR *p = enc_to_utf16(name, NULL);
2470 long n;
2472 if (p != NULL)
2474 n = (long)GetFileAttributesW(p);
2475 vim_free(p);
2476 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2477 return n;
2478 /* Retry with non-wide function (for Windows 98). */
2481 #endif
2482 return (long)GetFileAttributes((char *)name);
2487 * set file permission for `name' to `perm'
2490 mch_setperm(
2491 char_u *name,
2492 long perm)
2494 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2495 #ifdef FEAT_MBYTE
2496 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2498 WCHAR *p = enc_to_utf16(name, NULL);
2499 long n;
2501 if (p != NULL)
2503 n = (long)SetFileAttributesW(p, perm);
2504 vim_free(p);
2505 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2506 return n ? OK : FAIL;
2507 /* Retry with non-wide function (for Windows 98). */
2510 #endif
2511 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2515 * Set hidden flag for "name".
2517 void
2518 mch_hide(char_u *name)
2520 int perm;
2521 #ifdef FEAT_MBYTE
2522 WCHAR *p = NULL;
2524 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2525 p = enc_to_utf16(name, NULL);
2526 #endif
2528 #ifdef FEAT_MBYTE
2529 if (p != NULL)
2531 perm = GetFileAttributesW(p);
2532 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2534 /* Retry with non-wide function (for Windows 98). */
2535 vim_free(p);
2536 p = NULL;
2539 if (p == NULL)
2540 #endif
2541 perm = GetFileAttributes((char *)name);
2542 if (perm >= 0)
2544 perm |= FILE_ATTRIBUTE_HIDDEN;
2545 #ifdef FEAT_MBYTE
2546 if (p != NULL)
2548 if (SetFileAttributesW(p, perm) == 0
2549 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2551 /* Retry with non-wide function (for Windows 98). */
2552 vim_free(p);
2553 p = NULL;
2556 if (p == NULL)
2557 #endif
2558 SetFileAttributes((char *)name, perm);
2560 #ifdef FEAT_MBYTE
2561 vim_free(p);
2562 #endif
2566 * return TRUE if "name" is a directory
2567 * return FALSE if "name" is not a directory or upon error
2570 mch_isdir(char_u *name)
2572 int f = mch_getperm(name);
2574 if (f == -1)
2575 return FALSE; /* file does not exist at all */
2577 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2581 * Return TRUE if file "fname" has more than one link.
2584 mch_is_linked(char_u *fname)
2586 HANDLE hFile;
2587 int res = 0;
2588 BY_HANDLE_FILE_INFORMATION inf;
2589 #ifdef FEAT_MBYTE
2590 WCHAR *wn = NULL;
2592 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2593 wn = enc_to_utf16(fname, NULL);
2594 if (wn != NULL)
2596 hFile = CreateFileW(wn, /* file name */
2597 GENERIC_READ, /* access mode */
2598 0, /* share mode */
2599 NULL, /* security descriptor */
2600 OPEN_EXISTING, /* creation disposition */
2601 0, /* file attributes */
2602 NULL); /* handle to template file */
2603 if (hFile == INVALID_HANDLE_VALUE
2604 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2606 /* Retry with non-wide function (for Windows 98). */
2607 vim_free(wn);
2608 wn = NULL;
2611 if (wn == NULL)
2612 #endif
2613 hFile = CreateFile(fname, /* file name */
2614 GENERIC_READ, /* access mode */
2615 0, /* share mode */
2616 NULL, /* security descriptor */
2617 OPEN_EXISTING, /* creation disposition */
2618 0, /* file attributes */
2619 NULL); /* handle to template file */
2621 if (hFile != INVALID_HANDLE_VALUE)
2623 if (GetFileInformationByHandle(hFile, &inf) != 0
2624 && inf.nNumberOfLinks > 1)
2625 res = 1;
2626 CloseHandle(hFile);
2629 #ifdef FEAT_MBYTE
2630 vim_free(wn);
2631 #endif
2632 return res;
2636 * Return TRUE if file or directory "name" is writable (not readonly).
2637 * Strange semantics of Win32: a readonly directory is writable, but you can't
2638 * delete a file. Let's say this means it is writable.
2641 mch_writable(char_u *name)
2643 int perm = mch_getperm(name);
2645 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2646 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2650 * Return 1 if "name" can be executed, 0 if not.
2651 * Return -1 if unknown.
2654 mch_can_exe(char_u *name)
2656 char_u buf[_MAX_PATH];
2657 int len = (int)STRLEN(name);
2658 char_u *p;
2660 if (len >= _MAX_PATH) /* safety check */
2661 return FALSE;
2663 /* If there already is an extension try using the name directly. Also do
2664 * this with a Unix-shell like 'shell'. */
2665 if (vim_strchr(gettail(name), '.') != NULL
2666 || strstr((char *)gettail(p_sh), "sh") != NULL)
2667 if (executable_exists((char *)name))
2668 return TRUE;
2671 * Loop over all extensions in $PATHEXT.
2673 vim_strncpy(buf, name, _MAX_PATH - 1);
2674 p = mch_getenv("PATHEXT");
2675 if (p == NULL)
2676 p = (char_u *)".com;.exe;.bat;.cmd";
2677 while (*p)
2679 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2681 /* A single "." means no extension is added. */
2682 buf[len] = NUL;
2683 ++p;
2684 if (*p)
2685 ++p;
2687 else
2688 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2689 if (executable_exists((char *)buf))
2690 return TRUE;
2692 return FALSE;
2696 * Check what "name" is:
2697 * NODE_NORMAL: file or directory (or doesn't exist)
2698 * NODE_WRITABLE: writable device, socket, fifo, etc.
2699 * NODE_OTHER: non-writable things
2702 mch_nodetype(char_u *name)
2704 HANDLE hFile;
2705 int type;
2707 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2708 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2709 * here. */
2710 if (STRNCMP(name, "\\\\.\\", 4) == 0)
2711 return NODE_WRITABLE;
2713 hFile = CreateFile(name, /* file name */
2714 GENERIC_WRITE, /* access mode */
2715 0, /* share mode */
2716 NULL, /* security descriptor */
2717 OPEN_EXISTING, /* creation disposition */
2718 0, /* file attributes */
2719 NULL); /* handle to template file */
2721 if (hFile == INVALID_HANDLE_VALUE)
2722 return NODE_NORMAL;
2724 type = GetFileType(hFile);
2725 CloseHandle(hFile);
2726 if (type == FILE_TYPE_CHAR)
2727 return NODE_WRITABLE;
2728 if (type == FILE_TYPE_DISK)
2729 return NODE_NORMAL;
2730 return NODE_OTHER;
2733 #ifdef HAVE_ACL
2734 struct my_acl
2736 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2737 PSID pSidOwner;
2738 PSID pSidGroup;
2739 PACL pDacl;
2740 PACL pSacl;
2742 #endif
2745 * Return a pointer to the ACL of file "fname" in allocated memory.
2746 * Return NULL if the ACL is not available for whatever reason.
2748 vim_acl_T
2749 mch_get_acl(char_u *fname)
2751 #ifndef HAVE_ACL
2752 return (vim_acl_T)NULL;
2753 #else
2754 struct my_acl *p = NULL;
2756 /* This only works on Windows NT and 2000. */
2757 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2759 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2760 if (p != NULL)
2762 if (pGetNamedSecurityInfo(
2763 (LPTSTR)fname, // Abstract filename
2764 SE_FILE_OBJECT, // File Object
2765 // Retrieve the entire security descriptor.
2766 OWNER_SECURITY_INFORMATION |
2767 GROUP_SECURITY_INFORMATION |
2768 DACL_SECURITY_INFORMATION |
2769 SACL_SECURITY_INFORMATION,
2770 &p->pSidOwner, // Ownership information.
2771 &p->pSidGroup, // Group membership.
2772 &p->pDacl, // Discretionary information.
2773 &p->pSacl, // For auditing purposes.
2774 &p->pSecurityDescriptor
2775 ) != ERROR_SUCCESS)
2777 mch_free_acl((vim_acl_T)p);
2778 p = NULL;
2783 return (vim_acl_T)p;
2784 #endif
2788 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2789 * Errors are ignored.
2790 * This must only be called with "acl" equal to what mch_get_acl() returned.
2792 void
2793 mch_set_acl(char_u *fname, vim_acl_T acl)
2795 #ifdef HAVE_ACL
2796 struct my_acl *p = (struct my_acl *)acl;
2798 if (p != NULL && advapi_lib != NULL)
2799 (void)pSetNamedSecurityInfo(
2800 (LPTSTR)fname, // Abstract filename
2801 SE_FILE_OBJECT, // File Object
2802 // Retrieve the entire security descriptor.
2803 OWNER_SECURITY_INFORMATION |
2804 GROUP_SECURITY_INFORMATION |
2805 DACL_SECURITY_INFORMATION |
2806 SACL_SECURITY_INFORMATION,
2807 p->pSidOwner, // Ownership information.
2808 p->pSidGroup, // Group membership.
2809 p->pDacl, // Discretionary information.
2810 p->pSacl // For auditing purposes.
2812 #endif
2815 void
2816 mch_free_acl(vim_acl_T acl)
2818 #ifdef HAVE_ACL
2819 struct my_acl *p = (struct my_acl *)acl;
2821 if (p != NULL)
2823 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2824 vim_free(p);
2826 #endif
2829 #ifndef FEAT_GUI_W32
2832 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2834 static BOOL WINAPI
2835 handler_routine(
2836 DWORD dwCtrlType)
2838 switch (dwCtrlType)
2840 case CTRL_C_EVENT:
2841 if (ctrl_c_interrupts)
2842 g_fCtrlCPressed = TRUE;
2843 return TRUE;
2845 case CTRL_BREAK_EVENT:
2846 g_fCBrkPressed = TRUE;
2847 return TRUE;
2849 /* fatal events: shut down gracefully */
2850 case CTRL_CLOSE_EVENT:
2851 case CTRL_LOGOFF_EVENT:
2852 case CTRL_SHUTDOWN_EVENT:
2853 windgoto((int)Rows - 1, 0);
2854 g_fForceExit = TRUE;
2856 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
2857 (dwCtrlType == CTRL_CLOSE_EVENT
2858 ? _("close")
2859 : dwCtrlType == CTRL_LOGOFF_EVENT
2860 ? _("logoff")
2861 : _("shutdown")));
2862 #ifdef DEBUG
2863 OutputDebugString(IObuff);
2864 #endif
2866 preserve_exit(); /* output IObuff, preserve files and exit */
2868 return TRUE; /* not reached */
2870 default:
2871 return FALSE;
2877 * set the tty in (raw) ? "raw" : "cooked" mode
2879 void
2880 mch_settmode(int tmode)
2882 DWORD cmodein;
2883 DWORD cmodeout;
2884 BOOL bEnableHandler;
2886 GetConsoleMode(g_hConIn, &cmodein);
2887 GetConsoleMode(g_hConOut, &cmodeout);
2888 if (tmode == TMODE_RAW)
2890 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2891 ENABLE_ECHO_INPUT);
2892 #ifdef FEAT_MOUSE
2893 if (g_fMouseActive)
2894 cmodein |= ENABLE_MOUSE_INPUT;
2895 #endif
2896 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2897 bEnableHandler = TRUE;
2899 else /* cooked */
2901 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2902 ENABLE_ECHO_INPUT);
2903 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2904 bEnableHandler = FALSE;
2906 SetConsoleMode(g_hConIn, cmodein);
2907 SetConsoleMode(g_hConOut, cmodeout);
2908 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
2910 #ifdef MCH_WRITE_DUMP
2911 if (fdDump)
2913 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
2914 tmode == TMODE_RAW ? "raw" :
2915 tmode == TMODE_COOK ? "cooked" : "normal",
2916 cmodein, cmodeout);
2917 fflush(fdDump);
2919 #endif
2924 * Get the size of the current window in `Rows' and `Columns'
2925 * Return OK when size could be determined, FAIL otherwise.
2928 mch_get_shellsize(void)
2930 CONSOLE_SCREEN_BUFFER_INFO csbi;
2932 if (!g_fTermcapMode && g_cbTermcap.IsValid)
2935 * For some reason, we are trying to get the screen dimensions
2936 * even though we are not in termcap mode. The 'Rows' and 'Columns'
2937 * variables are really intended to mean the size of Vim screen
2938 * while in termcap mode.
2940 Rows = g_cbTermcap.Info.dwSize.Y;
2941 Columns = g_cbTermcap.Info.dwSize.X;
2943 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2945 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2946 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2948 else
2950 Rows = 25;
2951 Columns = 80;
2953 return OK;
2957 * Set a console window to `xSize' * `ySize'
2959 static void
2960 ResizeConBufAndWindow(
2961 HANDLE hConsole,
2962 int xSize,
2963 int ySize)
2965 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
2966 SMALL_RECT srWindowRect; /* hold the new console size */
2967 COORD coordScreen;
2969 #ifdef MCH_WRITE_DUMP
2970 if (fdDump)
2972 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
2973 fflush(fdDump);
2975 #endif
2977 /* get the largest size we can size the console window to */
2978 coordScreen = GetLargestConsoleWindowSize(hConsole);
2980 /* define the new console window size and scroll position */
2981 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
2982 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
2983 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
2985 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2987 int sx, sy;
2989 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2990 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2991 if (sy < ySize || sx < xSize)
2994 * Increasing number of lines/columns, do buffer first.
2995 * Use the maximal size in x and y direction.
2997 if (sy < ySize)
2998 coordScreen.Y = ySize;
2999 else
3000 coordScreen.Y = sy;
3001 if (sx < xSize)
3002 coordScreen.X = xSize;
3003 else
3004 coordScreen.X = sx;
3005 SetConsoleScreenBufferSize(hConsole, coordScreen);
3009 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3011 #ifdef MCH_WRITE_DUMP
3012 if (fdDump)
3014 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3015 GetLastError());
3016 fflush(fdDump);
3018 #endif
3021 /* define the new console buffer size */
3022 coordScreen.X = xSize;
3023 coordScreen.Y = ySize;
3025 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3027 #ifdef MCH_WRITE_DUMP
3028 if (fdDump)
3030 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3031 GetLastError());
3032 fflush(fdDump);
3034 #endif
3040 * Set the console window to `Rows' * `Columns'
3042 void
3043 mch_set_shellsize(void)
3045 COORD coordScreen;
3047 /* Don't change window size while still starting up */
3048 if (suppress_winsize != 0)
3050 suppress_winsize = 2;
3051 return;
3054 if (term_console)
3056 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3058 /* Clamp Rows and Columns to reasonable values */
3059 if (Rows > coordScreen.Y)
3060 Rows = coordScreen.Y;
3061 if (Columns > coordScreen.X)
3062 Columns = coordScreen.X;
3064 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3069 * Rows and/or Columns has changed.
3071 void
3072 mch_new_shellsize(void)
3074 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3079 * Called when started up, to set the winsize that was delayed.
3081 void
3082 mch_set_winsize_now(void)
3084 if (suppress_winsize == 2)
3086 suppress_winsize = 0;
3087 mch_set_shellsize();
3088 shell_resized();
3090 suppress_winsize = 0;
3092 #endif /* FEAT_GUI_W32 */
3096 #if defined(FEAT_GUI_W32) || defined(PROTO)
3099 * Specialised version of system() for Win32 GUI mode.
3100 * This version proceeds as follows:
3101 * 1. Create a console window for use by the subprocess
3102 * 2. Run the subprocess (it gets the allocated console by default)
3103 * 3. Wait for the subprocess to terminate and get its exit code
3104 * 4. Prompt the user to press a key to close the console window
3106 static int
3107 mch_system(char *cmd, int options)
3109 STARTUPINFO si;
3110 PROCESS_INFORMATION pi;
3111 DWORD ret = 0;
3112 HWND hwnd = GetFocus();
3114 si.cb = sizeof(si);
3115 si.lpReserved = NULL;
3116 si.lpDesktop = NULL;
3117 si.lpTitle = NULL;
3118 si.dwFlags = STARTF_USESHOWWINDOW;
3120 * It's nicer to run a filter command in a minimized window, but in
3121 * Windows 95 this makes the command MUCH slower. We can't do it under
3122 * Win32s either as it stops the synchronous spawn workaround working.
3124 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
3125 si.wShowWindow = SW_SHOWMINIMIZED;
3126 else
3127 si.wShowWindow = SW_SHOWNORMAL;
3128 si.cbReserved2 = 0;
3129 si.lpReserved2 = NULL;
3131 /* There is a strange error on Windows 95 when using "c:\\command.com".
3132 * When the "c:\\" is left out it works OK...? */
3133 if (mch_windows95()
3134 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3135 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3136 cmd += 3;
3138 /* Now, run the command */
3139 CreateProcess(NULL, /* Executable name */
3140 cmd, /* Command to execute */
3141 NULL, /* Process security attributes */
3142 NULL, /* Thread security attributes */
3143 FALSE, /* Inherit handles */
3144 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3145 CREATE_NEW_CONSOLE,
3146 NULL, /* Environment */
3147 NULL, /* Current directory */
3148 &si, /* Startup information */
3149 &pi); /* Process information */
3152 /* Wait for the command to terminate before continuing */
3153 if (g_PlatformId != VER_PLATFORM_WIN32s)
3155 #ifdef FEAT_GUI
3156 int delay = 1;
3158 /* Keep updating the window while waiting for the shell to finish. */
3159 for (;;)
3161 MSG msg;
3163 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3165 TranslateMessage(&msg);
3166 DispatchMessage(&msg);
3168 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3169 break;
3171 /* We start waiting for a very short time and then increase it, so
3172 * that we respond quickly when the process is quick, and don't
3173 * consume too much overhead when it's slow. */
3174 if (delay < 50)
3175 delay += 10;
3177 #else
3178 WaitForSingleObject(pi.hProcess, INFINITE);
3179 #endif
3181 /* Get the command exit code */
3182 GetExitCodeProcess(pi.hProcess, &ret);
3184 else
3187 * This ugly code is the only quick way of performing
3188 * a synchronous spawn under Win32s. Yuk.
3190 num_windows = 0;
3191 EnumWindows(win32ssynch_cb, 0);
3192 old_num_windows = num_windows;
3195 Sleep(1000);
3196 num_windows = 0;
3197 EnumWindows(win32ssynch_cb, 0);
3198 } while (num_windows == old_num_windows);
3199 ret = 0;
3202 /* Close the handles to the subprocess, so that it goes away */
3203 CloseHandle(pi.hThread);
3204 CloseHandle(pi.hProcess);
3206 /* Try to get input focus back. Doesn't always work though. */
3207 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3209 return ret;
3211 #else
3213 # define mch_system(c, o) system(c)
3215 #endif
3218 * Either execute a command by calling the shell or start a new shell
3221 mch_call_shell(
3222 char_u *cmd,
3223 int options) /* SHELL_*, see vim.h */
3225 int x = 0;
3226 int tmode = cur_tmode;
3227 #ifdef FEAT_TITLE
3228 char szShellTitle[512];
3230 /* Change the title to reflect that we are in a subshell. */
3231 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3233 if (cmd == NULL)
3234 strcat(szShellTitle, " :sh");
3235 else
3237 strcat(szShellTitle, " - !");
3238 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3239 strcat(szShellTitle, cmd);
3241 mch_settitle(szShellTitle, NULL);
3243 #endif
3245 out_flush();
3247 #ifdef MCH_WRITE_DUMP
3248 if (fdDump)
3250 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3251 fflush(fdDump);
3253 #endif
3256 * Catch all deadly signals while running the external command, because a
3257 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3259 signal(SIGINT, SIG_IGN);
3260 #if defined(__GNUC__) && !defined(__MINGW32__)
3261 signal(SIGKILL, SIG_IGN);
3262 #else
3263 signal(SIGBREAK, SIG_IGN);
3264 #endif
3265 signal(SIGILL, SIG_IGN);
3266 signal(SIGFPE, SIG_IGN);
3267 signal(SIGSEGV, SIG_IGN);
3268 signal(SIGTERM, SIG_IGN);
3269 signal(SIGABRT, SIG_IGN);
3271 if (options & SHELL_COOKED)
3272 settmode(TMODE_COOK); /* set to normal mode */
3274 if (cmd == NULL)
3276 x = mch_system(p_sh, options);
3278 else
3280 /* we use "command" or "cmd" to start the shell; slow but easy */
3281 char_u *newcmd;
3282 long_u cmdlen = (
3283 #ifdef FEAT_GUI_W32
3284 STRLEN(vimrun_path) +
3285 #endif
3286 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
3288 newcmd = lalloc(cmdlen, TRUE);
3289 if (newcmd != NULL)
3291 char_u *cmdbase = (*cmd == '"' ? cmd + 1 : cmd);
3293 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3295 STARTUPINFO si;
3296 PROCESS_INFORMATION pi;
3298 si.cb = sizeof(si);
3299 si.lpReserved = NULL;
3300 si.lpDesktop = NULL;
3301 si.lpTitle = NULL;
3302 si.dwFlags = 0;
3303 si.cbReserved2 = 0;
3304 si.lpReserved2 = NULL;
3306 cmdbase = skipwhite(cmdbase + 5);
3307 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3308 && vim_iswhite(cmdbase[4]))
3310 cmdbase = skipwhite(cmdbase + 4);
3311 si.dwFlags = STARTF_USESHOWWINDOW;
3312 si.wShowWindow = SW_SHOWMINNOACTIVE;
3315 /* When the command is in double quotes, but 'shellxquote' is
3316 * empty, keep the double quotes around the command.
3317 * Otherwise remove the double quotes, they aren't needed
3318 * here, because we don't use a shell to run the command. */
3319 if (*cmd == '"' && *p_sxq == NUL)
3321 newcmd[0] = '"';
3322 STRCPY(newcmd + 1, cmdbase);
3324 else
3326 STRCPY(newcmd, cmdbase);
3327 if (*cmd == '"' && *newcmd != NUL)
3328 newcmd[STRLEN(newcmd) - 1] = NUL;
3332 * Now, start the command as a process, so that it doesn't
3333 * inherit our handles which causes unpleasant dangling swap
3334 * files if we exit before the spawned process
3336 if (CreateProcess (NULL, // Executable name
3337 newcmd, // Command to execute
3338 NULL, // Process security attributes
3339 NULL, // Thread security attributes
3340 FALSE, // Inherit handles
3341 CREATE_NEW_CONSOLE, // Creation flags
3342 NULL, // Environment
3343 NULL, // Current directory
3344 &si, // Startup information
3345 &pi)) // Process information
3346 x = 0;
3347 else
3349 x = -1;
3350 #ifdef FEAT_GUI_W32
3351 EMSG(_("E371: Command not found"));
3352 #endif
3354 /* Close the handles to the subprocess, so that it goes away */
3355 CloseHandle(pi.hThread);
3356 CloseHandle(pi.hProcess);
3358 else
3360 #if defined(FEAT_GUI_W32)
3361 if (need_vimrun_warning)
3363 MessageBox(NULL,
3364 _("VIMRUN.EXE not found in your $PATH.\n"
3365 "External commands will not pause after completion.\n"
3366 "See :help win32-vimrun for more information."),
3367 _("Vim Warning"),
3368 MB_ICONWARNING);
3369 need_vimrun_warning = FALSE;
3371 if (!s_dont_use_vimrun)
3372 /* Use vimrun to execute the command. It opens a console
3373 * window, which can be closed without killing Vim. */
3374 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
3375 vimrun_path,
3376 (msg_silent != 0 || (options & SHELL_DOOUT))
3377 ? "-s " : "",
3378 p_sh, p_shcf, cmd);
3379 else
3380 #endif
3381 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
3382 p_sh, p_shcf, cmd);
3383 x = mch_system((char *)newcmd, options);
3385 vim_free(newcmd);
3389 if (tmode == TMODE_RAW)
3390 settmode(TMODE_RAW); /* set to raw mode */
3392 /* Print the return value, unless "vimrun" was used. */
3393 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
3394 #if defined(FEAT_GUI_W32)
3395 && ((options & SHELL_DOOUT) || s_dont_use_vimrun)
3396 #endif
3399 smsg(_("shell returned %d"), x);
3400 msg_putchar('\n');
3402 #ifdef FEAT_TITLE
3403 resettitle();
3404 #endif
3406 signal(SIGINT, SIG_DFL);
3407 #if defined(__GNUC__) && !defined(__MINGW32__)
3408 signal(SIGKILL, SIG_DFL);
3409 #else
3410 signal(SIGBREAK, SIG_DFL);
3411 #endif
3412 signal(SIGILL, SIG_DFL);
3413 signal(SIGFPE, SIG_DFL);
3414 signal(SIGSEGV, SIG_DFL);
3415 signal(SIGTERM, SIG_DFL);
3416 signal(SIGABRT, SIG_DFL);
3418 return x;
3422 #ifndef FEAT_GUI_W32
3425 * Start termcap mode
3427 static void
3428 termcap_mode_start(void)
3430 DWORD cmodein;
3432 if (g_fTermcapMode)
3433 return;
3435 SaveConsoleBuffer(&g_cbNonTermcap);
3437 if (g_cbTermcap.IsValid)
3440 * We've been in termcap mode before. Restore certain screen
3441 * characteristics, including the buffer size and the window
3442 * size. Since we will be redrawing the screen, we don't need
3443 * to restore the actual contents of the buffer.
3445 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
3446 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
3447 Rows = g_cbTermcap.Info.dwSize.Y;
3448 Columns = g_cbTermcap.Info.dwSize.X;
3450 else
3453 * This is our first time entering termcap mode. Clear the console
3454 * screen buffer, and resize the buffer to match the current window
3455 * size. We will use this as the size of our editing environment.
3457 ClearConsoleBuffer(g_attrCurrent);
3458 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3461 #ifdef FEAT_TITLE
3462 resettitle();
3463 #endif
3465 GetConsoleMode(g_hConIn, &cmodein);
3466 #ifdef FEAT_MOUSE
3467 if (g_fMouseActive)
3468 cmodein |= ENABLE_MOUSE_INPUT;
3469 else
3470 cmodein &= ~ENABLE_MOUSE_INPUT;
3471 #endif
3472 cmodein |= ENABLE_WINDOW_INPUT;
3473 SetConsoleMode(g_hConIn, cmodein);
3475 redraw_later_clear();
3476 g_fTermcapMode = TRUE;
3481 * End termcap mode
3483 static void
3484 termcap_mode_end(void)
3486 DWORD cmodein;
3487 ConsoleBuffer *cb;
3488 COORD coord;
3489 DWORD dwDummy;
3491 if (!g_fTermcapMode)
3492 return;
3494 SaveConsoleBuffer(&g_cbTermcap);
3496 GetConsoleMode(g_hConIn, &cmodein);
3497 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
3498 SetConsoleMode(g_hConIn, cmodein);
3500 #ifdef FEAT_RESTORE_ORIG_SCREEN
3501 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
3502 #else
3503 cb = &g_cbNonTermcap;
3504 #endif
3505 RestoreConsoleBuffer(cb, p_rs);
3506 SetConsoleCursorInfo(g_hConOut, &g_cci);
3508 if (p_rs || exiting)
3511 * Clear anything that happens to be on the current line.
3513 coord.X = 0;
3514 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
3515 FillConsoleOutputCharacter(g_hConOut, ' ',
3516 cb->Info.dwSize.X, coord, &dwDummy);
3518 * The following is just for aesthetics. If we are exiting without
3519 * restoring the screen, then we want to have a prompt string
3520 * appear at the bottom line. However, the command interpreter
3521 * seems to always advance the cursor one line before displaying
3522 * the prompt string, which causes the screen to scroll. To
3523 * counter this, move the cursor up one line before exiting.
3525 if (exiting && !p_rs)
3526 coord.Y--;
3528 * Position the cursor at the leftmost column of the desired row.
3530 SetConsoleCursorPosition(g_hConOut, coord);
3533 g_fTermcapMode = FALSE;
3535 #endif /* FEAT_GUI_W32 */
3538 #ifdef FEAT_GUI_W32
3539 /*ARGSUSED*/
3540 void
3541 mch_write(
3542 char_u *s,
3543 int len)
3545 /* never used */
3548 #else
3551 * clear `n' chars, starting from `coord'
3553 static void
3554 clear_chars(
3555 COORD coord,
3556 DWORD n)
3558 DWORD dwDummy;
3560 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
3561 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
3566 * Clear the screen
3568 static void
3569 clear_screen(void)
3571 g_coord.X = g_coord.Y = 0;
3572 clear_chars(g_coord, Rows * Columns);
3577 * Clear to end of display
3579 static void
3580 clear_to_end_of_display(void)
3582 clear_chars(g_coord, (Rows - g_coord.Y - 1)
3583 * Columns + (Columns - g_coord.X));
3588 * Clear to end of line
3590 static void
3591 clear_to_end_of_line(void)
3593 clear_chars(g_coord, Columns - g_coord.X);
3598 * Scroll the scroll region up by `cLines' lines
3600 static void
3601 scroll(unsigned cLines)
3603 COORD oldcoord = g_coord;
3605 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
3606 delete_lines(cLines);
3608 g_coord = oldcoord;
3613 * Set the scroll region
3615 static void
3616 set_scroll_region(
3617 unsigned left,
3618 unsigned top,
3619 unsigned right,
3620 unsigned bottom)
3622 if (left >= right
3623 || top >= bottom
3624 || right > (unsigned) Columns - 1
3625 || bottom > (unsigned) Rows - 1)
3626 return;
3628 g_srScrollRegion.Left = left;
3629 g_srScrollRegion.Top = top;
3630 g_srScrollRegion.Right = right;
3631 g_srScrollRegion.Bottom = bottom;
3636 * Insert `cLines' lines at the current cursor position
3638 static void
3639 insert_lines(unsigned cLines)
3641 SMALL_RECT source;
3642 COORD dest;
3643 CHAR_INFO fill;
3645 dest.X = 0;
3646 dest.Y = g_coord.Y + cLines;
3648 source.Left = 0;
3649 source.Top = g_coord.Y;
3650 source.Right = g_srScrollRegion.Right;
3651 source.Bottom = g_srScrollRegion.Bottom - cLines;
3653 fill.Char.AsciiChar = ' ';
3654 fill.Attributes = g_attrCurrent;
3656 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3658 /* Here we have to deal with a win32 console flake: If the scroll
3659 * region looks like abc and we scroll c to a and fill with d we get
3660 * cbd... if we scroll block c one line at a time to a, we get cdd...
3661 * vim expects cdd consistently... So we have to deal with that
3662 * here... (this also occurs scrolling the same way in the other
3663 * direction). */
3665 if (source.Bottom < dest.Y)
3667 COORD coord;
3669 coord.X = 0;
3670 coord.Y = source.Bottom;
3671 clear_chars(coord, Columns * (dest.Y - source.Bottom));
3677 * Delete `cLines' lines at the current cursor position
3679 static void
3680 delete_lines(unsigned cLines)
3682 SMALL_RECT source;
3683 COORD dest;
3684 CHAR_INFO fill;
3685 int nb;
3687 dest.X = 0;
3688 dest.Y = g_coord.Y;
3690 source.Left = 0;
3691 source.Top = g_coord.Y + cLines;
3692 source.Right = g_srScrollRegion.Right;
3693 source.Bottom = g_srScrollRegion.Bottom;
3695 fill.Char.AsciiChar = ' ';
3696 fill.Attributes = g_attrCurrent;
3698 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3700 /* Here we have to deal with a win32 console flake: If the scroll
3701 * region looks like abc and we scroll c to a and fill with d we get
3702 * cbd... if we scroll block c one line at a time to a, we get cdd...
3703 * vim expects cdd consistently... So we have to deal with that
3704 * here... (this also occurs scrolling the same way in the other
3705 * direction). */
3707 nb = dest.Y + (source.Bottom - source.Top) + 1;
3709 if (nb < source.Top)
3711 COORD coord;
3713 coord.X = 0;
3714 coord.Y = nb;
3715 clear_chars(coord, Columns * (source.Top - nb));
3721 * Set the cursor position
3723 static void
3724 gotoxy(
3725 unsigned x,
3726 unsigned y)
3728 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
3729 return;
3731 /* external cursor coords are 1-based; internal are 0-based */
3732 g_coord.X = x - 1;
3733 g_coord.Y = y - 1;
3734 SetConsoleCursorPosition(g_hConOut, g_coord);
3739 * Set the current text attribute = (foreground | background)
3740 * See ../doc/os_win32.txt for the numbers.
3742 static void
3743 textattr(WORD wAttr)
3745 g_attrCurrent = wAttr;
3747 SetConsoleTextAttribute(g_hConOut, wAttr);
3751 static void
3752 textcolor(WORD wAttr)
3754 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
3756 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3760 static void
3761 textbackground(WORD wAttr)
3763 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
3765 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3770 * restore the default text attribute (whatever we started with)
3772 static void
3773 normvideo(void)
3775 textattr(g_attrDefault);
3779 static WORD g_attrPreStandout = 0;
3782 * Make the text standout, by brightening it
3784 static void
3785 standout(void)
3787 g_attrPreStandout = g_attrCurrent;
3788 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
3793 * Turn off standout mode
3795 static void
3796 standend(void)
3798 if (g_attrPreStandout)
3800 textattr(g_attrPreStandout);
3801 g_attrPreStandout = 0;
3807 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
3809 void
3810 mch_set_normal_colors(void)
3812 char_u *p;
3813 int n;
3815 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
3816 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
3817 if (T_ME[0] == ESC && T_ME[1] == '|')
3819 p = T_ME + 2;
3820 n = getdigits(&p);
3821 if (*p == 'm' && n > 0)
3823 cterm_normal_fg_color = (n & 0xf) + 1;
3824 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
3831 * visual bell: flash the screen
3833 static void
3834 visual_bell(void)
3836 COORD coordOrigin = {0, 0};
3837 WORD attrFlash = ~g_attrCurrent & 0xff;
3839 DWORD dwDummy;
3840 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
3842 if (oldattrs == NULL)
3843 return;
3844 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3845 coordOrigin, &dwDummy);
3846 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
3847 coordOrigin, &dwDummy);
3849 Sleep(15); /* wait for 15 msec */
3850 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3851 coordOrigin, &dwDummy);
3852 vim_free(oldattrs);
3857 * Make the cursor visible or invisible
3859 static void
3860 cursor_visible(BOOL fVisible)
3862 s_cursor_visible = fVisible;
3863 #ifdef MCH_CURSOR_SHAPE
3864 mch_update_cursor();
3865 #endif
3870 * write `cchToWrite' characters in `pchBuf' to the screen
3871 * Returns the number of characters actually written (at least one).
3873 static BOOL
3874 write_chars(
3875 LPCSTR pchBuf,
3876 DWORD cchToWrite)
3878 COORD coord = g_coord;
3879 DWORD written;
3881 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
3882 coord, &written);
3883 /* When writing fails or didn't write a single character, pretend one
3884 * character was written, otherwise we get stuck. */
3885 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
3886 coord, &written) == 0
3887 || written == 0)
3888 written = 1;
3890 g_coord.X += (SHORT) written;
3892 while (g_coord.X > g_srScrollRegion.Right)
3894 g_coord.X -= (SHORT) Columns;
3895 if (g_coord.Y < g_srScrollRegion.Bottom)
3896 g_coord.Y++;
3899 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3901 return written;
3906 * mch_write(): write the output buffer to the screen, translating ESC
3907 * sequences into calls to console output routines.
3909 void
3910 mch_write(
3911 char_u *s,
3912 int len)
3914 s[len] = NUL;
3916 if (!term_console)
3918 write(1, s, (unsigned)len);
3919 return;
3922 /* translate ESC | sequences into faked bios calls */
3923 while (len--)
3925 /* optimization: use one single write_chars for runs of text,
3926 * rather than once per character It ain't curses, but it helps. */
3927 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
3929 if (p_wd)
3931 WaitForChar(p_wd);
3932 if (prefix != 0)
3933 prefix = 1;
3936 if (prefix != 0)
3938 DWORD nWritten;
3940 nWritten = write_chars(s, prefix);
3941 #ifdef MCH_WRITE_DUMP
3942 if (fdDump)
3944 fputc('>', fdDump);
3945 fwrite(s, sizeof(char_u), nWritten, fdDump);
3946 fputs("<\n", fdDump);
3948 #endif
3949 len -= (nWritten - 1);
3950 s += nWritten;
3952 else if (s[0] == '\n')
3954 /* \n, newline: go to the beginning of the next line or scroll */
3955 if (g_coord.Y == g_srScrollRegion.Bottom)
3957 scroll(1);
3958 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
3960 else
3962 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
3964 #ifdef MCH_WRITE_DUMP
3965 if (fdDump)
3966 fputs("\\n\n", fdDump);
3967 #endif
3968 s++;
3970 else if (s[0] == '\r')
3972 /* \r, carriage return: go to beginning of line */
3973 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
3974 #ifdef MCH_WRITE_DUMP
3975 if (fdDump)
3976 fputs("\\r\n", fdDump);
3977 #endif
3978 s++;
3980 else if (s[0] == '\b')
3982 /* \b, backspace: move cursor one position left */
3983 if (g_coord.X > g_srScrollRegion.Left)
3984 g_coord.X--;
3985 else if (g_coord.Y > g_srScrollRegion.Top)
3987 g_coord.X = g_srScrollRegion.Right;
3988 g_coord.Y--;
3990 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3991 #ifdef MCH_WRITE_DUMP
3992 if (fdDump)
3993 fputs("\\b\n", fdDump);
3994 #endif
3995 s++;
3997 else if (s[0] == '\a')
3999 /* \a, bell */
4000 MessageBeep(0xFFFFFFFF);
4001 #ifdef MCH_WRITE_DUMP
4002 if (fdDump)
4003 fputs("\\a\n", fdDump);
4004 #endif
4005 s++;
4007 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4009 #ifdef MCH_WRITE_DUMP
4010 char_u *old_s = s;
4011 #endif
4012 char_u *p;
4013 int arg1 = 0, arg2 = 0;
4015 switch (s[2])
4017 /* one or two numeric arguments, separated by ';' */
4019 case '0': case '1': case '2': case '3': case '4':
4020 case '5': case '6': case '7': case '8': case '9':
4021 p = s + 2;
4022 arg1 = getdigits(&p); /* no check for length! */
4023 if (p > s + len)
4024 break;
4026 if (*p == ';')
4028 ++p;
4029 arg2 = getdigits(&p); /* no check for length! */
4030 if (p > s + len)
4031 break;
4033 if (*p == 'H')
4034 gotoxy(arg2, arg1);
4035 else if (*p == 'r')
4036 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4038 else if (*p == 'A')
4040 /* move cursor up arg1 lines in same column */
4041 gotoxy(g_coord.X + 1,
4042 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4044 else if (*p == 'C')
4046 /* move cursor right arg1 columns in same line */
4047 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4048 g_coord.Y + 1);
4050 else if (*p == 'H')
4052 gotoxy(1, arg1);
4054 else if (*p == 'L')
4056 insert_lines(arg1);
4058 else if (*p == 'm')
4060 if (arg1 == 0)
4061 normvideo();
4062 else
4063 textattr((WORD) arg1);
4065 else if (*p == 'f')
4067 textcolor((WORD) arg1);
4069 else if (*p == 'b')
4071 textbackground((WORD) arg1);
4073 else if (*p == 'M')
4075 delete_lines(arg1);
4078 len -= (int)(p - s);
4079 s = p + 1;
4080 break;
4083 /* Three-character escape sequences */
4085 case 'A':
4086 /* move cursor up one line in same column */
4087 gotoxy(g_coord.X + 1,
4088 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4089 goto got3;
4091 case 'B':
4092 visual_bell();
4093 goto got3;
4095 case 'C':
4096 /* move cursor right one column in same line */
4097 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4098 g_coord.Y + 1);
4099 goto got3;
4101 case 'E':
4102 termcap_mode_end();
4103 goto got3;
4105 case 'F':
4106 standout();
4107 goto got3;
4109 case 'f':
4110 standend();
4111 goto got3;
4113 case 'H':
4114 gotoxy(1, 1);
4115 goto got3;
4117 case 'j':
4118 clear_to_end_of_display();
4119 goto got3;
4121 case 'J':
4122 clear_screen();
4123 goto got3;
4125 case 'K':
4126 clear_to_end_of_line();
4127 goto got3;
4129 case 'L':
4130 insert_lines(1);
4131 goto got3;
4133 case 'M':
4134 delete_lines(1);
4135 goto got3;
4137 case 'S':
4138 termcap_mode_start();
4139 goto got3;
4141 case 'V':
4142 cursor_visible(TRUE);
4143 goto got3;
4145 case 'v':
4146 cursor_visible(FALSE);
4147 goto got3;
4149 got3:
4150 s += 3;
4151 len -= 2;
4154 #ifdef MCH_WRITE_DUMP
4155 if (fdDump)
4157 fputs("ESC | ", fdDump);
4158 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4159 fputc('\n', fdDump);
4161 #endif
4163 else
4165 /* Write a single character */
4166 DWORD nWritten;
4168 nWritten = write_chars(s, 1);
4169 #ifdef MCH_WRITE_DUMP
4170 if (fdDump)
4172 fputc('>', fdDump);
4173 fwrite(s, sizeof(char_u), nWritten, fdDump);
4174 fputs("<\n", fdDump);
4176 #endif
4178 len -= (nWritten - 1);
4179 s += nWritten;
4183 #ifdef MCH_WRITE_DUMP
4184 if (fdDump)
4185 fflush(fdDump);
4186 #endif
4189 #endif /* FEAT_GUI_W32 */
4193 * Delay for half a second.
4195 /*ARGSUSED*/
4196 void
4197 mch_delay(
4198 long msec,
4199 int ignoreinput)
4201 #ifdef FEAT_GUI_W32
4202 Sleep((int)msec); /* never wait for input */
4203 #else /* Console */
4204 if (ignoreinput)
4205 # ifdef FEAT_MZSCHEME
4206 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4208 int towait = p_mzq;
4210 /* if msec is large enough, wait by portions in p_mzq */
4211 while (msec > 0)
4213 mzvim_check_threads();
4214 if (msec < towait)
4215 towait = msec;
4216 Sleep(towait);
4217 msec -= towait;
4220 else
4221 # endif
4222 Sleep((int)msec);
4223 else
4224 WaitForChar(msec);
4225 #endif
4230 * this version of remove is not scared by a readonly (backup) file
4231 * Return 0 for success, -1 for failure.
4234 mch_remove(char_u *name)
4236 #ifdef FEAT_MBYTE
4237 WCHAR *wn = NULL;
4238 int n;
4240 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4242 wn = enc_to_utf16(name, NULL);
4243 if (wn != NULL)
4245 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4246 n = DeleteFileW(wn) ? 0 : -1;
4247 vim_free(wn);
4248 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4249 return n;
4250 /* Retry with non-wide function (for Windows 98). */
4253 #endif
4254 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4255 return DeleteFile(name) ? 0 : -1;
4260 * check for an "interrupt signal": CTRL-break or CTRL-C
4262 void
4263 mch_breakcheck(void)
4265 #ifndef FEAT_GUI_W32 /* never used */
4266 if (g_fCtrlCPressed || g_fCBrkPressed)
4268 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4269 got_int = TRUE;
4271 #endif
4276 * How much memory is available?
4277 * Return sum of available physical and page file memory.
4279 /*ARGSUSED*/
4280 long_u
4281 mch_avail_mem(int special)
4283 MEMORYSTATUS ms;
4285 ms.dwLength = sizeof(MEMORYSTATUS);
4286 GlobalMemoryStatus(&ms);
4287 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
4290 #ifdef FEAT_MBYTE
4292 * Same code as below, but with wide functions and no comments.
4293 * Return 0 for success, non-zero for failure.
4296 mch_wrename(WCHAR *wold, WCHAR *wnew)
4298 WCHAR *p;
4299 int i;
4300 WCHAR szTempFile[_MAX_PATH + 1];
4301 WCHAR szNewPath[_MAX_PATH + 1];
4302 HANDLE hf;
4304 if (!mch_windows95())
4306 p = wold;
4307 for (i = 0; wold[i] != NUL; ++i)
4308 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
4309 && wold[i + 1] != 0)
4310 p = wold + i + 1;
4311 if ((int)(wold + i - p) < 8 || p[6] != '~')
4312 return (MoveFileW(wold, wnew) == 0);
4315 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
4316 return -1;
4317 *p = NUL;
4319 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
4320 return -2;
4322 if (!DeleteFileW(szTempFile))
4323 return -3;
4325 if (!MoveFileW(wold, szTempFile))
4326 return -4;
4328 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4329 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4330 return -5;
4331 if (!CloseHandle(hf))
4332 return -6;
4334 if (!MoveFileW(szTempFile, wnew))
4336 (void)MoveFileW(szTempFile, wold);
4337 return -7;
4340 DeleteFileW(szTempFile);
4342 if (!DeleteFileW(wold))
4343 return -8;
4345 return 0;
4347 #endif
4351 * mch_rename() works around a bug in rename (aka MoveFile) in
4352 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4353 * file whose short file name is "FOO.BAR" (its long file name will
4354 * be correct: "foo.bar~"). Because a file can be accessed by
4355 * either its SFN or its LFN, "foo.bar" has effectively been
4356 * renamed to "foo.bar", which is not at all what was wanted. This
4357 * seems to happen only when renaming files with three-character
4358 * extensions by appending a suffix that does not include ".".
4359 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4361 * There is another problem, which isn't really a bug but isn't right either:
4362 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
4363 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
4364 * service pack 6. Doesn't seem to happen on Windows 98.
4366 * Like rename(), returns 0 upon success, non-zero upon failure.
4367 * Should probably set errno appropriately when errors occur.
4370 mch_rename(
4371 const char *pszOldFile,
4372 const char *pszNewFile)
4374 char szTempFile[_MAX_PATH+1];
4375 char szNewPath[_MAX_PATH+1];
4376 char *pszFilePart;
4377 HANDLE hf;
4378 #ifdef FEAT_MBYTE
4379 WCHAR *wold = NULL;
4380 WCHAR *wnew = NULL;
4381 int retval = -1;
4383 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4385 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
4386 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
4387 if (wold != NULL && wnew != NULL)
4388 retval = mch_wrename(wold, wnew);
4389 vim_free(wold);
4390 vim_free(wnew);
4391 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4392 return retval;
4393 /* Retry with non-wide function (for Windows 98). */
4395 #endif
4398 * No need to play tricks if not running Windows 95, unless the file name
4399 * contains a "~" as the seventh character.
4401 if (!mch_windows95())
4403 pszFilePart = (char *)gettail((char_u *)pszOldFile);
4404 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
4405 return rename(pszOldFile, pszNewFile);
4408 /* Get base path of new file name. Undocumented feature: If pszNewFile is
4409 * a directory, no error is returned and pszFilePart will be NULL. */
4410 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
4411 || pszFilePart == NULL)
4412 return -1;
4413 *pszFilePart = NUL;
4415 /* Get (and create) a unique temporary file name in directory of new file */
4416 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
4417 return -2;
4419 /* blow the temp file away */
4420 if (!DeleteFile(szTempFile))
4421 return -3;
4423 /* rename old file to the temp file */
4424 if (!MoveFile(pszOldFile, szTempFile))
4425 return -4;
4427 /* now create an empty file called pszOldFile; this prevents the operating
4428 * system using pszOldFile as an alias (SFN) if we're renaming within the
4429 * same directory. For example, we're editing a file called
4430 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
4431 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
4432 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
4433 * cause all sorts of problems later in buf_write(). So, we create an
4434 * empty file called filena~1.txt and the system will have to find some
4435 * other SFN for filena~1.txt~, such as filena~2.txt
4437 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4438 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4439 return -5;
4440 if (!CloseHandle(hf))
4441 return -6;
4443 /* rename the temp file to the new file */
4444 if (!MoveFile(szTempFile, pszNewFile))
4446 /* Renaming failed. Rename the file back to its old name, so that it
4447 * looks like nothing happened. */
4448 (void)MoveFile(szTempFile, pszOldFile);
4450 return -7;
4453 /* Seems to be left around on Novell filesystems */
4454 DeleteFile(szTempFile);
4456 /* finally, remove the empty old file */
4457 if (!DeleteFile(pszOldFile))
4458 return -8;
4460 return 0; /* success */
4464 * Get the default shell for the current hardware platform
4466 char *
4467 default_shell(void)
4469 char* psz = NULL;
4471 PlatformId();
4473 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
4474 psz = "cmd.exe";
4475 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
4476 psz = "command.com";
4478 return psz;
4482 * mch_access() extends access() to do more detailed check on network drives.
4483 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
4486 mch_access(char *n, int p)
4488 HANDLE hFile;
4489 DWORD am;
4490 int retval = -1; /* default: fail */
4491 #ifdef FEAT_MBYTE
4492 WCHAR *wn = NULL;
4494 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4495 wn = enc_to_utf16(n, NULL);
4496 #endif
4498 if (mch_isdir(n))
4500 char TempName[_MAX_PATH + 16] = "";
4501 #ifdef FEAT_MBYTE
4502 WCHAR TempNameW[_MAX_PATH + 16] = L"";
4503 #endif
4505 if (p & R_OK)
4507 /* Read check is performed by seeing if we can do a find file on
4508 * the directory for any file. */
4509 #ifdef FEAT_MBYTE
4510 if (wn != NULL)
4512 int i;
4513 WIN32_FIND_DATAW d;
4515 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
4516 TempNameW[i] = wn[i];
4517 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
4518 TempNameW[i++] = '\\';
4519 TempNameW[i++] = '*';
4520 TempNameW[i++] = 0;
4522 hFile = FindFirstFileW(TempNameW, &d);
4523 if (hFile == INVALID_HANDLE_VALUE)
4525 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4526 goto getout;
4528 /* Retry with non-wide function (for Windows 98). */
4529 vim_free(wn);
4530 wn = NULL;
4532 else
4533 (void)FindClose(hFile);
4535 if (wn == NULL)
4536 #endif
4538 char *pch;
4539 WIN32_FIND_DATA d;
4541 vim_strncpy(TempName, n, _MAX_PATH);
4542 pch = TempName + STRLEN(TempName) - 1;
4543 if (*pch != '\\' && *pch != '/')
4544 *++pch = '\\';
4545 *++pch = '*';
4546 *++pch = NUL;
4548 hFile = FindFirstFile(TempName, &d);
4549 if (hFile == INVALID_HANDLE_VALUE)
4550 goto getout;
4551 (void)FindClose(hFile);
4555 if (p & W_OK)
4557 /* Trying to create a temporary file in the directory should catch
4558 * directories on read-only network shares. However, in
4559 * directories whose ACL allows writes but denies deletes will end
4560 * up keeping the temporary file :-(. */
4561 #ifdef FEAT_MBYTE
4562 if (wn != NULL)
4564 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
4566 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4567 goto getout;
4569 /* Retry with non-wide function (for Windows 98). */
4570 vim_free(wn);
4571 wn = NULL;
4573 else
4574 DeleteFileW(TempNameW);
4576 if (wn == NULL)
4577 #endif
4579 if (!GetTempFileName(n, "VIM", 0, TempName))
4580 goto getout;
4581 mch_remove((char_u *)TempName);
4585 else
4587 /* Trying to open the file for the required access does ACL, read-only
4588 * network share, and file attribute checks. */
4589 am = ((p & W_OK) ? GENERIC_WRITE : 0)
4590 | ((p & R_OK) ? GENERIC_READ : 0);
4591 #ifdef FEAT_MBYTE
4592 if (wn != NULL)
4594 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4595 if (hFile == INVALID_HANDLE_VALUE
4596 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4598 /* Retry with non-wide function (for Windows 98). */
4599 vim_free(wn);
4600 wn = NULL;
4603 if (wn == NULL)
4604 #endif
4605 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4606 if (hFile == INVALID_HANDLE_VALUE)
4607 goto getout;
4608 CloseHandle(hFile);
4611 retval = 0; /* success */
4612 getout:
4613 #ifdef FEAT_MBYTE
4614 vim_free(wn);
4615 #endif
4616 return retval;
4619 #if defined(FEAT_MBYTE) || defined(PROTO)
4621 * Version of open() that may use UTF-16 file name.
4624 mch_open(char *name, int flags, int mode)
4626 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
4627 # ifndef __BORLANDC__
4628 WCHAR *wn;
4629 int f;
4631 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4633 wn = enc_to_utf16(name, NULL);
4634 if (wn != NULL)
4636 f = _wopen(wn, flags, mode);
4637 vim_free(wn);
4638 if (f >= 0)
4639 return f;
4640 /* Retry with non-wide function (for Windows 98). Can't use
4641 * GetLastError() here and it's unclear what errno gets set to if
4642 * the _wopen() fails for missing wide functions. */
4645 # endif
4647 return open(name, flags, mode);
4651 * Version of fopen() that may use UTF-16 file name.
4653 FILE *
4654 mch_fopen(char *name, char *mode)
4656 WCHAR *wn, *wm;
4657 FILE *f = NULL;
4659 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
4660 # ifdef __BORLANDC__
4661 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4662 && g_PlatformId == VER_PLATFORM_WIN32_NT
4663 # endif
4666 # if defined(DEBUG) && _MSC_VER >= 1400
4667 /* Work around an annoying assertion in the Microsoft debug CRT
4668 * when mode's text/binary setting doesn't match _get_fmode(). */
4669 char newMode = mode[strlen(mode) - 1];
4670 int oldMode = 0;
4672 _get_fmode(&oldMode);
4673 if (newMode == 't')
4674 _set_fmode(_O_TEXT);
4675 else if (newMode == 'b')
4676 _set_fmode(_O_BINARY);
4677 # endif
4678 wn = enc_to_utf16(name, NULL);
4679 wm = enc_to_utf16(mode, NULL);
4680 if (wn != NULL && wm != NULL)
4681 f = _wfopen(wn, wm);
4682 vim_free(wn);
4683 vim_free(wm);
4685 # if defined(DEBUG) && _MSC_VER >= 1400
4686 _set_fmode(oldMode);
4687 # endif
4689 if (f != NULL)
4690 return f;
4691 /* Retry with non-wide function (for Windows 98). Can't use
4692 * GetLastError() here and it's unclear what errno gets set to if
4693 * the _wfopen() fails for missing wide functions. */
4696 return fopen(name, mode);
4698 #endif
4700 #ifdef FEAT_MBYTE
4702 * SUB STREAM (aka info stream) handling:
4704 * NTFS can have sub streams for each file. Normal contents of file is
4705 * stored in the main stream, and extra contents (author information and
4706 * title and so on) can be stored in sub stream. After Windows 2000, user
4707 * can access and store those informations in sub streams via explorer's
4708 * property menuitem in right click menu. Those informations in sub streams
4709 * were lost when copying only the main stream. So we have to copy sub
4710 * streams.
4712 * Incomplete explanation:
4713 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
4714 * More useful info and an example:
4715 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
4719 * Copy info stream data "substream". Read from the file with BackupRead(sh)
4720 * and write to stream "substream" of file "to".
4721 * Errors are ignored.
4723 static void
4724 copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
4726 HANDLE hTo;
4727 WCHAR *to_name;
4729 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
4730 wcscpy(to_name, to);
4731 wcscat(to_name, substream);
4733 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
4734 FILE_ATTRIBUTE_NORMAL, NULL);
4735 if (hTo != INVALID_HANDLE_VALUE)
4737 long done;
4738 DWORD todo;
4739 DWORD readcnt, written;
4740 char buf[4096];
4742 /* Copy block of bytes at a time. Abort when something goes wrong. */
4743 for (done = 0; done < len; done += written)
4745 /* (size_t) cast for Borland C 5.5 */
4746 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
4747 : (size_t)(len - done));
4748 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
4749 FALSE, FALSE, context)
4750 || readcnt != todo
4751 || !WriteFile(hTo, buf, todo, &written, NULL)
4752 || written != todo)
4753 break;
4755 CloseHandle(hTo);
4758 free(to_name);
4762 * Copy info streams from file "from" to file "to".
4764 static void
4765 copy_infostreams(char_u *from, char_u *to)
4767 WCHAR *fromw;
4768 WCHAR *tow;
4769 HANDLE sh;
4770 WIN32_STREAM_ID sid;
4771 int headersize;
4772 WCHAR streamname[_MAX_PATH];
4773 DWORD readcount;
4774 void *context = NULL;
4775 DWORD lo, hi;
4776 int len;
4778 /* Convert the file names to wide characters. */
4779 fromw = enc_to_utf16(from, NULL);
4780 tow = enc_to_utf16(to, NULL);
4781 if (fromw != NULL && tow != NULL)
4783 /* Open the file for reading. */
4784 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
4785 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4786 if (sh != INVALID_HANDLE_VALUE)
4788 /* Use BackupRead() to find the info streams. Repeat until we
4789 * have done them all.*/
4790 for (;;)
4792 /* Get the header to find the length of the stream name. If
4793 * the "readcount" is zero we have done all info streams. */
4794 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
4795 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
4796 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
4797 &readcount, FALSE, FALSE, &context)
4798 || readcount == 0)
4799 break;
4801 /* We only deal with streams that have a name. The normal
4802 * file data appears to be without a name, even though docs
4803 * suggest it is called "::$DATA". */
4804 if (sid.dwStreamNameSize > 0)
4806 /* Read the stream name. */
4807 if (!BackupRead(sh, (LPBYTE)streamname,
4808 sid.dwStreamNameSize,
4809 &readcount, FALSE, FALSE, &context))
4810 break;
4812 /* Copy an info stream with a name ":anything:$DATA".
4813 * Skip "::$DATA", it has no stream name (examples suggest
4814 * it might be used for the normal file contents).
4815 * Note that BackupRead() counts bytes, but the name is in
4816 * wide characters. */
4817 len = readcount / sizeof(WCHAR);
4818 streamname[len] = 0;
4819 if (len > 7 && wcsicmp(streamname + len - 6,
4820 L":$DATA") == 0)
4822 streamname[len - 6] = 0;
4823 copy_substream(sh, &context, tow, streamname,
4824 (long)sid.Size.u.LowPart);
4828 /* Advance to the next stream. We might try seeking too far,
4829 * but BackupSeek() doesn't skip over stream borders, thus
4830 * that's OK. */
4831 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
4832 &lo, &hi, &context);
4835 /* Clear the context. */
4836 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
4838 CloseHandle(sh);
4841 vim_free(fromw);
4842 vim_free(tow);
4844 #endif
4847 * Copy file attributes from file "from" to file "to".
4848 * For Windows NT and later we copy info streams.
4849 * Always returns zero, errors are ignored.
4852 mch_copy_file_attribute(char_u *from, char_u *to)
4854 #ifdef FEAT_MBYTE
4855 /* File streams only work on Windows NT and later. */
4856 PlatformId();
4857 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
4858 copy_infostreams(from, to);
4859 #endif
4860 return 0;
4863 #if defined(MYRESETSTKOFLW) || defined(PROTO)
4865 * Recreate a destroyed stack guard page in win32.
4866 * Written by Benjamin Peterson.
4869 /* These magic numbers are from the MS header files */
4870 #define MIN_STACK_WIN9X 17
4871 #define MIN_STACK_WINNT 2
4874 * This function does the same thing as _resetstkoflw(), which is only
4875 * available in DevStudio .net and later.
4876 * Returns 0 for failure, 1 for success.
4879 myresetstkoflw(void)
4881 BYTE *pStackPtr;
4882 BYTE *pGuardPage;
4883 BYTE *pStackBase;
4884 BYTE *pLowestPossiblePage;
4885 MEMORY_BASIC_INFORMATION mbi;
4886 SYSTEM_INFO si;
4887 DWORD nPageSize;
4888 DWORD dummy;
4890 /* This code will not work on win32s. */
4891 PlatformId();
4892 if (g_PlatformId == VER_PLATFORM_WIN32s)
4893 return 0;
4895 /* We need to know the system page size. */
4896 GetSystemInfo(&si);
4897 nPageSize = si.dwPageSize;
4899 /* ...and the current stack pointer */
4900 pStackPtr = (BYTE*)_alloca(1);
4902 /* ...and the base of the stack. */
4903 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
4904 return 0;
4905 pStackBase = (BYTE*)mbi.AllocationBase;
4907 /* ...and the page thats min_stack_req pages away from stack base; this is
4908 * the lowest page we could use. */
4909 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
4910 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
4912 /* On Win95, we want the next page down from the end of the stack. */
4913 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
4915 /* Find the page that's only 1 page down from the page that the stack
4916 * ptr is in. */
4917 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
4918 / (DWORD)nPageSize) - 1));
4919 if (pGuardPage < pLowestPossiblePage)
4920 return 0;
4922 /* Apply the noaccess attribute to the page -- there's no guard
4923 * attribute in win95-type OSes. */
4924 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
4925 return 0;
4927 else
4929 /* On NT, however, we want the first committed page in the stack Start
4930 * at the stack base and move forward through memory until we find a
4931 * committed block. */
4932 BYTE *pBlock = pStackBase;
4934 for (;;)
4936 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
4937 return 0;
4939 pBlock += mbi.RegionSize;
4941 if (mbi.State & MEM_COMMIT)
4942 break;
4945 /* mbi now describes the first committed block in the stack. */
4946 if (mbi.Protect & PAGE_GUARD)
4947 return 1;
4949 /* decide where the guard page should start */
4950 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
4951 pGuardPage = pLowestPossiblePage;
4952 else
4953 pGuardPage = (BYTE*)mbi.BaseAddress;
4955 /* allocate the guard page */
4956 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
4957 return 0;
4959 /* apply the guard attribute to the page */
4960 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
4961 &dummy))
4962 return 0;
4965 return 1;
4967 #endif
4970 #if defined(FEAT_MBYTE) || defined(PROTO)
4972 * The command line arguments in UCS2
4974 static int nArgsW = 0;
4975 static LPWSTR *ArglistW = NULL;
4976 static int global_argc = 0;
4977 static char **global_argv;
4979 static int used_file_argc = 0; /* last argument in global_argv[] used
4980 for the argument list. */
4981 static int *used_file_indexes = NULL; /* indexes in global_argv[] for
4982 command line arguments added to
4983 the argument list */
4984 static int used_file_count = 0; /* nr of entries in used_file_indexes */
4985 static int used_file_literal = FALSE; /* take file names literally */
4986 static int used_file_full_path = FALSE; /* file name was full path */
4987 static int used_file_diff_mode = FALSE; /* file name was with diff mode */
4988 static int used_alist_count = 0;
4992 * Get the command line arguments. Unicode version.
4993 * Returns argc. Zero when something fails.
4996 get_cmd_argsW(char ***argvp)
4998 char **argv = NULL;
4999 int argc = 0;
5000 int i;
5002 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5003 if (ArglistW != NULL)
5005 argv = malloc((nArgsW + 1) * sizeof(char *));
5006 if (argv != NULL)
5008 argc = nArgsW;
5009 argv[argc] = NULL;
5010 for (i = 0; i < argc; ++i)
5012 int len;
5014 /* Convert each Unicode argument to the current codepage. */
5015 WideCharToMultiByte_alloc(GetACP(), 0,
5016 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
5017 (LPSTR *)&argv[i], &len, 0, 0);
5018 if (argv[i] == NULL)
5020 /* Out of memory, clear everything. */
5021 while (i > 0)
5022 free(argv[--i]);
5023 free(argv);
5024 argc = 0;
5030 global_argc = argc;
5031 global_argv = argv;
5032 if (argc > 0)
5033 used_file_indexes = malloc(argc * sizeof(int));
5035 if (argvp != NULL)
5036 *argvp = argv;
5037 return argc;
5040 void
5041 free_cmd_argsW(void)
5043 if (ArglistW != NULL)
5045 GlobalFree(ArglistW);
5046 ArglistW = NULL;
5051 * Remember "name" is an argument that was added to the argument list.
5052 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5053 * is called.
5055 void
5056 used_file_arg(char *name, int literal, int full_path, int diff_mode)
5058 int i;
5060 if (used_file_indexes == NULL)
5061 return;
5062 for (i = used_file_argc + 1; i < global_argc; ++i)
5063 if (STRCMP(global_argv[i], name) == 0)
5065 used_file_argc = i;
5066 used_file_indexes[used_file_count++] = i;
5067 break;
5069 used_file_literal = literal;
5070 used_file_full_path = full_path;
5071 used_file_diff_mode = diff_mode;
5075 * Remember the length of the argument list as it was. If it changes then we
5076 * leave it alone when 'encoding' is set.
5078 void
5079 set_alist_count(void)
5081 used_alist_count = GARGCOUNT;
5085 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5086 * has been changed while starting up. Use the UCS-2 command line arguments
5087 * and convert them to 'encoding'.
5089 void
5090 fix_arg_enc(void)
5092 int i;
5093 int idx;
5094 char_u *str;
5095 int *fnum_list;
5097 /* Safety checks:
5098 * - if argument count differs between the wide and non-wide argument
5099 * list, something must be wrong.
5100 * - the file name arguments must have been located.
5101 * - the length of the argument list wasn't changed by the user.
5103 if (global_argc != nArgsW
5104 || ArglistW == NULL
5105 || used_file_indexes == NULL
5106 || used_file_count == 0
5107 || used_alist_count != GARGCOUNT)
5108 return;
5110 /* Remember the buffer numbers for the arguments. */
5111 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5112 if (fnum_list == NULL)
5113 return; /* out of memory */
5114 for (i = 0; i < GARGCOUNT; ++i)
5115 fnum_list[i] = GARGLIST[i].ae_fnum;
5117 /* Clear the argument list. Make room for the new arguments. */
5118 alist_clear(&global_alist);
5119 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
5120 return; /* out of memory */
5122 for (i = 0; i < used_file_count; ++i)
5124 idx = used_file_indexes[i];
5125 str = utf16_to_enc(ArglistW[idx], NULL);
5126 if (str != NULL)
5128 #ifdef FEAT_DIFF
5129 /* When using diff mode may need to concatenate file name to
5130 * directory name. Just like it's done in main(). */
5131 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5132 && !mch_isdir(alist_name(&GARGLIST[0])))
5134 char_u *r;
5136 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5137 if (r != NULL)
5139 vim_free(str);
5140 str = r;
5143 #endif
5144 /* Re-use the old buffer by renaming it. When not using literal
5145 * names it's done by alist_expand() below. */
5146 if (used_file_literal)
5147 buf_set_name(fnum_list[i], str);
5149 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
5153 if (!used_file_literal)
5155 /* Now expand wildcards in the arguments. */
5156 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5157 * filename characters but are excluded from 'isfname' to make
5158 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5159 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
5160 alist_expand(fnum_list, used_alist_count);
5161 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5164 /* If wildcard expansion failed, we are editing the first file of the
5165 * arglist and there is no file name: Edit the first argument now. */
5166 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5168 do_cmdline_cmd((char_u *)":rewind");
5169 if (GARGCOUNT == 1 && used_file_full_path)
5170 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5173 set_alist_count();
5175 #endif