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.
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.
27 # include "if_mzsch.h"
30 #include <sys/types.h>
45 #if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
46 # include <shellapi.h>
50 # ifndef FROM_LEFT_1ST_BUTTON_PRESSED
51 # define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
53 # ifndef RIGHTMOST_BUTTON_PRESSED
54 # define RIGHTMOST_BUTTON_PRESSED 0x0002
56 # ifndef FROM_LEFT_2ND_BUTTON_PRESSED
57 # define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
59 # ifndef FROM_LEFT_3RD_BUTTON_PRESSED
60 # define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
62 # ifndef FROM_LEFT_4TH_BUTTON_PRESSED
63 # define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
70 # define MOUSE_MOVED 0x0001
73 # define DOUBLE_CLICK 0x0002
77 /* Record all output and all keyboard & mouse input */
78 /* #define MCH_WRITE_DUMP */
85 * When generating prototypes for Win32 on Unix, these lines make the syntax
86 * errors disappear. They do not need to be correct.
91 typedef char * LPCSTR
;
92 typedef char * LPWSTR
;
93 typedef int ACCESS_MASK
;
96 typedef int CONSOLE_CURSOR_INFO
;
103 typedef int HINSTANCE
;
105 typedef int INPUT_RECORD
;
106 typedef int KEY_EVENT_RECORD
;
114 typedef int MOUSE_EVENT_RECORD
;
118 typedef int PRINTDLG
;
119 typedef int PSECURITY_DESCRIPTOR
;
121 typedef int SECURITY_INFORMATION
;
123 typedef int SMALL_RECT
;
124 typedef int TEXTMETRIC
;
125 typedef int TOKEN_INFORMATION_CLASS
;
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); */
142 # define WINBASEAPI __stdcall
144 #if defined(__BORLANDC__)
145 typedef BOOL (__stdcall
*PFNGCKLN
)(LPSTR
);
147 typedef WINBASEAPI
BOOL (WINAPI
*PFNGCKLN
)(LPSTR
);
149 static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName
= NULL
;
152 #if defined(__BORLANDC__)
153 /* Strangely Borland uses a non-standard name. */
154 # define wcsicmp(a, b) wcscmpi((a), (b))
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
;
200 static int s_dont_use_vimrun
= TRUE
;
201 static int need_vimrun_warning
= FALSE
;
202 static char *vimrun_path
= "vimrun ";
206 static int suppress_winsize
= 1; /* don't fiddle with console */
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);
220 exe_name
= FullName_save((char_u
*)temp
, FALSE
);
223 if (!did_set_PATH
&& exe_name
!= NULL
)
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));
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
);
247 #if defined(DYNAMIC_GETTEXT) || defined(PROTO)
248 # ifndef GETTEXT_DLL_WITHENC
249 # define GETTEXT_DLL_WITHENC "libintl2.dll"
252 # define GETTEXT_DLL "libintl.dll"
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
)
278 {"gettext", (FARPROC
*)&dyn_libintl_gettext
},
279 {"textdomain", (FARPROC
*)&dyn_libintl_textdomain
},
280 {"bindtextdomain", (FARPROC
*)&dyn_libintl_bindtextdomain
},
284 /* No need to initialize twice. */
287 /* Load gettext library (libintl.dll) */
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.
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. */
308 char_u dirname
[_MAX_PATH
];
310 /* Try using the path from gvim.exe to find the .dll there. */
312 STRCPY(dirname
, exe_name
);
313 STRCPY(gettail(dirname
), GETTEXT_DLL
);
314 hLibintlDLL
= LoadLibrary((char *)dirname
);
320 EMSG2(_(e_loadlib
), GETTEXT_DLL
);
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
)
336 EMSG2(_(e_loadfunc
), libintl_entry
[i
].name
);
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
;
357 FreeLibrary(hLibintlDLL
);
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
;
367 null_libintl_gettext(const char *msgid
)
374 null_libintl_bindtextdomain(const char *domainname
, const char *dirname
)
381 null_libintl_bind_textdomain_codeset(const char *domainname
,
389 null_libintl_textdomain(const char *domainname
)
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
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
;
422 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
423 * VER_PLATFORM_WIN32_WINDOWS (Win95).
428 static int done
= FALSE
;
434 ovi
.dwOSVersionInfoSize
= sizeof(ovi
);
437 g_PlatformId
= ovi
.dwPlatformId
;
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
);
476 * Return TRUE when running on Windows 95 (or 98 or ME).
477 * Only to be used after mch_init().
482 return g_PlatformId
== VER_PLATFORM_WIN32_WINDOWS
;
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
;
495 win32ssynch_cb(HWND hwnd
, LPARAM lparam
)
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.
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*/
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', },
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', },
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)
597 #if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
598 # define AChar AsciiChar
600 # define AChar uChar.AsciiChar
603 /* The return code indicates key code size. */
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];
619 pker
->AChar
= (CHAR
) awAnsiCode
[1];
624 if (pker
->AChar
!= 0)
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);
656 pker
->AChar
= (CHAR
) awAnsiCode
[0];
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)
675 static BOOL g_fJustGotFocus
= FALSE
;
678 * Decode a KEY_EVENT into one or two keystrokes
682 KEY_EVENT_RECORD
*pker
,
689 const int nModifs
= pker
->dwControlKeyState
& (SHIFT
| ALT
| CTRL
);
692 g_fJustGotFocus
= FALSE
;
694 /* ignore key up events */
698 /* ignore some keystrokes */
699 switch (pker
->wVirtualKeyCode
)
704 case VK_MENU
: /* Alt key */
712 if ((nModifs
& CTRL
) != 0 && (nModifs
& ~CTRL
) == 0 && pker
->AChar
== NUL
)
714 /* Ctrl-6 is Ctrl-^ */
715 if (pker
->wVirtualKeyCode
== '6')
720 /* Ctrl-2 is Ctrl-@ */
721 else if (pker
->wVirtualKeyCode
== '2')
726 /* Ctrl-- is Ctrl-_ */
727 else if (pker
->wVirtualKeyCode
== 0xBD)
735 if (pker
->wVirtualKeyCode
== VK_TAB
&& (nModifs
& SHIFT_PRESSED
))
742 for (i
= sizeof(VirtKeyMap
) / sizeof(VirtKeyMap
[0]); --i
>= 0; )
744 if (VirtKeyMap
[i
].wVirtKey
== pker
->wVirtualKeyCode
)
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
;
757 if (VirtKeyMap
[i
].fAnsiKey
)
768 i
= win32_kbd_patch_key(pker
);
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
);
801 # pragma optimize("", on)
804 #endif /* FEAT_GUI_W32 */
810 * For the GUI the mouse handling is in gui_w32.c.
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
837 GetConsoleMode(g_hConIn
, &cmodein
);
840 cmodein
|= ENABLE_MOUSE_INPUT
;
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.
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;
885 static int s_old_topfill
= 0;
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
;
901 if (cButtons
== 0 && !GetNumberOfConsoleMouseButtons(&cButtons
))
904 if (!g_fMouseAvail
|| !g_fMouseActive
)
910 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
913 g_fJustGotFocus
= FALSE
;
917 /* unprocessed mouse click? */
918 if (g_nMouseClick
!= -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
)
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 */
940 nButton
= MOUSE_RELEASE
;
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
)
958 /* wait a short time for next input event */
959 if (WaitForSingleObject(g_hConIn
, p_mouset
/ 3)
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
))
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
)
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
)
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
1044 || s_old_topfill
!= curwin
->w_topfill
1046 || (int)(dwCurrentTime
- s_dwLastClickTime
) > p_mouset
)
1050 else if (++s_cClicks
> 4)
1055 s_dwLastClickTime
= dwCurrentTime
;
1058 else if (pmer
->dwEventFlags
== MOUSE_MOVED
)
1060 if (nButton
!= -1 && nButton
!= MOUSE_RELEASE
)
1061 nButton
= MOUSE_DRAG
;
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
)
1093 s_xOldMouse
= g_xMouse
;
1094 s_yOldMouse
= g_yMouse
;
1095 s_old_topline
= curwin
->w_topline
;
1097 s_old_topfill
= curwin
->w_topfill
;
1099 s_nOldMouseClick
= g_nMouseClick
;
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)
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
);
1126 mch_update_cursor(void)
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 */
1139 thickness
= shape_table
[idx
].percentage
;
1140 mch_set_cursor_shape(thickness
);
1144 #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1146 * Handle FOCUS_EVENT.
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.
1161 WaitForChar(long msec
)
1163 DWORD dwNow
= 0, dwEndTime
= 0;
1169 /* Wait until the specified time has elapsed. */
1170 dwEndTime
= GetTickCount() + msec
;
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.
1180 #ifdef FEAT_MZSCHEME
1181 mzvim_check_threads();
1183 #ifdef FEAT_CLIENTSERVER
1184 serverProcessPendingMessages();
1188 || g_nMouseClick
!= -1
1190 #ifdef FEAT_CLIENTSERVER
1191 || input_available()
1198 /* If the specified wait time has passed, return. */
1199 dwNow
= GetTickCount();
1200 if (dwNow
>= dwEndTime
)
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' */
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
)
1218 if (WaitForSingleObject(g_hConIn
, dwWaitTime
) != WAIT_OBJECT_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
);
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
);
1259 if (decode_key_event(&ir
.Event
.KeyEvent
, &ch
, &ch2
,
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
)
1271 else if (ir
.EventType
== MOUSE_EVENT
1272 && decode_mouse_event(&ir
.Event
.MouseEvent
))
1280 #ifdef FEAT_CLIENTSERVER
1281 /* Something might have been received while we were waiting. */
1282 if (input_available())
1288 #ifndef FEAT_GUI_MSWIN
1290 * return non-zero if a character is available
1293 mch_char_avail(void)
1295 return WaitForChar(0L);
1300 * Create the console input. Used when reading stdin doesn't work.
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
1316 tgetch(int *pmodifiers
, char_u
*pch2
)
1325 #ifdef FEAT_CLIENTSERVER
1326 (void)WaitForChar(-1L);
1327 if (input_available())
1330 if (g_nMouseClick
!= -1)
1334 if (ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
) == 0)
1336 if (did_create_conin
)
1342 if (ir
.EventType
== KEY_EVENT
)
1344 if (decode_key_event(&ir
.Event
.KeyEvent
, &ch
, pch2
,
1348 else if (ir
.EventType
== FOCUS_EVENT
)
1349 handle_focus_event(ir
);
1350 else if (ir
.EventType
== WINDOW_BUFFER_SIZE_EVENT
)
1353 else if (ir
.EventType
== MOUSE_EVENT
)
1355 if (decode_mouse_event(&ir
.Event
.MouseEvent
))
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.
1380 #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
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)
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;
1405 else if (time
< 0 || time
> 250)
1407 /* don't wait too long, a request might be pending */
1415 if (!WaitForChar(time
)) /* no character available */
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
1427 if (!WaitForChar(p_ut
))
1430 if (trigger_cursorhold() && maxlen
>= 3)
1434 buf
[2] = (int)KE_CURSORHOLD
;
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
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. */
1468 if (g_nMouseClick
!= -1)
1470 # ifdef MCH_WRITE_DUMP
1472 fprintf(fdDump
, "{%02x @ %d, %d}",
1473 g_nMouseClick
, g_xMouse
, g_yMouse
);
1475 typeahead
[typeaheadlen
++] = ESC
+ 128;
1476 typeahead
[typeaheadlen
++] = 'M';
1477 typeahead
[typeaheadlen
++] = g_nMouseClick
;
1478 typeahead
[typeaheadlen
++] = g_xMouse
+ '!';
1479 typeahead
[typeaheadlen
++] = g_yMouse
+ '!';
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. */
1498 if (c
== Ctrl_C
&& ctrl_c_interrupts
)
1500 #if defined(FEAT_CLIENTSERVER)
1507 if (g_nMouseClick
== -1)
1512 /* A key may have one or two bytes. */
1513 typeahead
[typeaheadlen
] = c
;
1516 typeahead
[typeaheadlen
+ 1] = ch2
;
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
);
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
1533 if ((modifiers
& MOD_MASK_ALT
)
1535 && (typeahead
[typeaheadlen
] & 0x80) == 0
1542 n
= (*mb_char2bytes
)(typeahead
[typeaheadlen
] | 0x80,
1543 typeahead
+ typeaheadlen
);
1545 typeahead
[typeaheadlen
] |= 0x80;
1547 modifiers
&= ~MOD_MASK_ALT
;
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
;
1562 #ifdef MCH_WRITE_DUMP
1570 #ifdef MCH_WRITE_DUMP
1573 fputs("]\n", fdDump
);
1579 /* Move typeahead to "buf", as much as fits. */
1581 while (len
< maxlen
&& typeaheadlen
> 0)
1583 buf
[len
++] = typeahead
[0];
1584 mch_memmove(typeahead
, typeahead
+ 1, --typeaheadlen
);
1588 #else /* FEAT_GUI_W32 */
1590 #endif /* FEAT_GUI_W32 */
1594 # include <shellapi.h> /* required for FindExecutable() */
1598 * Return TRUE if "name" is in $PATH.
1599 * TODO: Should somehow check if it's really executable.
1602 executable_exists(char *name
)
1605 char fname
[_MAX_PATH
];
1608 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
1610 WCHAR
*p
= enc_to_utf16(name
, NULL
);
1611 WCHAR fnamew
[_MAX_PATH
];
1617 n
= (long)SearchPathW(NULL
, p
, NULL
, _MAX_PATH
, fnamew
, &dumw
);
1619 if (n
> 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
1623 if (GetFileAttributesW(fnamew
) & FILE_ATTRIBUTE_DIRECTORY
)
1627 /* Retry with non-wide function (for Windows 98). */
1631 if (SearchPath(NULL
, name
, NULL
, _MAX_PATH
, fname
, &dum
) == 0)
1633 if (mch_isdir(fname
))
1641 * GUI version of mch_init().
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? */
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\" ");
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
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");
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()
1724 * Clears the entire contents of the console screen buffer, using the
1725 * specified attribute.
1730 ClearConsoleBuffer(WORD wAttribute
)
1732 CONSOLE_SCREEN_BUFFER_INFO csbi
;
1734 DWORD NumCells
, dummy
;
1736 if (!GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
1739 NumCells
= csbi
.dwSize
.X
* csbi
.dwSize
.Y
;
1742 if (!FillConsoleOutputCharacter(g_hConOut
, ' ', NumCells
,
1747 if (!FillConsoleOutputAttribute(g_hConOut
, wAttribute
, NumCells
,
1757 * FitConsoleWindow()
1759 * Checks if the console window will fit within given buffer dimensions.
1760 * Also, if requested, will shrink the window to fit.
1769 CONSOLE_SCREEN_BUFFER_INFO csbi
;
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
;
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
;
1798 if (NeedAdjust
&& WantAdjust
)
1800 if (!SetConsoleWindowInfo(g_hConOut
, TRUE
, &csbi
.srWindow
))
1809 typedef struct ConsoleBufferStruct
1812 CONSOLE_SCREEN_BUFFER_INFO Info
;
1818 * SaveConsoleBuffer()
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().
1824 * TRUE if all information was saved; FALSE otherwise
1825 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1833 SMALL_RECT ReadRegion
;
1839 if (!GetConsoleScreenBufferInfo(g_hConOut
, &cb
->Info
))
1841 cb
->IsValid
= FALSE
;
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
)
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).
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.
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.
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
);
1908 * RestoreConsoleBuffer()
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().
1917 RestoreConsoleBuffer(
1922 SMALL_RECT WriteRegion
;
1924 if (cb
== NULL
|| !cb
->IsValid
)
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.
1933 ClearConsoleBuffer(cb
->Info
.wAttributes
);
1935 FitConsoleWindow(cb
->Info
.dwSize
, TRUE
);
1936 if (!SetConsoleScreenBufferSize(g_hConOut
, cb
->Info
.dwSize
))
1938 if (!SetConsoleTextAttribute(g_hConOut
, cb
->Info
.wAttributes
))
1944 * No need to restore the screen buffer contents, so we're done.
1949 if (!SetConsoleCursorPosition(g_hConOut
, cb
->Info
.dwCursorPosition
))
1951 if (!SetConsoleWindowInfo(g_hConOut
, TRUE
, &cb
->Info
.srWindow
))
1955 * Restore the screen buffer contents.
1957 if (cb
->Buffer
!= NULL
)
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 */
1978 #define FEAT_RESTORE_ORIG_SCREEN
1979 #ifdef FEAT_RESTORE_ORIG_SCREEN
1980 static ConsoleBuffer g_cbOrig
= { 0 };
1982 static ConsoleBuffer g_cbNonTermcap
= { 0 };
1983 static ConsoleBuffer g_cbTermcap
= { 0 };
1987 typedef HWND (__stdcall
*GETCONSOLEWINDOWPROC
)(VOID
);
1989 typedef WINBASEAPI
HWND (WINAPI
*GETCONSOLEWINDOWPROC
)(VOID
);
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 */
2000 #define ICON_SMALL 0
2008 * Attempts to retrieve the small icon and/or the big icon currently in
2009 * use by a given window.
2022 if (phIconSmall
!= NULL
)
2023 *phIconSmall
= (HICON
)SendMessage(hWnd
, WM_GETICON
,
2024 (WPARAM
)ICON_SMALL
, (LPARAM
)0);
2026 *phIcon
= (HICON
)SendMessage(hWnd
, WM_GETICON
,
2027 (WPARAM
)ICON_BIG
, (LPARAM
)0);
2034 * Attempts to change the small icon and/or the big icon currently in
2035 * use by a given window.
2045 HICON hPrevIconSmall
;
2051 if (hIconSmall
!= NULL
)
2052 hPrevIconSmall
= (HICON
)SendMessage(hWnd
, WM_SETICON
,
2053 (WPARAM
)ICON_SMALL
, (LPARAM
)hIconSmall
);
2055 hPrevIcon
= (HICON
)SendMessage(hWnd
, WM_SETICON
,
2056 (WPARAM
)ICON_BIG
,(LPARAM
) hIcon
);
2061 * SaveConsoleTitleAndIcon()
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).
2071 SaveConsoleTitleAndIcon(void)
2073 GETCONSOLEWINDOWPROC GetConsoleWindowProc
;
2075 /* Save the original title. */
2076 if (!GetConsoleTitle(g_szOrigTitle
, sizeof(g_szOrigTitle
)))
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
2086 if ((GetConsoleWindowProc
= (GETCONSOLEWINDOWPROC
)
2087 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2088 "GetConsoleWindow")) != NULL
)
2090 g_hWnd
= (*GetConsoleWindowProc
)();
2095 /* Save the original console window icon. */
2096 GetConsoleIcon(g_hWnd
, &g_hOrigIconSmall
, &g_hOrigIcon
);
2097 if (g_hOrigIconSmall
== NULL
|| g_hOrigIcon
== NULL
)
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
;
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().
2119 #ifndef FEAT_RESTORE_ORIG_SCREEN
2120 CONSOLE_SCREEN_BUFFER_INFO csbi
;
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 */
2133 /* Obtain handles for the standard Console I/O devices */
2134 if (read_cmd_fd
== 0)
2135 g_hConIn
= GetStdHandle(STD_INPUT_HANDLE
);
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
;
2145 /* Get current text attributes */
2146 GetConsoleScreenBufferInfo(g_hConOut
, &csbi
);
2147 g_attrCurrent
= g_attrDefault
= csbi
.wAttributes
;
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
);
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
);
2174 #ifdef MCH_WRITE_DUMP
2175 fdDump
= fopen("dump", "wt");
2182 fputs(ctime(&t
), fdDump
);
2187 g_fWindInitCalled
= TRUE
;
2190 g_fMouseAvail
= GetSystemMetrics(SM_MOUSEPRESENT
);
2193 #ifdef FEAT_CLIPBOARD
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");
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()!
2222 if (g_fWindInitCalled
)
2223 settmode(TMODE_COOK
);
2225 ml_close_all(TRUE
); /* remove all memfiles */
2227 if (g_fWindInitCalled
)
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
);
2240 #ifdef MCH_WRITE_DUMP
2246 fputs(ctime(&t
), fdDump
);
2253 SetConsoleCursorInfo(g_hConOut
, &g_cci
);
2254 SetConsoleMode(g_hConIn
, g_cmodein
);
2255 SetConsoleMode(g_hConOut
, g_cmodeout
);
2257 #ifdef DYNAMIC_GETTEXT
2263 #endif /* !FEAT_GUI_W32 */
2266 * Do we have an interactive window?
2277 return OK
; /* GUI always has a tty */
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.
2295 char szTrueName
[_MAX_PATH
+ 2];
2296 char *ptrue
, *ptruePrev
;
2297 char *porig
, *porigPrev
;
2303 flen
= (int)STRLEN(name
);
2304 if (flen
== 0 || flen
> _MAX_PATH
)
2309 /* Build the new name in szTrueName[] one component at a time. */
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
++;
2329 while (*porig
!= NUL
&& *porig
!= psepc
)
2336 l
= (*mb_ptr2len
)(porig
);
2338 *ptrue
++ = *porig
++;
2342 *ptrue
++ = *porig
++;
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
)
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
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
2375 && (_stricoll(porigPrev
,
2376 fb
.cAlternateFileName
) == 0
2377 && (int)(ptruePrev
- szTrueName
)
2378 + (int)strlen(fb
.cFileName
) < len
))))
2380 STRCPY(ptruePrev
, fb
.cFileName
);
2387 ptrue
= ptruePrev
+ strlen(ptruePrev
);
2391 STRCPY(name
, szTrueName
);
2396 * Insert user name in s[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);
2417 * Insert host name in s[len].
2426 if (!GetComputerName(s
, &cch
))
2427 vim_strncpy(s
, "PC (Win32 Vim)", len
- 1);
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.
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>
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
);
2467 vim_strncpy(buf
, p
, len
- 1);
2472 /* Retry with non-wide function (for Windows 98). */
2475 return (GetCurrentDirectory(len
, buf
) != 0 ? OK
: FAIL
);
2479 * get file permissions for `name'
2481 * else FILE_ATTRIBUTE_* defined in winnt.h
2484 mch_getperm(char_u
*name
)
2487 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2489 WCHAR
*p
= enc_to_utf16(name
, NULL
);
2494 n
= (long)GetFileAttributesW(p
);
2496 if (n
>= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
2498 /* Retry with non-wide function (for Windows 98). */
2502 return (long)GetFileAttributes((char *)name
);
2507 * set file permission for `name' to `perm'
2514 perm
|= FILE_ATTRIBUTE_ARCHIVE
; /* file has changed, set archive bit */
2516 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2518 WCHAR
*p
= enc_to_utf16(name
, NULL
);
2523 n
= (long)SetFileAttributesW(p
, perm
);
2525 if (n
|| GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
2526 return n
? OK
: FAIL
;
2527 /* Retry with non-wide function (for Windows 98). */
2531 return SetFileAttributes((char *)name
, perm
) ? OK
: FAIL
;
2535 * Set hidden flag for "name".
2538 mch_hide(char_u
*name
)
2544 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2545 p
= enc_to_utf16(name
, NULL
);
2551 perm
= GetFileAttributesW(p
);
2552 if (perm
< 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
2554 /* Retry with non-wide function (for Windows 98). */
2561 perm
= GetFileAttributes((char *)name
);
2564 perm
|= FILE_ATTRIBUTE_HIDDEN
;
2568 if (SetFileAttributesW(p
, perm
) == 0
2569 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
2571 /* Retry with non-wide function (for Windows 98). */
2578 SetFileAttributes((char *)name
, perm
);
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
);
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
)
2608 BY_HANDLE_FILE_INFORMATION inf
;
2612 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2613 wn
= enc_to_utf16(fname
, NULL
);
2616 hFile
= CreateFileW(wn
, /* file name */
2617 GENERIC_READ
, /* access 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). */
2633 hFile
= CreateFile(fname
, /* file name */
2634 GENERIC_READ
, /* access 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)
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
);
2680 if (len
>= _MAX_PATH
) /* safety check */
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
))
2691 * Loop over all extensions in $PATHEXT.
2693 vim_strncpy(buf
, name
, _MAX_PATH
- 1);
2694 p
= mch_getenv("PATHEXT");
2696 p
= (char_u
*)".com;.exe;.bat;.cmd";
2699 if (p
[0] == '.' && (p
[1] == NUL
|| p
[1] == ';'))
2701 /* A single "." means no extension is added. */
2708 copy_option_part(&p
, buf
+ len
, _MAX_PATH
- len
, ";");
2709 if (executable_exists((char *)buf
))
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
)
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
2730 if (STRNCMP(name
, "\\\\.\\", 4) == 0)
2731 return NODE_WRITABLE
;
2733 hFile
= CreateFile(name
, /* file name */
2734 GENERIC_WRITE
, /* access 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
)
2744 type
= GetFileType(hFile
);
2746 if (type
== FILE_TYPE_CHAR
)
2747 return NODE_WRITABLE
;
2748 if (type
== FILE_TYPE_DISK
)
2756 PSECURITY_DESCRIPTOR pSecurityDescriptor
;
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.
2769 mch_get_acl(char_u
*fname
)
2772 return (vim_acl_T
)NULL
;
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
));
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
2797 mch_free_acl((vim_acl_T
)p
);
2803 return (vim_acl_T
)p
;
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.
2813 mch_set_acl(char_u
*fname
, vim_acl_T 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.
2836 mch_free_acl(vim_acl_T acl
)
2839 struct my_acl
*p
= (struct my_acl
*)acl
;
2843 LocalFree(p
->pSecurityDescriptor
); // Free the memory just in case
2849 #ifndef FEAT_GUI_W32
2852 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2861 if (ctrl_c_interrupts
)
2862 g_fCtrlCPressed
= TRUE
;
2865 case CTRL_BREAK_EVENT
:
2866 g_fCBrkPressed
= 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
2879 : dwCtrlType
== CTRL_LOGOFF_EVENT
2883 OutputDebugString(IObuff
);
2886 preserve_exit(); /* output IObuff, preserve files and exit */
2888 return TRUE
; /* not reached */
2897 * set the tty in (raw) ? "raw" : "cooked" mode
2900 mch_settmode(int tmode
)
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
|
2914 cmodein
|= ENABLE_MOUSE_INPUT
;
2916 cmodeout
&= ~(ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
2917 bEnableHandler
= TRUE
;
2921 cmodein
|= (ENABLE_LINE_INPUT
| ENABLE_PROCESSED_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
2933 fprintf(fdDump
, "mch_settmode(%s, in = %x, out = %x)\n",
2934 tmode
== TMODE_RAW
? "raw" :
2935 tmode
== TMODE_COOK
? "cooked" : "normal",
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;
2977 * Set a console window to `xSize' * `ySize'
2980 ResizeConBufAndWindow(
2985 CONSOLE_SCREEN_BUFFER_INFO csbi
; /* hold current console buffer info */
2986 SMALL_RECT srWindowRect
; /* hold the new console size */
2989 #ifdef MCH_WRITE_DUMP
2992 fprintf(fdDump
, "ResizeConBufAndWindow(%d, %d)\n", xSize
, ySize
);
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
))
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.
3018 coordScreen
.Y
= ySize
;
3022 coordScreen
.X
= xSize
;
3025 SetConsoleScreenBufferSize(hConsole
, coordScreen
);
3029 if (!SetConsoleWindowInfo(g_hConOut
, TRUE
, &srWindowRect
))
3031 #ifdef MCH_WRITE_DUMP
3034 fprintf(fdDump
, "SetConsoleWindowInfo failed: %lx\n",
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
3050 fprintf(fdDump
, "SetConsoleScreenBufferSize failed: %lx\n",
3060 * Set the console window to `Rows' * `Columns'
3063 mch_set_shellsize(void)
3067 /* Don't change window size while still starting up */
3068 if (suppress_winsize
!= 0)
3070 suppress_winsize
= 2;
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.
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.
3102 mch_set_winsize_now(void)
3104 if (suppress_winsize
== 2)
3106 suppress_winsize
= 0;
3107 mch_set_shellsize();
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
3127 mch_system(char *cmd
, int options
)
3130 PROCESS_INFORMATION pi
;
3132 HWND hwnd
= GetFocus();
3135 si
.lpReserved
= NULL
;
3136 si
.lpDesktop
= 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
;
3147 si
.wShowWindow
= SW_SHOWNORMAL
;
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...? */
3154 && (STRNICMP(cmd
, "c:/command.com", 14) == 0
3155 || STRNICMP(cmd
, "c:\\command.com", 14) == 0))
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 */
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
)
3178 /* Keep updating the window while waiting for the shell to finish. */
3183 if (PeekMessage(&msg
, (HWND
)NULL
, 0, 0, PM_REMOVE
))
3185 TranslateMessage(&msg
);
3186 DispatchMessage(&msg
);
3188 if (WaitForSingleObject(pi
.hProcess
, delay
) != WAIT_TIMEOUT
)
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. */
3198 WaitForSingleObject(pi
.hProcess
, INFINITE
);
3201 /* Get the command exit code */
3202 GetExitCodeProcess(pi
.hProcess
, &ret
);
3207 * This ugly code is the only quick way of performing
3208 * a synchronous spawn under Win32s. Yuk.
3211 EnumWindows(win32ssynch_cb
, 0);
3212 old_num_windows
= num_windows
;
3217 EnumWindows(win32ssynch_cb
, 0);
3218 } while (num_windows
== old_num_windows
);
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);
3233 # define mch_system(c, o) system(c)
3238 * Either execute a command by calling the shell or start a new shell
3243 int options
) /* SHELL_*, see vim.h */
3246 int tmode
= cur_tmode
;
3248 char szShellTitle
[512];
3250 /* Change the title to reflect that we are in a subshell. */
3251 if (GetConsoleTitle(szShellTitle
, sizeof(szShellTitle
) - 4) > 0)
3254 strcat(szShellTitle
, " :sh");
3257 strcat(szShellTitle
, " - !");
3258 if ((strlen(szShellTitle
) + strlen(cmd
) < sizeof(szShellTitle
)))
3259 strcat(szShellTitle
, cmd
);
3261 mch_settitle(szShellTitle
, NULL
);
3267 #ifdef MCH_WRITE_DUMP
3270 fprintf(fdDump
, "mch_call_shell(\"%s\", %d)\n", cmd
, options
);
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
);
3283 signal(SIGBREAK
, SIG_IGN
);
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 */
3296 x
= mch_system(p_sh
, options
);
3300 /* we use "command" or "cmd" to start the shell; slow but easy */
3304 STRLEN(vimrun_path
) +
3306 STRLEN(p_sh
) + STRLEN(p_shcf
) + STRLEN(cmd
) + 10);
3308 newcmd
= lalloc(cmdlen
, TRUE
);
3311 char_u
*cmdbase
= (*cmd
== '"' ? cmd
+ 1 : cmd
);
3313 if ((STRNICMP(cmdbase
, "start", 5) == 0) && vim_iswhite(cmdbase
[5]))
3316 PROCESS_INFORMATION pi
;
3319 si
.lpReserved
= NULL
;
3320 si
.lpDesktop
= NULL
;
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
)
3342 STRCPY(newcmd
+ 1, cmdbase
);
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
3371 EMSG(_("E371: Command not found"));
3374 /* Close the handles to the subprocess, so that it goes away */
3375 CloseHandle(pi
.hThread
);
3376 CloseHandle(pi
.hProcess
);
3380 #if defined(FEAT_GUI_W32)
3381 if (need_vimrun_warning
)
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."),
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",
3396 (msg_silent
!= 0 || (options
& SHELL_DOOUT
))
3401 vim_snprintf((char *)newcmd
, cmdlen
, "%s %s %s",
3403 x
= mch_system((char *)newcmd
, options
);
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
)
3419 smsg(_("shell returned %d"), x
);
3426 signal(SIGINT
, SIG_DFL
);
3427 #if defined(__GNUC__) && !defined(__MINGW32__)
3428 signal(SIGKILL
, SIG_DFL
);
3430 signal(SIGBREAK
, SIG_DFL
);
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
);
3442 #ifndef FEAT_GUI_W32
3445 * Start termcap mode
3448 termcap_mode_start(void)
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
;
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
);
3485 GetConsoleMode(g_hConIn
, &cmodein
);
3488 cmodein
|= ENABLE_MOUSE_INPUT
;
3490 cmodein
&= ~ENABLE_MOUSE_INPUT
;
3492 cmodein
|= ENABLE_WINDOW_INPUT
;
3493 SetConsoleMode(g_hConIn
, cmodein
);
3495 redraw_later_clear();
3496 g_fTermcapMode
= TRUE
;
3504 termcap_mode_end(void)
3511 if (!g_fTermcapMode
)
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
;
3523 cb
= &g_cbNonTermcap
;
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.
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
)
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 */
3571 * clear `n' chars, starting from `coord'
3580 FillConsoleOutputCharacter(g_hConOut
, ' ', n
, coord
, &dwDummy
);
3581 FillConsoleOutputAttribute(g_hConOut
, g_attrCurrent
, n
, coord
, &dwDummy
);
3591 g_coord
.X
= g_coord
.Y
= 0;
3592 clear_chars(g_coord
, Rows
* Columns
);
3597 * Clear to end of display
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
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
3621 scroll(unsigned cLines
)
3623 COORD oldcoord
= g_coord
;
3625 gotoxy(g_srScrollRegion
.Left
+ 1, g_srScrollRegion
.Top
+ 1);
3626 delete_lines(cLines
);
3633 * Set the scroll region
3644 || right
> (unsigned) Columns
- 1
3645 || bottom
> (unsigned) Rows
- 1)
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
3659 insert_lines(unsigned cLines
)
3666 dest
.Y
= g_coord
.Y
+ cLines
;
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
3685 if (source
.Bottom
< dest
.Y
)
3690 coord
.Y
= source
.Bottom
;
3691 clear_chars(coord
, Columns
* (dest
.Y
- source
.Bottom
));
3697 * Delete `cLines' lines at the current cursor position
3700 delete_lines(unsigned cLines
)
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
3727 nb
= dest
.Y
+ (source
.Bottom
- source
.Top
) + 1;
3729 if (nb
< source
.Top
)
3735 clear_chars(coord
, Columns
* (source
.Top
- nb
));
3741 * Set the cursor position
3748 if (x
< 1 || x
> (unsigned)Columns
|| y
< 1 || y
> (unsigned)Rows
)
3751 /* external cursor coords are 1-based; internal are 0-based */
3754 SetConsoleCursorPosition(g_hConOut
, g_coord
);
3759 * Set the current text attribute = (foreground | background)
3760 * See ../doc/os_win32.txt for the numbers.
3763 textattr(WORD wAttr
)
3765 g_attrCurrent
= wAttr
;
3767 SetConsoleTextAttribute(g_hConOut
, wAttr
);
3772 textcolor(WORD wAttr
)
3774 g_attrCurrent
= (g_attrCurrent
& 0xf0) + wAttr
;
3776 SetConsoleTextAttribute(g_hConOut
, g_attrCurrent
);
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)
3795 textattr(g_attrDefault
);
3799 static WORD g_attrPreStandout
= 0;
3802 * Make the text standout, by brightening it
3807 g_attrPreStandout
= g_attrCurrent
;
3808 textattr((WORD
) (g_attrCurrent
|FOREGROUND_INTENSITY
|BACKGROUND_INTENSITY
));
3813 * Turn off standout mode
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.
3830 mch_set_normal_colors(void)
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] == '|')
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
3856 COORD coordOrigin
= {0, 0};
3857 WORD attrFlash
= ~g_attrCurrent
& 0xff;
3860 LPWORD oldattrs
= (LPWORD
)alloc(Rows
* Columns
* sizeof(WORD
));
3862 if (oldattrs
== NULL
)
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
);
3877 * Make the cursor visible or invisible
3880 cursor_visible(BOOL fVisible
)
3882 s_cursor_visible
= fVisible
;
3883 #ifdef MCH_CURSOR_SHAPE
3884 mch_update_cursor();
3890 * write `cchToWrite' characters in `pchBuf' to the screen
3891 * Returns the number of characters actually written (at least one).
3898 COORD coord
= g_coord
;
3901 FillConsoleOutputAttribute(g_hConOut
, g_attrCurrent
, cchToWrite
,
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
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
)
3919 gotoxy(g_coord
.X
+ 1, g_coord
.Y
+ 1);
3926 * mch_write(): write the output buffer to the screen, translating ESC
3927 * sequences into calls to console output routines.
3938 write(1, s
, (unsigned)len
);
3942 /* translate ESC | sequences into faked bios calls */
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");
3960 nWritten
= write_chars(s
, prefix
);
3961 #ifdef MCH_WRITE_DUMP
3965 fwrite(s
, sizeof(char_u
), nWritten
, fdDump
);
3966 fputs("<\n", fdDump
);
3969 len
-= (nWritten
- 1);
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
)
3978 gotoxy(g_srScrollRegion
.Left
+ 1, g_srScrollRegion
.Bottom
+ 1);
3982 gotoxy(g_srScrollRegion
.Left
+ 1, g_coord
.Y
+ 2);
3984 #ifdef MCH_WRITE_DUMP
3986 fputs("\\n\n", fdDump
);
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
3996 fputs("\\r\n", fdDump
);
4000 else if (s
[0] == '\b')
4002 /* \b, backspace: move cursor one position left */
4003 if (g_coord
.X
> g_srScrollRegion
.Left
)
4005 else if (g_coord
.Y
> g_srScrollRegion
.Top
)
4007 g_coord
.X
= g_srScrollRegion
.Right
;
4010 gotoxy(g_coord
.X
+ 1, g_coord
.Y
+ 1);
4011 #ifdef MCH_WRITE_DUMP
4013 fputs("\\b\n", fdDump
);
4017 else if (s
[0] == '\a')
4020 MessageBeep(0xFFFFFFFF);
4021 #ifdef MCH_WRITE_DUMP
4023 fputs("\\a\n", fdDump
);
4027 else if (s
[0] == ESC
&& len
>= 3-1 && s
[1] == '|')
4029 #ifdef MCH_WRITE_DUMP
4033 int arg1
= 0, arg2
= 0;
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':
4042 arg1
= getdigits(&p
); /* no check for length! */
4049 arg2
= getdigits(&p
); /* no check for length! */
4056 set_scroll_region(0, arg1
- 1, Columns
- 1, arg2
- 1);
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);
4066 /* move cursor right arg1 columns in same line */
4067 gotoxy(min(g_srScrollRegion
.Right
, g_coord
.X
+ arg1
) + 1,
4083 textattr((WORD
) arg1
);
4087 textcolor((WORD
) arg1
);
4091 textbackground((WORD
) arg1
);
4098 len
-= (int)(p
- s
);
4103 /* Three-character escape sequences */
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);
4116 /* move cursor right one column in same line */
4117 gotoxy(min(g_srScrollRegion
.Right
, g_coord
.X
+ 1) + 1,
4138 clear_to_end_of_display();
4146 clear_to_end_of_line();
4158 termcap_mode_start();
4162 cursor_visible(TRUE
);
4166 cursor_visible(FALSE
);
4174 #ifdef MCH_WRITE_DUMP
4177 fputs("ESC | ", fdDump
);
4178 fwrite(old_s
+ 2, sizeof(char_u
), s
- old_s
- 2, fdDump
);
4179 fputc('\n', fdDump
);
4185 /* Write a single character */
4188 nWritten
= write_chars(s
, 1);
4189 #ifdef MCH_WRITE_DUMP
4193 fwrite(s
, sizeof(char_u
), nWritten
, fdDump
);
4194 fputs("<\n", fdDump
);
4198 len
-= (nWritten
- 1);
4203 #ifdef MCH_WRITE_DUMP
4209 #endif /* FEAT_GUI_W32 */
4213 * Delay for half a second.
4222 Sleep((int)msec
); /* never wait for input */
4225 # ifdef FEAT_MZSCHEME
4226 if (mzthreads_allowed() && p_mzq
> 0 && msec
> p_mzq
)
4230 /* if msec is large enough, wait by portions in p_mzq */
4233 mzvim_check_threads();
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
)
4260 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4262 wn
= enc_to_utf16(name
, NULL
);
4265 SetFileAttributesW(wn
, FILE_ATTRIBUTE_NORMAL
);
4266 n
= DeleteFileW(wn
) ? 0 : -1;
4268 if (n
== 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4270 /* Retry with non-wide function (for Windows 98). */
4274 SetFileAttributes(name
, FILE_ATTRIBUTE_NORMAL
);
4275 return DeleteFile(name
) ? 0 : -1;
4280 * check for an "interrupt signal": CTRL-break or CTRL-C
4283 mch_breakcheck(void)
4285 #ifndef FEAT_GUI_W32 /* never used */
4286 if (g_fCtrlCPressed
|| g_fCBrkPressed
)
4288 g_fCtrlCPressed
= g_fCBrkPressed
= FALSE
;
4296 * How much memory is available?
4297 * Return sum of available physical and page file memory.
4301 mch_avail_mem(int special
)
4305 ms
.dwLength
= sizeof(MEMORYSTATUS
);
4306 GlobalMemoryStatus(&ms
);
4307 return (long_u
) (ms
.dwAvailPhys
+ ms
.dwAvailPageFile
);
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
)
4320 WCHAR szTempFile
[_MAX_PATH
+ 1];
4321 WCHAR szNewPath
[_MAX_PATH
+ 1];
4324 if (!mch_windows95())
4327 for (i
= 0; wold
[i
] != NUL
; ++i
)
4328 if ((wold
[i
] == '/' || wold
[i
] == '\\' || wold
[i
] == ':')
4329 && wold
[i
+ 1] != 0)
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
)
4339 if (GetTempFileNameW(szNewPath
, L
"VIM", 0, szTempFile
) == 0)
4342 if (!DeleteFileW(szTempFile
))
4345 if (!MoveFileW(wold
, szTempFile
))
4348 if ((hf
= CreateFileW(wold
, GENERIC_WRITE
, 0, NULL
, CREATE_NEW
,
4349 FILE_ATTRIBUTE_NORMAL
, NULL
)) == INVALID_HANDLE_VALUE
)
4351 if (!CloseHandle(hf
))
4354 if (!MoveFileW(szTempFile
, wnew
))
4356 (void)MoveFileW(szTempFile
, wold
);
4360 DeleteFileW(szTempFile
);
4362 if (!DeleteFileW(wold
))
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.
4391 const char *pszOldFile
,
4392 const char *pszNewFile
)
4394 char szTempFile
[_MAX_PATH
+1];
4395 char szNewPath
[_MAX_PATH
+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
);
4411 if (retval
== 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4413 /* Retry with non-wide function (for Windows 98). */
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
)
4435 /* Get (and create) a unique temporary file name in directory of new file */
4436 if (GetTempFileName(szNewPath
, "VIM", 0, szTempFile
) == 0)
4439 /* blow the temp file away */
4440 if (!DeleteFile(szTempFile
))
4443 /* rename old file to the temp file */
4444 if (!MoveFile(pszOldFile
, szTempFile
))
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
)
4460 if (!CloseHandle(hf
))
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
);
4473 /* Seems to be left around on Novell filesystems */
4474 DeleteFile(szTempFile
);
4476 /* finally, remove the empty old file */
4477 if (!DeleteFile(pszOldFile
))
4480 return 0; /* success */
4484 * Get the default shell for the current hardware platform
4493 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
) /* Windows NT */
4495 else if (g_PlatformId
== VER_PLATFORM_WIN32_WINDOWS
) /* Windows 95 */
4496 psz
= "command.com";
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
)
4510 int retval
= -1; /* default: fail */
4514 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4515 wn
= enc_to_utf16(n
, NULL
);
4520 char TempName
[_MAX_PATH
+ 16] = "";
4522 WCHAR TempNameW
[_MAX_PATH
+ 16] = L
"";
4527 /* Read check is performed by seeing if we can do a find file on
4528 * the directory for any file. */
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
++] = '*';
4542 hFile
= FindFirstFileW(TempNameW
, &d
);
4543 if (hFile
== INVALID_HANDLE_VALUE
)
4545 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4548 /* Retry with non-wide function (for Windows 98). */
4553 (void)FindClose(hFile
);
4561 vim_strncpy(TempName
, n
, _MAX_PATH
);
4562 pch
= TempName
+ STRLEN(TempName
) - 1;
4563 if (*pch
!= '\\' && *pch
!= '/')
4568 hFile
= FindFirstFile(TempName
, &d
);
4569 if (hFile
== INVALID_HANDLE_VALUE
)
4571 (void)FindClose(hFile
);
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 :-(. */
4584 if (!GetTempFileNameW(wn
, L
"VIM", 0, TempNameW
))
4586 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4589 /* Retry with non-wide function (for Windows 98). */
4594 DeleteFileW(TempNameW
);
4599 if (!GetTempFileName(n
, "VIM", 0, TempName
))
4601 mch_remove((char_u
*)TempName
);
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);
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). */
4625 hFile
= CreateFile(n
, am
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
4626 if (hFile
== INVALID_HANDLE_VALUE
)
4631 retval
= 0; /* success */
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__
4651 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4653 wn
= enc_to_utf16(name
, NULL
);
4656 f
= _wopen(wn
, flags
, mode
);
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. */
4667 return open(name
, flags
, mode
);
4671 * Version of fopen() that may use UTF-16 file name.
4674 mch_fopen(char *name
, char *mode
)
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
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];
4692 _get_fmode(&oldMode
);
4694 _set_fmode(_O_TEXT
);
4695 else if (newMode
== 'b')
4696 _set_fmode(_O_BINARY
);
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
);
4705 # if defined(DEBUG) && _MSC_VER >= 1400
4706 _set_fmode(oldMode
);
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
);
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
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.
4744 copy_substream(HANDLE sh
, void *context
, WCHAR
*to
, WCHAR
*substream
, long len
)
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
)
4759 DWORD readcnt
, written
;
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
)
4771 || !WriteFile(hTo
, buf
, todo
, &written
, NULL
)
4782 * Copy info streams from file "from" to file "to".
4785 copy_infostreams(char_u
*from
, char_u
*to
)
4790 WIN32_STREAM_ID sid
;
4792 WCHAR streamname
[_MAX_PATH
];
4794 void *context
= NULL
;
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.*/
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
)
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
))
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,
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
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
);
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
)
4875 /* File streams only work on Windows NT and later. */
4877 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
)
4878 copy_infostreams(from
, to
);
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)
4904 BYTE
*pLowestPossiblePage
;
4905 MEMORY_BASIC_INFORMATION mbi
;
4910 /* This code will not work on win32s. */
4912 if (g_PlatformId
== VER_PLATFORM_WIN32s
)
4915 /* We need to know the system page size. */
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)
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
4937 pGuardPage
= (BYTE
*)((DWORD
)nPageSize
* (((DWORD
)pStackPtr
4938 / (DWORD
)nPageSize
) - 1));
4939 if (pGuardPage
< pLowestPossiblePage
)
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
))
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
;
4956 if (VirtualQuery(pBlock
, &mbi
, sizeof mbi
) == 0)
4959 pBlock
+= mbi
.RegionSize
;
4961 if (mbi
.State
& MEM_COMMIT
)
4965 /* mbi now describes the first committed block in the stack. */
4966 if (mbi
.Protect
& PAGE_GUARD
)
4969 /* decide where the guard page should start */
4970 if ((long_u
)(mbi
.BaseAddress
) < (long_u
)pLowestPossiblePage
)
4971 pGuardPage
= pLowestPossiblePage
;
4973 pGuardPage
= (BYTE
*)mbi
.BaseAddress
;
4975 /* allocate the guard page */
4976 if (!VirtualAlloc(pGuardPage
, nPageSize
, MEM_COMMIT
, PAGE_READWRITE
))
4979 /* apply the guard attribute to the page */
4980 if (!VirtualProtect(pGuardPage
, nPageSize
, PAGE_READWRITE
| PAGE_GUARD
,
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
)
5022 ArglistW
= CommandLineToArgvW(GetCommandLineW(), &nArgsW
);
5023 if (ArglistW
!= NULL
)
5025 argv
= malloc((nArgsW
+ 1) * sizeof(char *));
5030 for (i
= 0; i
< argc
; ++i
)
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. */
5053 used_file_indexes
= malloc(argc
* sizeof(int));
5061 free_cmd_argsW(void)
5063 if (ArglistW
!= NULL
)
5065 GlobalFree(ArglistW
);
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()
5076 used_file_arg(char *name
, int literal
, int full_path
, int diff_mode
)
5080 if (used_file_indexes
== NULL
)
5082 for (i
= used_file_argc
+ 1; i
< global_argc
; ++i
)
5083 if (STRCMP(global_argv
[i
], name
) == 0)
5086 used_file_indexes
[used_file_count
++] = i
;
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.
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'.
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
5125 || used_file_indexes
== NULL
5126 || used_file_count
== 0
5127 || used_alist_count
!= GARGCOUNT
)
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
);
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])))
5156 r
= concat_fnames(str
, gettail(alist_name(&GARGLIST
[0])), TRUE
);
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]));