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)
249 # define GETTEXT_DLL "libintl.dll"
251 /* Dummy funcitons */
252 static char *null_libintl_gettext(const char *);
253 static char *null_libintl_textdomain(const char *);
254 static char *null_libintl_bindtextdomain(const char *, const char *);
255 static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
257 static HINSTANCE hLibintlDLL
= 0;
258 char *(*dyn_libintl_gettext
)(const char *) = null_libintl_gettext
;
259 char *(*dyn_libintl_textdomain
)(const char *) = null_libintl_textdomain
;
260 char *(*dyn_libintl_bindtextdomain
)(const char *, const char *)
261 = null_libintl_bindtextdomain
;
262 char *(*dyn_libintl_bind_textdomain_codeset
)(const char *, const char *)
263 = null_libintl_bind_textdomain_codeset
;
266 dyn_libintl_init(char *libname
)
275 {"gettext", (FARPROC
*)&dyn_libintl_gettext
},
276 {"textdomain", (FARPROC
*)&dyn_libintl_textdomain
},
277 {"bindtextdomain", (FARPROC
*)&dyn_libintl_bindtextdomain
},
281 /* No need to initialize twice. */
284 /* Load gettext library (libintl.dll) */
285 hLibintlDLL
= LoadLibrary(libname
!= NULL
? libname
: GETTEXT_DLL
);
288 char_u dirname
[_MAX_PATH
];
290 /* Try using the path from gvim.exe to find the .dll there. */
292 STRCPY(dirname
, exe_name
);
293 STRCPY(gettail(dirname
), GETTEXT_DLL
);
294 hLibintlDLL
= LoadLibrary((char *)dirname
);
300 EMSG2(_(e_loadlib
), GETTEXT_DLL
);
306 for (i
= 0; libintl_entry
[i
].name
!= NULL
307 && libintl_entry
[i
].ptr
!= NULL
; ++i
)
309 if ((*libintl_entry
[i
].ptr
= (FARPROC
)GetProcAddress(hLibintlDLL
,
310 libintl_entry
[i
].name
)) == NULL
)
316 EMSG2(_(e_loadfunc
), libintl_entry
[i
].name
);
323 /* The bind_textdomain_codeset() function is optional. */
324 dyn_libintl_bind_textdomain_codeset
= (void *)GetProcAddress(hLibintlDLL
,
325 "bind_textdomain_codeset");
326 if (dyn_libintl_bind_textdomain_codeset
== NULL
)
327 dyn_libintl_bind_textdomain_codeset
=
328 null_libintl_bind_textdomain_codeset
;
337 FreeLibrary(hLibintlDLL
);
339 dyn_libintl_gettext
= null_libintl_gettext
;
340 dyn_libintl_textdomain
= null_libintl_textdomain
;
341 dyn_libintl_bindtextdomain
= null_libintl_bindtextdomain
;
342 dyn_libintl_bind_textdomain_codeset
= null_libintl_bind_textdomain_codeset
;
347 null_libintl_gettext(const char *msgid
)
354 null_libintl_bindtextdomain(const char *domainname
, const char *dirname
)
361 null_libintl_bind_textdomain_codeset(const char *domainname
,
369 null_libintl_textdomain(const char *domainname
)
374 #endif /* DYNAMIC_GETTEXT */
376 /* This symbol is not defined in older versions of the SDK or Visual C++ */
378 #ifndef VER_PLATFORM_WIN32_WINDOWS
379 # define VER_PLATFORM_WIN32_WINDOWS 1
387 * These are needed to dynamically load the ADVAPI DLL, which is not
388 * implemented under Windows 95 (and causes VIM to crash)
390 typedef DWORD (WINAPI
*PSNSECINFO
) (LPTSTR
, enum SE_OBJECT_TYPE
,
391 SECURITY_INFORMATION
, PSID
, PSID
, PACL
, PACL
);
392 typedef DWORD (WINAPI
*PGNSECINFO
) (LPSTR
, enum SE_OBJECT_TYPE
,
393 SECURITY_INFORMATION
, PSID
*, PSID
*, PACL
*, PACL
*,
394 PSECURITY_DESCRIPTOR
*);
396 static HANDLE advapi_lib
= NULL
; /* Handle for ADVAPI library */
397 static PSNSECINFO pSetNamedSecurityInfo
;
398 static PGNSECINFO pGetNamedSecurityInfo
;
402 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
403 * VER_PLATFORM_WIN32_WINDOWS (Win95).
408 static int done
= FALSE
;
414 ovi
.dwOSVersionInfoSize
= sizeof(ovi
);
417 g_PlatformId
= ovi
.dwPlatformId
;
421 * Load the ADVAPI runtime if we are on anything
422 * other than Windows 95
424 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
)
427 * do this load. Problems: Doesn't unload at end of run (this is
428 * theoretically okay, since Windows should unload it when VIM
429 * terminates). Should we be using the 'mch_libcall' routines?
430 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
431 * time we verify security...
433 advapi_lib
= LoadLibrary("ADVAPI32.DLL");
434 if (advapi_lib
!= NULL
)
436 pSetNamedSecurityInfo
= (PSNSECINFO
)GetProcAddress(advapi_lib
,
437 "SetNamedSecurityInfoA");
438 pGetNamedSecurityInfo
= (PGNSECINFO
)GetProcAddress(advapi_lib
,
439 "GetNamedSecurityInfoA");
440 if (pSetNamedSecurityInfo
== NULL
441 || pGetNamedSecurityInfo
== NULL
)
443 /* If we can't get the function addresses, set advapi_lib
444 * to NULL so that we don't use them. */
445 FreeLibrary(advapi_lib
);
456 * Return TRUE when running on Windows 95 (or 98 or ME).
457 * Only to be used after mch_init().
462 return g_PlatformId
== VER_PLATFORM_WIN32_WINDOWS
;
467 * Used to work around the "can't do synchronous spawn"
468 * problem on Win32s, without resorting to Universal Thunk.
470 static int old_num_windows
;
471 static int num_windows
;
475 win32ssynch_cb(HWND hwnd
, LPARAM lparam
)
484 #define SHIFT (SHIFT_PRESSED)
485 #define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
486 #define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
487 #define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
490 /* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
491 * We map function keys to their ANSI terminal equivalents, as produced
492 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
493 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
494 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
495 * combinations of function/arrow/etc keys.
509 /* Key ANSI alone shift ctrl alt */
510 { VK_ESCAPE
,FALSE
, ESC
, ESC
, ESC
, ESC
, },
512 { VK_F1
, TRUE
, ';', 'T', '^', 'h', },
513 { VK_F2
, TRUE
, '<', 'U', '_', 'i', },
514 { VK_F3
, TRUE
, '=', 'V', '`', 'j', },
515 { VK_F4
, TRUE
, '>', 'W', 'a', 'k', },
516 { VK_F5
, TRUE
, '?', 'X', 'b', 'l', },
517 { VK_F6
, TRUE
, '@', 'Y', 'c', 'm', },
518 { VK_F7
, TRUE
, 'A', 'Z', 'd', 'n', },
519 { VK_F8
, TRUE
, 'B', '[', 'e', 'o', },
520 { VK_F9
, TRUE
, 'C', '\\', 'f', 'p', },
521 { VK_F10
, TRUE
, 'D', ']', 'g', 'q', },
522 { VK_F11
, TRUE
, '\205', '\207', '\211', '\213', },
523 { VK_F12
, TRUE
, '\206', '\210', '\212', '\214', },
525 { VK_HOME
, TRUE
, 'G', '\302', 'w', '\303', },
526 { VK_UP
, TRUE
, 'H', '\304', '\305', '\306', },
527 { VK_PRIOR
, TRUE
, 'I', '\307', '\204', '\310', }, /*PgUp*/
528 { VK_LEFT
, TRUE
, 'K', '\311', 's', '\312', },
529 { VK_RIGHT
, TRUE
, 'M', '\313', 't', '\314', },
530 { VK_END
, TRUE
, 'O', '\315', 'u', '\316', },
531 { VK_DOWN
, TRUE
, 'P', '\317', '\320', '\321', },
532 { VK_NEXT
, TRUE
, 'Q', '\322', 'v', '\323', }, /*PgDn*/
533 { VK_INSERT
,TRUE
, 'R', '\324', '\325', '\326', },
534 { VK_DELETE
,TRUE
, 'S', '\327', '\330', '\331', },
536 { VK_SNAPSHOT
,TRUE
, 0, 0, 0, 'r', }, /*PrtScrn*/
539 /* Most people don't have F13-F20, but what the hell... */
540 { VK_F13
, TRUE
, '\332', '\333', '\334', '\335', },
541 { VK_F14
, TRUE
, '\336', '\337', '\340', '\341', },
542 { VK_F15
, TRUE
, '\342', '\343', '\344', '\345', },
543 { VK_F16
, TRUE
, '\346', '\347', '\350', '\351', },
544 { VK_F17
, TRUE
, '\352', '\353', '\354', '\355', },
545 { VK_F18
, TRUE
, '\356', '\357', '\360', '\361', },
546 { VK_F19
, TRUE
, '\362', '\363', '\364', '\365', },
547 { VK_F20
, TRUE
, '\366', '\367', '\370', '\371', },
549 { VK_ADD
, TRUE
, 'N', 'N', 'N', 'N', }, /* keyp '+' */
550 { VK_SUBTRACT
, TRUE
,'J', 'J', 'J', 'J', }, /* keyp '-' */
551 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
552 { VK_MULTIPLY
, TRUE
,'7', '7', '7', '7', }, /* keyp '*' */
554 { VK_NUMPAD0
,TRUE
, '\332', '\333', '\334', '\335', },
555 { VK_NUMPAD1
,TRUE
, '\336', '\337', '\340', '\341', },
556 { VK_NUMPAD2
,TRUE
, '\342', '\343', '\344', '\345', },
557 { VK_NUMPAD3
,TRUE
, '\346', '\347', '\350', '\351', },
558 { VK_NUMPAD4
,TRUE
, '\352', '\353', '\354', '\355', },
559 { VK_NUMPAD5
,TRUE
, '\356', '\357', '\360', '\361', },
560 { VK_NUMPAD6
,TRUE
, '\362', '\363', '\364', '\365', },
561 { VK_NUMPAD7
,TRUE
, '\366', '\367', '\370', '\371', },
562 { VK_NUMPAD8
,TRUE
, '\372', '\373', '\374', '\375', },
563 /* Sorry, out of number space! <negri>*/
564 { VK_NUMPAD9
,TRUE
, '\376', '\377', '\377', '\367', },
570 // The ToAscii bug destroys several registers. Need to turn off optimization
571 // or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
572 # pragma warning(push)
573 # pragma warning(disable: 4748)
574 # pragma optimize("", off)
577 #if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
578 # define AChar AsciiChar
580 # define AChar uChar.AsciiChar
583 /* The return code indicates key code size. */
589 KEY_EVENT_RECORD
*pker
)
591 UINT uMods
= pker
->dwControlKeyState
;
592 static int s_iIsDead
= 0;
593 static WORD awAnsiCode
[2];
594 static BYTE abKeystate
[256];
599 pker
->AChar
= (CHAR
) awAnsiCode
[1];
604 if (pker
->AChar
!= 0)
607 memset(abKeystate
, 0, sizeof (abKeystate
));
609 // Should only be non-NULL on NT 4.0
610 if (s_pfnGetConsoleKeyboardLayoutName
!= NULL
)
612 CHAR szKLID
[KL_NAMELENGTH
];
614 if ((*s_pfnGetConsoleKeyboardLayoutName
)(szKLID
))
615 (void)LoadKeyboardLayout(szKLID
, KLF_ACTIVATE
);
618 /* Clear any pending dead keys */
619 ToAscii(VK_SPACE
, MapVirtualKey(VK_SPACE
, 0), abKeystate
, awAnsiCode
, 0);
621 if (uMods
& SHIFT_PRESSED
)
622 abKeystate
[VK_SHIFT
] = 0x80;
623 if (uMods
& CAPSLOCK_ON
)
624 abKeystate
[VK_CAPITAL
] = 1;
626 if ((uMods
& ALT_GR
) == ALT_GR
)
628 abKeystate
[VK_CONTROL
] = abKeystate
[VK_LCONTROL
] =
629 abKeystate
[VK_MENU
] = abKeystate
[VK_RMENU
] = 0x80;
632 s_iIsDead
= ToAscii(pker
->wVirtualKeyCode
, pker
->wVirtualScanCode
,
633 abKeystate
, awAnsiCode
, 0);
636 pker
->AChar
= (CHAR
) awAnsiCode
[0];
642 /* MUST switch optimization on again here, otherwise a call to
643 * decode_key_event() may crash (e.g. when hitting caps-lock) */
644 # pragma optimize("", on)
645 # pragma warning(pop)
647 # if (_MSC_VER < 1100)
648 /* MUST turn off global optimisation for this next function, or
649 * pressing ctrl-minus in insert mode crashes Vim when built with
650 * VC4.1. -- negri. */
651 # pragma optimize("g", off)
655 static BOOL g_fJustGotFocus
= FALSE
;
658 * Decode a KEY_EVENT into one or two keystrokes
662 KEY_EVENT_RECORD
*pker
,
669 const int nModifs
= pker
->dwControlKeyState
& (SHIFT
| ALT
| CTRL
);
672 g_fJustGotFocus
= FALSE
;
674 /* ignore key up events */
678 /* ignore some keystrokes */
679 switch (pker
->wVirtualKeyCode
)
684 case VK_MENU
: /* Alt key */
692 if ((nModifs
& CTRL
) != 0 && (nModifs
& ~CTRL
) == 0 && pker
->AChar
== NUL
)
694 /* Ctrl-6 is Ctrl-^ */
695 if (pker
->wVirtualKeyCode
== '6')
700 /* Ctrl-2 is Ctrl-@ */
701 else if (pker
->wVirtualKeyCode
== '2')
706 /* Ctrl-- is Ctrl-_ */
707 else if (pker
->wVirtualKeyCode
== 0xBD)
715 if (pker
->wVirtualKeyCode
== VK_TAB
&& (nModifs
& SHIFT_PRESSED
))
722 for (i
= sizeof(VirtKeyMap
) / sizeof(VirtKeyMap
[0]); --i
>= 0; )
724 if (VirtKeyMap
[i
].wVirtKey
== pker
->wVirtualKeyCode
)
727 *pch
= VirtKeyMap
[i
].chAlone
;
728 else if ((nModifs
& SHIFT
) != 0 && (nModifs
& ~SHIFT
) == 0)
729 *pch
= VirtKeyMap
[i
].chShift
;
730 else if ((nModifs
& CTRL
) != 0 && (nModifs
& ~CTRL
) == 0)
731 *pch
= VirtKeyMap
[i
].chCtrl
;
732 else if ((nModifs
& ALT
) != 0 && (nModifs
& ~ALT
) == 0)
733 *pch
= VirtKeyMap
[i
].chAlt
;
737 if (VirtKeyMap
[i
].fAnsiKey
)
748 i
= win32_kbd_patch_key(pker
);
754 *pch
= (i
> 0) ? pker
->AChar
: NUL
;
756 if (pmodifiers
!= NULL
)
758 /* Pass on the ALT key as a modifier, but only when not combined
759 * with CTRL (which is ALTGR). */
760 if ((nModifs
& ALT
) != 0 && (nModifs
& CTRL
) == 0)
761 *pmodifiers
|= MOD_MASK_ALT
;
763 /* Pass on SHIFT only for special keys, because we don't know when
764 * it's already included with the character. */
765 if ((nModifs
& SHIFT
) != 0 && *pch
<= 0x20)
766 *pmodifiers
|= MOD_MASK_SHIFT
;
768 /* Pass on CTRL only for non-special keys, because we don't know
769 * when it's already included with the character. And not when
770 * combined with ALT (which is ALTGR). */
771 if ((nModifs
& CTRL
) != 0 && (nModifs
& ALT
) == 0
772 && *pch
>= 0x20 && *pch
< 0x80)
773 *pmodifiers
|= MOD_MASK_CTRL
;
777 return (*pch
!= NUL
);
781 # pragma optimize("", on)
784 #endif /* FEAT_GUI_W32 */
790 * For the GUI the mouse handling is in gui_w32.c.
799 static int g_fMouseAvail
= FALSE
; /* mouse present */
800 static int g_fMouseActive
= FALSE
; /* mouse enabled */
801 static int g_nMouseClick
= -1; /* mouse status */
802 static int g_xMouse
; /* mouse x coordinate */
803 static int g_yMouse
; /* mouse y coordinate */
806 * Enable or disable mouse input
817 GetConsoleMode(g_hConIn
, &cmodein
);
820 cmodein
|= ENABLE_MOUSE_INPUT
;
822 cmodein
&= ~ENABLE_MOUSE_INPUT
;
824 SetConsoleMode(g_hConIn
, cmodein
);
829 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
830 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
831 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
832 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
833 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
834 * and we return the mouse position in g_xMouse and g_yMouse.
836 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
837 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
838 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
840 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
841 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
843 * Windows will send us MOUSE_MOVED notifications whenever the mouse
844 * moves, even if it stays within the same character cell. We ignore
845 * all MOUSE_MOVED messages if the position hasn't really changed, and
846 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
847 * we're only interested in MOUSE_DRAG).
849 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
850 * 2-button mouses by pressing the left & right buttons simultaneously.
851 * In practice, it's almost impossible to click both at the same time,
852 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
853 * in such cases, if the user is clicking quickly.
857 MOUSE_EVENT_RECORD
*pmer
)
859 static int s_nOldButton
= -1;
860 static int s_nOldMouseClick
= -1;
861 static int s_xOldMouse
= -1;
862 static int s_yOldMouse
= -1;
863 static linenr_T s_old_topline
= 0;
865 static int s_old_topfill
= 0;
867 static int s_cClicks
= 1;
868 static BOOL s_fReleased
= TRUE
;
869 static DWORD s_dwLastClickTime
= 0;
870 static BOOL s_fNextIsMiddle
= FALSE
;
872 static DWORD cButtons
= 0; /* number of buttons supported */
874 const DWORD LEFT
= FROM_LEFT_1ST_BUTTON_PRESSED
;
875 const DWORD MIDDLE
= FROM_LEFT_2ND_BUTTON_PRESSED
;
876 const DWORD RIGHT
= RIGHTMOST_BUTTON_PRESSED
;
877 const DWORD LEFT_RIGHT
= LEFT
| RIGHT
;
881 if (cButtons
== 0 && !GetNumberOfConsoleMouseButtons(&cButtons
))
884 if (!g_fMouseAvail
|| !g_fMouseActive
)
890 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
893 g_fJustGotFocus
= FALSE
;
897 /* unprocessed mouse click? */
898 if (g_nMouseClick
!= -1)
902 g_xMouse
= pmer
->dwMousePosition
.X
;
903 g_yMouse
= pmer
->dwMousePosition
.Y
;
905 if (pmer
->dwEventFlags
== MOUSE_MOVED
)
907 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
908 * events even when the mouse moves only within a char cell.) */
909 if (s_xOldMouse
== g_xMouse
&& s_yOldMouse
== g_yMouse
)
913 /* If no buttons are pressed... */
914 if ((pmer
->dwButtonState
& ((1 << cButtons
) - 1)) == 0)
916 /* If the last thing returned was MOUSE_RELEASE, ignore this */
920 nButton
= MOUSE_RELEASE
;
923 else /* one or more buttons pressed */
925 /* on a 2-button mouse, hold down left and right buttons
926 * simultaneously to get MIDDLE. */
928 if (cButtons
== 2 && s_nOldButton
!= MOUSE_DRAG
)
930 DWORD dwLR
= (pmer
->dwButtonState
& LEFT_RIGHT
);
932 /* if either left or right button only is pressed, see if the
933 * the next mouse event has both of them pressed */
934 if (dwLR
== LEFT
|| dwLR
== RIGHT
)
938 /* wait a short time for next input event */
939 if (WaitForSingleObject(g_hConIn
, p_mouset
/ 3)
946 MOUSE_EVENT_RECORD
* pmer2
= &ir
.Event
.MouseEvent
;
948 PeekConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
950 if (cRecords
== 0 || ir
.EventType
!= MOUSE_EVENT
951 || !(pmer2
->dwButtonState
& LEFT_RIGHT
))
955 if (pmer2
->dwEventFlags
!= MOUSE_MOVED
)
957 ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
959 return decode_mouse_event(pmer2
);
961 else if (s_xOldMouse
== pmer2
->dwMousePosition
.X
&&
962 s_yOldMouse
== pmer2
->dwMousePosition
.Y
)
964 /* throw away spurious mouse move */
965 ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
967 /* are there any more mouse events in queue? */
968 PeekConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
970 if (cRecords
==0 || ir
.EventType
!= MOUSE_EVENT
)
983 nButton
= (pmer
->dwEventFlags
== MOUSE_MOVED
)
984 ? MOUSE_DRAG
: MOUSE_MIDDLE
;
985 s_fNextIsMiddle
= FALSE
;
987 else if (cButtons
== 2 &&
988 ((pmer
->dwButtonState
& LEFT_RIGHT
) == LEFT_RIGHT
))
990 nButton
= MOUSE_MIDDLE
;
992 if (! s_fReleased
&& pmer
->dwEventFlags
!= MOUSE_MOVED
)
994 s_fNextIsMiddle
= TRUE
;
995 nButton
= MOUSE_RELEASE
;
998 else if ((pmer
->dwButtonState
& LEFT
) == LEFT
)
999 nButton
= MOUSE_LEFT
;
1000 else if ((pmer
->dwButtonState
& MIDDLE
) == MIDDLE
)
1001 nButton
= MOUSE_MIDDLE
;
1002 else if ((pmer
->dwButtonState
& RIGHT
) == RIGHT
)
1003 nButton
= MOUSE_RIGHT
;
1005 if (! s_fReleased
&& ! s_fNextIsMiddle
1006 && nButton
!= s_nOldButton
&& s_nOldButton
!= MOUSE_DRAG
)
1009 s_fReleased
= s_fNextIsMiddle
;
1012 if (pmer
->dwEventFlags
== 0 || pmer
->dwEventFlags
== DOUBLE_CLICK
)
1014 /* button pressed or released, without mouse moving */
1015 if (nButton
!= -1 && nButton
!= MOUSE_RELEASE
)
1017 DWORD dwCurrentTime
= GetTickCount();
1019 if (s_xOldMouse
!= g_xMouse
1020 || s_yOldMouse
!= g_yMouse
1021 || s_nOldButton
!= nButton
1022 || s_old_topline
!= curwin
->w_topline
1024 || s_old_topfill
!= curwin
->w_topfill
1026 || (int)(dwCurrentTime
- s_dwLastClickTime
) > p_mouset
)
1030 else if (++s_cClicks
> 4)
1035 s_dwLastClickTime
= dwCurrentTime
;
1038 else if (pmer
->dwEventFlags
== MOUSE_MOVED
)
1040 if (nButton
!= -1 && nButton
!= MOUSE_RELEASE
)
1041 nButton
= MOUSE_DRAG
;
1049 if (nButton
!= MOUSE_RELEASE
)
1050 s_nOldButton
= nButton
;
1052 g_nMouseClick
= nButton
;
1054 if (pmer
->dwControlKeyState
& SHIFT_PRESSED
)
1055 g_nMouseClick
|= MOUSE_SHIFT
;
1056 if (pmer
->dwControlKeyState
& (RIGHT_CTRL_PRESSED
| LEFT_CTRL_PRESSED
))
1057 g_nMouseClick
|= MOUSE_CTRL
;
1058 if (pmer
->dwControlKeyState
& (RIGHT_ALT_PRESSED
| LEFT_ALT_PRESSED
))
1059 g_nMouseClick
|= MOUSE_ALT
;
1061 if (nButton
!= MOUSE_DRAG
&& nButton
!= MOUSE_RELEASE
)
1062 SET_NUM_MOUSE_CLICKS(g_nMouseClick
, s_cClicks
);
1064 /* only pass on interesting (i.e., different) mouse events */
1065 if (s_xOldMouse
== g_xMouse
1066 && s_yOldMouse
== g_yMouse
1067 && s_nOldMouseClick
== g_nMouseClick
)
1073 s_xOldMouse
= g_xMouse
;
1074 s_yOldMouse
= g_yMouse
;
1075 s_old_topline
= curwin
->w_topline
;
1077 s_old_topfill
= curwin
->w_topfill
;
1079 s_nOldMouseClick
= g_nMouseClick
;
1084 # endif /* FEAT_GUI_W32 */
1085 #endif /* FEAT_MOUSE */
1088 #ifdef MCH_CURSOR_SHAPE
1090 * Set the shape of the cursor.
1091 * 'thickness' can be from 1 (thin) to 99 (block)
1094 mch_set_cursor_shape(int thickness
)
1096 CONSOLE_CURSOR_INFO ConsoleCursorInfo
;
1097 ConsoleCursorInfo
.dwSize
= thickness
;
1098 ConsoleCursorInfo
.bVisible
= s_cursor_visible
;
1100 SetConsoleCursorInfo(g_hConOut
, &ConsoleCursorInfo
);
1101 if (s_cursor_visible
)
1102 SetConsoleCursorPosition(g_hConOut
, g_coord
);
1106 mch_update_cursor(void)
1112 * How the cursor is drawn depends on the current mode.
1114 idx
= get_shape_idx(FALSE
);
1116 if (shape_table
[idx
].shape
== SHAPE_BLOCK
)
1117 thickness
= 99; /* 100 doesn't work on W95 */
1119 thickness
= shape_table
[idx
].percentage
;
1120 mch_set_cursor_shape(thickness
);
1124 #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1126 * Handle FOCUS_EVENT.
1129 handle_focus_event(INPUT_RECORD ir
)
1131 g_fJustGotFocus
= ir
.Event
.FocusEvent
.bSetFocus
;
1132 ui_focus_change((int)g_fJustGotFocus
);
1136 * Wait until console input from keyboard or mouse is available,
1137 * or the time is up.
1138 * Return TRUE if something is available FALSE if not.
1141 WaitForChar(long msec
)
1143 DWORD dwNow
= 0, dwEndTime
= 0;
1149 /* Wait until the specified time has elapsed. */
1150 dwEndTime
= GetTickCount() + msec
;
1153 dwEndTime
= INFINITE
;
1155 /* We need to loop until the end of the time period, because
1156 * we might get multiple unusable mouse events in that time.
1160 #ifdef FEAT_MZSCHEME
1161 mzvim_check_threads();
1163 #ifdef FEAT_CLIENTSERVER
1164 serverProcessPendingMessages();
1168 || g_nMouseClick
!= -1
1170 #ifdef FEAT_CLIENTSERVER
1171 || input_available()
1178 /* If the specified wait time has passed, return. */
1179 dwNow
= GetTickCount();
1180 if (dwNow
>= dwEndTime
)
1185 DWORD dwWaitTime
= dwEndTime
- dwNow
;
1187 #ifdef FEAT_MZSCHEME
1188 if (mzthreads_allowed() && p_mzq
> 0
1189 && (msec
< 0 || (long)dwWaitTime
> p_mzq
))
1190 dwWaitTime
= p_mzq
; /* don't wait longer than 'mzquantum' */
1192 #ifdef FEAT_CLIENTSERVER
1193 /* Wait for either an event on the console input or a message in
1194 * the client-server window. */
1195 if (MsgWaitForMultipleObjects(1, &g_hConIn
, FALSE
,
1196 dwWaitTime
, QS_SENDMESSAGE
) != WAIT_OBJECT_0
)
1198 if (WaitForSingleObject(g_hConIn
, dwWaitTime
) != WAIT_OBJECT_0
)
1204 PeekConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
1206 #ifdef FEAT_MBYTE_IME
1207 if (State
& CMDLINE
&& msg_row
== Rows
- 1)
1209 CONSOLE_SCREEN_BUFFER_INFO csbi
;
1211 if (GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
1213 if (csbi
.dwCursorPosition
.Y
!= msg_row
)
1215 /* The screen is now messed up, must redraw the
1216 * command line and later all the windows. */
1217 redraw_all_later(CLEAR
);
1218 cmdline_row
-= (msg_row
- csbi
.dwCursorPosition
.Y
);
1227 if (ir
.EventType
== KEY_EVENT
&& ir
.Event
.KeyEvent
.bKeyDown
)
1229 #ifdef FEAT_MBYTE_IME
1230 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1231 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1232 if (ir
.Event
.KeyEvent
.uChar
.UnicodeChar
== 0
1233 && ir
.Event
.KeyEvent
.wVirtualKeyCode
== 13)
1235 ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
1239 if (decode_key_event(&ir
.Event
.KeyEvent
, &ch
, &ch2
,
1244 ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
1246 if (ir
.EventType
== FOCUS_EVENT
)
1247 handle_focus_event(ir
);
1248 else if (ir
.EventType
== WINDOW_BUFFER_SIZE_EVENT
)
1251 else if (ir
.EventType
== MOUSE_EVENT
1252 && decode_mouse_event(&ir
.Event
.MouseEvent
))
1260 #ifdef FEAT_CLIENTSERVER
1261 /* Something might have been received while we were waiting. */
1262 if (input_available())
1268 #ifndef FEAT_GUI_MSWIN
1270 * return non-zero if a character is available
1273 mch_char_avail(void)
1275 return WaitForChar(0L);
1280 * Create the console input. Used when reading stdin doesn't work.
1285 g_hConIn
= CreateFile("CONIN$", GENERIC_READ
|GENERIC_WRITE
,
1286 FILE_SHARE_READ
|FILE_SHARE_WRITE
,
1287 (LPSECURITY_ATTRIBUTES
) NULL
,
1288 OPEN_EXISTING
, 0, (HANDLE
)NULL
);
1289 did_create_conin
= TRUE
;
1293 * Get a keystroke or a mouse event
1296 tgetch(int *pmodifiers
, char_u
*pch2
)
1305 #ifdef FEAT_CLIENTSERVER
1306 (void)WaitForChar(-1L);
1307 if (input_available())
1310 if (g_nMouseClick
!= -1)
1314 if (ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
) == 0)
1316 if (did_create_conin
)
1322 if (ir
.EventType
== KEY_EVENT
)
1324 if (decode_key_event(&ir
.Event
.KeyEvent
, &ch
, pch2
,
1328 else if (ir
.EventType
== FOCUS_EVENT
)
1329 handle_focus_event(ir
);
1330 else if (ir
.EventType
== WINDOW_BUFFER_SIZE_EVENT
)
1333 else if (ir
.EventType
== MOUSE_EVENT
)
1335 if (decode_mouse_event(&ir
.Event
.MouseEvent
))
1341 #endif /* !FEAT_GUI_W32 */
1345 * mch_inchar(): low-level input funcion.
1346 * Get one or more characters from the keyboard or the mouse.
1347 * If time == 0, do not wait for characters.
1348 * If time == n, wait a short time for characters.
1349 * If time == -1, wait forever for characters.
1350 * Returns the number of characters read into buf.
1360 #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1364 #define TYPEAHEADLEN 20
1365 static char_u typeahead
[TYPEAHEADLEN
]; /* previously typed bytes. */
1366 static int typeaheadlen
= 0;
1368 /* First use any typeahead that was kept because "buf" was too small. */
1369 if (typeaheadlen
> 0)
1373 if (want_sniff_request
)
1375 if (sniff_request_waiting
)
1377 /* return K_SNIFF */
1378 typeahead
[typeaheadlen
++] = CSI
;
1379 typeahead
[typeaheadlen
++] = (char_u
)KS_EXTRA
;
1380 typeahead
[typeaheadlen
++] = (char_u
)KE_SNIFF
;
1381 sniff_request_waiting
= 0;
1382 want_sniff_request
= 0;
1385 else if (time
< 0 || time
> 250)
1387 /* don't wait too long, a request might be pending */
1395 if (!WaitForChar(time
)) /* no character available */
1398 else /* time == -1, wait forever */
1400 mch_set_winsize_now(); /* Allow winsize changes from now on */
1403 * If there is no character available within 2 seconds (default)
1404 * write the autoscript file to disk. Or cause the CursorHold event
1407 if (!WaitForChar(p_ut
))
1410 if (trigger_cursorhold() && maxlen
>= 3)
1414 buf
[2] = (int)KE_CURSORHOLD
;
1423 * Try to read as many characters as there are, until the buffer is full.
1426 /* we will get at least one key. Get more if they are available. */
1427 g_fCBrkPressed
= FALSE
;
1429 #ifdef MCH_WRITE_DUMP
1434 /* Keep looping until there is something in the typeahead buffer and more
1435 * to get and still room in the buffer (up to two bytes for a char and
1436 * three bytes for a modifier). */
1437 while ((typeaheadlen
== 0 || WaitForChar(0L))
1438 && typeaheadlen
+ 5 <= TYPEAHEADLEN
)
1440 if (typebuf_changed(tb_change_cnt
))
1442 /* "buf" may be invalid now if a client put something in the
1443 * typeahead buffer and "buf" is in the typeahead buffer. */
1448 if (g_nMouseClick
!= -1)
1450 # ifdef MCH_WRITE_DUMP
1452 fprintf(fdDump
, "{%02x @ %d, %d}",
1453 g_nMouseClick
, g_xMouse
, g_yMouse
);
1455 typeahead
[typeaheadlen
++] = ESC
+ 128;
1456 typeahead
[typeaheadlen
++] = 'M';
1457 typeahead
[typeaheadlen
++] = g_nMouseClick
;
1458 typeahead
[typeaheadlen
++] = g_xMouse
+ '!';
1459 typeahead
[typeaheadlen
++] = g_yMouse
+ '!';
1468 c
= tgetch(&modifiers
, &ch2
);
1470 if (typebuf_changed(tb_change_cnt
))
1472 /* "buf" may be invalid now if a client put something in the
1473 * typeahead buffer and "buf" is in the typeahead buffer. */
1478 if (c
== Ctrl_C
&& ctrl_c_interrupts
)
1480 #if defined(FEAT_CLIENTSERVER)
1487 if (g_nMouseClick
== -1)
1492 /* A key may have one or two bytes. */
1493 typeahead
[typeaheadlen
] = c
;
1496 typeahead
[typeaheadlen
+ 1] = ch2
;
1500 /* Only convert normal characters, not special keys. Need to
1501 * convert before applying ALT, otherwise mapping <M-x> breaks
1502 * when 'tenc' is set. */
1503 if (input_conv
.vc_type
!= CONV_NONE
1504 && (ch2
== NUL
|| c
!= K_NUL
))
1505 n
= convert_input(typeahead
+ typeaheadlen
, n
,
1506 TYPEAHEADLEN
- typeaheadlen
);
1509 /* Use the ALT key to set the 8th bit of the character
1510 * when it's one byte, the 8th bit isn't set yet and not
1511 * using a double-byte encoding (would become a lead
1513 if ((modifiers
& MOD_MASK_ALT
)
1515 && (typeahead
[typeaheadlen
] & 0x80) == 0
1522 n
= (*mb_char2bytes
)(typeahead
[typeaheadlen
] | 0x80,
1523 typeahead
+ typeaheadlen
);
1525 typeahead
[typeaheadlen
] |= 0x80;
1527 modifiers
&= ~MOD_MASK_ALT
;
1532 /* Prepend modifiers to the character. */
1533 mch_memmove(typeahead
+ typeaheadlen
+ 3,
1534 typeahead
+ typeaheadlen
, n
);
1535 typeahead
[typeaheadlen
++] = K_SPECIAL
;
1536 typeahead
[typeaheadlen
++] = (char_u
)KS_MODIFIER
;
1537 typeahead
[typeaheadlen
++] = modifiers
;
1542 #ifdef MCH_WRITE_DUMP
1550 #ifdef MCH_WRITE_DUMP
1553 fputs("]\n", fdDump
);
1559 /* Move typeahead to "buf", as much as fits. */
1561 while (len
< maxlen
&& typeaheadlen
> 0)
1563 buf
[len
++] = typeahead
[0];
1564 mch_memmove(typeahead
, typeahead
+ 1, --typeaheadlen
);
1568 #else /* FEAT_GUI_W32 */
1570 #endif /* FEAT_GUI_W32 */
1574 # include <shellapi.h> /* required for FindExecutable() */
1578 * Return TRUE if "name" is in $PATH.
1579 * TODO: Should somehow check if it's really executable.
1582 executable_exists(char *name
)
1585 char fname
[_MAX_PATH
];
1588 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
1590 WCHAR
*p
= enc_to_utf16(name
, NULL
);
1591 WCHAR fnamew
[_MAX_PATH
];
1597 n
= (long)SearchPathW(NULL
, p
, NULL
, _MAX_PATH
, fnamew
, &dumw
);
1599 if (n
> 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
1603 if (GetFileAttributesW(fnamew
) & FILE_ATTRIBUTE_DIRECTORY
)
1607 /* Retry with non-wide function (for Windows 98). */
1611 if (SearchPath(NULL
, name
, NULL
, _MAX_PATH
, fname
, &dum
) == 0)
1613 if (mch_isdir(fname
))
1621 * GUI version of mch_init().
1630 /* Let critical errors result in a failure, not in a dialog box. Required
1631 * for the timestamp test to work on removed floppies. */
1632 SetErrorMode(SEM_FAILCRITICALERRORS
);
1634 _fmode
= O_BINARY
; /* we do our own CR-LF translation */
1636 /* Specify window size. Is there a place to get the default from? */
1640 /* Look for 'vimrun' */
1641 if (!gui_is_win32s())
1643 char_u vimrun_location
[_MAX_PATH
+ 4];
1645 /* First try in same directory as gvim.exe */
1646 STRCPY(vimrun_location
, exe_name
);
1647 STRCPY(gettail(vimrun_location
), "vimrun.exe");
1648 if (mch_getperm(vimrun_location
) >= 0)
1650 if (*skiptowhite(vimrun_location
) != NUL
)
1652 /* Enclose path with white space in double quotes. */
1653 mch_memmove(vimrun_location
+ 1, vimrun_location
,
1654 STRLEN(vimrun_location
) + 1);
1655 *vimrun_location
= '"';
1656 STRCPY(gettail(vimrun_location
), "vimrun\" ");
1659 STRCPY(gettail(vimrun_location
), "vimrun ");
1661 vimrun_path
= (char *)vim_strsave(vimrun_location
);
1662 s_dont_use_vimrun
= FALSE
;
1664 else if (executable_exists("vimrun.exe"))
1665 s_dont_use_vimrun
= FALSE
;
1667 /* Don't give the warning for a missing vimrun.exe right now, but only
1668 * when vimrun was supposed to be used. Don't bother people that do
1669 * not need vimrun.exe. */
1670 if (s_dont_use_vimrun
)
1671 need_vimrun_warning
= TRUE
;
1675 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1676 * Otherwise the default "findstr /n" is used.
1678 if (!executable_exists("findstr.exe"))
1679 set_option_value((char_u
*)"grepprg", 0, (char_u
*)"grep -n", 0);
1681 #ifdef FEAT_CLIPBOARD
1685 * Vim's own clipboard format recognises whether the text is char, line,
1686 * or rectangular block. Only useful for copying between two Vims.
1687 * "VimClipboard" was used for previous versions, using the first
1688 * character to specify MCHAR, MLINE or MBLOCK.
1690 clip_star
.format
= RegisterClipboardFormat("VimClipboard2");
1691 clip_star
.format_raw
= RegisterClipboardFormat("VimRawBytes");
1696 #else /* FEAT_GUI_W32 */
1698 #define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1699 #define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1702 * ClearConsoleBuffer()
1704 * Clears the entire contents of the console screen buffer, using the
1705 * specified attribute.
1710 ClearConsoleBuffer(WORD wAttribute
)
1712 CONSOLE_SCREEN_BUFFER_INFO csbi
;
1714 DWORD NumCells
, dummy
;
1716 if (!GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
1719 NumCells
= csbi
.dwSize
.X
* csbi
.dwSize
.Y
;
1722 if (!FillConsoleOutputCharacter(g_hConOut
, ' ', NumCells
,
1727 if (!FillConsoleOutputAttribute(g_hConOut
, wAttribute
, NumCells
,
1737 * FitConsoleWindow()
1739 * Checks if the console window will fit within given buffer dimensions.
1740 * Also, if requested, will shrink the window to fit.
1749 CONSOLE_SCREEN_BUFFER_INFO csbi
;
1751 BOOL NeedAdjust
= FALSE
;
1753 if (GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
1756 * A buffer resize will fail if the current console window does
1757 * not lie completely within that buffer. To avoid this, we might
1758 * have to move and possibly shrink the window.
1760 if (csbi
.srWindow
.Right
>= dwBufferSize
.X
)
1762 dwWindowSize
.X
= SRWIDTH(csbi
.srWindow
);
1763 if (dwWindowSize
.X
> dwBufferSize
.X
)
1764 dwWindowSize
.X
= dwBufferSize
.X
;
1765 csbi
.srWindow
.Right
= dwBufferSize
.X
- 1;
1766 csbi
.srWindow
.Left
= dwBufferSize
.X
- dwWindowSize
.X
;
1769 if (csbi
.srWindow
.Bottom
>= dwBufferSize
.Y
)
1771 dwWindowSize
.Y
= SRHEIGHT(csbi
.srWindow
);
1772 if (dwWindowSize
.Y
> dwBufferSize
.Y
)
1773 dwWindowSize
.Y
= dwBufferSize
.Y
;
1774 csbi
.srWindow
.Bottom
= dwBufferSize
.Y
- 1;
1775 csbi
.srWindow
.Top
= dwBufferSize
.Y
- dwWindowSize
.Y
;
1778 if (NeedAdjust
&& WantAdjust
)
1780 if (!SetConsoleWindowInfo(g_hConOut
, TRUE
, &csbi
.srWindow
))
1789 typedef struct ConsoleBufferStruct
1792 CONSOLE_SCREEN_BUFFER_INFO Info
;
1798 * SaveConsoleBuffer()
1800 * Saves important information about the console buffer, including the
1801 * actual buffer contents. The saved information is suitable for later
1802 * restoration by RestoreConsoleBuffer().
1804 * TRUE if all information was saved; FALSE otherwise
1805 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1813 SMALL_RECT ReadRegion
;
1819 if (!GetConsoleScreenBufferInfo(g_hConOut
, &cb
->Info
))
1821 cb
->IsValid
= FALSE
;
1827 * Allocate a buffer large enough to hold the entire console screen
1828 * buffer. If this ConsoleBuffer structure has already been initialized
1829 * with a buffer of the correct size, then just use that one.
1831 if (!cb
->IsValid
|| cb
->Buffer
== NULL
||
1832 cb
->BufferSize
.X
!= cb
->Info
.dwSize
.X
||
1833 cb
->BufferSize
.Y
!= cb
->Info
.dwSize
.Y
)
1835 cb
->BufferSize
.X
= cb
->Info
.dwSize
.X
;
1836 cb
->BufferSize
.Y
= cb
->Info
.dwSize
.Y
;
1837 NumCells
= cb
->BufferSize
.X
* cb
->BufferSize
.Y
;
1838 if (cb
->Buffer
!= NULL
)
1839 vim_free(cb
->Buffer
);
1840 cb
->Buffer
= (PCHAR_INFO
)alloc(NumCells
* sizeof(CHAR_INFO
));
1841 if (cb
->Buffer
== NULL
)
1846 * We will now copy the console screen buffer into our buffer.
1847 * ReadConsoleOutput() seems to be limited as far as how much you
1848 * can read at a time. Empirically, this number seems to be about
1849 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1850 * in chunks until it is all copied. The chunks will all have the
1851 * same horizontal characteristics, so initialize them now. The
1852 * height of each chunk will be (12000 / width).
1855 ReadRegion
.Left
= 0;
1856 ReadRegion
.Right
= cb
->Info
.dwSize
.X
- 1;
1857 Y_incr
= 12000 / cb
->Info
.dwSize
.X
;
1858 for (Y
= 0; Y
< cb
->BufferSize
.Y
; Y
+= Y_incr
)
1861 * Read into position (0, Y) in our buffer.
1865 * Read the region whose top left corner is (0, Y) and whose bottom
1866 * right corner is (width - 1, Y + Y_incr - 1). This should define
1867 * a region of size width by Y_incr. Don't worry if this region is
1868 * too large for the remaining buffer; it will be cropped.
1871 ReadRegion
.Bottom
= Y
+ Y_incr
- 1;
1872 if (!ReadConsoleOutput(g_hConOut
, /* output handle */
1873 cb
->Buffer
, /* our buffer */
1874 cb
->BufferSize
, /* dimensions of our buffer */
1875 BufferCoord
, /* offset in our buffer */
1876 &ReadRegion
)) /* region to save */
1878 vim_free(cb
->Buffer
);
1888 * RestoreConsoleBuffer()
1890 * Restores important information about the console buffer, including the
1891 * actual buffer contents, if desired. The information to restore is in
1892 * the same format used by SaveConsoleBuffer().
1897 RestoreConsoleBuffer(
1902 SMALL_RECT WriteRegion
;
1904 if (cb
== NULL
|| !cb
->IsValid
)
1908 * Before restoring the buffer contents, clear the current buffer, and
1909 * restore the cursor position and window information. Doing this now
1910 * prevents old buffer contents from "flashing" onto the screen.
1913 ClearConsoleBuffer(cb
->Info
.wAttributes
);
1915 FitConsoleWindow(cb
->Info
.dwSize
, TRUE
);
1916 if (!SetConsoleScreenBufferSize(g_hConOut
, cb
->Info
.dwSize
))
1918 if (!SetConsoleTextAttribute(g_hConOut
, cb
->Info
.wAttributes
))
1924 * No need to restore the screen buffer contents, so we're done.
1929 if (!SetConsoleCursorPosition(g_hConOut
, cb
->Info
.dwCursorPosition
))
1931 if (!SetConsoleWindowInfo(g_hConOut
, TRUE
, &cb
->Info
.srWindow
))
1935 * Restore the screen buffer contents.
1937 if (cb
->Buffer
!= NULL
)
1941 WriteRegion
.Left
= 0;
1942 WriteRegion
.Top
= 0;
1943 WriteRegion
.Right
= cb
->Info
.dwSize
.X
- 1;
1944 WriteRegion
.Bottom
= cb
->Info
.dwSize
.Y
- 1;
1945 if (!WriteConsoleOutput(g_hConOut
, /* output handle */
1946 cb
->Buffer
, /* our buffer */
1947 cb
->BufferSize
, /* dimensions of our buffer */
1948 BufferCoord
, /* offset in our buffer */
1949 &WriteRegion
)) /* region to restore */
1958 #define FEAT_RESTORE_ORIG_SCREEN
1959 #ifdef FEAT_RESTORE_ORIG_SCREEN
1960 static ConsoleBuffer g_cbOrig
= { 0 };
1962 static ConsoleBuffer g_cbNonTermcap
= { 0 };
1963 static ConsoleBuffer g_cbTermcap
= { 0 };
1967 typedef HWND (__stdcall
*GETCONSOLEWINDOWPROC
)(VOID
);
1969 typedef WINBASEAPI
HWND (WINAPI
*GETCONSOLEWINDOWPROC
)(VOID
);
1971 char g_szOrigTitle
[256] = { 0 };
1972 HWND g_hWnd
= NULL
; /* also used in os_mswin.c */
1973 static HICON g_hOrigIconSmall
= NULL
;
1974 static HICON g_hOrigIcon
= NULL
;
1975 static HICON g_hVimIcon
= NULL
;
1976 static BOOL g_fCanChangeIcon
= FALSE
;
1978 /* ICON* are not defined in VC++ 4.0 */
1980 #define ICON_SMALL 0
1988 * Attempts to retrieve the small icon and/or the big icon currently in
1989 * use by a given window.
2002 if (phIconSmall
!= NULL
)
2003 *phIconSmall
= (HICON
)SendMessage(hWnd
, WM_GETICON
,
2004 (WPARAM
)ICON_SMALL
, (LPARAM
)0);
2006 *phIcon
= (HICON
)SendMessage(hWnd
, WM_GETICON
,
2007 (WPARAM
)ICON_BIG
, (LPARAM
)0);
2014 * Attempts to change the small icon and/or the big icon currently in
2015 * use by a given window.
2025 HICON hPrevIconSmall
;
2031 if (hIconSmall
!= NULL
)
2032 hPrevIconSmall
= (HICON
)SendMessage(hWnd
, WM_SETICON
,
2033 (WPARAM
)ICON_SMALL
, (LPARAM
)hIconSmall
);
2035 hPrevIcon
= (HICON
)SendMessage(hWnd
, WM_SETICON
,
2036 (WPARAM
)ICON_BIG
,(LPARAM
) hIcon
);
2041 * SaveConsoleTitleAndIcon()
2043 * Saves the current console window title in g_szOrigTitle, for later
2044 * restoration. Also, attempts to obtain a handle to the console window,
2045 * and use it to save the small and big icons currently in use by the
2046 * console window. This is not always possible on some versions of Windows;
2047 * nor is it possible when running Vim remotely using Telnet (since the
2048 * console window the user sees is owned by a remote process).
2051 SaveConsoleTitleAndIcon(void)
2053 GETCONSOLEWINDOWPROC GetConsoleWindowProc
;
2055 /* Save the original title. */
2056 if (!GetConsoleTitle(g_szOrigTitle
, sizeof(g_szOrigTitle
)))
2060 * Obtain a handle to the console window using GetConsoleWindow() from
2061 * KERNEL32.DLL; we need to handle in order to change the window icon.
2062 * This function only exists on NT-based Windows, starting with Windows
2063 * 2000. On older operating systems, we can't change the window icon
2066 if ((GetConsoleWindowProc
= (GETCONSOLEWINDOWPROC
)
2067 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2068 "GetConsoleWindow")) != NULL
)
2070 g_hWnd
= (*GetConsoleWindowProc
)();
2075 /* Save the original console window icon. */
2076 GetConsoleIcon(g_hWnd
, &g_hOrigIconSmall
, &g_hOrigIcon
);
2077 if (g_hOrigIconSmall
== NULL
|| g_hOrigIcon
== NULL
)
2080 /* Extract the first icon contained in the Vim executable. */
2081 g_hVimIcon
= ExtractIcon(NULL
, exe_name
, 0);
2082 if (g_hVimIcon
!= NULL
)
2083 g_fCanChangeIcon
= TRUE
;
2087 static int g_fWindInitCalled
= FALSE
;
2088 static int g_fTermcapMode
= FALSE
;
2089 static CONSOLE_CURSOR_INFO g_cci
;
2090 static DWORD g_cmodein
= 0;
2091 static DWORD g_cmodeout
= 0;
2094 * non-GUI version of mch_init().
2099 #ifndef FEAT_RESTORE_ORIG_SCREEN
2100 CONSOLE_SCREEN_BUFFER_INFO csbi
;
2106 /* Let critical errors result in a failure, not in a dialog box. Required
2107 * for the timestamp test to work on removed floppies. */
2108 SetErrorMode(SEM_FAILCRITICALERRORS
);
2110 _fmode
= O_BINARY
; /* we do our own CR-LF translation */
2113 /* Obtain handles for the standard Console I/O devices */
2114 if (read_cmd_fd
== 0)
2115 g_hConIn
= GetStdHandle(STD_INPUT_HANDLE
);
2118 g_hConOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
2120 #ifdef FEAT_RESTORE_ORIG_SCREEN
2121 /* Save the initial console buffer for later restoration */
2122 SaveConsoleBuffer(&g_cbOrig
);
2123 g_attrCurrent
= g_attrDefault
= g_cbOrig
.Info
.wAttributes
;
2125 /* Get current text attributes */
2126 GetConsoleScreenBufferInfo(g_hConOut
, &csbi
);
2127 g_attrCurrent
= g_attrDefault
= csbi
.wAttributes
;
2129 if (cterm_normal_fg_color
== 0)
2130 cterm_normal_fg_color
= (g_attrCurrent
& 0xf) + 1;
2131 if (cterm_normal_bg_color
== 0)
2132 cterm_normal_bg_color
= ((g_attrCurrent
>> 4) & 0xf) + 1;
2134 /* set termcap codes to current text attributes */
2135 update_tcap(g_attrCurrent
);
2137 GetConsoleCursorInfo(g_hConOut
, &g_cci
);
2138 GetConsoleMode(g_hConIn
, &g_cmodein
);
2139 GetConsoleMode(g_hConOut
, &g_cmodeout
);
2142 SaveConsoleTitleAndIcon();
2144 * Set both the small and big icons of the console window to Vim's icon.
2145 * Note that Vim presently only has one size of icon (32x32), but it
2146 * automatically gets scaled down to 16x16 when setting the small icon.
2148 if (g_fCanChangeIcon
)
2149 SetConsoleIcon(g_hWnd
, g_hVimIcon
, g_hVimIcon
);
2154 #ifdef MCH_WRITE_DUMP
2155 fdDump
= fopen("dump", "wt");
2162 fputs(ctime(&t
), fdDump
);
2167 g_fWindInitCalled
= TRUE
;
2170 g_fMouseAvail
= GetSystemMetrics(SM_MOUSEPRESENT
);
2173 #ifdef FEAT_CLIPBOARD
2177 * Vim's own clipboard format recognises whether the text is char, line, or
2178 * rectangular block. Only useful for copying between two Vims.
2179 * "VimClipboard" was used for previous versions, using the first
2180 * character to specify MCHAR, MLINE or MBLOCK.
2182 clip_star
.format
= RegisterClipboardFormat("VimClipboard2");
2183 clip_star
.format_raw
= RegisterClipboardFormat("VimRawBytes");
2186 /* This will be NULL on anything but NT 4.0 */
2187 s_pfnGetConsoleKeyboardLayoutName
=
2188 (PFNGCKLN
) GetProcAddress(GetModuleHandle("kernel32.dll"),
2189 "GetConsoleKeyboardLayoutNameA");
2193 * non-GUI version of mch_exit().
2194 * Shut down and exit with status `r'
2195 * Careful: mch_exit() may be called before mch_init()!
2202 if (g_fWindInitCalled
)
2203 settmode(TMODE_COOK
);
2205 ml_close_all(TRUE
); /* remove all memfiles */
2207 if (g_fWindInitCalled
)
2210 mch_restore_title(3);
2212 * Restore both the small and big icons of the console window to
2213 * what they were at startup. Don't do this when the window is
2214 * closed, Vim would hang here.
2216 if (g_fCanChangeIcon
&& !g_fForceExit
)
2217 SetConsoleIcon(g_hWnd
, g_hOrigIconSmall
, g_hOrigIcon
);
2220 #ifdef MCH_WRITE_DUMP
2226 fputs(ctime(&t
), fdDump
);
2233 SetConsoleCursorInfo(g_hConOut
, &g_cci
);
2234 SetConsoleMode(g_hConIn
, g_cmodein
);
2235 SetConsoleMode(g_hConOut
, g_cmodeout
);
2237 #ifdef DYNAMIC_GETTEXT
2243 #endif /* !FEAT_GUI_W32 */
2246 * Do we have an interactive window?
2257 return OK
; /* GUI always has a tty */
2267 * fname_case(): Set the case of the file name, if it already exists.
2268 * When "len" is > 0, also expand short to long filenames.
2275 char szTrueName
[_MAX_PATH
+ 2];
2276 char *ptrue
, *ptruePrev
;
2277 char *porig
, *porigPrev
;
2283 flen
= (int)STRLEN(name
);
2284 if (flen
== 0 || flen
> _MAX_PATH
)
2289 /* Build the new name in szTrueName[] one component at a time. */
2293 if (isalpha(porig
[0]) && porig
[1] == ':')
2295 /* copy leading drive letter */
2296 *ptrue
++ = *porig
++;
2297 *ptrue
++ = *porig
++;
2298 *ptrue
= NUL
; /* in case nothing follows */
2301 while (*porig
!= NUL
)
2303 /* copy \ characters */
2304 while (*porig
== psepc
)
2305 *ptrue
++ = *porig
++;
2309 while (*porig
!= NUL
&& *porig
!= psepc
)
2316 l
= (*mb_ptr2len
)(porig
);
2318 *ptrue
++ = *porig
++;
2322 *ptrue
++ = *porig
++;
2326 /* Skip "", "." and "..". */
2327 if (ptrue
> ptruePrev
2328 && (ptruePrev
[0] != '.'
2329 || (ptruePrev
[1] != NUL
2330 && (ptruePrev
[1] != '.' || ptruePrev
[2] != NUL
)))
2331 && (hFind
= FindFirstFile(szTrueName
, &fb
))
2332 != INVALID_HANDLE_VALUE
)
2337 /* Only use the match when it's the same name (ignoring case) or
2338 * expansion is allowed and there is a match with the short name
2339 * and there is enough room. */
2340 if (_stricoll(porigPrev
, fb
.cFileName
) == 0
2342 && (_stricoll(porigPrev
, fb
.cAlternateFileName
) == 0
2343 && (int)(ptruePrev
- szTrueName
)
2344 + (int)strlen(fb
.cFileName
) < len
)))
2346 STRCPY(ptruePrev
, fb
.cFileName
);
2348 /* Look for exact match and prefer it if found. Must be a
2349 * long name, otherwise there would be only one match. */
2350 while (FindNextFile(hFind
, &fb
))
2352 if (*fb
.cAlternateFileName
!= NUL
2353 && (strcoll(porigPrev
, fb
.cFileName
) == 0
2355 && (_stricoll(porigPrev
,
2356 fb
.cAlternateFileName
) == 0
2357 && (int)(ptruePrev
- szTrueName
)
2358 + (int)strlen(fb
.cFileName
) < len
))))
2360 STRCPY(ptruePrev
, fb
.cFileName
);
2367 ptrue
= ptruePrev
+ strlen(ptruePrev
);
2371 STRCPY(name
, szTrueName
);
2376 * Insert user name in s[len].
2383 char szUserName
[256 + 1]; /* UNLEN is 256 */
2384 DWORD cch
= sizeof szUserName
;
2386 if (GetUserName(szUserName
, &cch
))
2388 vim_strncpy(s
, szUserName
, len
- 1);
2397 * Insert host name in s[len].
2406 if (!GetComputerName(s
, &cch
))
2407 vim_strncpy(s
, "PC (Win32 Vim)", len
- 1);
2417 return (long)GetCurrentProcessId();
2422 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2423 * Return OK for success, FAIL for failure.
2431 * Originally this was:
2432 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2433 * But the Win32s known bug list says that getcwd() doesn't work
2434 * so use the Win32 system call instead. <Negri>
2437 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2439 WCHAR wbuf
[_MAX_PATH
+ 1];
2441 if (GetCurrentDirectoryW(_MAX_PATH
, wbuf
) != 0)
2443 char_u
*p
= utf16_to_enc(wbuf
, NULL
);
2447 vim_strncpy(buf
, p
, len
- 1);
2452 /* Retry with non-wide function (for Windows 98). */
2455 return (GetCurrentDirectory(len
, buf
) != 0 ? OK
: FAIL
);
2459 * get file permissions for `name'
2461 * else FILE_ATTRIBUTE_* defined in winnt.h
2464 mch_getperm(char_u
*name
)
2467 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2469 WCHAR
*p
= enc_to_utf16(name
, NULL
);
2474 n
= (long)GetFileAttributesW(p
);
2476 if (n
>= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
2478 /* Retry with non-wide function (for Windows 98). */
2482 return (long)GetFileAttributes((char *)name
);
2487 * set file permission for `name' to `perm'
2494 perm
|= FILE_ATTRIBUTE_ARCHIVE
; /* file has changed, set archive bit */
2496 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2498 WCHAR
*p
= enc_to_utf16(name
, NULL
);
2503 n
= (long)SetFileAttributesW(p
, perm
);
2505 if (n
|| GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
2506 return n
? OK
: FAIL
;
2507 /* Retry with non-wide function (for Windows 98). */
2511 return SetFileAttributes((char *)name
, perm
) ? OK
: FAIL
;
2515 * Set hidden flag for "name".
2518 mch_hide(char_u
*name
)
2524 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2525 p
= enc_to_utf16(name
, NULL
);
2531 perm
= GetFileAttributesW(p
);
2532 if (perm
< 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
2534 /* Retry with non-wide function (for Windows 98). */
2541 perm
= GetFileAttributes((char *)name
);
2544 perm
|= FILE_ATTRIBUTE_HIDDEN
;
2548 if (SetFileAttributesW(p
, perm
) == 0
2549 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
2551 /* Retry with non-wide function (for Windows 98). */
2558 SetFileAttributes((char *)name
, perm
);
2566 * return TRUE if "name" is a directory
2567 * return FALSE if "name" is not a directory or upon error
2570 mch_isdir(char_u
*name
)
2572 int f
= mch_getperm(name
);
2575 return FALSE
; /* file does not exist at all */
2577 return (f
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
2581 * Return TRUE if file "fname" has more than one link.
2584 mch_is_linked(char_u
*fname
)
2588 BY_HANDLE_FILE_INFORMATION inf
;
2592 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2593 wn
= enc_to_utf16(fname
, NULL
);
2596 hFile
= CreateFileW(wn
, /* file name */
2597 GENERIC_READ
, /* access mode */
2599 NULL
, /* security descriptor */
2600 OPEN_EXISTING
, /* creation disposition */
2601 0, /* file attributes */
2602 NULL
); /* handle to template file */
2603 if (hFile
== INVALID_HANDLE_VALUE
2604 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
2606 /* Retry with non-wide function (for Windows 98). */
2613 hFile
= CreateFile(fname
, /* file name */
2614 GENERIC_READ
, /* access mode */
2616 NULL
, /* security descriptor */
2617 OPEN_EXISTING
, /* creation disposition */
2618 0, /* file attributes */
2619 NULL
); /* handle to template file */
2621 if (hFile
!= INVALID_HANDLE_VALUE
)
2623 if (GetFileInformationByHandle(hFile
, &inf
) != 0
2624 && inf
.nNumberOfLinks
> 1)
2636 * Return TRUE if file or directory "name" is writable (not readonly).
2637 * Strange semantics of Win32: a readonly directory is writable, but you can't
2638 * delete a file. Let's say this means it is writable.
2641 mch_writable(char_u
*name
)
2643 int perm
= mch_getperm(name
);
2645 return (perm
!= -1 && (!(perm
& FILE_ATTRIBUTE_READONLY
)
2646 || (perm
& FILE_ATTRIBUTE_DIRECTORY
)));
2650 * Return 1 if "name" can be executed, 0 if not.
2651 * Return -1 if unknown.
2654 mch_can_exe(char_u
*name
)
2656 char_u buf
[_MAX_PATH
];
2657 int len
= (int)STRLEN(name
);
2660 if (len
>= _MAX_PATH
) /* safety check */
2663 /* If there already is an extension try using the name directly. Also do
2664 * this with a Unix-shell like 'shell'. */
2665 if (vim_strchr(gettail(name
), '.') != NULL
2666 || strstr((char *)gettail(p_sh
), "sh") != NULL
)
2667 if (executable_exists((char *)name
))
2671 * Loop over all extensions in $PATHEXT.
2673 vim_strncpy(buf
, name
, _MAX_PATH
- 1);
2674 p
= mch_getenv("PATHEXT");
2676 p
= (char_u
*)".com;.exe;.bat;.cmd";
2679 if (p
[0] == '.' && (p
[1] == NUL
|| p
[1] == ';'))
2681 /* A single "." means no extension is added. */
2688 copy_option_part(&p
, buf
+ len
, _MAX_PATH
- len
, ";");
2689 if (executable_exists((char *)buf
))
2696 * Check what "name" is:
2697 * NODE_NORMAL: file or directory (or doesn't exist)
2698 * NODE_WRITABLE: writable device, socket, fifo, etc.
2699 * NODE_OTHER: non-writable things
2702 mch_nodetype(char_u
*name
)
2707 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2708 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2710 if (STRNCMP(name
, "\\\\.\\", 4) == 0)
2711 return NODE_WRITABLE
;
2713 hFile
= CreateFile(name
, /* file name */
2714 GENERIC_WRITE
, /* access mode */
2716 NULL
, /* security descriptor */
2717 OPEN_EXISTING
, /* creation disposition */
2718 0, /* file attributes */
2719 NULL
); /* handle to template file */
2721 if (hFile
== INVALID_HANDLE_VALUE
)
2724 type
= GetFileType(hFile
);
2726 if (type
== FILE_TYPE_CHAR
)
2727 return NODE_WRITABLE
;
2728 if (type
== FILE_TYPE_DISK
)
2736 PSECURITY_DESCRIPTOR pSecurityDescriptor
;
2745 * Return a pointer to the ACL of file "fname" in allocated memory.
2746 * Return NULL if the ACL is not available for whatever reason.
2749 mch_get_acl(char_u
*fname
)
2752 return (vim_acl_T
)NULL
;
2754 struct my_acl
*p
= NULL
;
2756 /* This only works on Windows NT and 2000. */
2757 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
&& advapi_lib
!= NULL
)
2759 p
= (struct my_acl
*)alloc_clear((unsigned)sizeof(struct my_acl
));
2762 if (pGetNamedSecurityInfo(
2763 (LPTSTR
)fname
, // Abstract filename
2764 SE_FILE_OBJECT
, // File Object
2765 // Retrieve the entire security descriptor.
2766 OWNER_SECURITY_INFORMATION
|
2767 GROUP_SECURITY_INFORMATION
|
2768 DACL_SECURITY_INFORMATION
|
2769 SACL_SECURITY_INFORMATION
,
2770 &p
->pSidOwner
, // Ownership information.
2771 &p
->pSidGroup
, // Group membership.
2772 &p
->pDacl
, // Discretionary information.
2773 &p
->pSacl
, // For auditing purposes.
2774 &p
->pSecurityDescriptor
2777 mch_free_acl((vim_acl_T
)p
);
2783 return (vim_acl_T
)p
;
2788 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2789 * Errors are ignored.
2790 * This must only be called with "acl" equal to what mch_get_acl() returned.
2793 mch_set_acl(char_u
*fname
, vim_acl_T acl
)
2796 struct my_acl
*p
= (struct my_acl
*)acl
;
2798 if (p
!= NULL
&& advapi_lib
!= NULL
)
2799 (void)pSetNamedSecurityInfo(
2800 (LPTSTR
)fname
, // Abstract filename
2801 SE_FILE_OBJECT
, // File Object
2802 // Retrieve the entire security descriptor.
2803 OWNER_SECURITY_INFORMATION
|
2804 GROUP_SECURITY_INFORMATION
|
2805 DACL_SECURITY_INFORMATION
|
2806 SACL_SECURITY_INFORMATION
,
2807 p
->pSidOwner
, // Ownership information.
2808 p
->pSidGroup
, // Group membership.
2809 p
->pDacl
, // Discretionary information.
2810 p
->pSacl
// For auditing purposes.
2816 mch_free_acl(vim_acl_T acl
)
2819 struct my_acl
*p
= (struct my_acl
*)acl
;
2823 LocalFree(p
->pSecurityDescriptor
); // Free the memory just in case
2829 #ifndef FEAT_GUI_W32
2832 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2841 if (ctrl_c_interrupts
)
2842 g_fCtrlCPressed
= TRUE
;
2845 case CTRL_BREAK_EVENT
:
2846 g_fCBrkPressed
= TRUE
;
2849 /* fatal events: shut down gracefully */
2850 case CTRL_CLOSE_EVENT
:
2851 case CTRL_LOGOFF_EVENT
:
2852 case CTRL_SHUTDOWN_EVENT
:
2853 windgoto((int)Rows
- 1, 0);
2854 g_fForceExit
= TRUE
;
2856 vim_snprintf((char *)IObuff
, IOSIZE
, _("Vim: Caught %s event\n"),
2857 (dwCtrlType
== CTRL_CLOSE_EVENT
2859 : dwCtrlType
== CTRL_LOGOFF_EVENT
2863 OutputDebugString(IObuff
);
2866 preserve_exit(); /* output IObuff, preserve files and exit */
2868 return TRUE
; /* not reached */
2877 * set the tty in (raw) ? "raw" : "cooked" mode
2880 mch_settmode(int tmode
)
2884 BOOL bEnableHandler
;
2886 GetConsoleMode(g_hConIn
, &cmodein
);
2887 GetConsoleMode(g_hConOut
, &cmodeout
);
2888 if (tmode
== TMODE_RAW
)
2890 cmodein
&= ~(ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
|
2894 cmodein
|= ENABLE_MOUSE_INPUT
;
2896 cmodeout
&= ~(ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
2897 bEnableHandler
= TRUE
;
2901 cmodein
|= (ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
|
2903 cmodeout
|= (ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
2904 bEnableHandler
= FALSE
;
2906 SetConsoleMode(g_hConIn
, cmodein
);
2907 SetConsoleMode(g_hConOut
, cmodeout
);
2908 SetConsoleCtrlHandler(handler_routine
, bEnableHandler
);
2910 #ifdef MCH_WRITE_DUMP
2913 fprintf(fdDump
, "mch_settmode(%s, in = %x, out = %x)\n",
2914 tmode
== TMODE_RAW
? "raw" :
2915 tmode
== TMODE_COOK
? "cooked" : "normal",
2924 * Get the size of the current window in `Rows' and `Columns'
2925 * Return OK when size could be determined, FAIL otherwise.
2928 mch_get_shellsize(void)
2930 CONSOLE_SCREEN_BUFFER_INFO csbi
;
2932 if (!g_fTermcapMode
&& g_cbTermcap
.IsValid
)
2935 * For some reason, we are trying to get the screen dimensions
2936 * even though we are not in termcap mode. The 'Rows' and 'Columns'
2937 * variables are really intended to mean the size of Vim screen
2938 * while in termcap mode.
2940 Rows
= g_cbTermcap
.Info
.dwSize
.Y
;
2941 Columns
= g_cbTermcap
.Info
.dwSize
.X
;
2943 else if (GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
2945 Rows
= csbi
.srWindow
.Bottom
- csbi
.srWindow
.Top
+ 1;
2946 Columns
= csbi
.srWindow
.Right
- csbi
.srWindow
.Left
+ 1;
2957 * Set a console window to `xSize' * `ySize'
2960 ResizeConBufAndWindow(
2965 CONSOLE_SCREEN_BUFFER_INFO csbi
; /* hold current console buffer info */
2966 SMALL_RECT srWindowRect
; /* hold the new console size */
2969 #ifdef MCH_WRITE_DUMP
2972 fprintf(fdDump
, "ResizeConBufAndWindow(%d, %d)\n", xSize
, ySize
);
2977 /* get the largest size we can size the console window to */
2978 coordScreen
= GetLargestConsoleWindowSize(hConsole
);
2980 /* define the new console window size and scroll position */
2981 srWindowRect
.Left
= srWindowRect
.Top
= (SHORT
) 0;
2982 srWindowRect
.Right
= (SHORT
) (min(xSize
, coordScreen
.X
) - 1);
2983 srWindowRect
.Bottom
= (SHORT
) (min(ySize
, coordScreen
.Y
) - 1);
2985 if (GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
2989 sx
= csbi
.srWindow
.Right
- csbi
.srWindow
.Left
+ 1;
2990 sy
= csbi
.srWindow
.Bottom
- csbi
.srWindow
.Top
+ 1;
2991 if (sy
< ySize
|| sx
< xSize
)
2994 * Increasing number of lines/columns, do buffer first.
2995 * Use the maximal size in x and y direction.
2998 coordScreen
.Y
= ySize
;
3002 coordScreen
.X
= xSize
;
3005 SetConsoleScreenBufferSize(hConsole
, coordScreen
);
3009 if (!SetConsoleWindowInfo(g_hConOut
, TRUE
, &srWindowRect
))
3011 #ifdef MCH_WRITE_DUMP
3014 fprintf(fdDump
, "SetConsoleWindowInfo failed: %lx\n",
3021 /* define the new console buffer size */
3022 coordScreen
.X
= xSize
;
3023 coordScreen
.Y
= ySize
;
3025 if (!SetConsoleScreenBufferSize(hConsole
, coordScreen
))
3027 #ifdef MCH_WRITE_DUMP
3030 fprintf(fdDump
, "SetConsoleScreenBufferSize failed: %lx\n",
3040 * Set the console window to `Rows' * `Columns'
3043 mch_set_shellsize(void)
3047 /* Don't change window size while still starting up */
3048 if (suppress_winsize
!= 0)
3050 suppress_winsize
= 2;
3056 coordScreen
= GetLargestConsoleWindowSize(g_hConOut
);
3058 /* Clamp Rows and Columns to reasonable values */
3059 if (Rows
> coordScreen
.Y
)
3060 Rows
= coordScreen
.Y
;
3061 if (Columns
> coordScreen
.X
)
3062 Columns
= coordScreen
.X
;
3064 ResizeConBufAndWindow(g_hConOut
, Columns
, Rows
);
3069 * Rows and/or Columns has changed.
3072 mch_new_shellsize(void)
3074 set_scroll_region(0, 0, Columns
- 1, Rows
- 1);
3079 * Called when started up, to set the winsize that was delayed.
3082 mch_set_winsize_now(void)
3084 if (suppress_winsize
== 2)
3086 suppress_winsize
= 0;
3087 mch_set_shellsize();
3090 suppress_winsize
= 0;
3092 #endif /* FEAT_GUI_W32 */
3096 #if defined(FEAT_GUI_W32) || defined(PROTO)
3099 * Specialised version of system() for Win32 GUI mode.
3100 * This version proceeds as follows:
3101 * 1. Create a console window for use by the subprocess
3102 * 2. Run the subprocess (it gets the allocated console by default)
3103 * 3. Wait for the subprocess to terminate and get its exit code
3104 * 4. Prompt the user to press a key to close the console window
3107 mch_system(char *cmd
, int options
)
3110 PROCESS_INFORMATION pi
;
3112 HWND hwnd
= GetFocus();
3115 si
.lpReserved
= NULL
;
3116 si
.lpDesktop
= NULL
;
3118 si
.dwFlags
= STARTF_USESHOWWINDOW
;
3120 * It's nicer to run a filter command in a minimized window, but in
3121 * Windows 95 this makes the command MUCH slower. We can't do it under
3122 * Win32s either as it stops the synchronous spawn workaround working.
3124 if ((options
& SHELL_DOOUT
) && !mch_windows95() && !gui_is_win32s())
3125 si
.wShowWindow
= SW_SHOWMINIMIZED
;
3127 si
.wShowWindow
= SW_SHOWNORMAL
;
3129 si
.lpReserved2
= NULL
;
3131 /* There is a strange error on Windows 95 when using "c:\\command.com".
3132 * When the "c:\\" is left out it works OK...? */
3134 && (STRNICMP(cmd
, "c:/command.com", 14) == 0
3135 || STRNICMP(cmd
, "c:\\command.com", 14) == 0))
3138 /* Now, run the command */
3139 CreateProcess(NULL
, /* Executable name */
3140 cmd
, /* Command to execute */
3141 NULL
, /* Process security attributes */
3142 NULL
, /* Thread security attributes */
3143 FALSE
, /* Inherit handles */
3144 CREATE_DEFAULT_ERROR_MODE
| /* Creation flags */
3146 NULL
, /* Environment */
3147 NULL
, /* Current directory */
3148 &si
, /* Startup information */
3149 &pi
); /* Process information */
3152 /* Wait for the command to terminate before continuing */
3153 if (g_PlatformId
!= VER_PLATFORM_WIN32s
)
3158 /* Keep updating the window while waiting for the shell to finish. */
3163 if (PeekMessage(&msg
, (HWND
)NULL
, 0, 0, PM_REMOVE
))
3165 TranslateMessage(&msg
);
3166 DispatchMessage(&msg
);
3168 if (WaitForSingleObject(pi
.hProcess
, delay
) != WAIT_TIMEOUT
)
3171 /* We start waiting for a very short time and then increase it, so
3172 * that we respond quickly when the process is quick, and don't
3173 * consume too much overhead when it's slow. */
3178 WaitForSingleObject(pi
.hProcess
, INFINITE
);
3181 /* Get the command exit code */
3182 GetExitCodeProcess(pi
.hProcess
, &ret
);
3187 * This ugly code is the only quick way of performing
3188 * a synchronous spawn under Win32s. Yuk.
3191 EnumWindows(win32ssynch_cb
, 0);
3192 old_num_windows
= num_windows
;
3197 EnumWindows(win32ssynch_cb
, 0);
3198 } while (num_windows
== old_num_windows
);
3202 /* Close the handles to the subprocess, so that it goes away */
3203 CloseHandle(pi
.hThread
);
3204 CloseHandle(pi
.hProcess
);
3206 /* Try to get input focus back. Doesn't always work though. */
3207 PostMessage(hwnd
, WM_SETFOCUS
, 0, 0);
3213 # define mch_system(c, o) system(c)
3218 * Either execute a command by calling the shell or start a new shell
3223 int options
) /* SHELL_*, see vim.h */
3226 int tmode
= cur_tmode
;
3228 char szShellTitle
[512];
3230 /* Change the title to reflect that we are in a subshell. */
3231 if (GetConsoleTitle(szShellTitle
, sizeof(szShellTitle
) - 4) > 0)
3234 strcat(szShellTitle
, " :sh");
3237 strcat(szShellTitle
, " - !");
3238 if ((strlen(szShellTitle
) + strlen(cmd
) < sizeof(szShellTitle
)))
3239 strcat(szShellTitle
, cmd
);
3241 mch_settitle(szShellTitle
, NULL
);
3247 #ifdef MCH_WRITE_DUMP
3250 fprintf(fdDump
, "mch_call_shell(\"%s\", %d)\n", cmd
, options
);
3256 * Catch all deadly signals while running the external command, because a
3257 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3259 signal(SIGINT
, SIG_IGN
);
3260 #if defined(__GNUC__) && !defined(__MINGW32__)
3261 signal(SIGKILL
, SIG_IGN
);
3263 signal(SIGBREAK
, SIG_IGN
);
3265 signal(SIGILL
, SIG_IGN
);
3266 signal(SIGFPE
, SIG_IGN
);
3267 signal(SIGSEGV
, SIG_IGN
);
3268 signal(SIGTERM
, SIG_IGN
);
3269 signal(SIGABRT
, SIG_IGN
);
3271 if (options
& SHELL_COOKED
)
3272 settmode(TMODE_COOK
); /* set to normal mode */
3276 x
= mch_system(p_sh
, options
);
3280 /* we use "command" or "cmd" to start the shell; slow but easy */
3284 STRLEN(vimrun_path
) +
3286 STRLEN(p_sh
) + STRLEN(p_shcf
) + STRLEN(cmd
) + 10);
3288 newcmd
= lalloc(cmdlen
, TRUE
);
3291 char_u
*cmdbase
= (*cmd
== '"' ? cmd
+ 1 : cmd
);
3293 if ((STRNICMP(cmdbase
, "start", 5) == 0) && vim_iswhite(cmdbase
[5]))
3296 PROCESS_INFORMATION pi
;
3299 si
.lpReserved
= NULL
;
3300 si
.lpDesktop
= NULL
;
3304 si
.lpReserved2
= NULL
;
3306 cmdbase
= skipwhite(cmdbase
+ 5);
3307 if ((STRNICMP(cmdbase
, "/min", 4) == 0)
3308 && vim_iswhite(cmdbase
[4]))
3310 cmdbase
= skipwhite(cmdbase
+ 4);
3311 si
.dwFlags
= STARTF_USESHOWWINDOW
;
3312 si
.wShowWindow
= SW_SHOWMINNOACTIVE
;
3315 /* When the command is in double quotes, but 'shellxquote' is
3316 * empty, keep the double quotes around the command.
3317 * Otherwise remove the double quotes, they aren't needed
3318 * here, because we don't use a shell to run the command. */
3319 if (*cmd
== '"' && *p_sxq
== NUL
)
3322 STRCPY(newcmd
+ 1, cmdbase
);
3326 STRCPY(newcmd
, cmdbase
);
3327 if (*cmd
== '"' && *newcmd
!= NUL
)
3328 newcmd
[STRLEN(newcmd
) - 1] = NUL
;
3332 * Now, start the command as a process, so that it doesn't
3333 * inherit our handles which causes unpleasant dangling swap
3334 * files if we exit before the spawned process
3336 if (CreateProcess (NULL
, // Executable name
3337 newcmd
, // Command to execute
3338 NULL
, // Process security attributes
3339 NULL
, // Thread security attributes
3340 FALSE
, // Inherit handles
3341 CREATE_NEW_CONSOLE
, // Creation flags
3342 NULL
, // Environment
3343 NULL
, // Current directory
3344 &si
, // Startup information
3345 &pi
)) // Process information
3351 EMSG(_("E371: Command not found"));
3354 /* Close the handles to the subprocess, so that it goes away */
3355 CloseHandle(pi
.hThread
);
3356 CloseHandle(pi
.hProcess
);
3360 #if defined(FEAT_GUI_W32)
3361 if (need_vimrun_warning
)
3364 _("VIMRUN.EXE not found in your $PATH.\n"
3365 "External commands will not pause after completion.\n"
3366 "See :help win32-vimrun for more information."),
3369 need_vimrun_warning
= FALSE
;
3371 if (!s_dont_use_vimrun
)
3372 /* Use vimrun to execute the command. It opens a console
3373 * window, which can be closed without killing Vim. */
3374 vim_snprintf((char *)newcmd
, cmdlen
, "%s%s%s %s %s",
3376 (msg_silent
!= 0 || (options
& SHELL_DOOUT
))
3381 vim_snprintf((char *)newcmd
, cmdlen
, "%s %s %s",
3383 x
= mch_system((char *)newcmd
, options
);
3389 if (tmode
== TMODE_RAW
)
3390 settmode(TMODE_RAW
); /* set to raw mode */
3392 /* Print the return value, unless "vimrun" was used. */
3393 if (x
!= 0 && !(options
& SHELL_SILENT
) && !emsg_silent
3394 #if defined(FEAT_GUI_W32)
3395 && ((options
& SHELL_DOOUT
) || s_dont_use_vimrun
)
3399 smsg(_("shell returned %d"), x
);
3406 signal(SIGINT
, SIG_DFL
);
3407 #if defined(__GNUC__) && !defined(__MINGW32__)
3408 signal(SIGKILL
, SIG_DFL
);
3410 signal(SIGBREAK
, SIG_DFL
);
3412 signal(SIGILL
, SIG_DFL
);
3413 signal(SIGFPE
, SIG_DFL
);
3414 signal(SIGSEGV
, SIG_DFL
);
3415 signal(SIGTERM
, SIG_DFL
);
3416 signal(SIGABRT
, SIG_DFL
);
3422 #ifndef FEAT_GUI_W32
3425 * Start termcap mode
3428 termcap_mode_start(void)
3435 SaveConsoleBuffer(&g_cbNonTermcap
);
3437 if (g_cbTermcap
.IsValid
)
3440 * We've been in termcap mode before. Restore certain screen
3441 * characteristics, including the buffer size and the window
3442 * size. Since we will be redrawing the screen, we don't need
3443 * to restore the actual contents of the buffer.
3445 RestoreConsoleBuffer(&g_cbTermcap
, FALSE
);
3446 SetConsoleWindowInfo(g_hConOut
, TRUE
, &g_cbTermcap
.Info
.srWindow
);
3447 Rows
= g_cbTermcap
.Info
.dwSize
.Y
;
3448 Columns
= g_cbTermcap
.Info
.dwSize
.X
;
3453 * This is our first time entering termcap mode. Clear the console
3454 * screen buffer, and resize the buffer to match the current window
3455 * size. We will use this as the size of our editing environment.
3457 ClearConsoleBuffer(g_attrCurrent
);
3458 ResizeConBufAndWindow(g_hConOut
, Columns
, Rows
);
3465 GetConsoleMode(g_hConIn
, &cmodein
);
3468 cmodein
|= ENABLE_MOUSE_INPUT
;
3470 cmodein
&= ~ENABLE_MOUSE_INPUT
;
3472 cmodein
|= ENABLE_WINDOW_INPUT
;
3473 SetConsoleMode(g_hConIn
, cmodein
);
3475 redraw_later_clear();
3476 g_fTermcapMode
= TRUE
;
3484 termcap_mode_end(void)
3491 if (!g_fTermcapMode
)
3494 SaveConsoleBuffer(&g_cbTermcap
);
3496 GetConsoleMode(g_hConIn
, &cmodein
);
3497 cmodein
&= ~(ENABLE_MOUSE_INPUT
| ENABLE_WINDOW_INPUT
);
3498 SetConsoleMode(g_hConIn
, cmodein
);
3500 #ifdef FEAT_RESTORE_ORIG_SCREEN
3501 cb
= exiting
? &g_cbOrig
: &g_cbNonTermcap
;
3503 cb
= &g_cbNonTermcap
;
3505 RestoreConsoleBuffer(cb
, p_rs
);
3506 SetConsoleCursorInfo(g_hConOut
, &g_cci
);
3508 if (p_rs
|| exiting
)
3511 * Clear anything that happens to be on the current line.
3514 coord
.Y
= (SHORT
) (p_rs
? cb
->Info
.dwCursorPosition
.Y
: (Rows
- 1));
3515 FillConsoleOutputCharacter(g_hConOut
, ' ',
3516 cb
->Info
.dwSize
.X
, coord
, &dwDummy
);
3518 * The following is just for aesthetics. If we are exiting without
3519 * restoring the screen, then we want to have a prompt string
3520 * appear at the bottom line. However, the command interpreter
3521 * seems to always advance the cursor one line before displaying
3522 * the prompt string, which causes the screen to scroll. To
3523 * counter this, move the cursor up one line before exiting.
3525 if (exiting
&& !p_rs
)
3528 * Position the cursor at the leftmost column of the desired row.
3530 SetConsoleCursorPosition(g_hConOut
, coord
);
3533 g_fTermcapMode
= FALSE
;
3535 #endif /* FEAT_GUI_W32 */
3551 * clear `n' chars, starting from `coord'
3560 FillConsoleOutputCharacter(g_hConOut
, ' ', n
, coord
, &dwDummy
);
3561 FillConsoleOutputAttribute(g_hConOut
, g_attrCurrent
, n
, coord
, &dwDummy
);
3571 g_coord
.X
= g_coord
.Y
= 0;
3572 clear_chars(g_coord
, Rows
* Columns
);
3577 * Clear to end of display
3580 clear_to_end_of_display(void)
3582 clear_chars(g_coord
, (Rows
- g_coord
.Y
- 1)
3583 * Columns
+ (Columns
- g_coord
.X
));
3588 * Clear to end of line
3591 clear_to_end_of_line(void)
3593 clear_chars(g_coord
, Columns
- g_coord
.X
);
3598 * Scroll the scroll region up by `cLines' lines
3601 scroll(unsigned cLines
)
3603 COORD oldcoord
= g_coord
;
3605 gotoxy(g_srScrollRegion
.Left
+ 1, g_srScrollRegion
.Top
+ 1);
3606 delete_lines(cLines
);
3613 * Set the scroll region
3624 || right
> (unsigned) Columns
- 1
3625 || bottom
> (unsigned) Rows
- 1)
3628 g_srScrollRegion
.Left
= left
;
3629 g_srScrollRegion
.Top
= top
;
3630 g_srScrollRegion
.Right
= right
;
3631 g_srScrollRegion
.Bottom
= bottom
;
3636 * Insert `cLines' lines at the current cursor position
3639 insert_lines(unsigned cLines
)
3646 dest
.Y
= g_coord
.Y
+ cLines
;
3649 source
.Top
= g_coord
.Y
;
3650 source
.Right
= g_srScrollRegion
.Right
;
3651 source
.Bottom
= g_srScrollRegion
.Bottom
- cLines
;
3653 fill
.Char
.AsciiChar
= ' ';
3654 fill
.Attributes
= g_attrCurrent
;
3656 ScrollConsoleScreenBuffer(g_hConOut
, &source
, NULL
, dest
, &fill
);
3658 /* Here we have to deal with a win32 console flake: If the scroll
3659 * region looks like abc and we scroll c to a and fill with d we get
3660 * cbd... if we scroll block c one line at a time to a, we get cdd...
3661 * vim expects cdd consistently... So we have to deal with that
3662 * here... (this also occurs scrolling the same way in the other
3665 if (source
.Bottom
< dest
.Y
)
3670 coord
.Y
= source
.Bottom
;
3671 clear_chars(coord
, Columns
* (dest
.Y
- source
.Bottom
));
3677 * Delete `cLines' lines at the current cursor position
3680 delete_lines(unsigned cLines
)
3691 source
.Top
= g_coord
.Y
+ cLines
;
3692 source
.Right
= g_srScrollRegion
.Right
;
3693 source
.Bottom
= g_srScrollRegion
.Bottom
;
3695 fill
.Char
.AsciiChar
= ' ';
3696 fill
.Attributes
= g_attrCurrent
;
3698 ScrollConsoleScreenBuffer(g_hConOut
, &source
, NULL
, dest
, &fill
);
3700 /* Here we have to deal with a win32 console flake: If the scroll
3701 * region looks like abc and we scroll c to a and fill with d we get
3702 * cbd... if we scroll block c one line at a time to a, we get cdd...
3703 * vim expects cdd consistently... So we have to deal with that
3704 * here... (this also occurs scrolling the same way in the other
3707 nb
= dest
.Y
+ (source
.Bottom
- source
.Top
) + 1;
3709 if (nb
< source
.Top
)
3715 clear_chars(coord
, Columns
* (source
.Top
- nb
));
3721 * Set the cursor position
3728 if (x
< 1 || x
> (unsigned)Columns
|| y
< 1 || y
> (unsigned)Rows
)
3731 /* external cursor coords are 1-based; internal are 0-based */
3734 SetConsoleCursorPosition(g_hConOut
, g_coord
);
3739 * Set the current text attribute = (foreground | background)
3740 * See ../doc/os_win32.txt for the numbers.
3743 textattr(WORD wAttr
)
3745 g_attrCurrent
= wAttr
;
3747 SetConsoleTextAttribute(g_hConOut
, wAttr
);
3752 textcolor(WORD wAttr
)
3754 g_attrCurrent
= (g_attrCurrent
& 0xf0) + wAttr
;
3756 SetConsoleTextAttribute(g_hConOut
, g_attrCurrent
);
3761 textbackground(WORD wAttr
)
3763 g_attrCurrent
= (g_attrCurrent
& 0x0f) + (wAttr
<< 4);
3765 SetConsoleTextAttribute(g_hConOut
, g_attrCurrent
);
3770 * restore the default text attribute (whatever we started with)
3775 textattr(g_attrDefault
);
3779 static WORD g_attrPreStandout
= 0;
3782 * Make the text standout, by brightening it
3787 g_attrPreStandout
= g_attrCurrent
;
3788 textattr((WORD
) (g_attrCurrent
|FOREGROUND_INTENSITY
|BACKGROUND_INTENSITY
));
3793 * Turn off standout mode
3798 if (g_attrPreStandout
)
3800 textattr(g_attrPreStandout
);
3801 g_attrPreStandout
= 0;
3807 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
3810 mch_set_normal_colors(void)
3815 cterm_normal_fg_color
= (g_attrDefault
& 0xf) + 1;
3816 cterm_normal_bg_color
= ((g_attrDefault
>> 4) & 0xf) + 1;
3817 if (T_ME
[0] == ESC
&& T_ME
[1] == '|')
3821 if (*p
== 'm' && n
> 0)
3823 cterm_normal_fg_color
= (n
& 0xf) + 1;
3824 cterm_normal_bg_color
= ((n
>> 4) & 0xf) + 1;
3831 * visual bell: flash the screen
3836 COORD coordOrigin
= {0, 0};
3837 WORD attrFlash
= ~g_attrCurrent
& 0xff;
3840 LPWORD oldattrs
= (LPWORD
)alloc(Rows
* Columns
* sizeof(WORD
));
3842 if (oldattrs
== NULL
)
3844 ReadConsoleOutputAttribute(g_hConOut
, oldattrs
, Rows
* Columns
,
3845 coordOrigin
, &dwDummy
);
3846 FillConsoleOutputAttribute(g_hConOut
, attrFlash
, Rows
* Columns
,
3847 coordOrigin
, &dwDummy
);
3849 Sleep(15); /* wait for 15 msec */
3850 WriteConsoleOutputAttribute(g_hConOut
, oldattrs
, Rows
* Columns
,
3851 coordOrigin
, &dwDummy
);
3857 * Make the cursor visible or invisible
3860 cursor_visible(BOOL fVisible
)
3862 s_cursor_visible
= fVisible
;
3863 #ifdef MCH_CURSOR_SHAPE
3864 mch_update_cursor();
3870 * write `cchToWrite' characters in `pchBuf' to the screen
3871 * Returns the number of characters actually written (at least one).
3878 COORD coord
= g_coord
;
3881 FillConsoleOutputAttribute(g_hConOut
, g_attrCurrent
, cchToWrite
,
3883 /* When writing fails or didn't write a single character, pretend one
3884 * character was written, otherwise we get stuck. */
3885 if (WriteConsoleOutputCharacter(g_hConOut
, pchBuf
, cchToWrite
,
3886 coord
, &written
) == 0
3890 g_coord
.X
+= (SHORT
) written
;
3892 while (g_coord
.X
> g_srScrollRegion
.Right
)
3894 g_coord
.X
-= (SHORT
) Columns
;
3895 if (g_coord
.Y
< g_srScrollRegion
.Bottom
)
3899 gotoxy(g_coord
.X
+ 1, g_coord
.Y
+ 1);
3906 * mch_write(): write the output buffer to the screen, translating ESC
3907 * sequences into calls to console output routines.
3918 write(1, s
, (unsigned)len
);
3922 /* translate ESC | sequences into faked bios calls */
3925 /* optimization: use one single write_chars for runs of text,
3926 * rather than once per character It ain't curses, but it helps. */
3927 DWORD prefix
= (DWORD
)strcspn(s
, "\n\r\b\a\033");
3940 nWritten
= write_chars(s
, prefix
);
3941 #ifdef MCH_WRITE_DUMP
3945 fwrite(s
, sizeof(char_u
), nWritten
, fdDump
);
3946 fputs("<\n", fdDump
);
3949 len
-= (nWritten
- 1);
3952 else if (s
[0] == '\n')
3954 /* \n, newline: go to the beginning of the next line or scroll */
3955 if (g_coord
.Y
== g_srScrollRegion
.Bottom
)
3958 gotoxy(g_srScrollRegion
.Left
+ 1, g_srScrollRegion
.Bottom
+ 1);
3962 gotoxy(g_srScrollRegion
.Left
+ 1, g_coord
.Y
+ 2);
3964 #ifdef MCH_WRITE_DUMP
3966 fputs("\\n\n", fdDump
);
3970 else if (s
[0] == '\r')
3972 /* \r, carriage return: go to beginning of line */
3973 gotoxy(g_srScrollRegion
.Left
+1, g_coord
.Y
+ 1);
3974 #ifdef MCH_WRITE_DUMP
3976 fputs("\\r\n", fdDump
);
3980 else if (s
[0] == '\b')
3982 /* \b, backspace: move cursor one position left */
3983 if (g_coord
.X
> g_srScrollRegion
.Left
)
3985 else if (g_coord
.Y
> g_srScrollRegion
.Top
)
3987 g_coord
.X
= g_srScrollRegion
.Right
;
3990 gotoxy(g_coord
.X
+ 1, g_coord
.Y
+ 1);
3991 #ifdef MCH_WRITE_DUMP
3993 fputs("\\b\n", fdDump
);
3997 else if (s
[0] == '\a')
4000 MessageBeep(0xFFFFFFFF);
4001 #ifdef MCH_WRITE_DUMP
4003 fputs("\\a\n", fdDump
);
4007 else if (s
[0] == ESC
&& len
>= 3-1 && s
[1] == '|')
4009 #ifdef MCH_WRITE_DUMP
4013 int arg1
= 0, arg2
= 0;
4017 /* one or two numeric arguments, separated by ';' */
4019 case '0': case '1': case '2': case '3': case '4':
4020 case '5': case '6': case '7': case '8': case '9':
4022 arg1
= getdigits(&p
); /* no check for length! */
4029 arg2
= getdigits(&p
); /* no check for length! */
4036 set_scroll_region(0, arg1
- 1, Columns
- 1, arg2
- 1);
4040 /* move cursor up arg1 lines in same column */
4041 gotoxy(g_coord
.X
+ 1,
4042 max(g_srScrollRegion
.Top
, g_coord
.Y
- arg1
) + 1);
4046 /* move cursor right arg1 columns in same line */
4047 gotoxy(min(g_srScrollRegion
.Right
, g_coord
.X
+ arg1
) + 1,
4063 textattr((WORD
) arg1
);
4067 textcolor((WORD
) arg1
);
4071 textbackground((WORD
) arg1
);
4078 len
-= (int)(p
- s
);
4083 /* Three-character escape sequences */
4086 /* move cursor up one line in same column */
4087 gotoxy(g_coord
.X
+ 1,
4088 max(g_srScrollRegion
.Top
, g_coord
.Y
- 1) + 1);
4096 /* move cursor right one column in same line */
4097 gotoxy(min(g_srScrollRegion
.Right
, g_coord
.X
+ 1) + 1,
4118 clear_to_end_of_display();
4126 clear_to_end_of_line();
4138 termcap_mode_start();
4142 cursor_visible(TRUE
);
4146 cursor_visible(FALSE
);
4154 #ifdef MCH_WRITE_DUMP
4157 fputs("ESC | ", fdDump
);
4158 fwrite(old_s
+ 2, sizeof(char_u
), s
- old_s
- 2, fdDump
);
4159 fputc('\n', fdDump
);
4165 /* Write a single character */
4168 nWritten
= write_chars(s
, 1);
4169 #ifdef MCH_WRITE_DUMP
4173 fwrite(s
, sizeof(char_u
), nWritten
, fdDump
);
4174 fputs("<\n", fdDump
);
4178 len
-= (nWritten
- 1);
4183 #ifdef MCH_WRITE_DUMP
4189 #endif /* FEAT_GUI_W32 */
4193 * Delay for half a second.
4202 Sleep((int)msec
); /* never wait for input */
4205 # ifdef FEAT_MZSCHEME
4206 if (mzthreads_allowed() && p_mzq
> 0 && msec
> p_mzq
)
4210 /* if msec is large enough, wait by portions in p_mzq */
4213 mzvim_check_threads();
4230 * this version of remove is not scared by a readonly (backup) file
4231 * Return 0 for success, -1 for failure.
4234 mch_remove(char_u
*name
)
4240 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4242 wn
= enc_to_utf16(name
, NULL
);
4245 SetFileAttributesW(wn
, FILE_ATTRIBUTE_NORMAL
);
4246 n
= DeleteFileW(wn
) ? 0 : -1;
4248 if (n
== 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4250 /* Retry with non-wide function (for Windows 98). */
4254 SetFileAttributes(name
, FILE_ATTRIBUTE_NORMAL
);
4255 return DeleteFile(name
) ? 0 : -1;
4260 * check for an "interrupt signal": CTRL-break or CTRL-C
4263 mch_breakcheck(void)
4265 #ifndef FEAT_GUI_W32 /* never used */
4266 if (g_fCtrlCPressed
|| g_fCBrkPressed
)
4268 g_fCtrlCPressed
= g_fCBrkPressed
= FALSE
;
4276 * How much memory is available?
4277 * Return sum of available physical and page file memory.
4281 mch_avail_mem(int special
)
4285 ms
.dwLength
= sizeof(MEMORYSTATUS
);
4286 GlobalMemoryStatus(&ms
);
4287 return (long_u
) (ms
.dwAvailPhys
+ ms
.dwAvailPageFile
);
4292 * Same code as below, but with wide functions and no comments.
4293 * Return 0 for success, non-zero for failure.
4296 mch_wrename(WCHAR
*wold
, WCHAR
*wnew
)
4300 WCHAR szTempFile
[_MAX_PATH
+ 1];
4301 WCHAR szNewPath
[_MAX_PATH
+ 1];
4304 if (!mch_windows95())
4307 for (i
= 0; wold
[i
] != NUL
; ++i
)
4308 if ((wold
[i
] == '/' || wold
[i
] == '\\' || wold
[i
] == ':')
4309 && wold
[i
+ 1] != 0)
4311 if ((int)(wold
+ i
- p
) < 8 || p
[6] != '~')
4312 return (MoveFileW(wold
, wnew
) == 0);
4315 if (GetFullPathNameW(wnew
, _MAX_PATH
, szNewPath
, &p
) == 0 || p
== NULL
)
4319 if (GetTempFileNameW(szNewPath
, L
"VIM", 0, szTempFile
) == 0)
4322 if (!DeleteFileW(szTempFile
))
4325 if (!MoveFileW(wold
, szTempFile
))
4328 if ((hf
= CreateFileW(wold
, GENERIC_WRITE
, 0, NULL
, CREATE_NEW
,
4329 FILE_ATTRIBUTE_NORMAL
, NULL
)) == INVALID_HANDLE_VALUE
)
4331 if (!CloseHandle(hf
))
4334 if (!MoveFileW(szTempFile
, wnew
))
4336 (void)MoveFileW(szTempFile
, wold
);
4340 DeleteFileW(szTempFile
);
4342 if (!DeleteFileW(wold
))
4351 * mch_rename() works around a bug in rename (aka MoveFile) in
4352 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4353 * file whose short file name is "FOO.BAR" (its long file name will
4354 * be correct: "foo.bar~"). Because a file can be accessed by
4355 * either its SFN or its LFN, "foo.bar" has effectively been
4356 * renamed to "foo.bar", which is not at all what was wanted. This
4357 * seems to happen only when renaming files with three-character
4358 * extensions by appending a suffix that does not include ".".
4359 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4361 * There is another problem, which isn't really a bug but isn't right either:
4362 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
4363 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
4364 * service pack 6. Doesn't seem to happen on Windows 98.
4366 * Like rename(), returns 0 upon success, non-zero upon failure.
4367 * Should probably set errno appropriately when errors occur.
4371 const char *pszOldFile
,
4372 const char *pszNewFile
)
4374 char szTempFile
[_MAX_PATH
+1];
4375 char szNewPath
[_MAX_PATH
+1];
4383 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4385 wold
= enc_to_utf16((char_u
*)pszOldFile
, NULL
);
4386 wnew
= enc_to_utf16((char_u
*)pszNewFile
, NULL
);
4387 if (wold
!= NULL
&& wnew
!= NULL
)
4388 retval
= mch_wrename(wold
, wnew
);
4391 if (retval
== 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4393 /* Retry with non-wide function (for Windows 98). */
4398 * No need to play tricks if not running Windows 95, unless the file name
4399 * contains a "~" as the seventh character.
4401 if (!mch_windows95())
4403 pszFilePart
= (char *)gettail((char_u
*)pszOldFile
);
4404 if (STRLEN(pszFilePart
) < 8 || pszFilePart
[6] != '~')
4405 return rename(pszOldFile
, pszNewFile
);
4408 /* Get base path of new file name. Undocumented feature: If pszNewFile is
4409 * a directory, no error is returned and pszFilePart will be NULL. */
4410 if (GetFullPathName(pszNewFile
, _MAX_PATH
, szNewPath
, &pszFilePart
) == 0
4411 || pszFilePart
== NULL
)
4415 /* Get (and create) a unique temporary file name in directory of new file */
4416 if (GetTempFileName(szNewPath
, "VIM", 0, szTempFile
) == 0)
4419 /* blow the temp file away */
4420 if (!DeleteFile(szTempFile
))
4423 /* rename old file to the temp file */
4424 if (!MoveFile(pszOldFile
, szTempFile
))
4427 /* now create an empty file called pszOldFile; this prevents the operating
4428 * system using pszOldFile as an alias (SFN) if we're renaming within the
4429 * same directory. For example, we're editing a file called
4430 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
4431 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
4432 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
4433 * cause all sorts of problems later in buf_write(). So, we create an
4434 * empty file called filena~1.txt and the system will have to find some
4435 * other SFN for filena~1.txt~, such as filena~2.txt
4437 if ((hf
= CreateFile(pszOldFile
, GENERIC_WRITE
, 0, NULL
, CREATE_NEW
,
4438 FILE_ATTRIBUTE_NORMAL
, NULL
)) == INVALID_HANDLE_VALUE
)
4440 if (!CloseHandle(hf
))
4443 /* rename the temp file to the new file */
4444 if (!MoveFile(szTempFile
, pszNewFile
))
4446 /* Renaming failed. Rename the file back to its old name, so that it
4447 * looks like nothing happened. */
4448 (void)MoveFile(szTempFile
, pszOldFile
);
4453 /* Seems to be left around on Novell filesystems */
4454 DeleteFile(szTempFile
);
4456 /* finally, remove the empty old file */
4457 if (!DeleteFile(pszOldFile
))
4460 return 0; /* success */
4464 * Get the default shell for the current hardware platform
4473 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
) /* Windows NT */
4475 else if (g_PlatformId
== VER_PLATFORM_WIN32_WINDOWS
) /* Windows 95 */
4476 psz
= "command.com";
4482 * mch_access() extends access() to do more detailed check on network drives.
4483 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
4486 mch_access(char *n
, int p
)
4490 int retval
= -1; /* default: fail */
4494 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4495 wn
= enc_to_utf16(n
, NULL
);
4500 char TempName
[_MAX_PATH
+ 16] = "";
4502 WCHAR TempNameW
[_MAX_PATH
+ 16] = L
"";
4507 /* Read check is performed by seeing if we can do a find file on
4508 * the directory for any file. */
4515 for (i
= 0; i
< _MAX_PATH
&& wn
[i
] != 0; ++i
)
4516 TempNameW
[i
] = wn
[i
];
4517 if (TempNameW
[i
- 1] != '\\' && TempNameW
[i
- 1] != '/')
4518 TempNameW
[i
++] = '\\';
4519 TempNameW
[i
++] = '*';
4522 hFile
= FindFirstFileW(TempNameW
, &d
);
4523 if (hFile
== INVALID_HANDLE_VALUE
)
4525 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4528 /* Retry with non-wide function (for Windows 98). */
4533 (void)FindClose(hFile
);
4541 vim_strncpy(TempName
, n
, _MAX_PATH
);
4542 pch
= TempName
+ STRLEN(TempName
) - 1;
4543 if (*pch
!= '\\' && *pch
!= '/')
4548 hFile
= FindFirstFile(TempName
, &d
);
4549 if (hFile
== INVALID_HANDLE_VALUE
)
4551 (void)FindClose(hFile
);
4557 /* Trying to create a temporary file in the directory should catch
4558 * directories on read-only network shares. However, in
4559 * directories whose ACL allows writes but denies deletes will end
4560 * up keeping the temporary file :-(. */
4564 if (!GetTempFileNameW(wn
, L
"VIM", 0, TempNameW
))
4566 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4569 /* Retry with non-wide function (for Windows 98). */
4574 DeleteFileW(TempNameW
);
4579 if (!GetTempFileName(n
, "VIM", 0, TempName
))
4581 mch_remove((char_u
*)TempName
);
4587 /* Trying to open the file for the required access does ACL, read-only
4588 * network share, and file attribute checks. */
4589 am
= ((p
& W_OK
) ? GENERIC_WRITE
: 0)
4590 | ((p
& R_OK
) ? GENERIC_READ
: 0);
4594 hFile
= CreateFileW(wn
, am
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
4595 if (hFile
== INVALID_HANDLE_VALUE
4596 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
4598 /* Retry with non-wide function (for Windows 98). */
4605 hFile
= CreateFile(n
, am
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
4606 if (hFile
== INVALID_HANDLE_VALUE
)
4611 retval
= 0; /* success */
4619 #if defined(FEAT_MBYTE) || defined(PROTO)
4621 * Version of open() that may use UTF-16 file name.
4624 mch_open(char *name
, int flags
, int mode
)
4626 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
4627 # ifndef __BORLANDC__
4631 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4633 wn
= enc_to_utf16(name
, NULL
);
4636 f
= _wopen(wn
, flags
, mode
);
4640 /* Retry with non-wide function (for Windows 98). Can't use
4641 * GetLastError() here and it's unclear what errno gets set to if
4642 * the _wopen() fails for missing wide functions. */
4647 return open(name
, flags
, mode
);
4651 * Version of fopen() that may use UTF-16 file name.
4654 mch_fopen(char *name
, char *mode
)
4659 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
4660 # ifdef __BORLANDC__
4661 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4662 && g_PlatformId
== VER_PLATFORM_WIN32_NT
4666 # if defined(DEBUG) && _MSC_VER >= 1400
4667 /* Work around an annoying assertion in the Microsoft debug CRT
4668 * when mode's text/binary setting doesn't match _get_fmode(). */
4669 char newMode
= mode
[strlen(mode
) - 1];
4672 _get_fmode(&oldMode
);
4674 _set_fmode(_O_TEXT
);
4675 else if (newMode
== 'b')
4676 _set_fmode(_O_BINARY
);
4678 wn
= enc_to_utf16(name
, NULL
);
4679 wm
= enc_to_utf16(mode
, NULL
);
4680 if (wn
!= NULL
&& wm
!= NULL
)
4681 f
= _wfopen(wn
, wm
);
4685 # if defined(DEBUG) && _MSC_VER >= 1400
4686 _set_fmode(oldMode
);
4691 /* Retry with non-wide function (for Windows 98). Can't use
4692 * GetLastError() here and it's unclear what errno gets set to if
4693 * the _wfopen() fails for missing wide functions. */
4696 return fopen(name
, mode
);
4702 * SUB STREAM (aka info stream) handling:
4704 * NTFS can have sub streams for each file. Normal contents of file is
4705 * stored in the main stream, and extra contents (author information and
4706 * title and so on) can be stored in sub stream. After Windows 2000, user
4707 * can access and store those informations in sub streams via explorer's
4708 * property menuitem in right click menu. Those informations in sub streams
4709 * were lost when copying only the main stream. So we have to copy sub
4712 * Incomplete explanation:
4713 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
4714 * More useful info and an example:
4715 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
4719 * Copy info stream data "substream". Read from the file with BackupRead(sh)
4720 * and write to stream "substream" of file "to".
4721 * Errors are ignored.
4724 copy_substream(HANDLE sh
, void *context
, WCHAR
*to
, WCHAR
*substream
, long len
)
4729 to_name
= malloc((wcslen(to
) + wcslen(substream
) + 1) * sizeof(WCHAR
));
4730 wcscpy(to_name
, to
);
4731 wcscat(to_name
, substream
);
4733 hTo
= CreateFileW(to_name
, GENERIC_WRITE
, 0, NULL
, OPEN_ALWAYS
,
4734 FILE_ATTRIBUTE_NORMAL
, NULL
);
4735 if (hTo
!= INVALID_HANDLE_VALUE
)
4739 DWORD readcnt
, written
;
4742 /* Copy block of bytes at a time. Abort when something goes wrong. */
4743 for (done
= 0; done
< len
; done
+= written
)
4745 /* (size_t) cast for Borland C 5.5 */
4746 todo
= (DWORD
)((size_t)(len
- done
) > sizeof(buf
) ? sizeof(buf
)
4747 : (size_t)(len
- done
));
4748 if (!BackupRead(sh
, (LPBYTE
)buf
, todo
, &readcnt
,
4749 FALSE
, FALSE
, context
)
4751 || !WriteFile(hTo
, buf
, todo
, &written
, NULL
)
4762 * Copy info streams from file "from" to file "to".
4765 copy_infostreams(char_u
*from
, char_u
*to
)
4770 WIN32_STREAM_ID sid
;
4772 WCHAR streamname
[_MAX_PATH
];
4774 void *context
= NULL
;
4778 /* Convert the file names to wide characters. */
4779 fromw
= enc_to_utf16(from
, NULL
);
4780 tow
= enc_to_utf16(to
, NULL
);
4781 if (fromw
!= NULL
&& tow
!= NULL
)
4783 /* Open the file for reading. */
4784 sh
= CreateFileW(fromw
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
4785 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4786 if (sh
!= INVALID_HANDLE_VALUE
)
4788 /* Use BackupRead() to find the info streams. Repeat until we
4789 * have done them all.*/
4792 /* Get the header to find the length of the stream name. If
4793 * the "readcount" is zero we have done all info streams. */
4794 ZeroMemory(&sid
, sizeof(WIN32_STREAM_ID
));
4795 headersize
= (int)((char *)&sid
.cStreamName
- (char *)&sid
.dwStreamId
);
4796 if (!BackupRead(sh
, (LPBYTE
)&sid
, headersize
,
4797 &readcount
, FALSE
, FALSE
, &context
)
4801 /* We only deal with streams that have a name. The normal
4802 * file data appears to be without a name, even though docs
4803 * suggest it is called "::$DATA". */
4804 if (sid
.dwStreamNameSize
> 0)
4806 /* Read the stream name. */
4807 if (!BackupRead(sh
, (LPBYTE
)streamname
,
4808 sid
.dwStreamNameSize
,
4809 &readcount
, FALSE
, FALSE
, &context
))
4812 /* Copy an info stream with a name ":anything:$DATA".
4813 * Skip "::$DATA", it has no stream name (examples suggest
4814 * it might be used for the normal file contents).
4815 * Note that BackupRead() counts bytes, but the name is in
4816 * wide characters. */
4817 len
= readcount
/ sizeof(WCHAR
);
4818 streamname
[len
] = 0;
4819 if (len
> 7 && wcsicmp(streamname
+ len
- 6,
4822 streamname
[len
- 6] = 0;
4823 copy_substream(sh
, &context
, tow
, streamname
,
4824 (long)sid
.Size
.u
.LowPart
);
4828 /* Advance to the next stream. We might try seeking too far,
4829 * but BackupSeek() doesn't skip over stream borders, thus
4831 (void)BackupSeek(sh
, sid
.Size
.u
.LowPart
, sid
.Size
.u
.HighPart
,
4832 &lo
, &hi
, &context
);
4835 /* Clear the context. */
4836 (void)BackupRead(sh
, NULL
, 0, &readcount
, TRUE
, FALSE
, &context
);
4847 * Copy file attributes from file "from" to file "to".
4848 * For Windows NT and later we copy info streams.
4849 * Always returns zero, errors are ignored.
4852 mch_copy_file_attribute(char_u
*from
, char_u
*to
)
4855 /* File streams only work on Windows NT and later. */
4857 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
)
4858 copy_infostreams(from
, to
);
4863 #if defined(MYRESETSTKOFLW) || defined(PROTO)
4865 * Recreate a destroyed stack guard page in win32.
4866 * Written by Benjamin Peterson.
4869 /* These magic numbers are from the MS header files */
4870 #define MIN_STACK_WIN9X 17
4871 #define MIN_STACK_WINNT 2
4874 * This function does the same thing as _resetstkoflw(), which is only
4875 * available in DevStudio .net and later.
4876 * Returns 0 for failure, 1 for success.
4879 myresetstkoflw(void)
4884 BYTE
*pLowestPossiblePage
;
4885 MEMORY_BASIC_INFORMATION mbi
;
4890 /* This code will not work on win32s. */
4892 if (g_PlatformId
== VER_PLATFORM_WIN32s
)
4895 /* We need to know the system page size. */
4897 nPageSize
= si
.dwPageSize
;
4899 /* ...and the current stack pointer */
4900 pStackPtr
= (BYTE
*)_alloca(1);
4902 /* ...and the base of the stack. */
4903 if (VirtualQuery(pStackPtr
, &mbi
, sizeof mbi
) == 0)
4905 pStackBase
= (BYTE
*)mbi
.AllocationBase
;
4907 /* ...and the page thats min_stack_req pages away from stack base; this is
4908 * the lowest page we could use. */
4909 pLowestPossiblePage
= pStackBase
+ ((g_PlatformId
== VER_PLATFORM_WIN32_NT
)
4910 ? MIN_STACK_WINNT
: MIN_STACK_WIN9X
) * nPageSize
;
4912 /* On Win95, we want the next page down from the end of the stack. */
4913 if (g_PlatformId
== VER_PLATFORM_WIN32_WINDOWS
)
4915 /* Find the page that's only 1 page down from the page that the stack
4917 pGuardPage
= (BYTE
*)((DWORD
)nPageSize
* (((DWORD
)pStackPtr
4918 / (DWORD
)nPageSize
) - 1));
4919 if (pGuardPage
< pLowestPossiblePage
)
4922 /* Apply the noaccess attribute to the page -- there's no guard
4923 * attribute in win95-type OSes. */
4924 if (!VirtualProtect(pGuardPage
, nPageSize
, PAGE_NOACCESS
, &dummy
))
4929 /* On NT, however, we want the first committed page in the stack Start
4930 * at the stack base and move forward through memory until we find a
4931 * committed block. */
4932 BYTE
*pBlock
= pStackBase
;
4936 if (VirtualQuery(pBlock
, &mbi
, sizeof mbi
) == 0)
4939 pBlock
+= mbi
.RegionSize
;
4941 if (mbi
.State
& MEM_COMMIT
)
4945 /* mbi now describes the first committed block in the stack. */
4946 if (mbi
.Protect
& PAGE_GUARD
)
4949 /* decide where the guard page should start */
4950 if ((long_u
)(mbi
.BaseAddress
) < (long_u
)pLowestPossiblePage
)
4951 pGuardPage
= pLowestPossiblePage
;
4953 pGuardPage
= (BYTE
*)mbi
.BaseAddress
;
4955 /* allocate the guard page */
4956 if (!VirtualAlloc(pGuardPage
, nPageSize
, MEM_COMMIT
, PAGE_READWRITE
))
4959 /* apply the guard attribute to the page */
4960 if (!VirtualProtect(pGuardPage
, nPageSize
, PAGE_READWRITE
| PAGE_GUARD
,
4970 #if defined(FEAT_MBYTE) || defined(PROTO)
4972 * The command line arguments in UCS2
4974 static int nArgsW
= 0;
4975 static LPWSTR
*ArglistW
= NULL
;
4976 static int global_argc
= 0;
4977 static char **global_argv
;
4979 static int used_file_argc
= 0; /* last argument in global_argv[] used
4980 for the argument list. */
4981 static int *used_file_indexes
= NULL
; /* indexes in global_argv[] for
4982 command line arguments added to
4983 the argument list */
4984 static int used_file_count
= 0; /* nr of entries in used_file_indexes */
4985 static int used_file_literal
= FALSE
; /* take file names literally */
4986 static int used_file_full_path
= FALSE
; /* file name was full path */
4987 static int used_file_diff_mode
= FALSE
; /* file name was with diff mode */
4988 static int used_alist_count
= 0;
4992 * Get the command line arguments. Unicode version.
4993 * Returns argc. Zero when something fails.
4996 get_cmd_argsW(char ***argvp
)
5002 ArglistW
= CommandLineToArgvW(GetCommandLineW(), &nArgsW
);
5003 if (ArglistW
!= NULL
)
5005 argv
= malloc((nArgsW
+ 1) * sizeof(char *));
5010 for (i
= 0; i
< argc
; ++i
)
5014 /* Convert each Unicode argument to the current codepage. */
5015 WideCharToMultiByte_alloc(GetACP(), 0,
5016 ArglistW
[i
], (int)wcslen(ArglistW
[i
]) + 1,
5017 (LPSTR
*)&argv
[i
], &len
, 0, 0);
5018 if (argv
[i
] == NULL
)
5020 /* Out of memory, clear everything. */
5033 used_file_indexes
= malloc(argc
* sizeof(int));
5041 free_cmd_argsW(void)
5043 if (ArglistW
!= NULL
)
5045 GlobalFree(ArglistW
);
5051 * Remember "name" is an argument that was added to the argument list.
5052 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5056 used_file_arg(char *name
, int literal
, int full_path
, int diff_mode
)
5060 if (used_file_indexes
== NULL
)
5062 for (i
= used_file_argc
+ 1; i
< global_argc
; ++i
)
5063 if (STRCMP(global_argv
[i
], name
) == 0)
5066 used_file_indexes
[used_file_count
++] = i
;
5069 used_file_literal
= literal
;
5070 used_file_full_path
= full_path
;
5071 used_file_diff_mode
= diff_mode
;
5075 * Remember the length of the argument list as it was. If it changes then we
5076 * leave it alone when 'encoding' is set.
5079 set_alist_count(void)
5081 used_alist_count
= GARGCOUNT
;
5085 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5086 * has been changed while starting up. Use the UCS-2 command line arguments
5087 * and convert them to 'encoding'.
5098 * - if argument count differs between the wide and non-wide argument
5099 * list, something must be wrong.
5100 * - the file name arguments must have been located.
5101 * - the length of the argument list wasn't changed by the user.
5103 if (global_argc
!= nArgsW
5105 || used_file_indexes
== NULL
5106 || used_file_count
== 0
5107 || used_alist_count
!= GARGCOUNT
)
5110 /* Remember the buffer numbers for the arguments. */
5111 fnum_list
= (int *)alloc((int)sizeof(int) * GARGCOUNT
);
5112 if (fnum_list
== NULL
)
5113 return; /* out of memory */
5114 for (i
= 0; i
< GARGCOUNT
; ++i
)
5115 fnum_list
[i
] = GARGLIST
[i
].ae_fnum
;
5117 /* Clear the argument list. Make room for the new arguments. */
5118 alist_clear(&global_alist
);
5119 if (ga_grow(&global_alist
.al_ga
, used_file_count
) == FAIL
)
5120 return; /* out of memory */
5122 for (i
= 0; i
< used_file_count
; ++i
)
5124 idx
= used_file_indexes
[i
];
5125 str
= utf16_to_enc(ArglistW
[idx
], NULL
);
5129 /* When using diff mode may need to concatenate file name to
5130 * directory name. Just like it's done in main(). */
5131 if (used_file_diff_mode
&& mch_isdir(str
) && GARGCOUNT
> 0
5132 && !mch_isdir(alist_name(&GARGLIST
[0])))
5136 r
= concat_fnames(str
, gettail(alist_name(&GARGLIST
[0])), TRUE
);
5144 /* Re-use the old buffer by renaming it. When not using literal
5145 * names it's done by alist_expand() below. */
5146 if (used_file_literal
)
5147 buf_set_name(fnum_list
[i
], str
);
5149 alist_add(&global_alist
, str
, used_file_literal
? 2 : 0);
5153 if (!used_file_literal
)
5155 /* Now expand wildcards in the arguments. */
5156 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5157 * filename characters but are excluded from 'isfname' to make
5158 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5159 do_cmdline_cmd((char_u
*)":let SaVe_ISF = &isf|set isf+=(,)");
5160 alist_expand(fnum_list
, used_alist_count
);
5161 do_cmdline_cmd((char_u
*)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5164 /* If wildcard expansion failed, we are editing the first file of the
5165 * arglist and there is no file name: Edit the first argument now. */
5166 if (curwin
->w_arg_idx
== 0 && curbuf
->b_fname
== NULL
)
5168 do_cmdline_cmd((char_u
*)":rewind");
5169 if (GARGCOUNT
== 1 && used_file_full_path
)
5170 (void)vim_chdirfile(alist_name(&GARGLIST
[0]));