Add previous/next window key binding
[MacVim/KaoriYa.git] / src / os_win32.c
blob7d9e1477897ce12a483f4d619f025012fe5007cd
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_WITHENC
249 # define GETTEXT_DLL_WITHENC "libintl2.dll"
250 # endif
251 # ifndef GETTEXT_DLL
252 # define GETTEXT_DLL "libintl.dll"
253 # endif
254 /* Dummy funcitons */
255 static char *null_libintl_gettext(const char *);
256 static char *null_libintl_textdomain(const char *);
257 static char *null_libintl_bindtextdomain(const char *, const char *);
258 static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
260 static HINSTANCE hLibintlDLL = 0;
261 char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
262 char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
263 char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
264 = null_libintl_bindtextdomain;
265 char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
266 = null_libintl_bind_textdomain_codeset;
269 dyn_libintl_init(char *libname)
271 int i;
272 static struct
274 char *name;
275 FARPROC *ptr;
276 } libintl_entry[] =
278 {"gettext", (FARPROC*)&dyn_libintl_gettext},
279 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
280 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
281 {NULL, NULL}
284 /* No need to initialize twice. */
285 if (hLibintlDLL)
286 return 1;
287 /* Load gettext library (libintl.dll) */
289 * Priority:
290 * 1. libname if it isn't NULL.
291 * 2. GETTEXT_DLL_WITHENC to convert encodings.
292 * 3. GETTEXT_DLL to use message in only native encoding.
294 if (libname != NULL)
296 hLibintlDLL = LoadLibrary(libname);
297 /* If failed to load libname, try to load default libraries. */
299 if (hLibintlDLL == NULL)
301 hLibintlDLL = LoadLibrary(GETTEXT_DLL_WITHENC);
302 if (hLibintlDLL == NULL)
303 hLibintlDLL = LoadLibrary(GETTEXT_DLL);
305 /* Get functions of gettext library. */
306 if (!hLibintlDLL)
308 char_u dirname[_MAX_PATH];
310 /* Try using the path from gvim.exe to find the .dll there. */
311 get_exe_name();
312 STRCPY(dirname, exe_name);
313 STRCPY(gettail(dirname), GETTEXT_DLL);
314 hLibintlDLL = LoadLibrary((char *)dirname);
315 if (!hLibintlDLL)
317 if (p_verbose > 0)
319 verbose_enter();
320 EMSG2(_(e_loadlib), GETTEXT_DLL);
321 verbose_leave();
323 return 0;
326 for (i = 0; libintl_entry[i].name != NULL
327 && libintl_entry[i].ptr != NULL; ++i)
329 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
330 libintl_entry[i].name)) == NULL)
332 dyn_libintl_end();
333 if (p_verbose > 0)
335 verbose_enter();
336 EMSG2(_(e_loadfunc), libintl_entry[i].name);
337 verbose_leave();
339 return 0;
343 /* The bind_textdomain_codeset() function is optional. */
344 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
345 "bind_textdomain_codeset");
346 if (dyn_libintl_bind_textdomain_codeset == NULL)
347 dyn_libintl_bind_textdomain_codeset =
348 null_libintl_bind_textdomain_codeset;
350 return 1;
353 void
354 dyn_libintl_end()
356 if (hLibintlDLL)
357 FreeLibrary(hLibintlDLL);
358 hLibintlDLL = NULL;
359 dyn_libintl_gettext = null_libintl_gettext;
360 dyn_libintl_textdomain = null_libintl_textdomain;
361 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
362 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
365 /*ARGSUSED*/
366 static char *
367 null_libintl_gettext(const char *msgid)
369 return (char*)msgid;
372 /*ARGSUSED*/
373 static char *
374 null_libintl_bindtextdomain(const char *domainname, const char *dirname)
376 return NULL;
379 /*ARGSUSED*/
380 static char *
381 null_libintl_bind_textdomain_codeset(const char *domainname,
382 const char *codeset)
384 return NULL;
387 /*ARGSUSED*/
388 static char *
389 null_libintl_textdomain(const char *domainname)
391 return NULL;
394 #endif /* DYNAMIC_GETTEXT */
396 /* This symbol is not defined in older versions of the SDK or Visual C++ */
398 #ifndef VER_PLATFORM_WIN32_WINDOWS
399 # define VER_PLATFORM_WIN32_WINDOWS 1
400 #endif
402 DWORD g_PlatformId;
404 #ifdef HAVE_ACL
405 # include <aclapi.h>
407 * These are needed to dynamically load the ADVAPI DLL, which is not
408 * implemented under Windows 95 (and causes VIM to crash)
410 typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
411 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
412 typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
413 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
414 PSECURITY_DESCRIPTOR *);
416 static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
417 static PSNSECINFO pSetNamedSecurityInfo;
418 static PGNSECINFO pGetNamedSecurityInfo;
419 #endif
422 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
423 * VER_PLATFORM_WIN32_WINDOWS (Win95).
425 void
426 PlatformId(void)
428 static int done = FALSE;
430 if (!done)
432 OSVERSIONINFO ovi;
434 ovi.dwOSVersionInfoSize = sizeof(ovi);
435 GetVersionEx(&ovi);
437 g_PlatformId = ovi.dwPlatformId;
439 #ifdef HAVE_ACL
441 * Load the ADVAPI runtime if we are on anything
442 * other than Windows 95
444 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
447 * do this load. Problems: Doesn't unload at end of run (this is
448 * theoretically okay, since Windows should unload it when VIM
449 * terminates). Should we be using the 'mch_libcall' routines?
450 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
451 * time we verify security...
453 advapi_lib = LoadLibrary("ADVAPI32.DLL");
454 if (advapi_lib != NULL)
456 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
457 "SetNamedSecurityInfoA");
458 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
459 "GetNamedSecurityInfoA");
460 if (pSetNamedSecurityInfo == NULL
461 || pGetNamedSecurityInfo == NULL)
463 /* If we can't get the function addresses, set advapi_lib
464 * to NULL so that we don't use them. */
465 FreeLibrary(advapi_lib);
466 advapi_lib = NULL;
470 #endif
471 done = TRUE;
476 * Return TRUE when running on Windows 95 (or 98 or ME).
477 * Only to be used after mch_init().
480 mch_windows95(void)
482 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
485 #ifdef FEAT_GUI_W32
487 * Used to work around the "can't do synchronous spawn"
488 * problem on Win32s, without resorting to Universal Thunk.
490 static int old_num_windows;
491 static int num_windows;
493 /*ARGSUSED*/
494 static BOOL CALLBACK
495 win32ssynch_cb(HWND hwnd, LPARAM lparam)
497 num_windows++;
498 return TRUE;
500 #endif
502 #ifndef FEAT_GUI_W32
504 #define SHIFT (SHIFT_PRESSED)
505 #define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
506 #define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
507 #define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
510 /* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
511 * We map function keys to their ANSI terminal equivalents, as produced
512 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
513 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
514 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
515 * combinations of function/arrow/etc keys.
518 static const struct
520 WORD wVirtKey;
521 BOOL fAnsiKey;
522 int chAlone;
523 int chShift;
524 int chCtrl;
525 int chAlt;
526 } VirtKeyMap[] =
529 /* Key ANSI alone shift ctrl alt */
530 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
532 { VK_F1, TRUE, ';', 'T', '^', 'h', },
533 { VK_F2, TRUE, '<', 'U', '_', 'i', },
534 { VK_F3, TRUE, '=', 'V', '`', 'j', },
535 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
536 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
537 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
538 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
539 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
540 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
541 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
542 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
543 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
545 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
546 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
547 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
548 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
549 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
550 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
551 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
552 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
553 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
554 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
556 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
558 #if 0
559 /* Most people don't have F13-F20, but what the hell... */
560 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
561 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
562 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
563 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
564 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
565 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
566 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
567 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
568 #endif
569 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
570 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
571 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
572 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
574 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
575 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
576 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
577 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
578 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
579 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
580 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
581 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
582 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
583 /* Sorry, out of number space! <negri>*/
584 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
589 #ifdef _MSC_VER
590 // The ToAscii bug destroys several registers. Need to turn off optimization
591 // or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
592 # pragma warning(push)
593 # pragma warning(disable: 4748)
594 # pragma optimize("", off)
595 #endif
597 #if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
598 # define AChar AsciiChar
599 #else
600 # define AChar uChar.AsciiChar
601 #endif
603 /* The return code indicates key code size. */
604 static int
605 #ifdef __BORLANDC__
606 __stdcall
607 #endif
608 win32_kbd_patch_key(
609 KEY_EVENT_RECORD *pker)
611 UINT uMods = pker->dwControlKeyState;
612 static int s_iIsDead = 0;
613 static WORD awAnsiCode[2];
614 static BYTE abKeystate[256];
617 if (s_iIsDead == 2)
619 pker->AChar = (CHAR) awAnsiCode[1];
620 s_iIsDead = 0;
621 return 1;
624 if (pker->AChar != 0)
625 return 1;
627 memset(abKeystate, 0, sizeof (abKeystate));
629 // Should only be non-NULL on NT 4.0
630 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
632 CHAR szKLID[KL_NAMELENGTH];
634 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
635 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
638 /* Clear any pending dead keys */
639 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
641 if (uMods & SHIFT_PRESSED)
642 abKeystate[VK_SHIFT] = 0x80;
643 if (uMods & CAPSLOCK_ON)
644 abKeystate[VK_CAPITAL] = 1;
646 if ((uMods & ALT_GR) == ALT_GR)
648 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
649 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
652 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
653 abKeystate, awAnsiCode, 0);
655 if (s_iIsDead > 0)
656 pker->AChar = (CHAR) awAnsiCode[0];
658 return s_iIsDead;
661 #ifdef _MSC_VER
662 /* MUST switch optimization on again here, otherwise a call to
663 * decode_key_event() may crash (e.g. when hitting caps-lock) */
664 # pragma optimize("", on)
665 # pragma warning(pop)
667 # if (_MSC_VER < 1100)
668 /* MUST turn off global optimisation for this next function, or
669 * pressing ctrl-minus in insert mode crashes Vim when built with
670 * VC4.1. -- negri. */
671 # pragma optimize("g", off)
672 # endif
673 #endif
675 static BOOL g_fJustGotFocus = FALSE;
678 * Decode a KEY_EVENT into one or two keystrokes
680 static BOOL
681 decode_key_event(
682 KEY_EVENT_RECORD *pker,
683 char_u *pch,
684 char_u *pch2,
685 int *pmodifiers,
686 BOOL fDoPost)
688 int i;
689 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
691 *pch = *pch2 = NUL;
692 g_fJustGotFocus = FALSE;
694 /* ignore key up events */
695 if (!pker->bKeyDown)
696 return FALSE;
698 /* ignore some keystrokes */
699 switch (pker->wVirtualKeyCode)
701 /* modifiers */
702 case VK_SHIFT:
703 case VK_CONTROL:
704 case VK_MENU: /* Alt key */
705 return FALSE;
707 default:
708 break;
711 /* special cases */
712 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
714 /* Ctrl-6 is Ctrl-^ */
715 if (pker->wVirtualKeyCode == '6')
717 *pch = Ctrl_HAT;
718 return TRUE;
720 /* Ctrl-2 is Ctrl-@ */
721 else if (pker->wVirtualKeyCode == '2')
723 *pch = NUL;
724 return TRUE;
726 /* Ctrl-- is Ctrl-_ */
727 else if (pker->wVirtualKeyCode == 0xBD)
729 *pch = Ctrl__;
730 return TRUE;
734 /* Shift-TAB */
735 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
737 *pch = K_NUL;
738 *pch2 = '\017';
739 return TRUE;
742 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
744 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
746 if (nModifs == 0)
747 *pch = VirtKeyMap[i].chAlone;
748 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
749 *pch = VirtKeyMap[i].chShift;
750 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
751 *pch = VirtKeyMap[i].chCtrl;
752 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
753 *pch = VirtKeyMap[i].chAlt;
755 if (*pch != 0)
757 if (VirtKeyMap[i].fAnsiKey)
759 *pch2 = *pch;
760 *pch = K_NUL;
763 return TRUE;
768 i = win32_kbd_patch_key(pker);
770 if (i < 0)
771 *pch = NUL;
772 else
774 *pch = (i > 0) ? pker->AChar : NUL;
776 if (pmodifiers != NULL)
778 /* Pass on the ALT key as a modifier, but only when not combined
779 * with CTRL (which is ALTGR). */
780 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
781 *pmodifiers |= MOD_MASK_ALT;
783 /* Pass on SHIFT only for special keys, because we don't know when
784 * it's already included with the character. */
785 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
786 *pmodifiers |= MOD_MASK_SHIFT;
788 /* Pass on CTRL only for non-special keys, because we don't know
789 * when it's already included with the character. And not when
790 * combined with ALT (which is ALTGR). */
791 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
792 && *pch >= 0x20 && *pch < 0x80)
793 *pmodifiers |= MOD_MASK_CTRL;
797 return (*pch != NUL);
800 #ifdef _MSC_VER
801 # pragma optimize("", on)
802 #endif
804 #endif /* FEAT_GUI_W32 */
807 #ifdef FEAT_MOUSE
810 * For the GUI the mouse handling is in gui_w32.c.
812 # ifdef FEAT_GUI_W32
813 /*ARGSUSED*/
814 void
815 mch_setmouse(int on)
818 # else
819 static int g_fMouseAvail = FALSE; /* mouse present */
820 static int g_fMouseActive = FALSE; /* mouse enabled */
821 static int g_nMouseClick = -1; /* mouse status */
822 static int g_xMouse; /* mouse x coordinate */
823 static int g_yMouse; /* mouse y coordinate */
826 * Enable or disable mouse input
828 void
829 mch_setmouse(int on)
831 DWORD cmodein;
833 if (!g_fMouseAvail)
834 return;
836 g_fMouseActive = on;
837 GetConsoleMode(g_hConIn, &cmodein);
839 if (g_fMouseActive)
840 cmodein |= ENABLE_MOUSE_INPUT;
841 else
842 cmodein &= ~ENABLE_MOUSE_INPUT;
844 SetConsoleMode(g_hConIn, cmodein);
849 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
850 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
851 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
852 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
853 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
854 * and we return the mouse position in g_xMouse and g_yMouse.
856 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
857 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
858 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
860 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
861 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
863 * Windows will send us MOUSE_MOVED notifications whenever the mouse
864 * moves, even if it stays within the same character cell. We ignore
865 * all MOUSE_MOVED messages if the position hasn't really changed, and
866 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
867 * we're only interested in MOUSE_DRAG).
869 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
870 * 2-button mouses by pressing the left & right buttons simultaneously.
871 * In practice, it's almost impossible to click both at the same time,
872 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
873 * in such cases, if the user is clicking quickly.
875 static BOOL
876 decode_mouse_event(
877 MOUSE_EVENT_RECORD *pmer)
879 static int s_nOldButton = -1;
880 static int s_nOldMouseClick = -1;
881 static int s_xOldMouse = -1;
882 static int s_yOldMouse = -1;
883 static linenr_T s_old_topline = 0;
884 #ifdef FEAT_DIFF
885 static int s_old_topfill = 0;
886 #endif
887 static int s_cClicks = 1;
888 static BOOL s_fReleased = TRUE;
889 static DWORD s_dwLastClickTime = 0;
890 static BOOL s_fNextIsMiddle = FALSE;
892 static DWORD cButtons = 0; /* number of buttons supported */
894 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
895 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
896 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
897 const DWORD LEFT_RIGHT = LEFT | RIGHT;
899 int nButton;
901 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
902 cButtons = 2;
904 if (!g_fMouseAvail || !g_fMouseActive)
906 g_nMouseClick = -1;
907 return FALSE;
910 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
911 if (g_fJustGotFocus)
913 g_fJustGotFocus = FALSE;
914 return FALSE;
917 /* unprocessed mouse click? */
918 if (g_nMouseClick != -1)
919 return TRUE;
921 nButton = -1;
922 g_xMouse = pmer->dwMousePosition.X;
923 g_yMouse = pmer->dwMousePosition.Y;
925 if (pmer->dwEventFlags == MOUSE_MOVED)
927 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
928 * events even when the mouse moves only within a char cell.) */
929 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
930 return FALSE;
933 /* If no buttons are pressed... */
934 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
936 /* If the last thing returned was MOUSE_RELEASE, ignore this */
937 if (s_fReleased)
938 return FALSE;
940 nButton = MOUSE_RELEASE;
941 s_fReleased = TRUE;
943 else /* one or more buttons pressed */
945 /* on a 2-button mouse, hold down left and right buttons
946 * simultaneously to get MIDDLE. */
948 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
950 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
952 /* if either left or right button only is pressed, see if the
953 * the next mouse event has both of them pressed */
954 if (dwLR == LEFT || dwLR == RIGHT)
956 for (;;)
958 /* wait a short time for next input event */
959 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
960 != WAIT_OBJECT_0)
961 break;
962 else
964 DWORD cRecords = 0;
965 INPUT_RECORD ir;
966 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
968 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
970 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
971 || !(pmer2->dwButtonState & LEFT_RIGHT))
972 break;
973 else
975 if (pmer2->dwEventFlags != MOUSE_MOVED)
977 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
979 return decode_mouse_event(pmer2);
981 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
982 s_yOldMouse == pmer2->dwMousePosition.Y)
984 /* throw away spurious mouse move */
985 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
987 /* are there any more mouse events in queue? */
988 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
990 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
991 break;
993 else
994 break;
1001 if (s_fNextIsMiddle)
1003 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1004 ? MOUSE_DRAG : MOUSE_MIDDLE;
1005 s_fNextIsMiddle = FALSE;
1007 else if (cButtons == 2 &&
1008 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1010 nButton = MOUSE_MIDDLE;
1012 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1014 s_fNextIsMiddle = TRUE;
1015 nButton = MOUSE_RELEASE;
1018 else if ((pmer->dwButtonState & LEFT) == LEFT)
1019 nButton = MOUSE_LEFT;
1020 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1021 nButton = MOUSE_MIDDLE;
1022 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1023 nButton = MOUSE_RIGHT;
1025 if (! s_fReleased && ! s_fNextIsMiddle
1026 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1027 return FALSE;
1029 s_fReleased = s_fNextIsMiddle;
1032 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1034 /* button pressed or released, without mouse moving */
1035 if (nButton != -1 && nButton != MOUSE_RELEASE)
1037 DWORD dwCurrentTime = GetTickCount();
1039 if (s_xOldMouse != g_xMouse
1040 || s_yOldMouse != g_yMouse
1041 || s_nOldButton != nButton
1042 || s_old_topline != curwin->w_topline
1043 #ifdef FEAT_DIFF
1044 || s_old_topfill != curwin->w_topfill
1045 #endif
1046 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1048 s_cClicks = 1;
1050 else if (++s_cClicks > 4)
1052 s_cClicks = 1;
1055 s_dwLastClickTime = dwCurrentTime;
1058 else if (pmer->dwEventFlags == MOUSE_MOVED)
1060 if (nButton != -1 && nButton != MOUSE_RELEASE)
1061 nButton = MOUSE_DRAG;
1063 s_cClicks = 1;
1066 if (nButton == -1)
1067 return FALSE;
1069 if (nButton != MOUSE_RELEASE)
1070 s_nOldButton = nButton;
1072 g_nMouseClick = nButton;
1074 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1075 g_nMouseClick |= MOUSE_SHIFT;
1076 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1077 g_nMouseClick |= MOUSE_CTRL;
1078 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1079 g_nMouseClick |= MOUSE_ALT;
1081 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1082 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1084 /* only pass on interesting (i.e., different) mouse events */
1085 if (s_xOldMouse == g_xMouse
1086 && s_yOldMouse == g_yMouse
1087 && s_nOldMouseClick == g_nMouseClick)
1089 g_nMouseClick = -1;
1090 return FALSE;
1093 s_xOldMouse = g_xMouse;
1094 s_yOldMouse = g_yMouse;
1095 s_old_topline = curwin->w_topline;
1096 #ifdef FEAT_DIFF
1097 s_old_topfill = curwin->w_topfill;
1098 #endif
1099 s_nOldMouseClick = g_nMouseClick;
1101 return TRUE;
1104 # endif /* FEAT_GUI_W32 */
1105 #endif /* FEAT_MOUSE */
1108 #ifdef MCH_CURSOR_SHAPE
1110 * Set the shape of the cursor.
1111 * 'thickness' can be from 1 (thin) to 99 (block)
1113 static void
1114 mch_set_cursor_shape(int thickness)
1116 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1117 ConsoleCursorInfo.dwSize = thickness;
1118 ConsoleCursorInfo.bVisible = s_cursor_visible;
1120 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1121 if (s_cursor_visible)
1122 SetConsoleCursorPosition(g_hConOut, g_coord);
1125 void
1126 mch_update_cursor(void)
1128 int idx;
1129 int thickness;
1132 * How the cursor is drawn depends on the current mode.
1134 idx = get_shape_idx(FALSE);
1136 if (shape_table[idx].shape == SHAPE_BLOCK)
1137 thickness = 99; /* 100 doesn't work on W95 */
1138 else
1139 thickness = shape_table[idx].percentage;
1140 mch_set_cursor_shape(thickness);
1142 #endif
1144 #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1146 * Handle FOCUS_EVENT.
1148 static void
1149 handle_focus_event(INPUT_RECORD ir)
1151 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1152 ui_focus_change((int)g_fJustGotFocus);
1156 * Wait until console input from keyboard or mouse is available,
1157 * or the time is up.
1158 * Return TRUE if something is available FALSE if not.
1160 static int
1161 WaitForChar(long msec)
1163 DWORD dwNow = 0, dwEndTime = 0;
1164 INPUT_RECORD ir;
1165 DWORD cRecords;
1166 char_u ch, ch2;
1168 if (msec > 0)
1169 /* Wait until the specified time has elapsed. */
1170 dwEndTime = GetTickCount() + msec;
1171 else if (msec < 0)
1172 /* Wait forever. */
1173 dwEndTime = INFINITE;
1175 /* We need to loop until the end of the time period, because
1176 * we might get multiple unusable mouse events in that time.
1178 for (;;)
1180 #ifdef FEAT_MZSCHEME
1181 mzvim_check_threads();
1182 #endif
1183 #ifdef FEAT_CLIENTSERVER
1184 serverProcessPendingMessages();
1185 #endif
1186 if (0
1187 #ifdef FEAT_MOUSE
1188 || g_nMouseClick != -1
1189 #endif
1190 #ifdef FEAT_CLIENTSERVER
1191 || input_available()
1192 #endif
1194 return TRUE;
1196 if (msec > 0)
1198 /* If the specified wait time has passed, return. */
1199 dwNow = GetTickCount();
1200 if (dwNow >= dwEndTime)
1201 break;
1203 if (msec != 0)
1205 DWORD dwWaitTime = dwEndTime - dwNow;
1207 #ifdef FEAT_MZSCHEME
1208 if (mzthreads_allowed() && p_mzq > 0
1209 && (msec < 0 || (long)dwWaitTime > p_mzq))
1210 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1211 #endif
1212 #ifdef FEAT_CLIENTSERVER
1213 /* Wait for either an event on the console input or a message in
1214 * the client-server window. */
1215 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
1216 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
1217 #else
1218 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
1219 #endif
1220 continue;
1223 cRecords = 0;
1224 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1226 #ifdef FEAT_MBYTE_IME
1227 if (State & CMDLINE && msg_row == Rows - 1)
1229 CONSOLE_SCREEN_BUFFER_INFO csbi;
1231 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1233 if (csbi.dwCursorPosition.Y != msg_row)
1235 /* The screen is now messed up, must redraw the
1236 * command line and later all the windows. */
1237 redraw_all_later(CLEAR);
1238 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1239 redrawcmd();
1243 #endif
1245 if (cRecords > 0)
1247 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1249 #ifdef FEAT_MBYTE_IME
1250 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1251 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1252 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1253 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1255 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1256 continue;
1258 #endif
1259 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1260 NULL, FALSE))
1261 return TRUE;
1264 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1266 if (ir.EventType == FOCUS_EVENT)
1267 handle_focus_event(ir);
1268 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1269 shell_resized();
1270 #ifdef FEAT_MOUSE
1271 else if (ir.EventType == MOUSE_EVENT
1272 && decode_mouse_event(&ir.Event.MouseEvent))
1273 return TRUE;
1274 #endif
1276 else if (msec == 0)
1277 break;
1280 #ifdef FEAT_CLIENTSERVER
1281 /* Something might have been received while we were waiting. */
1282 if (input_available())
1283 return TRUE;
1284 #endif
1285 return FALSE;
1288 #ifndef FEAT_GUI_MSWIN
1290 * return non-zero if a character is available
1293 mch_char_avail(void)
1295 return WaitForChar(0L);
1297 #endif
1300 * Create the console input. Used when reading stdin doesn't work.
1302 static void
1303 create_conin(void)
1305 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1306 FILE_SHARE_READ|FILE_SHARE_WRITE,
1307 (LPSECURITY_ATTRIBUTES) NULL,
1308 OPEN_EXISTING, 0, (HANDLE)NULL);
1309 did_create_conin = TRUE;
1313 * Get a keystroke or a mouse event
1315 static char_u
1316 tgetch(int *pmodifiers, char_u *pch2)
1318 char_u ch;
1320 for (;;)
1322 INPUT_RECORD ir;
1323 DWORD cRecords = 0;
1325 #ifdef FEAT_CLIENTSERVER
1326 (void)WaitForChar(-1L);
1327 if (input_available())
1328 return 0;
1329 # ifdef FEAT_MOUSE
1330 if (g_nMouseClick != -1)
1331 return 0;
1332 # endif
1333 #endif
1334 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1336 if (did_create_conin)
1337 read_error_exit();
1338 create_conin();
1339 continue;
1342 if (ir.EventType == KEY_EVENT)
1344 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1345 pmodifiers, TRUE))
1346 return ch;
1348 else if (ir.EventType == FOCUS_EVENT)
1349 handle_focus_event(ir);
1350 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1351 shell_resized();
1352 #ifdef FEAT_MOUSE
1353 else if (ir.EventType == MOUSE_EVENT)
1355 if (decode_mouse_event(&ir.Event.MouseEvent))
1356 return 0;
1358 #endif
1361 #endif /* !FEAT_GUI_W32 */
1365 * mch_inchar(): low-level input funcion.
1366 * Get one or more characters from the keyboard or the mouse.
1367 * If time == 0, do not wait for characters.
1368 * If time == n, wait a short time for characters.
1369 * If time == -1, wait forever for characters.
1370 * Returns the number of characters read into buf.
1372 /*ARGSUSED*/
1374 mch_inchar(
1375 char_u *buf,
1376 int maxlen,
1377 long time,
1378 int tb_change_cnt)
1380 #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1382 int len;
1383 int c;
1384 #define TYPEAHEADLEN 20
1385 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1386 static int typeaheadlen = 0;
1388 /* First use any typeahead that was kept because "buf" was too small. */
1389 if (typeaheadlen > 0)
1390 goto theend;
1392 #ifdef FEAT_SNIFF
1393 if (want_sniff_request)
1395 if (sniff_request_waiting)
1397 /* return K_SNIFF */
1398 typeahead[typeaheadlen++] = CSI;
1399 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1400 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1401 sniff_request_waiting = 0;
1402 want_sniff_request = 0;
1403 goto theend;
1405 else if (time < 0 || time > 250)
1407 /* don't wait too long, a request might be pending */
1408 time = 250;
1411 #endif
1413 if (time >= 0)
1415 if (!WaitForChar(time)) /* no character available */
1416 return 0;
1418 else /* time == -1, wait forever */
1420 mch_set_winsize_now(); /* Allow winsize changes from now on */
1423 * If there is no character available within 2 seconds (default)
1424 * write the autoscript file to disk. Or cause the CursorHold event
1425 * to be triggered.
1427 if (!WaitForChar(p_ut))
1429 #ifdef FEAT_AUTOCMD
1430 if (trigger_cursorhold() && maxlen >= 3)
1432 buf[0] = K_SPECIAL;
1433 buf[1] = KS_EXTRA;
1434 buf[2] = (int)KE_CURSORHOLD;
1435 return 3;
1437 #endif
1438 before_blocking();
1443 * Try to read as many characters as there are, until the buffer is full.
1446 /* we will get at least one key. Get more if they are available. */
1447 g_fCBrkPressed = FALSE;
1449 #ifdef MCH_WRITE_DUMP
1450 if (fdDump)
1451 fputc('[', fdDump);
1452 #endif
1454 /* Keep looping until there is something in the typeahead buffer and more
1455 * to get and still room in the buffer (up to two bytes for a char and
1456 * three bytes for a modifier). */
1457 while ((typeaheadlen == 0 || WaitForChar(0L))
1458 && typeaheadlen + 5 <= TYPEAHEADLEN)
1460 if (typebuf_changed(tb_change_cnt))
1462 /* "buf" may be invalid now if a client put something in the
1463 * typeahead buffer and "buf" is in the typeahead buffer. */
1464 typeaheadlen = 0;
1465 break;
1467 #ifdef FEAT_MOUSE
1468 if (g_nMouseClick != -1)
1470 # ifdef MCH_WRITE_DUMP
1471 if (fdDump)
1472 fprintf(fdDump, "{%02x @ %d, %d}",
1473 g_nMouseClick, g_xMouse, g_yMouse);
1474 # endif
1475 typeahead[typeaheadlen++] = ESC + 128;
1476 typeahead[typeaheadlen++] = 'M';
1477 typeahead[typeaheadlen++] = g_nMouseClick;
1478 typeahead[typeaheadlen++] = g_xMouse + '!';
1479 typeahead[typeaheadlen++] = g_yMouse + '!';
1480 g_nMouseClick = -1;
1482 else
1483 #endif
1485 char_u ch2 = NUL;
1486 int modifiers = 0;
1488 c = tgetch(&modifiers, &ch2);
1490 if (typebuf_changed(tb_change_cnt))
1492 /* "buf" may be invalid now if a client put something in the
1493 * typeahead buffer and "buf" is in the typeahead buffer. */
1494 typeaheadlen = 0;
1495 break;
1498 if (c == Ctrl_C && ctrl_c_interrupts)
1500 #if defined(FEAT_CLIENTSERVER)
1501 trash_input_buf();
1502 #endif
1503 got_int = TRUE;
1506 #ifdef FEAT_MOUSE
1507 if (g_nMouseClick == -1)
1508 #endif
1510 int n = 1;
1512 /* A key may have one or two bytes. */
1513 typeahead[typeaheadlen] = c;
1514 if (ch2 != NUL)
1516 typeahead[typeaheadlen + 1] = ch2;
1517 ++n;
1519 #ifdef FEAT_MBYTE
1520 /* Only convert normal characters, not special keys. Need to
1521 * convert before applying ALT, otherwise mapping <M-x> breaks
1522 * when 'tenc' is set. */
1523 if (input_conv.vc_type != CONV_NONE
1524 && (ch2 == NUL || c != K_NUL))
1525 n = convert_input(typeahead + typeaheadlen, n,
1526 TYPEAHEADLEN - typeaheadlen);
1527 #endif
1529 /* Use the ALT key to set the 8th bit of the character
1530 * when it's one byte, the 8th bit isn't set yet and not
1531 * using a double-byte encoding (would become a lead
1532 * byte). */
1533 if ((modifiers & MOD_MASK_ALT)
1534 && n == 1
1535 && (typeahead[typeaheadlen] & 0x80) == 0
1536 #ifdef FEAT_MBYTE
1537 && !enc_dbcs
1538 #endif
1541 #ifdef FEAT_MBYTE
1542 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1543 typeahead + typeaheadlen);
1544 #else
1545 typeahead[typeaheadlen] |= 0x80;
1546 #endif
1547 modifiers &= ~MOD_MASK_ALT;
1550 if (modifiers != 0)
1552 /* Prepend modifiers to the character. */
1553 mch_memmove(typeahead + typeaheadlen + 3,
1554 typeahead + typeaheadlen, n);
1555 typeahead[typeaheadlen++] = K_SPECIAL;
1556 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1557 typeahead[typeaheadlen++] = modifiers;
1560 typeaheadlen += n;
1562 #ifdef MCH_WRITE_DUMP
1563 if (fdDump)
1564 fputc(c, fdDump);
1565 #endif
1570 #ifdef MCH_WRITE_DUMP
1571 if (fdDump)
1573 fputs("]\n", fdDump);
1574 fflush(fdDump);
1576 #endif
1578 theend:
1579 /* Move typeahead to "buf", as much as fits. */
1580 len = 0;
1581 while (len < maxlen && typeaheadlen > 0)
1583 buf[len++] = typeahead[0];
1584 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1586 return len;
1588 #else /* FEAT_GUI_W32 */
1589 return 0;
1590 #endif /* FEAT_GUI_W32 */
1593 #ifndef __MINGW32__
1594 # include <shellapi.h> /* required for FindExecutable() */
1595 #endif
1598 * Return TRUE if "name" is in $PATH.
1599 * TODO: Should somehow check if it's really executable.
1601 static int
1602 executable_exists(char *name)
1604 char *dum;
1605 char fname[_MAX_PATH];
1607 #ifdef FEAT_MBYTE
1608 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1610 WCHAR *p = enc_to_utf16(name, NULL);
1611 WCHAR fnamew[_MAX_PATH];
1612 WCHAR *dumw;
1613 long n;
1615 if (p != NULL)
1617 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1618 vim_free(p);
1619 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1621 if (n == 0)
1622 return FALSE;
1623 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1624 return FALSE;
1625 return TRUE;
1627 /* Retry with non-wide function (for Windows 98). */
1630 #endif
1631 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1632 return FALSE;
1633 if (mch_isdir(fname))
1634 return FALSE;
1635 return TRUE;
1638 #ifdef FEAT_GUI_W32
1641 * GUI version of mch_init().
1643 void
1644 mch_init(void)
1646 #ifndef __MINGW32__
1647 extern int _fmode;
1648 #endif
1650 /* Let critical errors result in a failure, not in a dialog box. Required
1651 * for the timestamp test to work on removed floppies. */
1652 SetErrorMode(SEM_FAILCRITICALERRORS);
1654 _fmode = O_BINARY; /* we do our own CR-LF translation */
1656 /* Specify window size. Is there a place to get the default from? */
1657 Rows = 25;
1658 Columns = 80;
1660 /* Look for 'vimrun' */
1661 if (!gui_is_win32s())
1663 char_u vimrun_location[_MAX_PATH + 4];
1665 /* First try in same directory as gvim.exe */
1666 STRCPY(vimrun_location, exe_name);
1667 STRCPY(gettail(vimrun_location), "vimrun.exe");
1668 if (mch_getperm(vimrun_location) >= 0)
1670 if (*skiptowhite(vimrun_location) != NUL)
1672 /* Enclose path with white space in double quotes. */
1673 mch_memmove(vimrun_location + 1, vimrun_location,
1674 STRLEN(vimrun_location) + 1);
1675 *vimrun_location = '"';
1676 STRCPY(gettail(vimrun_location), "vimrun\" ");
1678 else
1679 STRCPY(gettail(vimrun_location), "vimrun ");
1681 vimrun_path = (char *)vim_strsave(vimrun_location);
1682 s_dont_use_vimrun = FALSE;
1684 else if (executable_exists("vimrun.exe"))
1685 s_dont_use_vimrun = FALSE;
1687 /* Don't give the warning for a missing vimrun.exe right now, but only
1688 * when vimrun was supposed to be used. Don't bother people that do
1689 * not need vimrun.exe. */
1690 if (s_dont_use_vimrun)
1691 need_vimrun_warning = TRUE;
1695 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1696 * Otherwise the default "findstr /n" is used.
1698 if (!executable_exists("findstr.exe"))
1699 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1701 #ifdef FEAT_CLIPBOARD
1702 clip_init(TRUE);
1705 * Vim's own clipboard format recognises whether the text is char, line,
1706 * or rectangular block. Only useful for copying between two Vims.
1707 * "VimClipboard" was used for previous versions, using the first
1708 * character to specify MCHAR, MLINE or MBLOCK.
1710 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1711 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1712 #endif
1716 #else /* FEAT_GUI_W32 */
1718 #define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1719 #define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1722 * ClearConsoleBuffer()
1723 * Description:
1724 * Clears the entire contents of the console screen buffer, using the
1725 * specified attribute.
1726 * Returns:
1727 * TRUE on success
1729 static BOOL
1730 ClearConsoleBuffer(WORD wAttribute)
1732 CONSOLE_SCREEN_BUFFER_INFO csbi;
1733 COORD coord;
1734 DWORD NumCells, dummy;
1736 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1737 return FALSE;
1739 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1740 coord.X = 0;
1741 coord.Y = 0;
1742 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1743 coord, &dummy))
1745 return FALSE;
1747 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1748 coord, &dummy))
1750 return FALSE;
1753 return TRUE;
1757 * FitConsoleWindow()
1758 * Description:
1759 * Checks if the console window will fit within given buffer dimensions.
1760 * Also, if requested, will shrink the window to fit.
1761 * Returns:
1762 * TRUE on success
1764 static BOOL
1765 FitConsoleWindow(
1766 COORD dwBufferSize,
1767 BOOL WantAdjust)
1769 CONSOLE_SCREEN_BUFFER_INFO csbi;
1770 COORD dwWindowSize;
1771 BOOL NeedAdjust = FALSE;
1773 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1776 * A buffer resize will fail if the current console window does
1777 * not lie completely within that buffer. To avoid this, we might
1778 * have to move and possibly shrink the window.
1780 if (csbi.srWindow.Right >= dwBufferSize.X)
1782 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1783 if (dwWindowSize.X > dwBufferSize.X)
1784 dwWindowSize.X = dwBufferSize.X;
1785 csbi.srWindow.Right = dwBufferSize.X - 1;
1786 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1787 NeedAdjust = TRUE;
1789 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1791 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1792 if (dwWindowSize.Y > dwBufferSize.Y)
1793 dwWindowSize.Y = dwBufferSize.Y;
1794 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1795 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1796 NeedAdjust = TRUE;
1798 if (NeedAdjust && WantAdjust)
1800 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1801 return FALSE;
1803 return TRUE;
1806 return FALSE;
1809 typedef struct ConsoleBufferStruct
1811 BOOL IsValid;
1812 CONSOLE_SCREEN_BUFFER_INFO Info;
1813 PCHAR_INFO Buffer;
1814 COORD BufferSize;
1815 } ConsoleBuffer;
1818 * SaveConsoleBuffer()
1819 * Description:
1820 * Saves important information about the console buffer, including the
1821 * actual buffer contents. The saved information is suitable for later
1822 * restoration by RestoreConsoleBuffer().
1823 * Returns:
1824 * TRUE if all information was saved; FALSE otherwise
1825 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1827 static BOOL
1828 SaveConsoleBuffer(
1829 ConsoleBuffer *cb)
1831 DWORD NumCells;
1832 COORD BufferCoord;
1833 SMALL_RECT ReadRegion;
1834 WORD Y, Y_incr;
1836 if (cb == NULL)
1837 return FALSE;
1839 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1841 cb->IsValid = FALSE;
1842 return FALSE;
1844 cb->IsValid = TRUE;
1847 * Allocate a buffer large enough to hold the entire console screen
1848 * buffer. If this ConsoleBuffer structure has already been initialized
1849 * with a buffer of the correct size, then just use that one.
1851 if (!cb->IsValid || cb->Buffer == NULL ||
1852 cb->BufferSize.X != cb->Info.dwSize.X ||
1853 cb->BufferSize.Y != cb->Info.dwSize.Y)
1855 cb->BufferSize.X = cb->Info.dwSize.X;
1856 cb->BufferSize.Y = cb->Info.dwSize.Y;
1857 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
1858 if (cb->Buffer != NULL)
1859 vim_free(cb->Buffer);
1860 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
1861 if (cb->Buffer == NULL)
1862 return FALSE;
1866 * We will now copy the console screen buffer into our buffer.
1867 * ReadConsoleOutput() seems to be limited as far as how much you
1868 * can read at a time. Empirically, this number seems to be about
1869 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1870 * in chunks until it is all copied. The chunks will all have the
1871 * same horizontal characteristics, so initialize them now. The
1872 * height of each chunk will be (12000 / width).
1874 BufferCoord.X = 0;
1875 ReadRegion.Left = 0;
1876 ReadRegion.Right = cb->Info.dwSize.X - 1;
1877 Y_incr = 12000 / cb->Info.dwSize.X;
1878 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
1881 * Read into position (0, Y) in our buffer.
1883 BufferCoord.Y = Y;
1885 * Read the region whose top left corner is (0, Y) and whose bottom
1886 * right corner is (width - 1, Y + Y_incr - 1). This should define
1887 * a region of size width by Y_incr. Don't worry if this region is
1888 * too large for the remaining buffer; it will be cropped.
1890 ReadRegion.Top = Y;
1891 ReadRegion.Bottom = Y + Y_incr - 1;
1892 if (!ReadConsoleOutput(g_hConOut, /* output handle */
1893 cb->Buffer, /* our buffer */
1894 cb->BufferSize, /* dimensions of our buffer */
1895 BufferCoord, /* offset in our buffer */
1896 &ReadRegion)) /* region to save */
1898 vim_free(cb->Buffer);
1899 cb->Buffer = NULL;
1900 return FALSE;
1904 return TRUE;
1908 * RestoreConsoleBuffer()
1909 * Description:
1910 * Restores important information about the console buffer, including the
1911 * actual buffer contents, if desired. The information to restore is in
1912 * the same format used by SaveConsoleBuffer().
1913 * Returns:
1914 * TRUE on success
1916 static BOOL
1917 RestoreConsoleBuffer(
1918 ConsoleBuffer *cb,
1919 BOOL RestoreScreen)
1921 COORD BufferCoord;
1922 SMALL_RECT WriteRegion;
1924 if (cb == NULL || !cb->IsValid)
1925 return FALSE;
1928 * Before restoring the buffer contents, clear the current buffer, and
1929 * restore the cursor position and window information. Doing this now
1930 * prevents old buffer contents from "flashing" onto the screen.
1932 if (RestoreScreen)
1933 ClearConsoleBuffer(cb->Info.wAttributes);
1935 FitConsoleWindow(cb->Info.dwSize, TRUE);
1936 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
1937 return FALSE;
1938 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
1939 return FALSE;
1941 if (!RestoreScreen)
1944 * No need to restore the screen buffer contents, so we're done.
1946 return TRUE;
1949 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
1950 return FALSE;
1951 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
1952 return FALSE;
1955 * Restore the screen buffer contents.
1957 if (cb->Buffer != NULL)
1959 BufferCoord.X = 0;
1960 BufferCoord.Y = 0;
1961 WriteRegion.Left = 0;
1962 WriteRegion.Top = 0;
1963 WriteRegion.Right = cb->Info.dwSize.X - 1;
1964 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
1965 if (!WriteConsoleOutput(g_hConOut, /* output handle */
1966 cb->Buffer, /* our buffer */
1967 cb->BufferSize, /* dimensions of our buffer */
1968 BufferCoord, /* offset in our buffer */
1969 &WriteRegion)) /* region to restore */
1971 return FALSE;
1975 return TRUE;
1978 #define FEAT_RESTORE_ORIG_SCREEN
1979 #ifdef FEAT_RESTORE_ORIG_SCREEN
1980 static ConsoleBuffer g_cbOrig = { 0 };
1981 #endif
1982 static ConsoleBuffer g_cbNonTermcap = { 0 };
1983 static ConsoleBuffer g_cbTermcap = { 0 };
1985 #ifdef FEAT_TITLE
1986 #ifdef __BORLANDC__
1987 typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
1988 #else
1989 typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
1990 #endif
1991 char g_szOrigTitle[256] = { 0 };
1992 HWND g_hWnd = NULL; /* also used in os_mswin.c */
1993 static HICON g_hOrigIconSmall = NULL;
1994 static HICON g_hOrigIcon = NULL;
1995 static HICON g_hVimIcon = NULL;
1996 static BOOL g_fCanChangeIcon = FALSE;
1998 /* ICON* are not defined in VC++ 4.0 */
1999 #ifndef ICON_SMALL
2000 #define ICON_SMALL 0
2001 #endif
2002 #ifndef ICON_BIG
2003 #define ICON_BIG 1
2004 #endif
2006 * GetConsoleIcon()
2007 * Description:
2008 * Attempts to retrieve the small icon and/or the big icon currently in
2009 * use by a given window.
2010 * Returns:
2011 * TRUE on success
2013 static BOOL
2014 GetConsoleIcon(
2015 HWND hWnd,
2016 HICON *phIconSmall,
2017 HICON *phIcon)
2019 if (hWnd == NULL)
2020 return FALSE;
2022 if (phIconSmall != NULL)
2023 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2024 (WPARAM)ICON_SMALL, (LPARAM)0);
2025 if (phIcon != NULL)
2026 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2027 (WPARAM)ICON_BIG, (LPARAM)0);
2028 return TRUE;
2032 * SetConsoleIcon()
2033 * Description:
2034 * Attempts to change the small icon and/or the big icon currently in
2035 * use by a given window.
2036 * Returns:
2037 * TRUE on success
2039 static BOOL
2040 SetConsoleIcon(
2041 HWND hWnd,
2042 HICON hIconSmall,
2043 HICON hIcon)
2045 HICON hPrevIconSmall;
2046 HICON hPrevIcon;
2048 if (hWnd == NULL)
2049 return FALSE;
2051 if (hIconSmall != NULL)
2052 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2053 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
2054 if (hIcon != NULL)
2055 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2056 (WPARAM)ICON_BIG,(LPARAM) hIcon);
2057 return TRUE;
2061 * SaveConsoleTitleAndIcon()
2062 * Description:
2063 * Saves the current console window title in g_szOrigTitle, for later
2064 * restoration. Also, attempts to obtain a handle to the console window,
2065 * and use it to save the small and big icons currently in use by the
2066 * console window. This is not always possible on some versions of Windows;
2067 * nor is it possible when running Vim remotely using Telnet (since the
2068 * console window the user sees is owned by a remote process).
2070 static void
2071 SaveConsoleTitleAndIcon(void)
2073 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2075 /* Save the original title. */
2076 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2077 return;
2080 * Obtain a handle to the console window using GetConsoleWindow() from
2081 * KERNEL32.DLL; we need to handle in order to change the window icon.
2082 * This function only exists on NT-based Windows, starting with Windows
2083 * 2000. On older operating systems, we can't change the window icon
2084 * anyway.
2086 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2087 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2088 "GetConsoleWindow")) != NULL)
2090 g_hWnd = (*GetConsoleWindowProc)();
2092 if (g_hWnd == NULL)
2093 return;
2095 /* Save the original console window icon. */
2096 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2097 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2098 return;
2100 /* Extract the first icon contained in the Vim executable. */
2101 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2102 if (g_hVimIcon != NULL)
2103 g_fCanChangeIcon = TRUE;
2105 #endif
2107 static int g_fWindInitCalled = FALSE;
2108 static int g_fTermcapMode = FALSE;
2109 static CONSOLE_CURSOR_INFO g_cci;
2110 static DWORD g_cmodein = 0;
2111 static DWORD g_cmodeout = 0;
2114 * non-GUI version of mch_init().
2116 void
2117 mch_init(void)
2119 #ifndef FEAT_RESTORE_ORIG_SCREEN
2120 CONSOLE_SCREEN_BUFFER_INFO csbi;
2121 #endif
2122 #ifndef __MINGW32__
2123 extern int _fmode;
2124 #endif
2126 /* Let critical errors result in a failure, not in a dialog box. Required
2127 * for the timestamp test to work on removed floppies. */
2128 SetErrorMode(SEM_FAILCRITICALERRORS);
2130 _fmode = O_BINARY; /* we do our own CR-LF translation */
2131 out_flush();
2133 /* Obtain handles for the standard Console I/O devices */
2134 if (read_cmd_fd == 0)
2135 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2136 else
2137 create_conin();
2138 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2140 #ifdef FEAT_RESTORE_ORIG_SCREEN
2141 /* Save the initial console buffer for later restoration */
2142 SaveConsoleBuffer(&g_cbOrig);
2143 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2144 #else
2145 /* Get current text attributes */
2146 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2147 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2148 #endif
2149 if (cterm_normal_fg_color == 0)
2150 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2151 if (cterm_normal_bg_color == 0)
2152 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2154 /* set termcap codes to current text attributes */
2155 update_tcap(g_attrCurrent);
2157 GetConsoleCursorInfo(g_hConOut, &g_cci);
2158 GetConsoleMode(g_hConIn, &g_cmodein);
2159 GetConsoleMode(g_hConOut, &g_cmodeout);
2161 #ifdef FEAT_TITLE
2162 SaveConsoleTitleAndIcon();
2164 * Set both the small and big icons of the console window to Vim's icon.
2165 * Note that Vim presently only has one size of icon (32x32), but it
2166 * automatically gets scaled down to 16x16 when setting the small icon.
2168 if (g_fCanChangeIcon)
2169 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2170 #endif
2172 ui_get_shellsize();
2174 #ifdef MCH_WRITE_DUMP
2175 fdDump = fopen("dump", "wt");
2177 if (fdDump)
2179 time_t t;
2181 time(&t);
2182 fputs(ctime(&t), fdDump);
2183 fflush(fdDump);
2185 #endif
2187 g_fWindInitCalled = TRUE;
2189 #ifdef FEAT_MOUSE
2190 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2191 #endif
2193 #ifdef FEAT_CLIPBOARD
2194 clip_init(TRUE);
2197 * Vim's own clipboard format recognises whether the text is char, line, or
2198 * rectangular block. Only useful for copying between two Vims.
2199 * "VimClipboard" was used for previous versions, using the first
2200 * character to specify MCHAR, MLINE or MBLOCK.
2202 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2203 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2204 #endif
2206 /* This will be NULL on anything but NT 4.0 */
2207 s_pfnGetConsoleKeyboardLayoutName =
2208 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2209 "GetConsoleKeyboardLayoutNameA");
2213 * non-GUI version of mch_exit().
2214 * Shut down and exit with status `r'
2215 * Careful: mch_exit() may be called before mch_init()!
2217 void
2218 mch_exit(int r)
2220 stoptermcap();
2222 if (g_fWindInitCalled)
2223 settmode(TMODE_COOK);
2225 ml_close_all(TRUE); /* remove all memfiles */
2227 if (g_fWindInitCalled)
2229 #ifdef FEAT_TITLE
2230 mch_restore_title(3);
2232 * Restore both the small and big icons of the console window to
2233 * what they were at startup. Don't do this when the window is
2234 * closed, Vim would hang here.
2236 if (g_fCanChangeIcon && !g_fForceExit)
2237 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2238 #endif
2240 #ifdef MCH_WRITE_DUMP
2241 if (fdDump)
2243 time_t t;
2245 time(&t);
2246 fputs(ctime(&t), fdDump);
2247 fclose(fdDump);
2249 fdDump = NULL;
2250 #endif
2253 SetConsoleCursorInfo(g_hConOut, &g_cci);
2254 SetConsoleMode(g_hConIn, g_cmodein);
2255 SetConsoleMode(g_hConOut, g_cmodeout);
2257 #ifdef DYNAMIC_GETTEXT
2258 dyn_libintl_end();
2259 #endif
2261 exit(r);
2263 #endif /* !FEAT_GUI_W32 */
2266 * Do we have an interactive window?
2268 /*ARGSUSED*/
2270 mch_check_win(
2271 int argc,
2272 char **argv)
2274 get_exe_name();
2276 #ifdef FEAT_GUI_W32
2277 return OK; /* GUI always has a tty */
2278 #else
2279 if (isatty(1))
2280 return OK;
2281 return FAIL;
2282 #endif
2287 * fname_case(): Set the case of the file name, if it already exists.
2288 * When "len" is > 0, also expand short to long filenames.
2290 void
2291 fname_case(
2292 char_u *name,
2293 int len)
2295 char szTrueName[_MAX_PATH + 2];
2296 char *ptrue, *ptruePrev;
2297 char *porig, *porigPrev;
2298 int flen;
2299 WIN32_FIND_DATA fb;
2300 HANDLE hFind;
2301 int c;
2303 flen = (int)STRLEN(name);
2304 if (flen == 0 || flen > _MAX_PATH)
2305 return;
2307 slash_adjust(name);
2309 /* Build the new name in szTrueName[] one component at a time. */
2310 porig = name;
2311 ptrue = szTrueName;
2313 if (isalpha(porig[0]) && porig[1] == ':')
2315 /* copy leading drive letter */
2316 *ptrue++ = *porig++;
2317 *ptrue++ = *porig++;
2318 *ptrue = NUL; /* in case nothing follows */
2321 while (*porig != NUL)
2323 /* copy \ characters */
2324 while (*porig == psepc)
2325 *ptrue++ = *porig++;
2327 ptruePrev = ptrue;
2328 porigPrev = porig;
2329 while (*porig != NUL && *porig != psepc)
2331 #ifdef FEAT_MBYTE
2332 int l;
2334 if (enc_dbcs)
2336 l = (*mb_ptr2len)(porig);
2337 while (--l >= 0)
2338 *ptrue++ = *porig++;
2340 else
2341 #endif
2342 *ptrue++ = *porig++;
2344 *ptrue = NUL;
2346 /* Skip "", "." and "..". */
2347 if (ptrue > ptruePrev
2348 && (ptruePrev[0] != '.'
2349 || (ptruePrev[1] != NUL
2350 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
2351 && (hFind = FindFirstFile(szTrueName, &fb))
2352 != INVALID_HANDLE_VALUE)
2354 c = *porig;
2355 *porig = NUL;
2357 /* Only use the match when it's the same name (ignoring case) or
2358 * expansion is allowed and there is a match with the short name
2359 * and there is enough room. */
2360 if (_stricoll(porigPrev, fb.cFileName) == 0
2361 || (len > 0
2362 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2363 && (int)(ptruePrev - szTrueName)
2364 + (int)strlen(fb.cFileName) < len)))
2366 STRCPY(ptruePrev, fb.cFileName);
2368 /* Look for exact match and prefer it if found. Must be a
2369 * long name, otherwise there would be only one match. */
2370 while (FindNextFile(hFind, &fb))
2372 if (*fb.cAlternateFileName != NUL
2373 && (strcoll(porigPrev, fb.cFileName) == 0
2374 || (len > 0
2375 && (_stricoll(porigPrev,
2376 fb.cAlternateFileName) == 0
2377 && (int)(ptruePrev - szTrueName)
2378 + (int)strlen(fb.cFileName) < len))))
2380 STRCPY(ptruePrev, fb.cFileName);
2381 break;
2385 FindClose(hFind);
2386 *porig = c;
2387 ptrue = ptruePrev + strlen(ptruePrev);
2391 STRCPY(name, szTrueName);
2396 * Insert user name in s[len].
2399 mch_get_user_name(
2400 char_u *s,
2401 int len)
2403 char szUserName[256 + 1]; /* UNLEN is 256 */
2404 DWORD cch = sizeof szUserName;
2406 if (GetUserName(szUserName, &cch))
2408 vim_strncpy(s, szUserName, len - 1);
2409 return OK;
2411 s[0] = NUL;
2412 return FAIL;
2417 * Insert host name in s[len].
2419 void
2420 mch_get_host_name(
2421 char_u *s,
2422 int len)
2424 DWORD cch = len;
2426 if (!GetComputerName(s, &cch))
2427 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
2432 * return process ID
2434 long
2435 mch_get_pid(void)
2437 return (long)GetCurrentProcessId();
2442 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2443 * Return OK for success, FAIL for failure.
2446 mch_dirname(
2447 char_u *buf,
2448 int len)
2451 * Originally this was:
2452 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2453 * But the Win32s known bug list says that getcwd() doesn't work
2454 * so use the Win32 system call instead. <Negri>
2456 #ifdef FEAT_MBYTE
2457 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2459 WCHAR wbuf[_MAX_PATH + 1];
2461 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2463 char_u *p = utf16_to_enc(wbuf, NULL);
2465 if (p != NULL)
2467 vim_strncpy(buf, p, len - 1);
2468 vim_free(p);
2469 return OK;
2472 /* Retry with non-wide function (for Windows 98). */
2474 #endif
2475 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2479 * get file permissions for `name'
2480 * -1 : error
2481 * else FILE_ATTRIBUTE_* defined in winnt.h
2483 long
2484 mch_getperm(char_u *name)
2486 #ifdef FEAT_MBYTE
2487 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2489 WCHAR *p = enc_to_utf16(name, NULL);
2490 long n;
2492 if (p != NULL)
2494 n = (long)GetFileAttributesW(p);
2495 vim_free(p);
2496 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2497 return n;
2498 /* Retry with non-wide function (for Windows 98). */
2501 #endif
2502 return (long)GetFileAttributes((char *)name);
2507 * set file permission for `name' to `perm'
2510 mch_setperm(
2511 char_u *name,
2512 long perm)
2514 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2515 #ifdef FEAT_MBYTE
2516 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2518 WCHAR *p = enc_to_utf16(name, NULL);
2519 long n;
2521 if (p != NULL)
2523 n = (long)SetFileAttributesW(p, perm);
2524 vim_free(p);
2525 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2526 return n ? OK : FAIL;
2527 /* Retry with non-wide function (for Windows 98). */
2530 #endif
2531 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2535 * Set hidden flag for "name".
2537 void
2538 mch_hide(char_u *name)
2540 int perm;
2541 #ifdef FEAT_MBYTE
2542 WCHAR *p = NULL;
2544 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2545 p = enc_to_utf16(name, NULL);
2546 #endif
2548 #ifdef FEAT_MBYTE
2549 if (p != NULL)
2551 perm = GetFileAttributesW(p);
2552 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2554 /* Retry with non-wide function (for Windows 98). */
2555 vim_free(p);
2556 p = NULL;
2559 if (p == NULL)
2560 #endif
2561 perm = GetFileAttributes((char *)name);
2562 if (perm >= 0)
2564 perm |= FILE_ATTRIBUTE_HIDDEN;
2565 #ifdef FEAT_MBYTE
2566 if (p != NULL)
2568 if (SetFileAttributesW(p, perm) == 0
2569 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2571 /* Retry with non-wide function (for Windows 98). */
2572 vim_free(p);
2573 p = NULL;
2576 if (p == NULL)
2577 #endif
2578 SetFileAttributes((char *)name, perm);
2580 #ifdef FEAT_MBYTE
2581 vim_free(p);
2582 #endif
2586 * return TRUE if "name" is a directory
2587 * return FALSE if "name" is not a directory or upon error
2590 mch_isdir(char_u *name)
2592 int f = mch_getperm(name);
2594 if (f == -1)
2595 return FALSE; /* file does not exist at all */
2597 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2601 * Return TRUE if file "fname" has more than one link.
2604 mch_is_linked(char_u *fname)
2606 HANDLE hFile;
2607 int res = 0;
2608 BY_HANDLE_FILE_INFORMATION inf;
2609 #ifdef FEAT_MBYTE
2610 WCHAR *wn = NULL;
2612 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2613 wn = enc_to_utf16(fname, NULL);
2614 if (wn != NULL)
2616 hFile = CreateFileW(wn, /* file name */
2617 GENERIC_READ, /* access mode */
2618 0, /* share mode */
2619 NULL, /* security descriptor */
2620 OPEN_EXISTING, /* creation disposition */
2621 0, /* file attributes */
2622 NULL); /* handle to template file */
2623 if (hFile == INVALID_HANDLE_VALUE
2624 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2626 /* Retry with non-wide function (for Windows 98). */
2627 vim_free(wn);
2628 wn = NULL;
2631 if (wn == NULL)
2632 #endif
2633 hFile = CreateFile(fname, /* file name */
2634 GENERIC_READ, /* access mode */
2635 0, /* share mode */
2636 NULL, /* security descriptor */
2637 OPEN_EXISTING, /* creation disposition */
2638 0, /* file attributes */
2639 NULL); /* handle to template file */
2641 if (hFile != INVALID_HANDLE_VALUE)
2643 if (GetFileInformationByHandle(hFile, &inf) != 0
2644 && inf.nNumberOfLinks > 1)
2645 res = 1;
2646 CloseHandle(hFile);
2649 #ifdef FEAT_MBYTE
2650 vim_free(wn);
2651 #endif
2652 return res;
2656 * Return TRUE if file or directory "name" is writable (not readonly).
2657 * Strange semantics of Win32: a readonly directory is writable, but you can't
2658 * delete a file. Let's say this means it is writable.
2661 mch_writable(char_u *name)
2663 int perm = mch_getperm(name);
2665 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2666 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2670 * Return 1 if "name" can be executed, 0 if not.
2671 * Return -1 if unknown.
2674 mch_can_exe(char_u *name)
2676 char_u buf[_MAX_PATH];
2677 int len = (int)STRLEN(name);
2678 char_u *p;
2680 if (len >= _MAX_PATH) /* safety check */
2681 return FALSE;
2683 /* If there already is an extension try using the name directly. Also do
2684 * this with a Unix-shell like 'shell'. */
2685 if (vim_strchr(gettail(name), '.') != NULL
2686 || strstr((char *)gettail(p_sh), "sh") != NULL)
2687 if (executable_exists((char *)name))
2688 return TRUE;
2691 * Loop over all extensions in $PATHEXT.
2693 vim_strncpy(buf, name, _MAX_PATH - 1);
2694 p = mch_getenv("PATHEXT");
2695 if (p == NULL)
2696 p = (char_u *)".com;.exe;.bat;.cmd";
2697 while (*p)
2699 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2701 /* A single "." means no extension is added. */
2702 buf[len] = NUL;
2703 ++p;
2704 if (*p)
2705 ++p;
2707 else
2708 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2709 if (executable_exists((char *)buf))
2710 return TRUE;
2712 return FALSE;
2716 * Check what "name" is:
2717 * NODE_NORMAL: file or directory (or doesn't exist)
2718 * NODE_WRITABLE: writable device, socket, fifo, etc.
2719 * NODE_OTHER: non-writable things
2722 mch_nodetype(char_u *name)
2724 HANDLE hFile;
2725 int type;
2727 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2728 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2729 * here. */
2730 if (STRNCMP(name, "\\\\.\\", 4) == 0)
2731 return NODE_WRITABLE;
2733 hFile = CreateFile(name, /* file name */
2734 GENERIC_WRITE, /* access mode */
2735 0, /* share mode */
2736 NULL, /* security descriptor */
2737 OPEN_EXISTING, /* creation disposition */
2738 0, /* file attributes */
2739 NULL); /* handle to template file */
2741 if (hFile == INVALID_HANDLE_VALUE)
2742 return NODE_NORMAL;
2744 type = GetFileType(hFile);
2745 CloseHandle(hFile);
2746 if (type == FILE_TYPE_CHAR)
2747 return NODE_WRITABLE;
2748 if (type == FILE_TYPE_DISK)
2749 return NODE_NORMAL;
2750 return NODE_OTHER;
2753 #ifdef HAVE_ACL
2754 struct my_acl
2756 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2757 PSID pSidOwner;
2758 PSID pSidGroup;
2759 PACL pDacl;
2760 PACL pSacl;
2762 #endif
2765 * Return a pointer to the ACL of file "fname" in allocated memory.
2766 * Return NULL if the ACL is not available for whatever reason.
2768 vim_acl_T
2769 mch_get_acl(char_u *fname)
2771 #ifndef HAVE_ACL
2772 return (vim_acl_T)NULL;
2773 #else
2774 struct my_acl *p = NULL;
2776 /* This only works on Windows NT and 2000. */
2777 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2779 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2780 if (p != NULL)
2782 if (pGetNamedSecurityInfo(
2783 (LPTSTR)fname, // Abstract filename
2784 SE_FILE_OBJECT, // File Object
2785 // Retrieve the entire security descriptor.
2786 OWNER_SECURITY_INFORMATION |
2787 GROUP_SECURITY_INFORMATION |
2788 DACL_SECURITY_INFORMATION |
2789 SACL_SECURITY_INFORMATION,
2790 &p->pSidOwner, // Ownership information.
2791 &p->pSidGroup, // Group membership.
2792 &p->pDacl, // Discretionary information.
2793 &p->pSacl, // For auditing purposes.
2794 &p->pSecurityDescriptor
2795 ) != ERROR_SUCCESS)
2797 mch_free_acl((vim_acl_T)p);
2798 p = NULL;
2803 return (vim_acl_T)p;
2804 #endif
2808 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2809 * Errors are ignored.
2810 * This must only be called with "acl" equal to what mch_get_acl() returned.
2812 void
2813 mch_set_acl(char_u *fname, vim_acl_T acl)
2815 #ifdef HAVE_ACL
2816 struct my_acl *p = (struct my_acl *)acl;
2818 if (p != NULL && advapi_lib != NULL)
2819 (void)pSetNamedSecurityInfo(
2820 (LPTSTR)fname, // Abstract filename
2821 SE_FILE_OBJECT, // File Object
2822 // Retrieve the entire security descriptor.
2823 OWNER_SECURITY_INFORMATION |
2824 GROUP_SECURITY_INFORMATION |
2825 DACL_SECURITY_INFORMATION |
2826 SACL_SECURITY_INFORMATION,
2827 p->pSidOwner, // Ownership information.
2828 p->pSidGroup, // Group membership.
2829 p->pDacl, // Discretionary information.
2830 p->pSacl // For auditing purposes.
2832 #endif
2835 void
2836 mch_free_acl(vim_acl_T acl)
2838 #ifdef HAVE_ACL
2839 struct my_acl *p = (struct my_acl *)acl;
2841 if (p != NULL)
2843 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2844 vim_free(p);
2846 #endif
2849 #ifndef FEAT_GUI_W32
2852 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2854 static BOOL WINAPI
2855 handler_routine(
2856 DWORD dwCtrlType)
2858 switch (dwCtrlType)
2860 case CTRL_C_EVENT:
2861 if (ctrl_c_interrupts)
2862 g_fCtrlCPressed = TRUE;
2863 return TRUE;
2865 case CTRL_BREAK_EVENT:
2866 g_fCBrkPressed = TRUE;
2867 return TRUE;
2869 /* fatal events: shut down gracefully */
2870 case CTRL_CLOSE_EVENT:
2871 case CTRL_LOGOFF_EVENT:
2872 case CTRL_SHUTDOWN_EVENT:
2873 windgoto((int)Rows - 1, 0);
2874 g_fForceExit = TRUE;
2876 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
2877 (dwCtrlType == CTRL_CLOSE_EVENT
2878 ? _("close")
2879 : dwCtrlType == CTRL_LOGOFF_EVENT
2880 ? _("logoff")
2881 : _("shutdown")));
2882 #ifdef DEBUG
2883 OutputDebugString(IObuff);
2884 #endif
2886 preserve_exit(); /* output IObuff, preserve files and exit */
2888 return TRUE; /* not reached */
2890 default:
2891 return FALSE;
2897 * set the tty in (raw) ? "raw" : "cooked" mode
2899 void
2900 mch_settmode(int tmode)
2902 DWORD cmodein;
2903 DWORD cmodeout;
2904 BOOL bEnableHandler;
2906 GetConsoleMode(g_hConIn, &cmodein);
2907 GetConsoleMode(g_hConOut, &cmodeout);
2908 if (tmode == TMODE_RAW)
2910 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2911 ENABLE_ECHO_INPUT);
2912 #ifdef FEAT_MOUSE
2913 if (g_fMouseActive)
2914 cmodein |= ENABLE_MOUSE_INPUT;
2915 #endif
2916 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2917 bEnableHandler = TRUE;
2919 else /* cooked */
2921 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2922 ENABLE_ECHO_INPUT);
2923 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2924 bEnableHandler = FALSE;
2926 SetConsoleMode(g_hConIn, cmodein);
2927 SetConsoleMode(g_hConOut, cmodeout);
2928 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
2930 #ifdef MCH_WRITE_DUMP
2931 if (fdDump)
2933 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
2934 tmode == TMODE_RAW ? "raw" :
2935 tmode == TMODE_COOK ? "cooked" : "normal",
2936 cmodein, cmodeout);
2937 fflush(fdDump);
2939 #endif
2944 * Get the size of the current window in `Rows' and `Columns'
2945 * Return OK when size could be determined, FAIL otherwise.
2948 mch_get_shellsize(void)
2950 CONSOLE_SCREEN_BUFFER_INFO csbi;
2952 if (!g_fTermcapMode && g_cbTermcap.IsValid)
2955 * For some reason, we are trying to get the screen dimensions
2956 * even though we are not in termcap mode. The 'Rows' and 'Columns'
2957 * variables are really intended to mean the size of Vim screen
2958 * while in termcap mode.
2960 Rows = g_cbTermcap.Info.dwSize.Y;
2961 Columns = g_cbTermcap.Info.dwSize.X;
2963 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2965 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2966 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2968 else
2970 Rows = 25;
2971 Columns = 80;
2973 return OK;
2977 * Set a console window to `xSize' * `ySize'
2979 static void
2980 ResizeConBufAndWindow(
2981 HANDLE hConsole,
2982 int xSize,
2983 int ySize)
2985 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
2986 SMALL_RECT srWindowRect; /* hold the new console size */
2987 COORD coordScreen;
2989 #ifdef MCH_WRITE_DUMP
2990 if (fdDump)
2992 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
2993 fflush(fdDump);
2995 #endif
2997 /* get the largest size we can size the console window to */
2998 coordScreen = GetLargestConsoleWindowSize(hConsole);
3000 /* define the new console window size and scroll position */
3001 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3002 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3003 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3005 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3007 int sx, sy;
3009 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3010 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3011 if (sy < ySize || sx < xSize)
3014 * Increasing number of lines/columns, do buffer first.
3015 * Use the maximal size in x and y direction.
3017 if (sy < ySize)
3018 coordScreen.Y = ySize;
3019 else
3020 coordScreen.Y = sy;
3021 if (sx < xSize)
3022 coordScreen.X = xSize;
3023 else
3024 coordScreen.X = sx;
3025 SetConsoleScreenBufferSize(hConsole, coordScreen);
3029 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3031 #ifdef MCH_WRITE_DUMP
3032 if (fdDump)
3034 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3035 GetLastError());
3036 fflush(fdDump);
3038 #endif
3041 /* define the new console buffer size */
3042 coordScreen.X = xSize;
3043 coordScreen.Y = ySize;
3045 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3047 #ifdef MCH_WRITE_DUMP
3048 if (fdDump)
3050 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3051 GetLastError());
3052 fflush(fdDump);
3054 #endif
3060 * Set the console window to `Rows' * `Columns'
3062 void
3063 mch_set_shellsize(void)
3065 COORD coordScreen;
3067 /* Don't change window size while still starting up */
3068 if (suppress_winsize != 0)
3070 suppress_winsize = 2;
3071 return;
3074 if (term_console)
3076 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3078 /* Clamp Rows and Columns to reasonable values */
3079 if (Rows > coordScreen.Y)
3080 Rows = coordScreen.Y;
3081 if (Columns > coordScreen.X)
3082 Columns = coordScreen.X;
3084 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3089 * Rows and/or Columns has changed.
3091 void
3092 mch_new_shellsize(void)
3094 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3099 * Called when started up, to set the winsize that was delayed.
3101 void
3102 mch_set_winsize_now(void)
3104 if (suppress_winsize == 2)
3106 suppress_winsize = 0;
3107 mch_set_shellsize();
3108 shell_resized();
3110 suppress_winsize = 0;
3112 #endif /* FEAT_GUI_W32 */
3116 #if defined(FEAT_GUI_W32) || defined(PROTO)
3119 * Specialised version of system() for Win32 GUI mode.
3120 * This version proceeds as follows:
3121 * 1. Create a console window for use by the subprocess
3122 * 2. Run the subprocess (it gets the allocated console by default)
3123 * 3. Wait for the subprocess to terminate and get its exit code
3124 * 4. Prompt the user to press a key to close the console window
3126 static int
3127 mch_system(char *cmd, int options)
3129 STARTUPINFO si;
3130 PROCESS_INFORMATION pi;
3131 DWORD ret = 0;
3132 HWND hwnd = GetFocus();
3134 si.cb = sizeof(si);
3135 si.lpReserved = NULL;
3136 si.lpDesktop = NULL;
3137 si.lpTitle = NULL;
3138 si.dwFlags = STARTF_USESHOWWINDOW;
3140 * It's nicer to run a filter command in a minimized window, but in
3141 * Windows 95 this makes the command MUCH slower. We can't do it under
3142 * Win32s either as it stops the synchronous spawn workaround working.
3144 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
3145 si.wShowWindow = SW_SHOWMINIMIZED;
3146 else
3147 si.wShowWindow = SW_SHOWNORMAL;
3148 si.cbReserved2 = 0;
3149 si.lpReserved2 = NULL;
3151 /* There is a strange error on Windows 95 when using "c:\\command.com".
3152 * When the "c:\\" is left out it works OK...? */
3153 if (mch_windows95()
3154 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3155 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3156 cmd += 3;
3158 /* Now, run the command */
3159 CreateProcess(NULL, /* Executable name */
3160 cmd, /* Command to execute */
3161 NULL, /* Process security attributes */
3162 NULL, /* Thread security attributes */
3163 FALSE, /* Inherit handles */
3164 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3165 CREATE_NEW_CONSOLE,
3166 NULL, /* Environment */
3167 NULL, /* Current directory */
3168 &si, /* Startup information */
3169 &pi); /* Process information */
3172 /* Wait for the command to terminate before continuing */
3173 if (g_PlatformId != VER_PLATFORM_WIN32s)
3175 #ifdef FEAT_GUI
3176 int delay = 1;
3178 /* Keep updating the window while waiting for the shell to finish. */
3179 for (;;)
3181 MSG msg;
3183 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3185 TranslateMessage(&msg);
3186 DispatchMessage(&msg);
3188 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3189 break;
3191 /* We start waiting for a very short time and then increase it, so
3192 * that we respond quickly when the process is quick, and don't
3193 * consume too much overhead when it's slow. */
3194 if (delay < 50)
3195 delay += 10;
3197 #else
3198 WaitForSingleObject(pi.hProcess, INFINITE);
3199 #endif
3201 /* Get the command exit code */
3202 GetExitCodeProcess(pi.hProcess, &ret);
3204 else
3207 * This ugly code is the only quick way of performing
3208 * a synchronous spawn under Win32s. Yuk.
3210 num_windows = 0;
3211 EnumWindows(win32ssynch_cb, 0);
3212 old_num_windows = num_windows;
3215 Sleep(1000);
3216 num_windows = 0;
3217 EnumWindows(win32ssynch_cb, 0);
3218 } while (num_windows == old_num_windows);
3219 ret = 0;
3222 /* Close the handles to the subprocess, so that it goes away */
3223 CloseHandle(pi.hThread);
3224 CloseHandle(pi.hProcess);
3226 /* Try to get input focus back. Doesn't always work though. */
3227 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3229 return ret;
3231 #else
3233 # define mch_system(c, o) system(c)
3235 #endif
3238 * Either execute a command by calling the shell or start a new shell
3241 mch_call_shell(
3242 char_u *cmd,
3243 int options) /* SHELL_*, see vim.h */
3245 int x = 0;
3246 int tmode = cur_tmode;
3247 #ifdef FEAT_TITLE
3248 char szShellTitle[512];
3250 /* Change the title to reflect that we are in a subshell. */
3251 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3253 if (cmd == NULL)
3254 strcat(szShellTitle, " :sh");
3255 else
3257 strcat(szShellTitle, " - !");
3258 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3259 strcat(szShellTitle, cmd);
3261 mch_settitle(szShellTitle, NULL);
3263 #endif
3265 out_flush();
3267 #ifdef MCH_WRITE_DUMP
3268 if (fdDump)
3270 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3271 fflush(fdDump);
3273 #endif
3276 * Catch all deadly signals while running the external command, because a
3277 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3279 signal(SIGINT, SIG_IGN);
3280 #if defined(__GNUC__) && !defined(__MINGW32__)
3281 signal(SIGKILL, SIG_IGN);
3282 #else
3283 signal(SIGBREAK, SIG_IGN);
3284 #endif
3285 signal(SIGILL, SIG_IGN);
3286 signal(SIGFPE, SIG_IGN);
3287 signal(SIGSEGV, SIG_IGN);
3288 signal(SIGTERM, SIG_IGN);
3289 signal(SIGABRT, SIG_IGN);
3291 if (options & SHELL_COOKED)
3292 settmode(TMODE_COOK); /* set to normal mode */
3294 if (cmd == NULL)
3296 x = mch_system(p_sh, options);
3298 else
3300 /* we use "command" or "cmd" to start the shell; slow but easy */
3301 char_u *newcmd;
3302 long_u cmdlen = (
3303 #ifdef FEAT_GUI_W32
3304 STRLEN(vimrun_path) +
3305 #endif
3306 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
3308 newcmd = lalloc(cmdlen, TRUE);
3309 if (newcmd != NULL)
3311 char_u *cmdbase = (*cmd == '"' ? cmd + 1 : cmd);
3313 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3315 STARTUPINFO si;
3316 PROCESS_INFORMATION pi;
3318 si.cb = sizeof(si);
3319 si.lpReserved = NULL;
3320 si.lpDesktop = NULL;
3321 si.lpTitle = NULL;
3322 si.dwFlags = 0;
3323 si.cbReserved2 = 0;
3324 si.lpReserved2 = NULL;
3326 cmdbase = skipwhite(cmdbase + 5);
3327 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3328 && vim_iswhite(cmdbase[4]))
3330 cmdbase = skipwhite(cmdbase + 4);
3331 si.dwFlags = STARTF_USESHOWWINDOW;
3332 si.wShowWindow = SW_SHOWMINNOACTIVE;
3335 /* When the command is in double quotes, but 'shellxquote' is
3336 * empty, keep the double quotes around the command.
3337 * Otherwise remove the double quotes, they aren't needed
3338 * here, because we don't use a shell to run the command. */
3339 if (*cmd == '"' && *p_sxq == NUL)
3341 newcmd[0] = '"';
3342 STRCPY(newcmd + 1, cmdbase);
3344 else
3346 STRCPY(newcmd, cmdbase);
3347 if (*cmd == '"' && *newcmd != NUL)
3348 newcmd[STRLEN(newcmd) - 1] = NUL;
3352 * Now, start the command as a process, so that it doesn't
3353 * inherit our handles which causes unpleasant dangling swap
3354 * files if we exit before the spawned process
3356 if (CreateProcess (NULL, // Executable name
3357 newcmd, // Command to execute
3358 NULL, // Process security attributes
3359 NULL, // Thread security attributes
3360 FALSE, // Inherit handles
3361 CREATE_NEW_CONSOLE, // Creation flags
3362 NULL, // Environment
3363 NULL, // Current directory
3364 &si, // Startup information
3365 &pi)) // Process information
3366 x = 0;
3367 else
3369 x = -1;
3370 #ifdef FEAT_GUI_W32
3371 EMSG(_("E371: Command not found"));
3372 #endif
3374 /* Close the handles to the subprocess, so that it goes away */
3375 CloseHandle(pi.hThread);
3376 CloseHandle(pi.hProcess);
3378 else
3380 #if defined(FEAT_GUI_W32)
3381 if (need_vimrun_warning)
3383 MessageBox(NULL,
3384 _("VIMRUN.EXE not found in your $PATH.\n"
3385 "External commands will not pause after completion.\n"
3386 "See :help win32-vimrun for more information."),
3387 _("Vim Warning"),
3388 MB_ICONWARNING);
3389 need_vimrun_warning = FALSE;
3391 if (!s_dont_use_vimrun)
3392 /* Use vimrun to execute the command. It opens a console
3393 * window, which can be closed without killing Vim. */
3394 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
3395 vimrun_path,
3396 (msg_silent != 0 || (options & SHELL_DOOUT))
3397 ? "-s " : "",
3398 p_sh, p_shcf, cmd);
3399 else
3400 #endif
3401 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
3402 p_sh, p_shcf, cmd);
3403 x = mch_system((char *)newcmd, options);
3405 vim_free(newcmd);
3409 if (tmode == TMODE_RAW)
3410 settmode(TMODE_RAW); /* set to raw mode */
3412 /* Print the return value, unless "vimrun" was used. */
3413 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
3414 #if defined(FEAT_GUI_W32)
3415 && ((options & SHELL_DOOUT) || s_dont_use_vimrun)
3416 #endif
3419 smsg(_("shell returned %d"), x);
3420 msg_putchar('\n');
3422 #ifdef FEAT_TITLE
3423 resettitle();
3424 #endif
3426 signal(SIGINT, SIG_DFL);
3427 #if defined(__GNUC__) && !defined(__MINGW32__)
3428 signal(SIGKILL, SIG_DFL);
3429 #else
3430 signal(SIGBREAK, SIG_DFL);
3431 #endif
3432 signal(SIGILL, SIG_DFL);
3433 signal(SIGFPE, SIG_DFL);
3434 signal(SIGSEGV, SIG_DFL);
3435 signal(SIGTERM, SIG_DFL);
3436 signal(SIGABRT, SIG_DFL);
3438 return x;
3442 #ifndef FEAT_GUI_W32
3445 * Start termcap mode
3447 static void
3448 termcap_mode_start(void)
3450 DWORD cmodein;
3452 if (g_fTermcapMode)
3453 return;
3455 SaveConsoleBuffer(&g_cbNonTermcap);
3457 if (g_cbTermcap.IsValid)
3460 * We've been in termcap mode before. Restore certain screen
3461 * characteristics, including the buffer size and the window
3462 * size. Since we will be redrawing the screen, we don't need
3463 * to restore the actual contents of the buffer.
3465 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
3466 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
3467 Rows = g_cbTermcap.Info.dwSize.Y;
3468 Columns = g_cbTermcap.Info.dwSize.X;
3470 else
3473 * This is our first time entering termcap mode. Clear the console
3474 * screen buffer, and resize the buffer to match the current window
3475 * size. We will use this as the size of our editing environment.
3477 ClearConsoleBuffer(g_attrCurrent);
3478 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3481 #ifdef FEAT_TITLE
3482 resettitle();
3483 #endif
3485 GetConsoleMode(g_hConIn, &cmodein);
3486 #ifdef FEAT_MOUSE
3487 if (g_fMouseActive)
3488 cmodein |= ENABLE_MOUSE_INPUT;
3489 else
3490 cmodein &= ~ENABLE_MOUSE_INPUT;
3491 #endif
3492 cmodein |= ENABLE_WINDOW_INPUT;
3493 SetConsoleMode(g_hConIn, cmodein);
3495 redraw_later_clear();
3496 g_fTermcapMode = TRUE;
3501 * End termcap mode
3503 static void
3504 termcap_mode_end(void)
3506 DWORD cmodein;
3507 ConsoleBuffer *cb;
3508 COORD coord;
3509 DWORD dwDummy;
3511 if (!g_fTermcapMode)
3512 return;
3514 SaveConsoleBuffer(&g_cbTermcap);
3516 GetConsoleMode(g_hConIn, &cmodein);
3517 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
3518 SetConsoleMode(g_hConIn, cmodein);
3520 #ifdef FEAT_RESTORE_ORIG_SCREEN
3521 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
3522 #else
3523 cb = &g_cbNonTermcap;
3524 #endif
3525 RestoreConsoleBuffer(cb, p_rs);
3526 SetConsoleCursorInfo(g_hConOut, &g_cci);
3528 if (p_rs || exiting)
3531 * Clear anything that happens to be on the current line.
3533 coord.X = 0;
3534 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
3535 FillConsoleOutputCharacter(g_hConOut, ' ',
3536 cb->Info.dwSize.X, coord, &dwDummy);
3538 * The following is just for aesthetics. If we are exiting without
3539 * restoring the screen, then we want to have a prompt string
3540 * appear at the bottom line. However, the command interpreter
3541 * seems to always advance the cursor one line before displaying
3542 * the prompt string, which causes the screen to scroll. To
3543 * counter this, move the cursor up one line before exiting.
3545 if (exiting && !p_rs)
3546 coord.Y--;
3548 * Position the cursor at the leftmost column of the desired row.
3550 SetConsoleCursorPosition(g_hConOut, coord);
3553 g_fTermcapMode = FALSE;
3555 #endif /* FEAT_GUI_W32 */
3558 #ifdef FEAT_GUI_W32
3559 /*ARGSUSED*/
3560 void
3561 mch_write(
3562 char_u *s,
3563 int len)
3565 /* never used */
3568 #else
3571 * clear `n' chars, starting from `coord'
3573 static void
3574 clear_chars(
3575 COORD coord,
3576 DWORD n)
3578 DWORD dwDummy;
3580 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
3581 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
3586 * Clear the screen
3588 static void
3589 clear_screen(void)
3591 g_coord.X = g_coord.Y = 0;
3592 clear_chars(g_coord, Rows * Columns);
3597 * Clear to end of display
3599 static void
3600 clear_to_end_of_display(void)
3602 clear_chars(g_coord, (Rows - g_coord.Y - 1)
3603 * Columns + (Columns - g_coord.X));
3608 * Clear to end of line
3610 static void
3611 clear_to_end_of_line(void)
3613 clear_chars(g_coord, Columns - g_coord.X);
3618 * Scroll the scroll region up by `cLines' lines
3620 static void
3621 scroll(unsigned cLines)
3623 COORD oldcoord = g_coord;
3625 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
3626 delete_lines(cLines);
3628 g_coord = oldcoord;
3633 * Set the scroll region
3635 static void
3636 set_scroll_region(
3637 unsigned left,
3638 unsigned top,
3639 unsigned right,
3640 unsigned bottom)
3642 if (left >= right
3643 || top >= bottom
3644 || right > (unsigned) Columns - 1
3645 || bottom > (unsigned) Rows - 1)
3646 return;
3648 g_srScrollRegion.Left = left;
3649 g_srScrollRegion.Top = top;
3650 g_srScrollRegion.Right = right;
3651 g_srScrollRegion.Bottom = bottom;
3656 * Insert `cLines' lines at the current cursor position
3658 static void
3659 insert_lines(unsigned cLines)
3661 SMALL_RECT source;
3662 COORD dest;
3663 CHAR_INFO fill;
3665 dest.X = 0;
3666 dest.Y = g_coord.Y + cLines;
3668 source.Left = 0;
3669 source.Top = g_coord.Y;
3670 source.Right = g_srScrollRegion.Right;
3671 source.Bottom = g_srScrollRegion.Bottom - cLines;
3673 fill.Char.AsciiChar = ' ';
3674 fill.Attributes = g_attrCurrent;
3676 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3678 /* Here we have to deal with a win32 console flake: If the scroll
3679 * region looks like abc and we scroll c to a and fill with d we get
3680 * cbd... if we scroll block c one line at a time to a, we get cdd...
3681 * vim expects cdd consistently... So we have to deal with that
3682 * here... (this also occurs scrolling the same way in the other
3683 * direction). */
3685 if (source.Bottom < dest.Y)
3687 COORD coord;
3689 coord.X = 0;
3690 coord.Y = source.Bottom;
3691 clear_chars(coord, Columns * (dest.Y - source.Bottom));
3697 * Delete `cLines' lines at the current cursor position
3699 static void
3700 delete_lines(unsigned cLines)
3702 SMALL_RECT source;
3703 COORD dest;
3704 CHAR_INFO fill;
3705 int nb;
3707 dest.X = 0;
3708 dest.Y = g_coord.Y;
3710 source.Left = 0;
3711 source.Top = g_coord.Y + cLines;
3712 source.Right = g_srScrollRegion.Right;
3713 source.Bottom = g_srScrollRegion.Bottom;
3715 fill.Char.AsciiChar = ' ';
3716 fill.Attributes = g_attrCurrent;
3718 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3720 /* Here we have to deal with a win32 console flake: If the scroll
3721 * region looks like abc and we scroll c to a and fill with d we get
3722 * cbd... if we scroll block c one line at a time to a, we get cdd...
3723 * vim expects cdd consistently... So we have to deal with that
3724 * here... (this also occurs scrolling the same way in the other
3725 * direction). */
3727 nb = dest.Y + (source.Bottom - source.Top) + 1;
3729 if (nb < source.Top)
3731 COORD coord;
3733 coord.X = 0;
3734 coord.Y = nb;
3735 clear_chars(coord, Columns * (source.Top - nb));
3741 * Set the cursor position
3743 static void
3744 gotoxy(
3745 unsigned x,
3746 unsigned y)
3748 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
3749 return;
3751 /* external cursor coords are 1-based; internal are 0-based */
3752 g_coord.X = x - 1;
3753 g_coord.Y = y - 1;
3754 SetConsoleCursorPosition(g_hConOut, g_coord);
3759 * Set the current text attribute = (foreground | background)
3760 * See ../doc/os_win32.txt for the numbers.
3762 static void
3763 textattr(WORD wAttr)
3765 g_attrCurrent = wAttr;
3767 SetConsoleTextAttribute(g_hConOut, wAttr);
3771 static void
3772 textcolor(WORD wAttr)
3774 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
3776 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3780 static void
3781 textbackground(WORD wAttr)
3783 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
3785 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3790 * restore the default text attribute (whatever we started with)
3792 static void
3793 normvideo(void)
3795 textattr(g_attrDefault);
3799 static WORD g_attrPreStandout = 0;
3802 * Make the text standout, by brightening it
3804 static void
3805 standout(void)
3807 g_attrPreStandout = g_attrCurrent;
3808 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
3813 * Turn off standout mode
3815 static void
3816 standend(void)
3818 if (g_attrPreStandout)
3820 textattr(g_attrPreStandout);
3821 g_attrPreStandout = 0;
3827 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
3829 void
3830 mch_set_normal_colors(void)
3832 char_u *p;
3833 int n;
3835 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
3836 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
3837 if (T_ME[0] == ESC && T_ME[1] == '|')
3839 p = T_ME + 2;
3840 n = getdigits(&p);
3841 if (*p == 'm' && n > 0)
3843 cterm_normal_fg_color = (n & 0xf) + 1;
3844 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
3851 * visual bell: flash the screen
3853 static void
3854 visual_bell(void)
3856 COORD coordOrigin = {0, 0};
3857 WORD attrFlash = ~g_attrCurrent & 0xff;
3859 DWORD dwDummy;
3860 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
3862 if (oldattrs == NULL)
3863 return;
3864 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3865 coordOrigin, &dwDummy);
3866 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
3867 coordOrigin, &dwDummy);
3869 Sleep(15); /* wait for 15 msec */
3870 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3871 coordOrigin, &dwDummy);
3872 vim_free(oldattrs);
3877 * Make the cursor visible or invisible
3879 static void
3880 cursor_visible(BOOL fVisible)
3882 s_cursor_visible = fVisible;
3883 #ifdef MCH_CURSOR_SHAPE
3884 mch_update_cursor();
3885 #endif
3890 * write `cchToWrite' characters in `pchBuf' to the screen
3891 * Returns the number of characters actually written (at least one).
3893 static BOOL
3894 write_chars(
3895 LPCSTR pchBuf,
3896 DWORD cchToWrite)
3898 COORD coord = g_coord;
3899 DWORD written;
3901 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
3902 coord, &written);
3903 /* When writing fails or didn't write a single character, pretend one
3904 * character was written, otherwise we get stuck. */
3905 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
3906 coord, &written) == 0
3907 || written == 0)
3908 written = 1;
3910 g_coord.X += (SHORT) written;
3912 while (g_coord.X > g_srScrollRegion.Right)
3914 g_coord.X -= (SHORT) Columns;
3915 if (g_coord.Y < g_srScrollRegion.Bottom)
3916 g_coord.Y++;
3919 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3921 return written;
3926 * mch_write(): write the output buffer to the screen, translating ESC
3927 * sequences into calls to console output routines.
3929 void
3930 mch_write(
3931 char_u *s,
3932 int len)
3934 s[len] = NUL;
3936 if (!term_console)
3938 write(1, s, (unsigned)len);
3939 return;
3942 /* translate ESC | sequences into faked bios calls */
3943 while (len--)
3945 /* optimization: use one single write_chars for runs of text,
3946 * rather than once per character It ain't curses, but it helps. */
3947 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
3949 if (p_wd)
3951 WaitForChar(p_wd);
3952 if (prefix != 0)
3953 prefix = 1;
3956 if (prefix != 0)
3958 DWORD nWritten;
3960 nWritten = write_chars(s, prefix);
3961 #ifdef MCH_WRITE_DUMP
3962 if (fdDump)
3964 fputc('>', fdDump);
3965 fwrite(s, sizeof(char_u), nWritten, fdDump);
3966 fputs("<\n", fdDump);
3968 #endif
3969 len -= (nWritten - 1);
3970 s += nWritten;
3972 else if (s[0] == '\n')
3974 /* \n, newline: go to the beginning of the next line or scroll */
3975 if (g_coord.Y == g_srScrollRegion.Bottom)
3977 scroll(1);
3978 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
3980 else
3982 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
3984 #ifdef MCH_WRITE_DUMP
3985 if (fdDump)
3986 fputs("\\n\n", fdDump);
3987 #endif
3988 s++;
3990 else if (s[0] == '\r')
3992 /* \r, carriage return: go to beginning of line */
3993 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
3994 #ifdef MCH_WRITE_DUMP
3995 if (fdDump)
3996 fputs("\\r\n", fdDump);
3997 #endif
3998 s++;
4000 else if (s[0] == '\b')
4002 /* \b, backspace: move cursor one position left */
4003 if (g_coord.X > g_srScrollRegion.Left)
4004 g_coord.X--;
4005 else if (g_coord.Y > g_srScrollRegion.Top)
4007 g_coord.X = g_srScrollRegion.Right;
4008 g_coord.Y--;
4010 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4011 #ifdef MCH_WRITE_DUMP
4012 if (fdDump)
4013 fputs("\\b\n", fdDump);
4014 #endif
4015 s++;
4017 else if (s[0] == '\a')
4019 /* \a, bell */
4020 MessageBeep(0xFFFFFFFF);
4021 #ifdef MCH_WRITE_DUMP
4022 if (fdDump)
4023 fputs("\\a\n", fdDump);
4024 #endif
4025 s++;
4027 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4029 #ifdef MCH_WRITE_DUMP
4030 char_u *old_s = s;
4031 #endif
4032 char_u *p;
4033 int arg1 = 0, arg2 = 0;
4035 switch (s[2])
4037 /* one or two numeric arguments, separated by ';' */
4039 case '0': case '1': case '2': case '3': case '4':
4040 case '5': case '6': case '7': case '8': case '9':
4041 p = s + 2;
4042 arg1 = getdigits(&p); /* no check for length! */
4043 if (p > s + len)
4044 break;
4046 if (*p == ';')
4048 ++p;
4049 arg2 = getdigits(&p); /* no check for length! */
4050 if (p > s + len)
4051 break;
4053 if (*p == 'H')
4054 gotoxy(arg2, arg1);
4055 else if (*p == 'r')
4056 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4058 else if (*p == 'A')
4060 /* move cursor up arg1 lines in same column */
4061 gotoxy(g_coord.X + 1,
4062 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4064 else if (*p == 'C')
4066 /* move cursor right arg1 columns in same line */
4067 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4068 g_coord.Y + 1);
4070 else if (*p == 'H')
4072 gotoxy(1, arg1);
4074 else if (*p == 'L')
4076 insert_lines(arg1);
4078 else if (*p == 'm')
4080 if (arg1 == 0)
4081 normvideo();
4082 else
4083 textattr((WORD) arg1);
4085 else if (*p == 'f')
4087 textcolor((WORD) arg1);
4089 else if (*p == 'b')
4091 textbackground((WORD) arg1);
4093 else if (*p == 'M')
4095 delete_lines(arg1);
4098 len -= (int)(p - s);
4099 s = p + 1;
4100 break;
4103 /* Three-character escape sequences */
4105 case 'A':
4106 /* move cursor up one line in same column */
4107 gotoxy(g_coord.X + 1,
4108 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4109 goto got3;
4111 case 'B':
4112 visual_bell();
4113 goto got3;
4115 case 'C':
4116 /* move cursor right one column in same line */
4117 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4118 g_coord.Y + 1);
4119 goto got3;
4121 case 'E':
4122 termcap_mode_end();
4123 goto got3;
4125 case 'F':
4126 standout();
4127 goto got3;
4129 case 'f':
4130 standend();
4131 goto got3;
4133 case 'H':
4134 gotoxy(1, 1);
4135 goto got3;
4137 case 'j':
4138 clear_to_end_of_display();
4139 goto got3;
4141 case 'J':
4142 clear_screen();
4143 goto got3;
4145 case 'K':
4146 clear_to_end_of_line();
4147 goto got3;
4149 case 'L':
4150 insert_lines(1);
4151 goto got3;
4153 case 'M':
4154 delete_lines(1);
4155 goto got3;
4157 case 'S':
4158 termcap_mode_start();
4159 goto got3;
4161 case 'V':
4162 cursor_visible(TRUE);
4163 goto got3;
4165 case 'v':
4166 cursor_visible(FALSE);
4167 goto got3;
4169 got3:
4170 s += 3;
4171 len -= 2;
4174 #ifdef MCH_WRITE_DUMP
4175 if (fdDump)
4177 fputs("ESC | ", fdDump);
4178 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4179 fputc('\n', fdDump);
4181 #endif
4183 else
4185 /* Write a single character */
4186 DWORD nWritten;
4188 nWritten = write_chars(s, 1);
4189 #ifdef MCH_WRITE_DUMP
4190 if (fdDump)
4192 fputc('>', fdDump);
4193 fwrite(s, sizeof(char_u), nWritten, fdDump);
4194 fputs("<\n", fdDump);
4196 #endif
4198 len -= (nWritten - 1);
4199 s += nWritten;
4203 #ifdef MCH_WRITE_DUMP
4204 if (fdDump)
4205 fflush(fdDump);
4206 #endif
4209 #endif /* FEAT_GUI_W32 */
4213 * Delay for half a second.
4215 /*ARGSUSED*/
4216 void
4217 mch_delay(
4218 long msec,
4219 int ignoreinput)
4221 #ifdef FEAT_GUI_W32
4222 Sleep((int)msec); /* never wait for input */
4223 #else /* Console */
4224 if (ignoreinput)
4225 # ifdef FEAT_MZSCHEME
4226 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4228 int towait = p_mzq;
4230 /* if msec is large enough, wait by portions in p_mzq */
4231 while (msec > 0)
4233 mzvim_check_threads();
4234 if (msec < towait)
4235 towait = msec;
4236 Sleep(towait);
4237 msec -= towait;
4240 else
4241 # endif
4242 Sleep((int)msec);
4243 else
4244 WaitForChar(msec);
4245 #endif
4250 * this version of remove is not scared by a readonly (backup) file
4251 * Return 0 for success, -1 for failure.
4254 mch_remove(char_u *name)
4256 #ifdef FEAT_MBYTE
4257 WCHAR *wn = NULL;
4258 int n;
4260 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4262 wn = enc_to_utf16(name, NULL);
4263 if (wn != NULL)
4265 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4266 n = DeleteFileW(wn) ? 0 : -1;
4267 vim_free(wn);
4268 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4269 return n;
4270 /* Retry with non-wide function (for Windows 98). */
4273 #endif
4274 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4275 return DeleteFile(name) ? 0 : -1;
4280 * check for an "interrupt signal": CTRL-break or CTRL-C
4282 void
4283 mch_breakcheck(void)
4285 #ifndef FEAT_GUI_W32 /* never used */
4286 if (g_fCtrlCPressed || g_fCBrkPressed)
4288 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4289 got_int = TRUE;
4291 #endif
4296 * How much memory is available?
4297 * Return sum of available physical and page file memory.
4299 /*ARGSUSED*/
4300 long_u
4301 mch_avail_mem(int special)
4303 MEMORYSTATUS ms;
4305 ms.dwLength = sizeof(MEMORYSTATUS);
4306 GlobalMemoryStatus(&ms);
4307 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
4310 #ifdef FEAT_MBYTE
4312 * Same code as below, but with wide functions and no comments.
4313 * Return 0 for success, non-zero for failure.
4316 mch_wrename(WCHAR *wold, WCHAR *wnew)
4318 WCHAR *p;
4319 int i;
4320 WCHAR szTempFile[_MAX_PATH + 1];
4321 WCHAR szNewPath[_MAX_PATH + 1];
4322 HANDLE hf;
4324 if (!mch_windows95())
4326 p = wold;
4327 for (i = 0; wold[i] != NUL; ++i)
4328 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
4329 && wold[i + 1] != 0)
4330 p = wold + i + 1;
4331 if ((int)(wold + i - p) < 8 || p[6] != '~')
4332 return (MoveFileW(wold, wnew) == 0);
4335 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
4336 return -1;
4337 *p = NUL;
4339 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
4340 return -2;
4342 if (!DeleteFileW(szTempFile))
4343 return -3;
4345 if (!MoveFileW(wold, szTempFile))
4346 return -4;
4348 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4349 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4350 return -5;
4351 if (!CloseHandle(hf))
4352 return -6;
4354 if (!MoveFileW(szTempFile, wnew))
4356 (void)MoveFileW(szTempFile, wold);
4357 return -7;
4360 DeleteFileW(szTempFile);
4362 if (!DeleteFileW(wold))
4363 return -8;
4365 return 0;
4367 #endif
4371 * mch_rename() works around a bug in rename (aka MoveFile) in
4372 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4373 * file whose short file name is "FOO.BAR" (its long file name will
4374 * be correct: "foo.bar~"). Because a file can be accessed by
4375 * either its SFN or its LFN, "foo.bar" has effectively been
4376 * renamed to "foo.bar", which is not at all what was wanted. This
4377 * seems to happen only when renaming files with three-character
4378 * extensions by appending a suffix that does not include ".".
4379 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4381 * There is another problem, which isn't really a bug but isn't right either:
4382 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
4383 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
4384 * service pack 6. Doesn't seem to happen on Windows 98.
4386 * Like rename(), returns 0 upon success, non-zero upon failure.
4387 * Should probably set errno appropriately when errors occur.
4390 mch_rename(
4391 const char *pszOldFile,
4392 const char *pszNewFile)
4394 char szTempFile[_MAX_PATH+1];
4395 char szNewPath[_MAX_PATH+1];
4396 char *pszFilePart;
4397 HANDLE hf;
4398 #ifdef FEAT_MBYTE
4399 WCHAR *wold = NULL;
4400 WCHAR *wnew = NULL;
4401 int retval = -1;
4403 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4405 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
4406 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
4407 if (wold != NULL && wnew != NULL)
4408 retval = mch_wrename(wold, wnew);
4409 vim_free(wold);
4410 vim_free(wnew);
4411 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4412 return retval;
4413 /* Retry with non-wide function (for Windows 98). */
4415 #endif
4418 * No need to play tricks if not running Windows 95, unless the file name
4419 * contains a "~" as the seventh character.
4421 if (!mch_windows95())
4423 pszFilePart = (char *)gettail((char_u *)pszOldFile);
4424 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
4425 return rename(pszOldFile, pszNewFile);
4428 /* Get base path of new file name. Undocumented feature: If pszNewFile is
4429 * a directory, no error is returned and pszFilePart will be NULL. */
4430 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
4431 || pszFilePart == NULL)
4432 return -1;
4433 *pszFilePart = NUL;
4435 /* Get (and create) a unique temporary file name in directory of new file */
4436 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
4437 return -2;
4439 /* blow the temp file away */
4440 if (!DeleteFile(szTempFile))
4441 return -3;
4443 /* rename old file to the temp file */
4444 if (!MoveFile(pszOldFile, szTempFile))
4445 return -4;
4447 /* now create an empty file called pszOldFile; this prevents the operating
4448 * system using pszOldFile as an alias (SFN) if we're renaming within the
4449 * same directory. For example, we're editing a file called
4450 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
4451 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
4452 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
4453 * cause all sorts of problems later in buf_write(). So, we create an
4454 * empty file called filena~1.txt and the system will have to find some
4455 * other SFN for filena~1.txt~, such as filena~2.txt
4457 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4458 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4459 return -5;
4460 if (!CloseHandle(hf))
4461 return -6;
4463 /* rename the temp file to the new file */
4464 if (!MoveFile(szTempFile, pszNewFile))
4466 /* Renaming failed. Rename the file back to its old name, so that it
4467 * looks like nothing happened. */
4468 (void)MoveFile(szTempFile, pszOldFile);
4470 return -7;
4473 /* Seems to be left around on Novell filesystems */
4474 DeleteFile(szTempFile);
4476 /* finally, remove the empty old file */
4477 if (!DeleteFile(pszOldFile))
4478 return -8;
4480 return 0; /* success */
4484 * Get the default shell for the current hardware platform
4486 char *
4487 default_shell(void)
4489 char* psz = NULL;
4491 PlatformId();
4493 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
4494 psz = "cmd.exe";
4495 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
4496 psz = "command.com";
4498 return psz;
4502 * mch_access() extends access() to do more detailed check on network drives.
4503 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
4506 mch_access(char *n, int p)
4508 HANDLE hFile;
4509 DWORD am;
4510 int retval = -1; /* default: fail */
4511 #ifdef FEAT_MBYTE
4512 WCHAR *wn = NULL;
4514 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4515 wn = enc_to_utf16(n, NULL);
4516 #endif
4518 if (mch_isdir(n))
4520 char TempName[_MAX_PATH + 16] = "";
4521 #ifdef FEAT_MBYTE
4522 WCHAR TempNameW[_MAX_PATH + 16] = L"";
4523 #endif
4525 if (p & R_OK)
4527 /* Read check is performed by seeing if we can do a find file on
4528 * the directory for any file. */
4529 #ifdef FEAT_MBYTE
4530 if (wn != NULL)
4532 int i;
4533 WIN32_FIND_DATAW d;
4535 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
4536 TempNameW[i] = wn[i];
4537 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
4538 TempNameW[i++] = '\\';
4539 TempNameW[i++] = '*';
4540 TempNameW[i++] = 0;
4542 hFile = FindFirstFileW(TempNameW, &d);
4543 if (hFile == INVALID_HANDLE_VALUE)
4545 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4546 goto getout;
4548 /* Retry with non-wide function (for Windows 98). */
4549 vim_free(wn);
4550 wn = NULL;
4552 else
4553 (void)FindClose(hFile);
4555 if (wn == NULL)
4556 #endif
4558 char *pch;
4559 WIN32_FIND_DATA d;
4561 vim_strncpy(TempName, n, _MAX_PATH);
4562 pch = TempName + STRLEN(TempName) - 1;
4563 if (*pch != '\\' && *pch != '/')
4564 *++pch = '\\';
4565 *++pch = '*';
4566 *++pch = NUL;
4568 hFile = FindFirstFile(TempName, &d);
4569 if (hFile == INVALID_HANDLE_VALUE)
4570 goto getout;
4571 (void)FindClose(hFile);
4575 if (p & W_OK)
4577 /* Trying to create a temporary file in the directory should catch
4578 * directories on read-only network shares. However, in
4579 * directories whose ACL allows writes but denies deletes will end
4580 * up keeping the temporary file :-(. */
4581 #ifdef FEAT_MBYTE
4582 if (wn != NULL)
4584 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
4586 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4587 goto getout;
4589 /* Retry with non-wide function (for Windows 98). */
4590 vim_free(wn);
4591 wn = NULL;
4593 else
4594 DeleteFileW(TempNameW);
4596 if (wn == NULL)
4597 #endif
4599 if (!GetTempFileName(n, "VIM", 0, TempName))
4600 goto getout;
4601 mch_remove((char_u *)TempName);
4605 else
4607 /* Trying to open the file for the required access does ACL, read-only
4608 * network share, and file attribute checks. */
4609 am = ((p & W_OK) ? GENERIC_WRITE : 0)
4610 | ((p & R_OK) ? GENERIC_READ : 0);
4611 #ifdef FEAT_MBYTE
4612 if (wn != NULL)
4614 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4615 if (hFile == INVALID_HANDLE_VALUE
4616 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4618 /* Retry with non-wide function (for Windows 98). */
4619 vim_free(wn);
4620 wn = NULL;
4623 if (wn == NULL)
4624 #endif
4625 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4626 if (hFile == INVALID_HANDLE_VALUE)
4627 goto getout;
4628 CloseHandle(hFile);
4631 retval = 0; /* success */
4632 getout:
4633 #ifdef FEAT_MBYTE
4634 vim_free(wn);
4635 #endif
4636 return retval;
4639 #if defined(FEAT_MBYTE) || defined(PROTO)
4641 * Version of open() that may use UTF-16 file name.
4644 mch_open(char *name, int flags, int mode)
4646 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
4647 # ifndef __BORLANDC__
4648 WCHAR *wn;
4649 int f;
4651 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4653 wn = enc_to_utf16(name, NULL);
4654 if (wn != NULL)
4656 f = _wopen(wn, flags, mode);
4657 vim_free(wn);
4658 if (f >= 0)
4659 return f;
4660 /* Retry with non-wide function (for Windows 98). Can't use
4661 * GetLastError() here and it's unclear what errno gets set to if
4662 * the _wopen() fails for missing wide functions. */
4665 # endif
4667 return open(name, flags, mode);
4671 * Version of fopen() that may use UTF-16 file name.
4673 FILE *
4674 mch_fopen(char *name, char *mode)
4676 WCHAR *wn, *wm;
4677 FILE *f = NULL;
4679 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
4680 # ifdef __BORLANDC__
4681 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4682 && g_PlatformId == VER_PLATFORM_WIN32_NT
4683 # endif
4686 # if defined(DEBUG) && _MSC_VER >= 1400
4687 /* Work around an annoying assertion in the Microsoft debug CRT
4688 * when mode's text/binary setting doesn't match _get_fmode(). */
4689 char newMode = mode[strlen(mode) - 1];
4690 int oldMode = 0;
4692 _get_fmode(&oldMode);
4693 if (newMode == 't')
4694 _set_fmode(_O_TEXT);
4695 else if (newMode == 'b')
4696 _set_fmode(_O_BINARY);
4697 # endif
4698 wn = enc_to_utf16(name, NULL);
4699 wm = enc_to_utf16(mode, NULL);
4700 if (wn != NULL && wm != NULL)
4701 f = _wfopen(wn, wm);
4702 vim_free(wn);
4703 vim_free(wm);
4705 # if defined(DEBUG) && _MSC_VER >= 1400
4706 _set_fmode(oldMode);
4707 # endif
4709 if (f != NULL)
4710 return f;
4711 /* Retry with non-wide function (for Windows 98). Can't use
4712 * GetLastError() here and it's unclear what errno gets set to if
4713 * the _wfopen() fails for missing wide functions. */
4716 return fopen(name, mode);
4718 #endif
4720 #ifdef FEAT_MBYTE
4722 * SUB STREAM (aka info stream) handling:
4724 * NTFS can have sub streams for each file. Normal contents of file is
4725 * stored in the main stream, and extra contents (author information and
4726 * title and so on) can be stored in sub stream. After Windows 2000, user
4727 * can access and store those informations in sub streams via explorer's
4728 * property menuitem in right click menu. Those informations in sub streams
4729 * were lost when copying only the main stream. So we have to copy sub
4730 * streams.
4732 * Incomplete explanation:
4733 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
4734 * More useful info and an example:
4735 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
4739 * Copy info stream data "substream". Read from the file with BackupRead(sh)
4740 * and write to stream "substream" of file "to".
4741 * Errors are ignored.
4743 static void
4744 copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
4746 HANDLE hTo;
4747 WCHAR *to_name;
4749 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
4750 wcscpy(to_name, to);
4751 wcscat(to_name, substream);
4753 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
4754 FILE_ATTRIBUTE_NORMAL, NULL);
4755 if (hTo != INVALID_HANDLE_VALUE)
4757 long done;
4758 DWORD todo;
4759 DWORD readcnt, written;
4760 char buf[4096];
4762 /* Copy block of bytes at a time. Abort when something goes wrong. */
4763 for (done = 0; done < len; done += written)
4765 /* (size_t) cast for Borland C 5.5 */
4766 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
4767 : (size_t)(len - done));
4768 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
4769 FALSE, FALSE, context)
4770 || readcnt != todo
4771 || !WriteFile(hTo, buf, todo, &written, NULL)
4772 || written != todo)
4773 break;
4775 CloseHandle(hTo);
4778 free(to_name);
4782 * Copy info streams from file "from" to file "to".
4784 static void
4785 copy_infostreams(char_u *from, char_u *to)
4787 WCHAR *fromw;
4788 WCHAR *tow;
4789 HANDLE sh;
4790 WIN32_STREAM_ID sid;
4791 int headersize;
4792 WCHAR streamname[_MAX_PATH];
4793 DWORD readcount;
4794 void *context = NULL;
4795 DWORD lo, hi;
4796 int len;
4798 /* Convert the file names to wide characters. */
4799 fromw = enc_to_utf16(from, NULL);
4800 tow = enc_to_utf16(to, NULL);
4801 if (fromw != NULL && tow != NULL)
4803 /* Open the file for reading. */
4804 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
4805 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4806 if (sh != INVALID_HANDLE_VALUE)
4808 /* Use BackupRead() to find the info streams. Repeat until we
4809 * have done them all.*/
4810 for (;;)
4812 /* Get the header to find the length of the stream name. If
4813 * the "readcount" is zero we have done all info streams. */
4814 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
4815 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
4816 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
4817 &readcount, FALSE, FALSE, &context)
4818 || readcount == 0)
4819 break;
4821 /* We only deal with streams that have a name. The normal
4822 * file data appears to be without a name, even though docs
4823 * suggest it is called "::$DATA". */
4824 if (sid.dwStreamNameSize > 0)
4826 /* Read the stream name. */
4827 if (!BackupRead(sh, (LPBYTE)streamname,
4828 sid.dwStreamNameSize,
4829 &readcount, FALSE, FALSE, &context))
4830 break;
4832 /* Copy an info stream with a name ":anything:$DATA".
4833 * Skip "::$DATA", it has no stream name (examples suggest
4834 * it might be used for the normal file contents).
4835 * Note that BackupRead() counts bytes, but the name is in
4836 * wide characters. */
4837 len = readcount / sizeof(WCHAR);
4838 streamname[len] = 0;
4839 if (len > 7 && wcsicmp(streamname + len - 6,
4840 L":$DATA") == 0)
4842 streamname[len - 6] = 0;
4843 copy_substream(sh, &context, tow, streamname,
4844 (long)sid.Size.u.LowPart);
4848 /* Advance to the next stream. We might try seeking too far,
4849 * but BackupSeek() doesn't skip over stream borders, thus
4850 * that's OK. */
4851 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
4852 &lo, &hi, &context);
4855 /* Clear the context. */
4856 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
4858 CloseHandle(sh);
4861 vim_free(fromw);
4862 vim_free(tow);
4864 #endif
4867 * Copy file attributes from file "from" to file "to".
4868 * For Windows NT and later we copy info streams.
4869 * Always returns zero, errors are ignored.
4872 mch_copy_file_attribute(char_u *from, char_u *to)
4874 #ifdef FEAT_MBYTE
4875 /* File streams only work on Windows NT and later. */
4876 PlatformId();
4877 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
4878 copy_infostreams(from, to);
4879 #endif
4880 return 0;
4883 #if defined(MYRESETSTKOFLW) || defined(PROTO)
4885 * Recreate a destroyed stack guard page in win32.
4886 * Written by Benjamin Peterson.
4889 /* These magic numbers are from the MS header files */
4890 #define MIN_STACK_WIN9X 17
4891 #define MIN_STACK_WINNT 2
4894 * This function does the same thing as _resetstkoflw(), which is only
4895 * available in DevStudio .net and later.
4896 * Returns 0 for failure, 1 for success.
4899 myresetstkoflw(void)
4901 BYTE *pStackPtr;
4902 BYTE *pGuardPage;
4903 BYTE *pStackBase;
4904 BYTE *pLowestPossiblePage;
4905 MEMORY_BASIC_INFORMATION mbi;
4906 SYSTEM_INFO si;
4907 DWORD nPageSize;
4908 DWORD dummy;
4910 /* This code will not work on win32s. */
4911 PlatformId();
4912 if (g_PlatformId == VER_PLATFORM_WIN32s)
4913 return 0;
4915 /* We need to know the system page size. */
4916 GetSystemInfo(&si);
4917 nPageSize = si.dwPageSize;
4919 /* ...and the current stack pointer */
4920 pStackPtr = (BYTE*)_alloca(1);
4922 /* ...and the base of the stack. */
4923 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
4924 return 0;
4925 pStackBase = (BYTE*)mbi.AllocationBase;
4927 /* ...and the page thats min_stack_req pages away from stack base; this is
4928 * the lowest page we could use. */
4929 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
4930 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
4932 /* On Win95, we want the next page down from the end of the stack. */
4933 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
4935 /* Find the page that's only 1 page down from the page that the stack
4936 * ptr is in. */
4937 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
4938 / (DWORD)nPageSize) - 1));
4939 if (pGuardPage < pLowestPossiblePage)
4940 return 0;
4942 /* Apply the noaccess attribute to the page -- there's no guard
4943 * attribute in win95-type OSes. */
4944 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
4945 return 0;
4947 else
4949 /* On NT, however, we want the first committed page in the stack Start
4950 * at the stack base and move forward through memory until we find a
4951 * committed block. */
4952 BYTE *pBlock = pStackBase;
4954 for (;;)
4956 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
4957 return 0;
4959 pBlock += mbi.RegionSize;
4961 if (mbi.State & MEM_COMMIT)
4962 break;
4965 /* mbi now describes the first committed block in the stack. */
4966 if (mbi.Protect & PAGE_GUARD)
4967 return 1;
4969 /* decide where the guard page should start */
4970 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
4971 pGuardPage = pLowestPossiblePage;
4972 else
4973 pGuardPage = (BYTE*)mbi.BaseAddress;
4975 /* allocate the guard page */
4976 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
4977 return 0;
4979 /* apply the guard attribute to the page */
4980 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
4981 &dummy))
4982 return 0;
4985 return 1;
4987 #endif
4990 #if defined(FEAT_MBYTE) || defined(PROTO)
4992 * The command line arguments in UCS2
4994 static int nArgsW = 0;
4995 static LPWSTR *ArglistW = NULL;
4996 static int global_argc = 0;
4997 static char **global_argv;
4999 static int used_file_argc = 0; /* last argument in global_argv[] used
5000 for the argument list. */
5001 static int *used_file_indexes = NULL; /* indexes in global_argv[] for
5002 command line arguments added to
5003 the argument list */
5004 static int used_file_count = 0; /* nr of entries in used_file_indexes */
5005 static int used_file_literal = FALSE; /* take file names literally */
5006 static int used_file_full_path = FALSE; /* file name was full path */
5007 static int used_file_diff_mode = FALSE; /* file name was with diff mode */
5008 static int used_alist_count = 0;
5012 * Get the command line arguments. Unicode version.
5013 * Returns argc. Zero when something fails.
5016 get_cmd_argsW(char ***argvp)
5018 char **argv = NULL;
5019 int argc = 0;
5020 int i;
5022 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5023 if (ArglistW != NULL)
5025 argv = malloc((nArgsW + 1) * sizeof(char *));
5026 if (argv != NULL)
5028 argc = nArgsW;
5029 argv[argc] = NULL;
5030 for (i = 0; i < argc; ++i)
5032 int len;
5034 /* Convert each Unicode argument to the current codepage. */
5035 WideCharToMultiByte_alloc(GetACP(), 0,
5036 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
5037 (LPSTR *)&argv[i], &len, 0, 0);
5038 if (argv[i] == NULL)
5040 /* Out of memory, clear everything. */
5041 while (i > 0)
5042 free(argv[--i]);
5043 free(argv);
5044 argc = 0;
5050 global_argc = argc;
5051 global_argv = argv;
5052 if (argc > 0)
5053 used_file_indexes = malloc(argc * sizeof(int));
5055 if (argvp != NULL)
5056 *argvp = argv;
5057 return argc;
5060 void
5061 free_cmd_argsW(void)
5063 if (ArglistW != NULL)
5065 GlobalFree(ArglistW);
5066 ArglistW = NULL;
5071 * Remember "name" is an argument that was added to the argument list.
5072 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5073 * is called.
5075 void
5076 used_file_arg(char *name, int literal, int full_path, int diff_mode)
5078 int i;
5080 if (used_file_indexes == NULL)
5081 return;
5082 for (i = used_file_argc + 1; i < global_argc; ++i)
5083 if (STRCMP(global_argv[i], name) == 0)
5085 used_file_argc = i;
5086 used_file_indexes[used_file_count++] = i;
5087 break;
5089 used_file_literal = literal;
5090 used_file_full_path = full_path;
5091 used_file_diff_mode = diff_mode;
5095 * Remember the length of the argument list as it was. If it changes then we
5096 * leave it alone when 'encoding' is set.
5098 void
5099 set_alist_count(void)
5101 used_alist_count = GARGCOUNT;
5105 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5106 * has been changed while starting up. Use the UCS-2 command line arguments
5107 * and convert them to 'encoding'.
5109 void
5110 fix_arg_enc(void)
5112 int i;
5113 int idx;
5114 char_u *str;
5115 int *fnum_list;
5117 /* Safety checks:
5118 * - if argument count differs between the wide and non-wide argument
5119 * list, something must be wrong.
5120 * - the file name arguments must have been located.
5121 * - the length of the argument list wasn't changed by the user.
5123 if (global_argc != nArgsW
5124 || ArglistW == NULL
5125 || used_file_indexes == NULL
5126 || used_file_count == 0
5127 || used_alist_count != GARGCOUNT)
5128 return;
5130 /* Remember the buffer numbers for the arguments. */
5131 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5132 if (fnum_list == NULL)
5133 return; /* out of memory */
5134 for (i = 0; i < GARGCOUNT; ++i)
5135 fnum_list[i] = GARGLIST[i].ae_fnum;
5137 /* Clear the argument list. Make room for the new arguments. */
5138 alist_clear(&global_alist);
5139 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
5140 return; /* out of memory */
5142 for (i = 0; i < used_file_count; ++i)
5144 idx = used_file_indexes[i];
5145 str = utf16_to_enc(ArglistW[idx], NULL);
5146 if (str != NULL)
5148 #ifdef FEAT_DIFF
5149 /* When using diff mode may need to concatenate file name to
5150 * directory name. Just like it's done in main(). */
5151 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5152 && !mch_isdir(alist_name(&GARGLIST[0])))
5154 char_u *r;
5156 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5157 if (r != NULL)
5159 vim_free(str);
5160 str = r;
5163 #endif
5164 /* Re-use the old buffer by renaming it. When not using literal
5165 * names it's done by alist_expand() below. */
5166 if (used_file_literal)
5167 buf_set_name(fnum_list[i], str);
5169 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
5173 if (!used_file_literal)
5175 /* Now expand wildcards in the arguments. */
5176 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5177 * filename characters but are excluded from 'isfname' to make
5178 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5179 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
5180 alist_expand(fnum_list, used_alist_count);
5181 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5184 /* If wildcard expansion failed, we are editing the first file of the
5185 * arglist and there is no file name: Edit the first argument now. */
5186 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5188 do_cmdline_cmd((char_u *)":rewind");
5189 if (GARGCOUNT == 1 && used_file_full_path)
5190 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5193 set_alist_count();
5195 #endif