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"
33 #include <sys/types.h>
48 #if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49 # include <shellapi.h>
53 # ifndef FROM_LEFT_1ST_BUTTON_PRESSED
54 # define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
56 # ifndef RIGHTMOST_BUTTON_PRESSED
57 # define RIGHTMOST_BUTTON_PRESSED 0x0002
59 # ifndef FROM_LEFT_2ND_BUTTON_PRESSED
60 # define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
62 # ifndef FROM_LEFT_3RD_BUTTON_PRESSED
63 # define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
65 # ifndef FROM_LEFT_4TH_BUTTON_PRESSED
66 # define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73 # define MOUSE_MOVED 0x0001
76 # define DOUBLE_CLICK 0x0002
80 /* Record all output and all keyboard & mouse input */
81 /* #define MCH_WRITE_DUMP */
88 * When generating prototypes for Win32 on Unix, these lines make the syntax
89 * errors disappear. They do not need to be correct.
94 typedef char * LPCSTR
;
95 typedef char * LPWSTR
;
96 typedef int ACCESS_MASK
;
99 typedef int CONSOLE_CURSOR_INFO
;
106 typedef int HINSTANCE
;
108 typedef int INPUT_RECORD
;
109 typedef int KEY_EVENT_RECORD
;
117 typedef int MOUSE_EVENT_RECORD
;
121 typedef int PRINTDLG
;
122 typedef int PSECURITY_DESCRIPTOR
;
124 typedef int SECURITY_INFORMATION
;
126 typedef int SMALL_RECT
;
127 typedef int TEXTMETRIC
;
128 typedef int TOKEN_INFORMATION_CLASS
;
136 /* Undocumented API in kernel32.dll needed to work around dead key bug in
137 * console-mode applications in NT 4.0. If you switch keyboard layouts
138 * in a console app to a layout that includes dead keys and then hit a
139 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
140 * and Michael Dietrich for helping me figure out this workaround.
143 /* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
145 # define WINBASEAPI __stdcall
147 #if defined(__BORLANDC__)
148 typedef BOOL (__stdcall
*PFNGCKLN
)(LPSTR
);
150 typedef WINBASEAPI
BOOL (WINAPI
*PFNGCKLN
)(LPSTR
);
152 static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName
= NULL
;
155 #if defined(__BORLANDC__)
156 /* Strangely Borland uses a non-standard name. */
157 # define wcsicmp(a, b) wcscmpi((a), (b))
161 /* Win32 Console handles for input and output */
162 static HANDLE g_hConIn
= INVALID_HANDLE_VALUE
;
163 static HANDLE g_hConOut
= INVALID_HANDLE_VALUE
;
165 /* Win32 Screen buffer,coordinate,console I/O information */
166 static SMALL_RECT g_srScrollRegion
;
167 static COORD g_coord
; /* 0-based, but external coords are 1-based */
169 /* The attribute of the screen when the editor was started */
170 static WORD g_attrDefault
= 7; /* lightgray text on black background */
171 static WORD g_attrCurrent
;
173 static int g_fCBrkPressed
= FALSE
; /* set by ctrl-break interrupt */
174 static int g_fCtrlCPressed
= FALSE
; /* set when ctrl-C or ctrl-break detected */
175 static int g_fForceExit
= FALSE
; /* set when forcefully exiting */
177 static void termcap_mode_start(void);
178 static void termcap_mode_end(void);
179 static void clear_chars(COORD coord
, DWORD n
);
180 static void clear_screen(void);
181 static void clear_to_end_of_display(void);
182 static void clear_to_end_of_line(void);
183 static void scroll(unsigned cLines
);
184 static void set_scroll_region(unsigned left
, unsigned top
,
185 unsigned right
, unsigned bottom
);
186 static void insert_lines(unsigned cLines
);
187 static void delete_lines(unsigned cLines
);
188 static void gotoxy(unsigned x
, unsigned y
);
189 static void normvideo(void);
190 static void textattr(WORD wAttr
);
191 static void textcolor(WORD wAttr
);
192 static void textbackground(WORD wAttr
);
193 static void standout(void);
194 static void standend(void);
195 static void visual_bell(void);
196 static void cursor_visible(BOOL fVisible
);
197 static BOOL
write_chars(LPCSTR pchBuf
, DWORD cchToWrite
);
198 static char_u
tgetch(int *pmodifiers
, char_u
*pch2
);
199 static void create_conin(void);
200 static int s_cursor_visible
= TRUE
;
201 static int did_create_conin
= FALSE
;
203 static int s_dont_use_vimrun
= TRUE
;
204 static int need_vimrun_warning
= FALSE
;
205 static char *vimrun_path
= "vimrun ";
209 static int suppress_winsize
= 1; /* don't fiddle with console */
216 static int did_set_PATH
= FALSE
;
218 if (exe_name
== NULL
)
220 /* store the name of the executable, may be used for $VIM */
221 GetModuleFileName(NULL
, temp
, 255);
223 exe_name
= FullName_save((char_u
*)temp
, FALSE
);
226 if (!did_set_PATH
&& exe_name
!= NULL
)
231 /* Append our starting directory to $PATH, so that when doing "!xxd"
232 * it's found in our starting directory. Needed because SearchPath()
233 * also looks there. */
234 p
= mch_getenv("PATH");
235 newpath
= alloc((unsigned)(STRLEN(p
) + STRLEN(exe_name
) + 2));
239 STRCAT(newpath
, ";");
240 vim_strncpy(newpath
+ STRLEN(newpath
), exe_name
,
241 gettail_sep(exe_name
) - exe_name
);
242 vim_setenv((char_u
*)"PATH", newpath
);
250 #if defined(DYNAMIC_GETTEXT) || defined(PROTO)
252 # define GETTEXT_DLL "libintl.dll"
254 /* Dummy funcitons */
255 static char *null_libintl_gettext(const char *);
256 static char *null_libintl_textdomain(const char *);
257 static char *null_libintl_bindtextdomain(const char *, const char *);
258 static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
260 static HINSTANCE hLibintlDLL
= 0;
261 char *(*dyn_libintl_gettext
)(const char *) = null_libintl_gettext
;
262 char *(*dyn_libintl_textdomain
)(const char *) = null_libintl_textdomain
;
263 char *(*dyn_libintl_bindtextdomain
)(const char *, const char *)
264 = null_libintl_bindtextdomain
;
265 char *(*dyn_libintl_bind_textdomain_codeset
)(const char *, const char *)
266 = null_libintl_bind_textdomain_codeset
;
269 dyn_libintl_init(char *libname
)
278 {"gettext", (FARPROC
*)&dyn_libintl_gettext
},
279 {"textdomain", (FARPROC
*)&dyn_libintl_textdomain
},
280 {"bindtextdomain", (FARPROC
*)&dyn_libintl_bindtextdomain
},
284 /* No need to initialize twice. */
287 /* Load gettext library (libintl.dll) */
288 hLibintlDLL
= LoadLibrary(libname
!= NULL
? libname
: GETTEXT_DLL
);
291 char_u dirname
[_MAX_PATH
];
293 /* Try using the path from gvim.exe to find the .dll there. */
295 STRCPY(dirname
, exe_name
);
296 STRCPY(gettail(dirname
), GETTEXT_DLL
);
297 hLibintlDLL
= LoadLibrary((char *)dirname
);
303 EMSG2(_(e_loadlib
), GETTEXT_DLL
);
309 for (i
= 0; libintl_entry
[i
].name
!= NULL
310 && libintl_entry
[i
].ptr
!= NULL
; ++i
)
312 if ((*libintl_entry
[i
].ptr
= (FARPROC
)GetProcAddress(hLibintlDLL
,
313 libintl_entry
[i
].name
)) == NULL
)
319 EMSG2(_(e_loadfunc
), libintl_entry
[i
].name
);
326 /* The bind_textdomain_codeset() function is optional. */
327 dyn_libintl_bind_textdomain_codeset
= (void *)GetProcAddress(hLibintlDLL
,
328 "bind_textdomain_codeset");
329 if (dyn_libintl_bind_textdomain_codeset
== NULL
)
330 dyn_libintl_bind_textdomain_codeset
=
331 null_libintl_bind_textdomain_codeset
;
340 FreeLibrary(hLibintlDLL
);
342 dyn_libintl_gettext
= null_libintl_gettext
;
343 dyn_libintl_textdomain
= null_libintl_textdomain
;
344 dyn_libintl_bindtextdomain
= null_libintl_bindtextdomain
;
345 dyn_libintl_bind_textdomain_codeset
= null_libintl_bind_textdomain_codeset
;
350 null_libintl_gettext(const char *msgid
)
357 null_libintl_bindtextdomain(const char *domainname
, const char *dirname
)
364 null_libintl_bind_textdomain_codeset(const char *domainname
,
372 null_libintl_textdomain(const char *domainname
)
377 #endif /* DYNAMIC_GETTEXT */
379 /* This symbol is not defined in older versions of the SDK or Visual C++ */
381 #ifndef VER_PLATFORM_WIN32_WINDOWS
382 # define VER_PLATFORM_WIN32_WINDOWS 1
390 * These are needed to dynamically load the ADVAPI DLL, which is not
391 * implemented under Windows 95 (and causes VIM to crash)
393 typedef DWORD (WINAPI
*PSNSECINFO
) (LPTSTR
, enum SE_OBJECT_TYPE
,
394 SECURITY_INFORMATION
, PSID
, PSID
, PACL
, PACL
);
395 typedef DWORD (WINAPI
*PGNSECINFO
) (LPSTR
, enum SE_OBJECT_TYPE
,
396 SECURITY_INFORMATION
, PSID
*, PSID
*, PACL
*, PACL
*,
397 PSECURITY_DESCRIPTOR
*);
399 static HANDLE advapi_lib
= NULL
; /* Handle for ADVAPI library */
400 static PSNSECINFO pSetNamedSecurityInfo
;
401 static PGNSECINFO pGetNamedSecurityInfo
;
405 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
406 * VER_PLATFORM_WIN32_WINDOWS (Win95).
411 static int done
= FALSE
;
417 ovi
.dwOSVersionInfoSize
= sizeof(ovi
);
420 g_PlatformId
= ovi
.dwPlatformId
;
424 * Load the ADVAPI runtime if we are on anything
425 * other than Windows 95
427 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
)
430 * do this load. Problems: Doesn't unload at end of run (this is
431 * theoretically okay, since Windows should unload it when VIM
432 * terminates). Should we be using the 'mch_libcall' routines?
433 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
434 * time we verify security...
436 advapi_lib
= LoadLibrary("ADVAPI32.DLL");
437 if (advapi_lib
!= NULL
)
439 pSetNamedSecurityInfo
= (PSNSECINFO
)GetProcAddress(advapi_lib
,
440 "SetNamedSecurityInfoA");
441 pGetNamedSecurityInfo
= (PGNSECINFO
)GetProcAddress(advapi_lib
,
442 "GetNamedSecurityInfoA");
443 if (pSetNamedSecurityInfo
== NULL
444 || pGetNamedSecurityInfo
== NULL
)
446 /* If we can't get the function addresses, set advapi_lib
447 * to NULL so that we don't use them. */
448 FreeLibrary(advapi_lib
);
459 * Return TRUE when running on Windows 95 (or 98 or ME).
460 * Only to be used after mch_init().
465 return g_PlatformId
== VER_PLATFORM_WIN32_WINDOWS
;
470 * Used to work around the "can't do synchronous spawn"
471 * problem on Win32s, without resorting to Universal Thunk.
473 static int old_num_windows
;
474 static int num_windows
;
478 win32ssynch_cb(HWND hwnd
, LPARAM lparam
)
487 #define SHIFT (SHIFT_PRESSED)
488 #define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
489 #define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
490 #define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
493 /* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
494 * We map function keys to their ANSI terminal equivalents, as produced
495 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
496 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
497 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
498 * combinations of function/arrow/etc keys.
512 /* Key ANSI alone shift ctrl alt */
513 { VK_ESCAPE
,FALSE
, ESC
, ESC
, ESC
, ESC
, },
515 { VK_F1
, TRUE
, ';', 'T', '^', 'h', },
516 { VK_F2
, TRUE
, '<', 'U', '_', 'i', },
517 { VK_F3
, TRUE
, '=', 'V', '`', 'j', },
518 { VK_F4
, TRUE
, '>', 'W', 'a', 'k', },
519 { VK_F5
, TRUE
, '?', 'X', 'b', 'l', },
520 { VK_F6
, TRUE
, '@', 'Y', 'c', 'm', },
521 { VK_F7
, TRUE
, 'A', 'Z', 'd', 'n', },
522 { VK_F8
, TRUE
, 'B', '[', 'e', 'o', },
523 { VK_F9
, TRUE
, 'C', '\\', 'f', 'p', },
524 { VK_F10
, TRUE
, 'D', ']', 'g', 'q', },
525 { VK_F11
, TRUE
, '\205', '\207', '\211', '\213', },
526 { VK_F12
, TRUE
, '\206', '\210', '\212', '\214', },
528 { VK_HOME
, TRUE
, 'G', '\302', 'w', '\303', },
529 { VK_UP
, TRUE
, 'H', '\304', '\305', '\306', },
530 { VK_PRIOR
, TRUE
, 'I', '\307', '\204', '\310', }, /*PgUp*/
531 { VK_LEFT
, TRUE
, 'K', '\311', 's', '\312', },
532 { VK_RIGHT
, TRUE
, 'M', '\313', 't', '\314', },
533 { VK_END
, TRUE
, 'O', '\315', 'u', '\316', },
534 { VK_DOWN
, TRUE
, 'P', '\317', '\320', '\321', },
535 { VK_NEXT
, TRUE
, 'Q', '\322', 'v', '\323', }, /*PgDn*/
536 { VK_INSERT
,TRUE
, 'R', '\324', '\325', '\326', },
537 { VK_DELETE
,TRUE
, 'S', '\327', '\330', '\331', },
539 { VK_SNAPSHOT
,TRUE
, 0, 0, 0, 'r', }, /*PrtScrn*/
542 /* Most people don't have F13-F20, but what the hell... */
543 { VK_F13
, TRUE
, '\332', '\333', '\334', '\335', },
544 { VK_F14
, TRUE
, '\336', '\337', '\340', '\341', },
545 { VK_F15
, TRUE
, '\342', '\343', '\344', '\345', },
546 { VK_F16
, TRUE
, '\346', '\347', '\350', '\351', },
547 { VK_F17
, TRUE
, '\352', '\353', '\354', '\355', },
548 { VK_F18
, TRUE
, '\356', '\357', '\360', '\361', },
549 { VK_F19
, TRUE
, '\362', '\363', '\364', '\365', },
550 { VK_F20
, TRUE
, '\366', '\367', '\370', '\371', },
552 { VK_ADD
, TRUE
, 'N', 'N', 'N', 'N', }, /* keyp '+' */
553 { VK_SUBTRACT
, TRUE
,'J', 'J', 'J', 'J', }, /* keyp '-' */
554 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
555 { VK_MULTIPLY
, TRUE
,'7', '7', '7', '7', }, /* keyp '*' */
557 { VK_NUMPAD0
,TRUE
, '\332', '\333', '\334', '\335', },
558 { VK_NUMPAD1
,TRUE
, '\336', '\337', '\340', '\341', },
559 { VK_NUMPAD2
,TRUE
, '\342', '\343', '\344', '\345', },
560 { VK_NUMPAD3
,TRUE
, '\346', '\347', '\350', '\351', },
561 { VK_NUMPAD4
,TRUE
, '\352', '\353', '\354', '\355', },
562 { VK_NUMPAD5
,TRUE
, '\356', '\357', '\360', '\361', },
563 { VK_NUMPAD6
,TRUE
, '\362', '\363', '\364', '\365', },
564 { VK_NUMPAD7
,TRUE
, '\366', '\367', '\370', '\371', },
565 { VK_NUMPAD8
,TRUE
, '\372', '\373', '\374', '\375', },
566 /* Sorry, out of number space! <negri>*/
567 { VK_NUMPAD9
,TRUE
, '\376', '\377', '\377', '\367', },
573 // The ToAscii bug destroys several registers. Need to turn off optimization
574 // or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
575 # pragma warning(push)
576 # pragma warning(disable: 4748)
577 # pragma optimize("", off)
580 #if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
581 # define AChar AsciiChar
583 # define AChar uChar.AsciiChar
586 /* The return code indicates key code size. */
592 KEY_EVENT_RECORD
*pker
)
594 UINT uMods
= pker
->dwControlKeyState
;
595 static int s_iIsDead
= 0;
596 static WORD awAnsiCode
[2];
597 static BYTE abKeystate
[256];
602 pker
->AChar
= (CHAR
) awAnsiCode
[1];
607 if (pker
->AChar
!= 0)
610 memset(abKeystate
, 0, sizeof (abKeystate
));
612 // Should only be non-NULL on NT 4.0
613 if (s_pfnGetConsoleKeyboardLayoutName
!= NULL
)
615 CHAR szKLID
[KL_NAMELENGTH
];
617 if ((*s_pfnGetConsoleKeyboardLayoutName
)(szKLID
))
618 (void)LoadKeyboardLayout(szKLID
, KLF_ACTIVATE
);
621 /* Clear any pending dead keys */
622 ToAscii(VK_SPACE
, MapVirtualKey(VK_SPACE
, 0), abKeystate
, awAnsiCode
, 0);
624 if (uMods
& SHIFT_PRESSED
)
625 abKeystate
[VK_SHIFT
] = 0x80;
626 if (uMods
& CAPSLOCK_ON
)
627 abKeystate
[VK_CAPITAL
] = 1;
629 if ((uMods
& ALT_GR
) == ALT_GR
)
631 abKeystate
[VK_CONTROL
] = abKeystate
[VK_LCONTROL
] =
632 abKeystate
[VK_MENU
] = abKeystate
[VK_RMENU
] = 0x80;
635 s_iIsDead
= ToAscii(pker
->wVirtualKeyCode
, pker
->wVirtualScanCode
,
636 abKeystate
, awAnsiCode
, 0);
639 pker
->AChar
= (CHAR
) awAnsiCode
[0];
645 /* MUST switch optimization on again here, otherwise a call to
646 * decode_key_event() may crash (e.g. when hitting caps-lock) */
647 # pragma optimize("", on)
648 # pragma warning(pop)
650 # if (_MSC_VER < 1100)
651 /* MUST turn off global optimisation for this next function, or
652 * pressing ctrl-minus in insert mode crashes Vim when built with
653 * VC4.1. -- negri. */
654 # pragma optimize("g", off)
658 static BOOL g_fJustGotFocus
= FALSE
;
661 * Decode a KEY_EVENT into one or two keystrokes
665 KEY_EVENT_RECORD
*pker
,
672 const int nModifs
= pker
->dwControlKeyState
& (SHIFT
| ALT
| CTRL
);
675 g_fJustGotFocus
= FALSE
;
677 /* ignore key up events */
681 /* ignore some keystrokes */
682 switch (pker
->wVirtualKeyCode
)
687 case VK_MENU
: /* Alt key */
695 if ((nModifs
& CTRL
) != 0 && (nModifs
& ~CTRL
) == 0 && pker
->AChar
== NUL
)
697 /* Ctrl-6 is Ctrl-^ */
698 if (pker
->wVirtualKeyCode
== '6')
703 /* Ctrl-2 is Ctrl-@ */
704 else if (pker
->wVirtualKeyCode
== '2')
709 /* Ctrl-- is Ctrl-_ */
710 else if (pker
->wVirtualKeyCode
== 0xBD)
718 if (pker
->wVirtualKeyCode
== VK_TAB
&& (nModifs
& SHIFT_PRESSED
))
725 for (i
= sizeof(VirtKeyMap
) / sizeof(VirtKeyMap
[0]); --i
>= 0; )
727 if (VirtKeyMap
[i
].wVirtKey
== pker
->wVirtualKeyCode
)
730 *pch
= VirtKeyMap
[i
].chAlone
;
731 else if ((nModifs
& SHIFT
) != 0 && (nModifs
& ~SHIFT
) == 0)
732 *pch
= VirtKeyMap
[i
].chShift
;
733 else if ((nModifs
& CTRL
) != 0 && (nModifs
& ~CTRL
) == 0)
734 *pch
= VirtKeyMap
[i
].chCtrl
;
735 else if ((nModifs
& ALT
) != 0 && (nModifs
& ~ALT
) == 0)
736 *pch
= VirtKeyMap
[i
].chAlt
;
740 if (VirtKeyMap
[i
].fAnsiKey
)
751 i
= win32_kbd_patch_key(pker
);
757 *pch
= (i
> 0) ? pker
->AChar
: NUL
;
759 if (pmodifiers
!= NULL
)
761 /* Pass on the ALT key as a modifier, but only when not combined
762 * with CTRL (which is ALTGR). */
763 if ((nModifs
& ALT
) != 0 && (nModifs
& CTRL
) == 0)
764 *pmodifiers
|= MOD_MASK_ALT
;
766 /* Pass on SHIFT only for special keys, because we don't know when
767 * it's already included with the character. */
768 if ((nModifs
& SHIFT
) != 0 && *pch
<= 0x20)
769 *pmodifiers
|= MOD_MASK_SHIFT
;
771 /* Pass on CTRL only for non-special keys, because we don't know
772 * when it's already included with the character. And not when
773 * combined with ALT (which is ALTGR). */
774 if ((nModifs
& CTRL
) != 0 && (nModifs
& ALT
) == 0
775 && *pch
>= 0x20 && *pch
< 0x80)
776 *pmodifiers
|= MOD_MASK_CTRL
;
780 return (*pch
!= NUL
);
784 # pragma optimize("", on)
787 #endif /* FEAT_GUI_W32 */
793 * For the GUI the mouse handling is in gui_w32.c.
802 static int g_fMouseAvail
= FALSE
; /* mouse present */
803 static int g_fMouseActive
= FALSE
; /* mouse enabled */
804 static int g_nMouseClick
= -1; /* mouse status */
805 static int g_xMouse
; /* mouse x coordinate */
806 static int g_yMouse
; /* mouse y coordinate */
809 * Enable or disable mouse input
820 GetConsoleMode(g_hConIn
, &cmodein
);
823 cmodein
|= ENABLE_MOUSE_INPUT
;
825 cmodein
&= ~ENABLE_MOUSE_INPUT
;
827 SetConsoleMode(g_hConIn
, cmodein
);
832 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
833 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
834 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
835 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
836 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
837 * and we return the mouse position in g_xMouse and g_yMouse.
839 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
840 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
841 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
843 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
844 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
846 * Windows will send us MOUSE_MOVED notifications whenever the mouse
847 * moves, even if it stays within the same character cell. We ignore
848 * all MOUSE_MOVED messages if the position hasn't really changed, and
849 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
850 * we're only interested in MOUSE_DRAG).
852 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
853 * 2-button mouses by pressing the left & right buttons simultaneously.
854 * In practice, it's almost impossible to click both at the same time,
855 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
856 * in such cases, if the user is clicking quickly.
860 MOUSE_EVENT_RECORD
*pmer
)
862 static int s_nOldButton
= -1;
863 static int s_nOldMouseClick
= -1;
864 static int s_xOldMouse
= -1;
865 static int s_yOldMouse
= -1;
866 static linenr_T s_old_topline
= 0;
868 static int s_old_topfill
= 0;
870 static int s_cClicks
= 1;
871 static BOOL s_fReleased
= TRUE
;
872 static DWORD s_dwLastClickTime
= 0;
873 static BOOL s_fNextIsMiddle
= FALSE
;
875 static DWORD cButtons
= 0; /* number of buttons supported */
877 const DWORD LEFT
= FROM_LEFT_1ST_BUTTON_PRESSED
;
878 const DWORD MIDDLE
= FROM_LEFT_2ND_BUTTON_PRESSED
;
879 const DWORD RIGHT
= RIGHTMOST_BUTTON_PRESSED
;
880 const DWORD LEFT_RIGHT
= LEFT
| RIGHT
;
884 if (cButtons
== 0 && !GetNumberOfConsoleMouseButtons(&cButtons
))
887 if (!g_fMouseAvail
|| !g_fMouseActive
)
893 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
896 g_fJustGotFocus
= FALSE
;
900 /* unprocessed mouse click? */
901 if (g_nMouseClick
!= -1)
905 g_xMouse
= pmer
->dwMousePosition
.X
;
906 g_yMouse
= pmer
->dwMousePosition
.Y
;
908 if (pmer
->dwEventFlags
== MOUSE_MOVED
)
910 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
911 * events even when the mouse moves only within a char cell.) */
912 if (s_xOldMouse
== g_xMouse
&& s_yOldMouse
== g_yMouse
)
916 /* If no buttons are pressed... */
917 if ((pmer
->dwButtonState
& ((1 << cButtons
) - 1)) == 0)
919 /* If the last thing returned was MOUSE_RELEASE, ignore this */
923 nButton
= MOUSE_RELEASE
;
926 else /* one or more buttons pressed */
928 /* on a 2-button mouse, hold down left and right buttons
929 * simultaneously to get MIDDLE. */
931 if (cButtons
== 2 && s_nOldButton
!= MOUSE_DRAG
)
933 DWORD dwLR
= (pmer
->dwButtonState
& LEFT_RIGHT
);
935 /* if either left or right button only is pressed, see if the
936 * the next mouse event has both of them pressed */
937 if (dwLR
== LEFT
|| dwLR
== RIGHT
)
941 /* wait a short time for next input event */
942 if (WaitForSingleObject(g_hConIn
, p_mouset
/ 3)
949 MOUSE_EVENT_RECORD
* pmer2
= &ir
.Event
.MouseEvent
;
951 PeekConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
953 if (cRecords
== 0 || ir
.EventType
!= MOUSE_EVENT
954 || !(pmer2
->dwButtonState
& LEFT_RIGHT
))
958 if (pmer2
->dwEventFlags
!= MOUSE_MOVED
)
960 ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
962 return decode_mouse_event(pmer2
);
964 else if (s_xOldMouse
== pmer2
->dwMousePosition
.X
&&
965 s_yOldMouse
== pmer2
->dwMousePosition
.Y
)
967 /* throw away spurious mouse move */
968 ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
970 /* are there any more mouse events in queue? */
971 PeekConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
973 if (cRecords
==0 || ir
.EventType
!= MOUSE_EVENT
)
986 nButton
= (pmer
->dwEventFlags
== MOUSE_MOVED
)
987 ? MOUSE_DRAG
: MOUSE_MIDDLE
;
988 s_fNextIsMiddle
= FALSE
;
990 else if (cButtons
== 2 &&
991 ((pmer
->dwButtonState
& LEFT_RIGHT
) == LEFT_RIGHT
))
993 nButton
= MOUSE_MIDDLE
;
995 if (! s_fReleased
&& pmer
->dwEventFlags
!= MOUSE_MOVED
)
997 s_fNextIsMiddle
= TRUE
;
998 nButton
= MOUSE_RELEASE
;
1001 else if ((pmer
->dwButtonState
& LEFT
) == LEFT
)
1002 nButton
= MOUSE_LEFT
;
1003 else if ((pmer
->dwButtonState
& MIDDLE
) == MIDDLE
)
1004 nButton
= MOUSE_MIDDLE
;
1005 else if ((pmer
->dwButtonState
& RIGHT
) == RIGHT
)
1006 nButton
= MOUSE_RIGHT
;
1008 if (! s_fReleased
&& ! s_fNextIsMiddle
1009 && nButton
!= s_nOldButton
&& s_nOldButton
!= MOUSE_DRAG
)
1012 s_fReleased
= s_fNextIsMiddle
;
1015 if (pmer
->dwEventFlags
== 0 || pmer
->dwEventFlags
== DOUBLE_CLICK
)
1017 /* button pressed or released, without mouse moving */
1018 if (nButton
!= -1 && nButton
!= MOUSE_RELEASE
)
1020 DWORD dwCurrentTime
= GetTickCount();
1022 if (s_xOldMouse
!= g_xMouse
1023 || s_yOldMouse
!= g_yMouse
1024 || s_nOldButton
!= nButton
1025 || s_old_topline
!= curwin
->w_topline
1027 || s_old_topfill
!= curwin
->w_topfill
1029 || (int)(dwCurrentTime
- s_dwLastClickTime
) > p_mouset
)
1033 else if (++s_cClicks
> 4)
1038 s_dwLastClickTime
= dwCurrentTime
;
1041 else if (pmer
->dwEventFlags
== MOUSE_MOVED
)
1043 if (nButton
!= -1 && nButton
!= MOUSE_RELEASE
)
1044 nButton
= MOUSE_DRAG
;
1052 if (nButton
!= MOUSE_RELEASE
)
1053 s_nOldButton
= nButton
;
1055 g_nMouseClick
= nButton
;
1057 if (pmer
->dwControlKeyState
& SHIFT_PRESSED
)
1058 g_nMouseClick
|= MOUSE_SHIFT
;
1059 if (pmer
->dwControlKeyState
& (RIGHT_CTRL_PRESSED
| LEFT_CTRL_PRESSED
))
1060 g_nMouseClick
|= MOUSE_CTRL
;
1061 if (pmer
->dwControlKeyState
& (RIGHT_ALT_PRESSED
| LEFT_ALT_PRESSED
))
1062 g_nMouseClick
|= MOUSE_ALT
;
1064 if (nButton
!= MOUSE_DRAG
&& nButton
!= MOUSE_RELEASE
)
1065 SET_NUM_MOUSE_CLICKS(g_nMouseClick
, s_cClicks
);
1067 /* only pass on interesting (i.e., different) mouse events */
1068 if (s_xOldMouse
== g_xMouse
1069 && s_yOldMouse
== g_yMouse
1070 && s_nOldMouseClick
== g_nMouseClick
)
1076 s_xOldMouse
= g_xMouse
;
1077 s_yOldMouse
= g_yMouse
;
1078 s_old_topline
= curwin
->w_topline
;
1080 s_old_topfill
= curwin
->w_topfill
;
1082 s_nOldMouseClick
= g_nMouseClick
;
1087 # endif /* FEAT_GUI_W32 */
1088 #endif /* FEAT_MOUSE */
1091 #ifdef MCH_CURSOR_SHAPE
1093 * Set the shape of the cursor.
1094 * 'thickness' can be from 1 (thin) to 99 (block)
1097 mch_set_cursor_shape(int thickness
)
1099 CONSOLE_CURSOR_INFO ConsoleCursorInfo
;
1100 ConsoleCursorInfo
.dwSize
= thickness
;
1101 ConsoleCursorInfo
.bVisible
= s_cursor_visible
;
1103 SetConsoleCursorInfo(g_hConOut
, &ConsoleCursorInfo
);
1104 if (s_cursor_visible
)
1105 SetConsoleCursorPosition(g_hConOut
, g_coord
);
1109 mch_update_cursor(void)
1115 * How the cursor is drawn depends on the current mode.
1117 idx
= get_shape_idx(FALSE
);
1119 if (shape_table
[idx
].shape
== SHAPE_BLOCK
)
1120 thickness
= 99; /* 100 doesn't work on W95 */
1122 thickness
= shape_table
[idx
].percentage
;
1123 mch_set_cursor_shape(thickness
);
1127 #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1129 * Handle FOCUS_EVENT.
1132 handle_focus_event(INPUT_RECORD ir
)
1134 g_fJustGotFocus
= ir
.Event
.FocusEvent
.bSetFocus
;
1135 ui_focus_change((int)g_fJustGotFocus
);
1139 * Wait until console input from keyboard or mouse is available,
1140 * or the time is up.
1141 * Return TRUE if something is available FALSE if not.
1144 WaitForChar(long msec
)
1146 DWORD dwNow
= 0, dwEndTime
= 0;
1152 /* Wait until the specified time has elapsed. */
1153 dwEndTime
= GetTickCount() + msec
;
1156 dwEndTime
= INFINITE
;
1158 /* We need to loop until the end of the time period, because
1159 * we might get multiple unusable mouse events in that time.
1163 #ifdef FEAT_MZSCHEME
1164 mzvim_check_threads();
1166 #ifdef FEAT_CLIENTSERVER
1167 serverProcessPendingMessages();
1171 || g_nMouseClick
!= -1
1173 #ifdef FEAT_CLIENTSERVER
1174 || input_available()
1181 /* If the specified wait time has passed, return. */
1182 dwNow
= GetTickCount();
1183 if (dwNow
>= dwEndTime
)
1188 DWORD dwWaitTime
= dwEndTime
- dwNow
;
1190 #ifdef FEAT_MZSCHEME
1191 if (mzthreads_allowed() && p_mzq
> 0
1192 && (msec
< 0 || (long)dwWaitTime
> p_mzq
))
1193 dwWaitTime
= p_mzq
; /* don't wait longer than 'mzquantum' */
1195 #ifdef FEAT_CLIENTSERVER
1196 /* Wait for either an event on the console input or a message in
1197 * the client-server window. */
1198 if (MsgWaitForMultipleObjects(1, &g_hConIn
, FALSE
,
1199 dwWaitTime
, QS_SENDMESSAGE
) != WAIT_OBJECT_0
)
1201 if (WaitForSingleObject(g_hConIn
, dwWaitTime
) != WAIT_OBJECT_0
)
1207 PeekConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
1209 #ifdef FEAT_MBYTE_IME
1210 if (State
& CMDLINE
&& msg_row
== Rows
- 1)
1212 CONSOLE_SCREEN_BUFFER_INFO csbi
;
1214 if (GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
1216 if (csbi
.dwCursorPosition
.Y
!= msg_row
)
1218 /* The screen is now messed up, must redraw the
1219 * command line and later all the windows. */
1220 redraw_all_later(CLEAR
);
1221 cmdline_row
-= (msg_row
- csbi
.dwCursorPosition
.Y
);
1230 if (ir
.EventType
== KEY_EVENT
&& ir
.Event
.KeyEvent
.bKeyDown
)
1232 #ifdef FEAT_MBYTE_IME
1233 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1234 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1235 if (ir
.Event
.KeyEvent
.uChar
.UnicodeChar
== 0
1236 && ir
.Event
.KeyEvent
.wVirtualKeyCode
== 13)
1238 ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
1242 if (decode_key_event(&ir
.Event
.KeyEvent
, &ch
, &ch2
,
1247 ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
);
1249 if (ir
.EventType
== FOCUS_EVENT
)
1250 handle_focus_event(ir
);
1251 else if (ir
.EventType
== WINDOW_BUFFER_SIZE_EVENT
)
1254 else if (ir
.EventType
== MOUSE_EVENT
1255 && decode_mouse_event(&ir
.Event
.MouseEvent
))
1263 #ifdef FEAT_CLIENTSERVER
1264 /* Something might have been received while we were waiting. */
1265 if (input_available())
1271 #ifndef FEAT_GUI_MSWIN
1273 * return non-zero if a character is available
1276 mch_char_avail(void)
1278 return WaitForChar(0L);
1283 * Create the console input. Used when reading stdin doesn't work.
1288 g_hConIn
= CreateFile("CONIN$", GENERIC_READ
|GENERIC_WRITE
,
1289 FILE_SHARE_READ
|FILE_SHARE_WRITE
,
1290 (LPSECURITY_ATTRIBUTES
) NULL
,
1291 OPEN_EXISTING
, 0, (HANDLE
)NULL
);
1292 did_create_conin
= TRUE
;
1296 * Get a keystroke or a mouse event
1299 tgetch(int *pmodifiers
, char_u
*pch2
)
1308 #ifdef FEAT_CLIENTSERVER
1309 (void)WaitForChar(-1L);
1310 if (input_available())
1313 if (g_nMouseClick
!= -1)
1317 if (ReadConsoleInput(g_hConIn
, &ir
, 1, &cRecords
) == 0)
1319 if (did_create_conin
)
1325 if (ir
.EventType
== KEY_EVENT
)
1327 if (decode_key_event(&ir
.Event
.KeyEvent
, &ch
, pch2
,
1331 else if (ir
.EventType
== FOCUS_EVENT
)
1332 handle_focus_event(ir
);
1333 else if (ir
.EventType
== WINDOW_BUFFER_SIZE_EVENT
)
1336 else if (ir
.EventType
== MOUSE_EVENT
)
1338 if (decode_mouse_event(&ir
.Event
.MouseEvent
))
1344 #endif /* !FEAT_GUI_W32 */
1348 * mch_inchar(): low-level input funcion.
1349 * Get one or more characters from the keyboard or the mouse.
1350 * If time == 0, do not wait for characters.
1351 * If time == n, wait a short time for characters.
1352 * If time == -1, wait forever for characters.
1353 * Returns the number of characters read into buf.
1363 #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1367 #define TYPEAHEADLEN 20
1368 static char_u typeahead
[TYPEAHEADLEN
]; /* previously typed bytes. */
1369 static int typeaheadlen
= 0;
1371 /* First use any typeahead that was kept because "buf" was too small. */
1372 if (typeaheadlen
> 0)
1376 if (want_sniff_request
)
1378 if (sniff_request_waiting
)
1380 /* return K_SNIFF */
1381 typeahead
[typeaheadlen
++] = CSI
;
1382 typeahead
[typeaheadlen
++] = (char_u
)KS_EXTRA
;
1383 typeahead
[typeaheadlen
++] = (char_u
)KE_SNIFF
;
1384 sniff_request_waiting
= 0;
1385 want_sniff_request
= 0;
1388 else if (time
< 0 || time
> 250)
1390 /* don't wait too long, a request might be pending */
1398 if (!WaitForChar(time
)) /* no character available */
1401 else /* time == -1, wait forever */
1403 mch_set_winsize_now(); /* Allow winsize changes from now on */
1406 * If there is no character available within 2 seconds (default)
1407 * write the autoscript file to disk. Or cause the CursorHold event
1410 if (!WaitForChar(p_ut
))
1413 if (trigger_cursorhold() && maxlen
>= 3)
1417 buf
[2] = (int)KE_CURSORHOLD
;
1426 * Try to read as many characters as there are, until the buffer is full.
1429 /* we will get at least one key. Get more if they are available. */
1430 g_fCBrkPressed
= FALSE
;
1432 #ifdef MCH_WRITE_DUMP
1437 /* Keep looping until there is something in the typeahead buffer and more
1438 * to get and still room in the buffer (up to two bytes for a char and
1439 * three bytes for a modifier). */
1440 while ((typeaheadlen
== 0 || WaitForChar(0L))
1441 && typeaheadlen
+ 5 <= TYPEAHEADLEN
)
1443 if (typebuf_changed(tb_change_cnt
))
1445 /* "buf" may be invalid now if a client put something in the
1446 * typeahead buffer and "buf" is in the typeahead buffer. */
1451 if (g_nMouseClick
!= -1)
1453 # ifdef MCH_WRITE_DUMP
1455 fprintf(fdDump
, "{%02x @ %d, %d}",
1456 g_nMouseClick
, g_xMouse
, g_yMouse
);
1458 typeahead
[typeaheadlen
++] = ESC
+ 128;
1459 typeahead
[typeaheadlen
++] = 'M';
1460 typeahead
[typeaheadlen
++] = g_nMouseClick
;
1461 typeahead
[typeaheadlen
++] = g_xMouse
+ '!';
1462 typeahead
[typeaheadlen
++] = g_yMouse
+ '!';
1471 c
= tgetch(&modifiers
, &ch2
);
1473 if (typebuf_changed(tb_change_cnt
))
1475 /* "buf" may be invalid now if a client put something in the
1476 * typeahead buffer and "buf" is in the typeahead buffer. */
1481 if (c
== Ctrl_C
&& ctrl_c_interrupts
)
1483 #if defined(FEAT_CLIENTSERVER)
1490 if (g_nMouseClick
== -1)
1495 /* A key may have one or two bytes. */
1496 typeahead
[typeaheadlen
] = c
;
1499 typeahead
[typeaheadlen
+ 1] = ch2
;
1503 /* Only convert normal characters, not special keys. Need to
1504 * convert before applying ALT, otherwise mapping <M-x> breaks
1505 * when 'tenc' is set. */
1506 if (input_conv
.vc_type
!= CONV_NONE
1507 && (ch2
== NUL
|| c
!= K_NUL
))
1508 n
= convert_input(typeahead
+ typeaheadlen
, n
,
1509 TYPEAHEADLEN
- typeaheadlen
);
1512 /* Use the ALT key to set the 8th bit of the character
1513 * when it's one byte, the 8th bit isn't set yet and not
1514 * using a double-byte encoding (would become a lead
1516 if ((modifiers
& MOD_MASK_ALT
)
1518 && (typeahead
[typeaheadlen
] & 0x80) == 0
1524 typeahead
[typeaheadlen
] |= 0x80;
1525 modifiers
&= ~MOD_MASK_ALT
;
1530 /* Prepend modifiers to the character. */
1531 mch_memmove(typeahead
+ typeaheadlen
+ 3,
1532 typeahead
+ typeaheadlen
, n
);
1533 typeahead
[typeaheadlen
++] = K_SPECIAL
;
1534 typeahead
[typeaheadlen
++] = (char_u
)KS_MODIFIER
;
1535 typeahead
[typeaheadlen
++] = modifiers
;
1540 #ifdef MCH_WRITE_DUMP
1548 #ifdef MCH_WRITE_DUMP
1551 fputs("]\n", fdDump
);
1557 /* Move typeahead to "buf", as much as fits. */
1559 while (len
< maxlen
&& typeaheadlen
> 0)
1561 buf
[len
++] = typeahead
[0];
1562 mch_memmove(typeahead
, typeahead
+ 1, --typeaheadlen
);
1566 #else /* FEAT_GUI_W32 */
1568 #endif /* FEAT_GUI_W32 */
1572 # include <shellapi.h> /* required for FindExecutable() */
1576 * Return TRUE if "name" is in $PATH.
1577 * TODO: Should somehow check if it's really executable.
1580 executable_exists(char *name
)
1583 char fname
[_MAX_PATH
];
1586 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
1588 WCHAR
*p
= enc_to_ucs2(name
, NULL
);
1589 WCHAR fnamew
[_MAX_PATH
];
1595 n
= (long)SearchPathW(NULL
, p
, NULL
, _MAX_PATH
, fnamew
, &dumw
);
1597 if (n
> 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
1601 if (GetFileAttributesW(fnamew
) & FILE_ATTRIBUTE_DIRECTORY
)
1605 /* Retry with non-wide function (for Windows 98). */
1609 if (SearchPath(NULL
, name
, NULL
, _MAX_PATH
, fname
, &dum
) == 0)
1611 if (mch_isdir(fname
))
1619 * GUI version of mch_init().
1628 /* Let critical errors result in a failure, not in a dialog box. Required
1629 * for the timestamp test to work on removed floppies. */
1630 SetErrorMode(SEM_FAILCRITICALERRORS
);
1632 _fmode
= O_BINARY
; /* we do our own CR-LF translation */
1634 /* Specify window size. Is there a place to get the default from? */
1638 /* Look for 'vimrun' */
1639 if (!gui_is_win32s())
1641 char_u vimrun_location
[_MAX_PATH
+ 4];
1643 /* First try in same directory as gvim.exe */
1644 STRCPY(vimrun_location
, exe_name
);
1645 STRCPY(gettail(vimrun_location
), "vimrun.exe");
1646 if (mch_getperm(vimrun_location
) >= 0)
1648 if (*skiptowhite(vimrun_location
) != NUL
)
1650 /* Enclose path with white space in double quotes. */
1651 mch_memmove(vimrun_location
+ 1, vimrun_location
,
1652 STRLEN(vimrun_location
) + 1);
1653 *vimrun_location
= '"';
1654 STRCPY(gettail(vimrun_location
), "vimrun\" ");
1657 STRCPY(gettail(vimrun_location
), "vimrun ");
1659 vimrun_path
= (char *)vim_strsave(vimrun_location
);
1660 s_dont_use_vimrun
= FALSE
;
1662 else if (executable_exists("vimrun.exe"))
1663 s_dont_use_vimrun
= FALSE
;
1665 /* Don't give the warning for a missing vimrun.exe right now, but only
1666 * when vimrun was supposed to be used. Don't bother people that do
1667 * not need vimrun.exe. */
1668 if (s_dont_use_vimrun
)
1669 need_vimrun_warning
= TRUE
;
1673 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1674 * Otherwise the default "findstr /n" is used.
1676 if (!executable_exists("findstr.exe"))
1677 set_option_value((char_u
*)"grepprg", 0, (char_u
*)"grep -n", 0);
1679 #ifdef FEAT_CLIPBOARD
1683 * Vim's own clipboard format recognises whether the text is char, line,
1684 * or rectangular block. Only useful for copying between two Vims.
1685 * "VimClipboard" was used for previous versions, using the first
1686 * character to specify MCHAR, MLINE or MBLOCK.
1688 clip_star
.format
= RegisterClipboardFormat("VimClipboard2");
1689 clip_star
.format_raw
= RegisterClipboardFormat("VimRawBytes");
1694 #else /* FEAT_GUI_W32 */
1696 #define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1697 #define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1700 * ClearConsoleBuffer()
1702 * Clears the entire contents of the console screen buffer, using the
1703 * specified attribute.
1708 ClearConsoleBuffer(WORD wAttribute
)
1710 CONSOLE_SCREEN_BUFFER_INFO csbi
;
1712 DWORD NumCells
, dummy
;
1714 if (!GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
1717 NumCells
= csbi
.dwSize
.X
* csbi
.dwSize
.Y
;
1720 if (!FillConsoleOutputCharacter(g_hConOut
, ' ', NumCells
,
1725 if (!FillConsoleOutputAttribute(g_hConOut
, wAttribute
, NumCells
,
1735 * FitConsoleWindow()
1737 * Checks if the console window will fit within given buffer dimensions.
1738 * Also, if requested, will shrink the window to fit.
1747 CONSOLE_SCREEN_BUFFER_INFO csbi
;
1749 BOOL NeedAdjust
= FALSE
;
1751 if (GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
1754 * A buffer resize will fail if the current console window does
1755 * not lie completely within that buffer. To avoid this, we might
1756 * have to move and possibly shrink the window.
1758 if (csbi
.srWindow
.Right
>= dwBufferSize
.X
)
1760 dwWindowSize
.X
= SRWIDTH(csbi
.srWindow
);
1761 if (dwWindowSize
.X
> dwBufferSize
.X
)
1762 dwWindowSize
.X
= dwBufferSize
.X
;
1763 csbi
.srWindow
.Right
= dwBufferSize
.X
- 1;
1764 csbi
.srWindow
.Left
= dwBufferSize
.X
- dwWindowSize
.X
;
1767 if (csbi
.srWindow
.Bottom
>= dwBufferSize
.Y
)
1769 dwWindowSize
.Y
= SRHEIGHT(csbi
.srWindow
);
1770 if (dwWindowSize
.Y
> dwBufferSize
.Y
)
1771 dwWindowSize
.Y
= dwBufferSize
.Y
;
1772 csbi
.srWindow
.Bottom
= dwBufferSize
.Y
- 1;
1773 csbi
.srWindow
.Top
= dwBufferSize
.Y
- dwWindowSize
.Y
;
1776 if (NeedAdjust
&& WantAdjust
)
1778 if (!SetConsoleWindowInfo(g_hConOut
, TRUE
, &csbi
.srWindow
))
1787 typedef struct ConsoleBufferStruct
1790 CONSOLE_SCREEN_BUFFER_INFO Info
;
1796 * SaveConsoleBuffer()
1798 * Saves important information about the console buffer, including the
1799 * actual buffer contents. The saved information is suitable for later
1800 * restoration by RestoreConsoleBuffer().
1802 * TRUE if all information was saved; FALSE otherwise
1803 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1811 SMALL_RECT ReadRegion
;
1817 if (!GetConsoleScreenBufferInfo(g_hConOut
, &cb
->Info
))
1819 cb
->IsValid
= FALSE
;
1825 * Allocate a buffer large enough to hold the entire console screen
1826 * buffer. If this ConsoleBuffer structure has already been initialized
1827 * with a buffer of the correct size, then just use that one.
1829 if (!cb
->IsValid
|| cb
->Buffer
== NULL
||
1830 cb
->BufferSize
.X
!= cb
->Info
.dwSize
.X
||
1831 cb
->BufferSize
.Y
!= cb
->Info
.dwSize
.Y
)
1833 cb
->BufferSize
.X
= cb
->Info
.dwSize
.X
;
1834 cb
->BufferSize
.Y
= cb
->Info
.dwSize
.Y
;
1835 NumCells
= cb
->BufferSize
.X
* cb
->BufferSize
.Y
;
1836 if (cb
->Buffer
!= NULL
)
1837 vim_free(cb
->Buffer
);
1838 cb
->Buffer
= (PCHAR_INFO
)alloc(NumCells
* sizeof(CHAR_INFO
));
1839 if (cb
->Buffer
== NULL
)
1844 * We will now copy the console screen buffer into our buffer.
1845 * ReadConsoleOutput() seems to be limited as far as how much you
1846 * can read at a time. Empirically, this number seems to be about
1847 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1848 * in chunks until it is all copied. The chunks will all have the
1849 * same horizontal characteristics, so initialize them now. The
1850 * height of each chunk will be (12000 / width).
1853 ReadRegion
.Left
= 0;
1854 ReadRegion
.Right
= cb
->Info
.dwSize
.X
- 1;
1855 Y_incr
= 12000 / cb
->Info
.dwSize
.X
;
1856 for (Y
= 0; Y
< cb
->BufferSize
.Y
; Y
+= Y_incr
)
1859 * Read into position (0, Y) in our buffer.
1863 * Read the region whose top left corner is (0, Y) and whose bottom
1864 * right corner is (width - 1, Y + Y_incr - 1). This should define
1865 * a region of size width by Y_incr. Don't worry if this region is
1866 * too large for the remaining buffer; it will be cropped.
1869 ReadRegion
.Bottom
= Y
+ Y_incr
- 1;
1870 if (!ReadConsoleOutput(g_hConOut
, /* output handle */
1871 cb
->Buffer
, /* our buffer */
1872 cb
->BufferSize
, /* dimensions of our buffer */
1873 BufferCoord
, /* offset in our buffer */
1874 &ReadRegion
)) /* region to save */
1876 vim_free(cb
->Buffer
);
1886 * RestoreConsoleBuffer()
1888 * Restores important information about the console buffer, including the
1889 * actual buffer contents, if desired. The information to restore is in
1890 * the same format used by SaveConsoleBuffer().
1895 RestoreConsoleBuffer(
1900 SMALL_RECT WriteRegion
;
1902 if (cb
== NULL
|| !cb
->IsValid
)
1906 * Before restoring the buffer contents, clear the current buffer, and
1907 * restore the cursor position and window information. Doing this now
1908 * prevents old buffer contents from "flashing" onto the screen.
1911 ClearConsoleBuffer(cb
->Info
.wAttributes
);
1913 FitConsoleWindow(cb
->Info
.dwSize
, TRUE
);
1914 if (!SetConsoleScreenBufferSize(g_hConOut
, cb
->Info
.dwSize
))
1916 if (!SetConsoleTextAttribute(g_hConOut
, cb
->Info
.wAttributes
))
1922 * No need to restore the screen buffer contents, so we're done.
1927 if (!SetConsoleCursorPosition(g_hConOut
, cb
->Info
.dwCursorPosition
))
1929 if (!SetConsoleWindowInfo(g_hConOut
, TRUE
, &cb
->Info
.srWindow
))
1933 * Restore the screen buffer contents.
1935 if (cb
->Buffer
!= NULL
)
1939 WriteRegion
.Left
= 0;
1940 WriteRegion
.Top
= 0;
1941 WriteRegion
.Right
= cb
->Info
.dwSize
.X
- 1;
1942 WriteRegion
.Bottom
= cb
->Info
.dwSize
.Y
- 1;
1943 if (!WriteConsoleOutput(g_hConOut
, /* output handle */
1944 cb
->Buffer
, /* our buffer */
1945 cb
->BufferSize
, /* dimensions of our buffer */
1946 BufferCoord
, /* offset in our buffer */
1947 &WriteRegion
)) /* region to restore */
1956 #define FEAT_RESTORE_ORIG_SCREEN
1957 #ifdef FEAT_RESTORE_ORIG_SCREEN
1958 static ConsoleBuffer g_cbOrig
= { 0 };
1960 static ConsoleBuffer g_cbNonTermcap
= { 0 };
1961 static ConsoleBuffer g_cbTermcap
= { 0 };
1965 typedef HWND (__stdcall
*GETCONSOLEWINDOWPROC
)(VOID
);
1967 typedef WINBASEAPI
HWND (WINAPI
*GETCONSOLEWINDOWPROC
)(VOID
);
1969 char g_szOrigTitle
[256] = { 0 };
1970 HWND g_hWnd
= NULL
; /* also used in os_mswin.c */
1971 static HICON g_hOrigIconSmall
= NULL
;
1972 static HICON g_hOrigIcon
= NULL
;
1973 static HICON g_hVimIcon
= NULL
;
1974 static BOOL g_fCanChangeIcon
= FALSE
;
1976 /* ICON* are not defined in VC++ 4.0 */
1978 #define ICON_SMALL 0
1986 * Attempts to retrieve the small icon and/or the big icon currently in
1987 * use by a given window.
2000 if (phIconSmall
!= NULL
)
2001 *phIconSmall
= (HICON
)SendMessage(hWnd
, WM_GETICON
,
2002 (WPARAM
)ICON_SMALL
, (LPARAM
)0);
2004 *phIcon
= (HICON
)SendMessage(hWnd
, WM_GETICON
,
2005 (WPARAM
)ICON_BIG
, (LPARAM
)0);
2012 * Attempts to change the small icon and/or the big icon currently in
2013 * use by a given window.
2023 HICON hPrevIconSmall
;
2029 if (hIconSmall
!= NULL
)
2030 hPrevIconSmall
= (HICON
)SendMessage(hWnd
, WM_SETICON
,
2031 (WPARAM
)ICON_SMALL
, (LPARAM
)hIconSmall
);
2033 hPrevIcon
= (HICON
)SendMessage(hWnd
, WM_SETICON
,
2034 (WPARAM
)ICON_BIG
,(LPARAM
) hIcon
);
2039 * SaveConsoleTitleAndIcon()
2041 * Saves the current console window title in g_szOrigTitle, for later
2042 * restoration. Also, attempts to obtain a handle to the console window,
2043 * and use it to save the small and big icons currently in use by the
2044 * console window. This is not always possible on some versions of Windows;
2045 * nor is it possible when running Vim remotely using Telnet (since the
2046 * console window the user sees is owned by a remote process).
2049 SaveConsoleTitleAndIcon(void)
2051 GETCONSOLEWINDOWPROC GetConsoleWindowProc
;
2053 /* Save the original title. */
2054 if (!GetConsoleTitle(g_szOrigTitle
, sizeof(g_szOrigTitle
)))
2058 * Obtain a handle to the console window using GetConsoleWindow() from
2059 * KERNEL32.DLL; we need to handle in order to change the window icon.
2060 * This function only exists on NT-based Windows, starting with Windows
2061 * 2000. On older operating systems, we can't change the window icon
2064 if ((GetConsoleWindowProc
= (GETCONSOLEWINDOWPROC
)
2065 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2066 "GetConsoleWindow")) != NULL
)
2068 g_hWnd
= (*GetConsoleWindowProc
)();
2073 /* Save the original console window icon. */
2074 GetConsoleIcon(g_hWnd
, &g_hOrigIconSmall
, &g_hOrigIcon
);
2075 if (g_hOrigIconSmall
== NULL
|| g_hOrigIcon
== NULL
)
2078 /* Extract the first icon contained in the Vim executable. */
2079 g_hVimIcon
= ExtractIcon(NULL
, exe_name
, 0);
2080 if (g_hVimIcon
!= NULL
)
2081 g_fCanChangeIcon
= TRUE
;
2085 static int g_fWindInitCalled
= FALSE
;
2086 static int g_fTermcapMode
= FALSE
;
2087 static CONSOLE_CURSOR_INFO g_cci
;
2088 static DWORD g_cmodein
= 0;
2089 static DWORD g_cmodeout
= 0;
2092 * non-GUI version of mch_init().
2097 #ifndef FEAT_RESTORE_ORIG_SCREEN
2098 CONSOLE_SCREEN_BUFFER_INFO csbi
;
2104 /* Let critical errors result in a failure, not in a dialog box. Required
2105 * for the timestamp test to work on removed floppies. */
2106 SetErrorMode(SEM_FAILCRITICALERRORS
);
2108 _fmode
= O_BINARY
; /* we do our own CR-LF translation */
2111 /* Obtain handles for the standard Console I/O devices */
2112 if (read_cmd_fd
== 0)
2113 g_hConIn
= GetStdHandle(STD_INPUT_HANDLE
);
2116 g_hConOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
2118 #ifdef FEAT_RESTORE_ORIG_SCREEN
2119 /* Save the initial console buffer for later restoration */
2120 SaveConsoleBuffer(&g_cbOrig
);
2121 g_attrCurrent
= g_attrDefault
= g_cbOrig
.Info
.wAttributes
;
2123 /* Get current text attributes */
2124 GetConsoleScreenBufferInfo(g_hConOut
, &csbi
);
2125 g_attrCurrent
= g_attrDefault
= csbi
.wAttributes
;
2127 if (cterm_normal_fg_color
== 0)
2128 cterm_normal_fg_color
= (g_attrCurrent
& 0xf) + 1;
2129 if (cterm_normal_bg_color
== 0)
2130 cterm_normal_bg_color
= ((g_attrCurrent
>> 4) & 0xf) + 1;
2132 /* set termcap codes to current text attributes */
2133 update_tcap(g_attrCurrent
);
2135 GetConsoleCursorInfo(g_hConOut
, &g_cci
);
2136 GetConsoleMode(g_hConIn
, &g_cmodein
);
2137 GetConsoleMode(g_hConOut
, &g_cmodeout
);
2140 SaveConsoleTitleAndIcon();
2142 * Set both the small and big icons of the console window to Vim's icon.
2143 * Note that Vim presently only has one size of icon (32x32), but it
2144 * automatically gets scaled down to 16x16 when setting the small icon.
2146 if (g_fCanChangeIcon
)
2147 SetConsoleIcon(g_hWnd
, g_hVimIcon
, g_hVimIcon
);
2152 #ifdef MCH_WRITE_DUMP
2153 fdDump
= fopen("dump", "wt");
2160 fputs(ctime(&t
), fdDump
);
2165 g_fWindInitCalled
= TRUE
;
2168 g_fMouseAvail
= GetSystemMetrics(SM_MOUSEPRESENT
);
2171 #ifdef FEAT_CLIPBOARD
2175 * Vim's own clipboard format recognises whether the text is char, line, or
2176 * rectangular block. Only useful for copying between two Vims.
2177 * "VimClipboard" was used for previous versions, using the first
2178 * character to specify MCHAR, MLINE or MBLOCK.
2180 clip_star
.format
= RegisterClipboardFormat("VimClipboard2");
2181 clip_star
.format_raw
= RegisterClipboardFormat("VimRawBytes");
2184 /* This will be NULL on anything but NT 4.0 */
2185 s_pfnGetConsoleKeyboardLayoutName
=
2186 (PFNGCKLN
) GetProcAddress(GetModuleHandle("kernel32.dll"),
2187 "GetConsoleKeyboardLayoutNameA");
2191 * non-GUI version of mch_exit().
2192 * Shut down and exit with status `r'
2193 * Careful: mch_exit() may be called before mch_init()!
2200 if (g_fWindInitCalled
)
2201 settmode(TMODE_COOK
);
2203 ml_close_all(TRUE
); /* remove all memfiles */
2205 if (g_fWindInitCalled
)
2208 mch_restore_title(3);
2210 * Restore both the small and big icons of the console window to
2211 * what they were at startup. Don't do this when the window is
2212 * closed, Vim would hang here.
2214 if (g_fCanChangeIcon
&& !g_fForceExit
)
2215 SetConsoleIcon(g_hWnd
, g_hOrigIconSmall
, g_hOrigIcon
);
2218 #ifdef MCH_WRITE_DUMP
2224 fputs(ctime(&t
), fdDump
);
2231 SetConsoleCursorInfo(g_hConOut
, &g_cci
);
2232 SetConsoleMode(g_hConIn
, g_cmodein
);
2233 SetConsoleMode(g_hConOut
, g_cmodeout
);
2235 #ifdef DYNAMIC_GETTEXT
2241 #endif /* !FEAT_GUI_W32 */
2244 * Do we have an interactive window?
2255 return OK
; /* GUI always has a tty */
2265 * fname_case(): Set the case of the file name, if it already exists.
2266 * When "len" is > 0, also expand short to long filenames.
2273 char szTrueName
[_MAX_PATH
+ 2];
2274 char *ptrue
, *ptruePrev
;
2275 char *porig
, *porigPrev
;
2281 flen
= (int)STRLEN(name
);
2282 if (flen
== 0 || flen
> _MAX_PATH
)
2287 /* Build the new name in szTrueName[] one component at a time. */
2291 if (isalpha(porig
[0]) && porig
[1] == ':')
2293 /* copy leading drive letter */
2294 *ptrue
++ = *porig
++;
2295 *ptrue
++ = *porig
++;
2296 *ptrue
= NUL
; /* in case nothing follows */
2299 while (*porig
!= NUL
)
2301 /* copy \ characters */
2302 while (*porig
== psepc
)
2303 *ptrue
++ = *porig
++;
2307 while (*porig
!= NUL
&& *porig
!= psepc
)
2314 l
= (*mb_ptr2len
)(porig
);
2316 *ptrue
++ = *porig
++;
2320 *ptrue
++ = *porig
++;
2324 /* Skip "", "." and "..". */
2325 if (ptrue
> ptruePrev
2326 && (ptruePrev
[0] != '.'
2327 || (ptruePrev
[1] != NUL
2328 && (ptruePrev
[1] != '.' || ptruePrev
[2] != NUL
)))
2329 && (hFind
= FindFirstFile(szTrueName
, &fb
))
2330 != INVALID_HANDLE_VALUE
)
2335 /* Only use the match when it's the same name (ignoring case) or
2336 * expansion is allowed and there is a match with the short name
2337 * and there is enough room. */
2338 if (_stricoll(porigPrev
, fb
.cFileName
) == 0
2340 && (_stricoll(porigPrev
, fb
.cAlternateFileName
) == 0
2341 && (int)(ptruePrev
- szTrueName
)
2342 + (int)strlen(fb
.cFileName
) < len
)))
2344 STRCPY(ptruePrev
, fb
.cFileName
);
2346 /* Look for exact match and prefer it if found. Must be a
2347 * long name, otherwise there would be only one match. */
2348 while (FindNextFile(hFind
, &fb
))
2350 if (*fb
.cAlternateFileName
!= NUL
2351 && (strcoll(porigPrev
, fb
.cFileName
) == 0
2353 && (_stricoll(porigPrev
,
2354 fb
.cAlternateFileName
) == 0
2355 && (int)(ptruePrev
- szTrueName
)
2356 + (int)strlen(fb
.cFileName
) < len
))))
2358 STRCPY(ptruePrev
, fb
.cFileName
);
2365 ptrue
= ptruePrev
+ strlen(ptruePrev
);
2369 STRCPY(name
, szTrueName
);
2374 * Insert user name in s[len].
2381 char szUserName
[256 + 1]; /* UNLEN is 256 */
2382 DWORD cch
= sizeof szUserName
;
2384 if (GetUserName(szUserName
, &cch
))
2386 vim_strncpy(s
, szUserName
, len
- 1);
2395 * Insert host name in s[len].
2404 if (!GetComputerName(s
, &cch
))
2405 vim_strncpy(s
, "PC (Win32 Vim)", len
- 1);
2415 return (long)GetCurrentProcessId();
2420 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2421 * Return OK for success, FAIL for failure.
2429 * Originally this was:
2430 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2431 * But the Win32s known bug list says that getcwd() doesn't work
2432 * so use the Win32 system call instead. <Negri>
2435 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2437 WCHAR wbuf
[_MAX_PATH
+ 1];
2439 if (GetCurrentDirectoryW(_MAX_PATH
, wbuf
) != 0)
2441 char_u
*p
= ucs2_to_enc(wbuf
, NULL
);
2445 vim_strncpy(buf
, p
, len
- 1);
2450 /* Retry with non-wide function (for Windows 98). */
2453 return (GetCurrentDirectory(len
, buf
) != 0 ? OK
: FAIL
);
2457 * get file permissions for `name'
2459 * else FILE_ATTRIBUTE_* defined in winnt.h
2462 mch_getperm(char_u
*name
)
2465 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2467 WCHAR
*p
= enc_to_ucs2(name
, NULL
);
2472 n
= (long)GetFileAttributesW(p
);
2474 if (n
>= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
2476 /* Retry with non-wide function (for Windows 98). */
2480 return (long)GetFileAttributes((char *)name
);
2485 * set file permission for `name' to `perm'
2492 perm
|= FILE_ATTRIBUTE_ARCHIVE
; /* file has changed, set archive bit */
2494 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2496 WCHAR
*p
= enc_to_ucs2(name
, NULL
);
2501 n
= (long)SetFileAttributesW(p
, perm
);
2503 if (n
|| GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
2504 return n
? OK
: FAIL
;
2505 /* Retry with non-wide function (for Windows 98). */
2509 return SetFileAttributes((char *)name
, perm
) ? OK
: FAIL
;
2513 * Set hidden flag for "name".
2516 mch_hide(char_u
*name
)
2522 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2523 p
= enc_to_ucs2(name
, NULL
);
2529 perm
= GetFileAttributesW(p
);
2530 if (perm
< 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
2532 /* Retry with non-wide function (for Windows 98). */
2539 perm
= GetFileAttributes((char *)name
);
2542 perm
|= FILE_ATTRIBUTE_HIDDEN
;
2546 if (SetFileAttributesW(p
, perm
) == 0
2547 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
2549 /* Retry with non-wide function (for Windows 98). */
2556 SetFileAttributes((char *)name
, perm
);
2564 * return TRUE if "name" is a directory
2565 * return FALSE if "name" is not a directory or upon error
2568 mch_isdir(char_u
*name
)
2570 int f
= mch_getperm(name
);
2573 return FALSE
; /* file does not exist at all */
2575 return (f
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
2579 * Return TRUE if file "fname" has more than one link.
2582 mch_is_linked(char_u
*fname
)
2586 BY_HANDLE_FILE_INFORMATION inf
;
2590 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
2591 wn
= enc_to_ucs2(fname
, NULL
);
2594 hFile
= CreateFileW(wn
, /* file name */
2595 GENERIC_READ
, /* access mode */
2597 NULL
, /* security descriptor */
2598 OPEN_EXISTING
, /* creation disposition */
2599 0, /* file attributes */
2600 NULL
); /* handle to template file */
2601 if (hFile
== INVALID_HANDLE_VALUE
2602 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
2604 /* Retry with non-wide function (for Windows 98). */
2611 hFile
= CreateFile(fname
, /* file name */
2612 GENERIC_READ
, /* access mode */
2614 NULL
, /* security descriptor */
2615 OPEN_EXISTING
, /* creation disposition */
2616 0, /* file attributes */
2617 NULL
); /* handle to template file */
2619 if (hFile
!= INVALID_HANDLE_VALUE
)
2621 if (GetFileInformationByHandle(hFile
, &inf
) != 0
2622 && inf
.nNumberOfLinks
> 1)
2634 * Return TRUE if file or directory "name" is writable (not readonly).
2635 * Strange semantics of Win32: a readonly directory is writable, but you can't
2636 * delete a file. Let's say this means it is writable.
2639 mch_writable(char_u
*name
)
2641 int perm
= mch_getperm(name
);
2643 return (perm
!= -1 && (!(perm
& FILE_ATTRIBUTE_READONLY
)
2644 || (perm
& FILE_ATTRIBUTE_DIRECTORY
)));
2648 * Return 1 if "name" can be executed, 0 if not.
2649 * Return -1 if unknown.
2652 mch_can_exe(char_u
*name
)
2654 char_u buf
[_MAX_PATH
];
2655 int len
= (int)STRLEN(name
);
2658 if (len
>= _MAX_PATH
) /* safety check */
2661 /* If there already is an extension try using the name directly. Also do
2662 * this with a Unix-shell like 'shell'. */
2663 if (vim_strchr(gettail(name
), '.') != NULL
2664 || strstr((char *)gettail(p_sh
), "sh") != NULL
)
2665 if (executable_exists((char *)name
))
2669 * Loop over all extensions in $PATHEXT.
2671 vim_strncpy(buf
, name
, _MAX_PATH
- 1);
2672 p
= mch_getenv("PATHEXT");
2674 p
= (char_u
*)".com;.exe;.bat;.cmd";
2677 if (p
[0] == '.' && (p
[1] == NUL
|| p
[1] == ';'))
2679 /* A single "." means no extension is added. */
2686 copy_option_part(&p
, buf
+ len
, _MAX_PATH
- len
, ";");
2687 if (executable_exists((char *)buf
))
2694 * Check what "name" is:
2695 * NODE_NORMAL: file or directory (or doesn't exist)
2696 * NODE_WRITABLE: writable device, socket, fifo, etc.
2697 * NODE_OTHER: non-writable things
2700 mch_nodetype(char_u
*name
)
2705 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2706 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2708 if (STRNCMP(name
, "\\\\.\\", 4) == 0)
2709 return NODE_WRITABLE
;
2711 hFile
= CreateFile(name
, /* file name */
2712 GENERIC_WRITE
, /* access mode */
2714 NULL
, /* security descriptor */
2715 OPEN_EXISTING
, /* creation disposition */
2716 0, /* file attributes */
2717 NULL
); /* handle to template file */
2719 if (hFile
== INVALID_HANDLE_VALUE
)
2722 type
= GetFileType(hFile
);
2724 if (type
== FILE_TYPE_CHAR
)
2725 return NODE_WRITABLE
;
2726 if (type
== FILE_TYPE_DISK
)
2734 PSECURITY_DESCRIPTOR pSecurityDescriptor
;
2743 * Return a pointer to the ACL of file "fname" in allocated memory.
2744 * Return NULL if the ACL is not available for whatever reason.
2747 mch_get_acl(char_u
*fname
)
2750 return (vim_acl_T
)NULL
;
2752 struct my_acl
*p
= NULL
;
2754 /* This only works on Windows NT and 2000. */
2755 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
&& advapi_lib
!= NULL
)
2757 p
= (struct my_acl
*)alloc_clear((unsigned)sizeof(struct my_acl
));
2760 if (pGetNamedSecurityInfo(
2761 (LPTSTR
)fname
, // Abstract filename
2762 SE_FILE_OBJECT
, // File Object
2763 // Retrieve the entire security descriptor.
2764 OWNER_SECURITY_INFORMATION
|
2765 GROUP_SECURITY_INFORMATION
|
2766 DACL_SECURITY_INFORMATION
|
2767 SACL_SECURITY_INFORMATION
,
2768 &p
->pSidOwner
, // Ownership information.
2769 &p
->pSidGroup
, // Group membership.
2770 &p
->pDacl
, // Discretionary information.
2771 &p
->pSacl
, // For auditing purposes.
2772 &p
->pSecurityDescriptor
2775 mch_free_acl((vim_acl_T
)p
);
2781 return (vim_acl_T
)p
;
2786 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2787 * Errors are ignored.
2788 * This must only be called with "acl" equal to what mch_get_acl() returned.
2791 mch_set_acl(char_u
*fname
, vim_acl_T acl
)
2794 struct my_acl
*p
= (struct my_acl
*)acl
;
2796 if (p
!= NULL
&& advapi_lib
!= NULL
)
2797 (void)pSetNamedSecurityInfo(
2798 (LPTSTR
)fname
, // Abstract filename
2799 SE_FILE_OBJECT
, // File Object
2800 // Retrieve the entire security descriptor.
2801 OWNER_SECURITY_INFORMATION
|
2802 GROUP_SECURITY_INFORMATION
|
2803 DACL_SECURITY_INFORMATION
|
2804 SACL_SECURITY_INFORMATION
,
2805 p
->pSidOwner
, // Ownership information.
2806 p
->pSidGroup
, // Group membership.
2807 p
->pDacl
, // Discretionary information.
2808 p
->pSacl
// For auditing purposes.
2814 mch_free_acl(vim_acl_T acl
)
2817 struct my_acl
*p
= (struct my_acl
*)acl
;
2821 LocalFree(p
->pSecurityDescriptor
); // Free the memory just in case
2827 #ifndef FEAT_GUI_W32
2830 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2839 if (ctrl_c_interrupts
)
2840 g_fCtrlCPressed
= TRUE
;
2843 case CTRL_BREAK_EVENT
:
2844 g_fCBrkPressed
= TRUE
;
2847 /* fatal events: shut down gracefully */
2848 case CTRL_CLOSE_EVENT
:
2849 case CTRL_LOGOFF_EVENT
:
2850 case CTRL_SHUTDOWN_EVENT
:
2851 windgoto((int)Rows
- 1, 0);
2852 g_fForceExit
= TRUE
;
2854 sprintf((char *)IObuff
, _("Vim: Caught %s event\n"),
2855 (dwCtrlType
== CTRL_CLOSE_EVENT
2857 : dwCtrlType
== CTRL_LOGOFF_EVENT
2861 OutputDebugString(IObuff
);
2864 preserve_exit(); /* output IObuff, preserve files and exit */
2866 return TRUE
; /* not reached */
2875 * set the tty in (raw) ? "raw" : "cooked" mode
2878 mch_settmode(int tmode
)
2882 BOOL bEnableHandler
;
2884 GetConsoleMode(g_hConIn
, &cmodein
);
2885 GetConsoleMode(g_hConOut
, &cmodeout
);
2886 if (tmode
== TMODE_RAW
)
2888 cmodein
&= ~(ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
|
2892 cmodein
|= ENABLE_MOUSE_INPUT
;
2894 cmodeout
&= ~(ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
2895 bEnableHandler
= TRUE
;
2899 cmodein
|= (ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
|
2901 cmodeout
|= (ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
2902 bEnableHandler
= FALSE
;
2904 SetConsoleMode(g_hConIn
, cmodein
);
2905 SetConsoleMode(g_hConOut
, cmodeout
);
2906 SetConsoleCtrlHandler(handler_routine
, bEnableHandler
);
2908 #ifdef MCH_WRITE_DUMP
2911 fprintf(fdDump
, "mch_settmode(%s, in = %x, out = %x)\n",
2912 tmode
== TMODE_RAW
? "raw" :
2913 tmode
== TMODE_COOK
? "cooked" : "normal",
2922 * Get the size of the current window in `Rows' and `Columns'
2923 * Return OK when size could be determined, FAIL otherwise.
2926 mch_get_shellsize(void)
2928 CONSOLE_SCREEN_BUFFER_INFO csbi
;
2930 if (!g_fTermcapMode
&& g_cbTermcap
.IsValid
)
2933 * For some reason, we are trying to get the screen dimensions
2934 * even though we are not in termcap mode. The 'Rows' and 'Columns'
2935 * variables are really intended to mean the size of Vim screen
2936 * while in termcap mode.
2938 Rows
= g_cbTermcap
.Info
.dwSize
.Y
;
2939 Columns
= g_cbTermcap
.Info
.dwSize
.X
;
2941 else if (GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
2943 Rows
= csbi
.srWindow
.Bottom
- csbi
.srWindow
.Top
+ 1;
2944 Columns
= csbi
.srWindow
.Right
- csbi
.srWindow
.Left
+ 1;
2955 * Set a console window to `xSize' * `ySize'
2958 ResizeConBufAndWindow(
2963 CONSOLE_SCREEN_BUFFER_INFO csbi
; /* hold current console buffer info */
2964 SMALL_RECT srWindowRect
; /* hold the new console size */
2967 #ifdef MCH_WRITE_DUMP
2970 fprintf(fdDump
, "ResizeConBufAndWindow(%d, %d)\n", xSize
, ySize
);
2975 /* get the largest size we can size the console window to */
2976 coordScreen
= GetLargestConsoleWindowSize(hConsole
);
2978 /* define the new console window size and scroll position */
2979 srWindowRect
.Left
= srWindowRect
.Top
= (SHORT
) 0;
2980 srWindowRect
.Right
= (SHORT
) (min(xSize
, coordScreen
.X
) - 1);
2981 srWindowRect
.Bottom
= (SHORT
) (min(ySize
, coordScreen
.Y
) - 1);
2983 if (GetConsoleScreenBufferInfo(g_hConOut
, &csbi
))
2987 sx
= csbi
.srWindow
.Right
- csbi
.srWindow
.Left
+ 1;
2988 sy
= csbi
.srWindow
.Bottom
- csbi
.srWindow
.Top
+ 1;
2989 if (sy
< ySize
|| sx
< xSize
)
2992 * Increasing number of lines/columns, do buffer first.
2993 * Use the maximal size in x and y direction.
2996 coordScreen
.Y
= ySize
;
3000 coordScreen
.X
= xSize
;
3003 SetConsoleScreenBufferSize(hConsole
, coordScreen
);
3007 if (!SetConsoleWindowInfo(g_hConOut
, TRUE
, &srWindowRect
))
3009 #ifdef MCH_WRITE_DUMP
3012 fprintf(fdDump
, "SetConsoleWindowInfo failed: %lx\n",
3019 /* define the new console buffer size */
3020 coordScreen
.X
= xSize
;
3021 coordScreen
.Y
= ySize
;
3023 if (!SetConsoleScreenBufferSize(hConsole
, coordScreen
))
3025 #ifdef MCH_WRITE_DUMP
3028 fprintf(fdDump
, "SetConsoleScreenBufferSize failed: %lx\n",
3038 * Set the console window to `Rows' * `Columns'
3041 mch_set_shellsize(void)
3045 /* Don't change window size while still starting up */
3046 if (suppress_winsize
!= 0)
3048 suppress_winsize
= 2;
3054 coordScreen
= GetLargestConsoleWindowSize(g_hConOut
);
3056 /* Clamp Rows and Columns to reasonable values */
3057 if (Rows
> coordScreen
.Y
)
3058 Rows
= coordScreen
.Y
;
3059 if (Columns
> coordScreen
.X
)
3060 Columns
= coordScreen
.X
;
3062 ResizeConBufAndWindow(g_hConOut
, Columns
, Rows
);
3067 * Rows and/or Columns has changed.
3070 mch_new_shellsize(void)
3072 set_scroll_region(0, 0, Columns
- 1, Rows
- 1);
3077 * Called when started up, to set the winsize that was delayed.
3080 mch_set_winsize_now(void)
3082 if (suppress_winsize
== 2)
3084 suppress_winsize
= 0;
3085 mch_set_shellsize();
3088 suppress_winsize
= 0;
3090 #endif /* FEAT_GUI_W32 */
3094 #if defined(FEAT_GUI_W32) || defined(PROTO)
3097 * Specialised version of system() for Win32 GUI mode.
3098 * This version proceeds as follows:
3099 * 1. Create a console window for use by the subprocess
3100 * 2. Run the subprocess (it gets the allocated console by default)
3101 * 3. Wait for the subprocess to terminate and get its exit code
3102 * 4. Prompt the user to press a key to close the console window
3105 mch_system(char *cmd
, int options
)
3108 PROCESS_INFORMATION pi
;
3110 HWND hwnd
= GetFocus();
3113 si
.lpReserved
= NULL
;
3114 si
.lpDesktop
= NULL
;
3116 si
.dwFlags
= STARTF_USESHOWWINDOW
;
3118 * It's nicer to run a filter command in a minimized window, but in
3119 * Windows 95 this makes the command MUCH slower. We can't do it under
3120 * Win32s either as it stops the synchronous spawn workaround working.
3122 if ((options
& SHELL_DOOUT
) && !mch_windows95() && !gui_is_win32s())
3123 si
.wShowWindow
= SW_SHOWMINIMIZED
;
3125 si
.wShowWindow
= SW_SHOWNORMAL
;
3127 si
.lpReserved2
= NULL
;
3129 /* There is a strange error on Windows 95 when using "c:\\command.com".
3130 * When the "c:\\" is left out it works OK...? */
3132 && (STRNICMP(cmd
, "c:/command.com", 14) == 0
3133 || STRNICMP(cmd
, "c:\\command.com", 14) == 0))
3136 /* Now, run the command */
3137 CreateProcess(NULL
, /* Executable name */
3138 cmd
, /* Command to execute */
3139 NULL
, /* Process security attributes */
3140 NULL
, /* Thread security attributes */
3141 FALSE
, /* Inherit handles */
3142 CREATE_DEFAULT_ERROR_MODE
| /* Creation flags */
3144 NULL
, /* Environment */
3145 NULL
, /* Current directory */
3146 &si
, /* Startup information */
3147 &pi
); /* Process information */
3150 /* Wait for the command to terminate before continuing */
3151 if (g_PlatformId
!= VER_PLATFORM_WIN32s
)
3156 /* Keep updating the window while waiting for the shell to finish. */
3161 if (PeekMessage(&msg
, (HWND
)NULL
, 0, 0, PM_REMOVE
))
3163 TranslateMessage(&msg
);
3164 DispatchMessage(&msg
);
3166 if (WaitForSingleObject(pi
.hProcess
, delay
) != WAIT_TIMEOUT
)
3169 /* We start waiting for a very short time and then increase it, so
3170 * that we respond quickly when the process is quick, and don't
3171 * consume too much overhead when it's slow. */
3176 WaitForSingleObject(pi
.hProcess
, INFINITE
);
3179 /* Get the command exit code */
3180 GetExitCodeProcess(pi
.hProcess
, &ret
);
3185 * This ugly code is the only quick way of performing
3186 * a synchronous spawn under Win32s. Yuk.
3189 EnumWindows(win32ssynch_cb
, 0);
3190 old_num_windows
= num_windows
;
3195 EnumWindows(win32ssynch_cb
, 0);
3196 } while (num_windows
== old_num_windows
);
3200 /* Close the handles to the subprocess, so that it goes away */
3201 CloseHandle(pi
.hThread
);
3202 CloseHandle(pi
.hProcess
);
3204 /* Try to get input focus back. Doesn't always work though. */
3205 PostMessage(hwnd
, WM_SETFOCUS
, 0, 0);
3211 # define mch_system(c, o) system(c)
3216 * Either execute a command by calling the shell or start a new shell
3221 int options
) /* SHELL_*, see vim.h */
3224 int tmode
= cur_tmode
;
3226 char szShellTitle
[512];
3228 /* Change the title to reflect that we are in a subshell. */
3229 if (GetConsoleTitle(szShellTitle
, sizeof(szShellTitle
) - 4) > 0)
3232 strcat(szShellTitle
, " :sh");
3235 strcat(szShellTitle
, " - !");
3236 if ((strlen(szShellTitle
) + strlen(cmd
) < sizeof(szShellTitle
)))
3237 strcat(szShellTitle
, cmd
);
3239 mch_settitle(szShellTitle
, NULL
);
3245 #ifdef MCH_WRITE_DUMP
3248 fprintf(fdDump
, "mch_call_shell(\"%s\", %d)\n", cmd
, options
);
3254 * Catch all deadly signals while running the external command, because a
3255 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3257 signal(SIGINT
, SIG_IGN
);
3258 #if defined(__GNUC__) && !defined(__MINGW32__)
3259 signal(SIGKILL
, SIG_IGN
);
3261 signal(SIGBREAK
, SIG_IGN
);
3263 signal(SIGILL
, SIG_IGN
);
3264 signal(SIGFPE
, SIG_IGN
);
3265 signal(SIGSEGV
, SIG_IGN
);
3266 signal(SIGTERM
, SIG_IGN
);
3267 signal(SIGABRT
, SIG_IGN
);
3269 if (options
& SHELL_COOKED
)
3270 settmode(TMODE_COOK
); /* set to normal mode */
3274 x
= mch_system(p_sh
, options
);
3278 /* we use "command" or "cmd" to start the shell; slow but easy */
3281 newcmd
= lalloc((long_u
) (
3283 STRLEN(vimrun_path
) +
3285 STRLEN(p_sh
) + STRLEN(p_shcf
) + STRLEN(cmd
) + 10), TRUE
);
3288 char_u
*cmdbase
= (*cmd
== '"' ? cmd
+ 1 : cmd
);
3290 if ((STRNICMP(cmdbase
, "start", 5) == 0) && vim_iswhite(cmdbase
[5]))
3293 PROCESS_INFORMATION pi
;
3296 si
.lpReserved
= NULL
;
3297 si
.lpDesktop
= NULL
;
3301 si
.lpReserved2
= NULL
;
3303 cmdbase
= skipwhite(cmdbase
+ 5);
3304 if ((STRNICMP(cmdbase
, "/min", 4) == 0)
3305 && vim_iswhite(cmdbase
[4]))
3307 cmdbase
= skipwhite(cmdbase
+ 4);
3308 si
.dwFlags
= STARTF_USESHOWWINDOW
;
3309 si
.wShowWindow
= SW_SHOWMINNOACTIVE
;
3312 /* When the command is in double quotes, but 'shellxquote' is
3313 * empty, keep the double quotes around the command.
3314 * Otherwise remove the double quotes, they aren't needed
3315 * here, because we don't use a shell to run the command. */
3316 if (*cmd
== '"' && *p_sxq
== NUL
)
3319 STRCPY(newcmd
+ 1, cmdbase
);
3323 STRCPY(newcmd
, cmdbase
);
3324 if (*cmd
== '"' && *newcmd
!= NUL
)
3325 newcmd
[STRLEN(newcmd
) - 1] = NUL
;
3329 * Now, start the command as a process, so that it doesn't
3330 * inherit our handles which causes unpleasant dangling swap
3331 * files if we exit before the spawned process
3333 if (CreateProcess (NULL
, // Executable name
3334 newcmd
, // Command to execute
3335 NULL
, // Process security attributes
3336 NULL
, // Thread security attributes
3337 FALSE
, // Inherit handles
3338 CREATE_NEW_CONSOLE
, // Creation flags
3339 NULL
, // Environment
3340 NULL
, // Current directory
3341 &si
, // Startup information
3342 &pi
)) // Process information
3348 EMSG(_("E371: Command not found"));
3351 /* Close the handles to the subprocess, so that it goes away */
3352 CloseHandle(pi
.hThread
);
3353 CloseHandle(pi
.hProcess
);
3357 #if defined(FEAT_GUI_W32)
3358 if (need_vimrun_warning
)
3361 _("VIMRUN.EXE not found in your $PATH.\n"
3362 "External commands will not pause after completion.\n"
3363 "See :help win32-vimrun for more information."),
3366 need_vimrun_warning
= FALSE
;
3368 if (!s_dont_use_vimrun
)
3369 /* Use vimrun to execute the command. It opens a console
3370 * window, which can be closed without killing Vim. */
3371 sprintf((char *)newcmd
, "%s%s%s %s %s",
3373 (msg_silent
!= 0 || (options
& SHELL_DOOUT
))
3378 sprintf((char *)newcmd
, "%s %s %s", p_sh
, p_shcf
, cmd
);
3379 x
= mch_system((char *)newcmd
, options
);
3385 if (tmode
== TMODE_RAW
)
3386 settmode(TMODE_RAW
); /* set to raw mode */
3388 /* Print the return value, unless "vimrun" was used. */
3389 if (x
!= 0 && !(options
& SHELL_SILENT
) && !emsg_silent
3390 #if defined(FEAT_GUI_W32)
3391 && ((options
& SHELL_DOOUT
) || s_dont_use_vimrun
)
3395 smsg(_("shell returned %d"), x
);
3402 signal(SIGINT
, SIG_DFL
);
3403 #if defined(__GNUC__) && !defined(__MINGW32__)
3404 signal(SIGKILL
, SIG_DFL
);
3406 signal(SIGBREAK
, SIG_DFL
);
3408 signal(SIGILL
, SIG_DFL
);
3409 signal(SIGFPE
, SIG_DFL
);
3410 signal(SIGSEGV
, SIG_DFL
);
3411 signal(SIGTERM
, SIG_DFL
);
3412 signal(SIGABRT
, SIG_DFL
);
3418 #ifndef FEAT_GUI_W32
3421 * Start termcap mode
3424 termcap_mode_start(void)
3431 SaveConsoleBuffer(&g_cbNonTermcap
);
3433 if (g_cbTermcap
.IsValid
)
3436 * We've been in termcap mode before. Restore certain screen
3437 * characteristics, including the buffer size and the window
3438 * size. Since we will be redrawing the screen, we don't need
3439 * to restore the actual contents of the buffer.
3441 RestoreConsoleBuffer(&g_cbTermcap
, FALSE
);
3442 SetConsoleWindowInfo(g_hConOut
, TRUE
, &g_cbTermcap
.Info
.srWindow
);
3443 Rows
= g_cbTermcap
.Info
.dwSize
.Y
;
3444 Columns
= g_cbTermcap
.Info
.dwSize
.X
;
3449 * This is our first time entering termcap mode. Clear the console
3450 * screen buffer, and resize the buffer to match the current window
3451 * size. We will use this as the size of our editing environment.
3453 ClearConsoleBuffer(g_attrCurrent
);
3454 ResizeConBufAndWindow(g_hConOut
, Columns
, Rows
);
3461 GetConsoleMode(g_hConIn
, &cmodein
);
3464 cmodein
|= ENABLE_MOUSE_INPUT
;
3466 cmodein
&= ~ENABLE_MOUSE_INPUT
;
3468 cmodein
|= ENABLE_WINDOW_INPUT
;
3469 SetConsoleMode(g_hConIn
, cmodein
);
3471 redraw_later_clear();
3472 g_fTermcapMode
= TRUE
;
3480 termcap_mode_end(void)
3487 if (!g_fTermcapMode
)
3490 SaveConsoleBuffer(&g_cbTermcap
);
3492 GetConsoleMode(g_hConIn
, &cmodein
);
3493 cmodein
&= ~(ENABLE_MOUSE_INPUT
| ENABLE_WINDOW_INPUT
);
3494 SetConsoleMode(g_hConIn
, cmodein
);
3496 #ifdef FEAT_RESTORE_ORIG_SCREEN
3497 cb
= exiting
? &g_cbOrig
: &g_cbNonTermcap
;
3499 cb
= &g_cbNonTermcap
;
3501 RestoreConsoleBuffer(cb
, p_rs
);
3502 SetConsoleCursorInfo(g_hConOut
, &g_cci
);
3504 if (p_rs
|| exiting
)
3507 * Clear anything that happens to be on the current line.
3510 coord
.Y
= (SHORT
) (p_rs
? cb
->Info
.dwCursorPosition
.Y
: (Rows
- 1));
3511 FillConsoleOutputCharacter(g_hConOut
, ' ',
3512 cb
->Info
.dwSize
.X
, coord
, &dwDummy
);
3514 * The following is just for aesthetics. If we are exiting without
3515 * restoring the screen, then we want to have a prompt string
3516 * appear at the bottom line. However, the command interpreter
3517 * seems to always advance the cursor one line before displaying
3518 * the prompt string, which causes the screen to scroll. To
3519 * counter this, move the cursor up one line before exiting.
3521 if (exiting
&& !p_rs
)
3524 * Position the cursor at the leftmost column of the desired row.
3526 SetConsoleCursorPosition(g_hConOut
, coord
);
3529 g_fTermcapMode
= FALSE
;
3531 #endif /* FEAT_GUI_W32 */
3547 * clear `n' chars, starting from `coord'
3556 FillConsoleOutputCharacter(g_hConOut
, ' ', n
, coord
, &dwDummy
);
3557 FillConsoleOutputAttribute(g_hConOut
, g_attrCurrent
, n
, coord
, &dwDummy
);
3567 g_coord
.X
= g_coord
.Y
= 0;
3568 clear_chars(g_coord
, Rows
* Columns
);
3573 * Clear to end of display
3576 clear_to_end_of_display(void)
3578 clear_chars(g_coord
, (Rows
- g_coord
.Y
- 1)
3579 * Columns
+ (Columns
- g_coord
.X
));
3584 * Clear to end of line
3587 clear_to_end_of_line(void)
3589 clear_chars(g_coord
, Columns
- g_coord
.X
);
3594 * Scroll the scroll region up by `cLines' lines
3597 scroll(unsigned cLines
)
3599 COORD oldcoord
= g_coord
;
3601 gotoxy(g_srScrollRegion
.Left
+ 1, g_srScrollRegion
.Top
+ 1);
3602 delete_lines(cLines
);
3609 * Set the scroll region
3620 || right
> (unsigned) Columns
- 1
3621 || bottom
> (unsigned) Rows
- 1)
3624 g_srScrollRegion
.Left
= left
;
3625 g_srScrollRegion
.Top
= top
;
3626 g_srScrollRegion
.Right
= right
;
3627 g_srScrollRegion
.Bottom
= bottom
;
3632 * Insert `cLines' lines at the current cursor position
3635 insert_lines(unsigned cLines
)
3642 dest
.Y
= g_coord
.Y
+ cLines
;
3645 source
.Top
= g_coord
.Y
;
3646 source
.Right
= g_srScrollRegion
.Right
;
3647 source
.Bottom
= g_srScrollRegion
.Bottom
- cLines
;
3649 fill
.Char
.AsciiChar
= ' ';
3650 fill
.Attributes
= g_attrCurrent
;
3652 ScrollConsoleScreenBuffer(g_hConOut
, &source
, NULL
, dest
, &fill
);
3654 /* Here we have to deal with a win32 console flake: If the scroll
3655 * region looks like abc and we scroll c to a and fill with d we get
3656 * cbd... if we scroll block c one line at a time to a, we get cdd...
3657 * vim expects cdd consistently... So we have to deal with that
3658 * here... (this also occurs scrolling the same way in the other
3661 if (source
.Bottom
< dest
.Y
)
3666 coord
.Y
= source
.Bottom
;
3667 clear_chars(coord
, Columns
* (dest
.Y
- source
.Bottom
));
3673 * Delete `cLines' lines at the current cursor position
3676 delete_lines(unsigned cLines
)
3687 source
.Top
= g_coord
.Y
+ cLines
;
3688 source
.Right
= g_srScrollRegion
.Right
;
3689 source
.Bottom
= g_srScrollRegion
.Bottom
;
3691 fill
.Char
.AsciiChar
= ' ';
3692 fill
.Attributes
= g_attrCurrent
;
3694 ScrollConsoleScreenBuffer(g_hConOut
, &source
, NULL
, dest
, &fill
);
3696 /* Here we have to deal with a win32 console flake: If the scroll
3697 * region looks like abc and we scroll c to a and fill with d we get
3698 * cbd... if we scroll block c one line at a time to a, we get cdd...
3699 * vim expects cdd consistently... So we have to deal with that
3700 * here... (this also occurs scrolling the same way in the other
3703 nb
= dest
.Y
+ (source
.Bottom
- source
.Top
) + 1;
3705 if (nb
< source
.Top
)
3711 clear_chars(coord
, Columns
* (source
.Top
- nb
));
3717 * Set the cursor position
3724 if (x
< 1 || x
> (unsigned)Columns
|| y
< 1 || y
> (unsigned)Rows
)
3727 /* external cursor coords are 1-based; internal are 0-based */
3730 SetConsoleCursorPosition(g_hConOut
, g_coord
);
3735 * Set the current text attribute = (foreground | background)
3736 * See ../doc/os_win32.txt for the numbers.
3739 textattr(WORD wAttr
)
3741 g_attrCurrent
= wAttr
;
3743 SetConsoleTextAttribute(g_hConOut
, wAttr
);
3748 textcolor(WORD wAttr
)
3750 g_attrCurrent
= (g_attrCurrent
& 0xf0) + wAttr
;
3752 SetConsoleTextAttribute(g_hConOut
, g_attrCurrent
);
3757 textbackground(WORD wAttr
)
3759 g_attrCurrent
= (g_attrCurrent
& 0x0f) + (wAttr
<< 4);
3761 SetConsoleTextAttribute(g_hConOut
, g_attrCurrent
);
3766 * restore the default text attribute (whatever we started with)
3771 textattr(g_attrDefault
);
3775 static WORD g_attrPreStandout
= 0;
3778 * Make the text standout, by brightening it
3783 g_attrPreStandout
= g_attrCurrent
;
3784 textattr((WORD
) (g_attrCurrent
|FOREGROUND_INTENSITY
|BACKGROUND_INTENSITY
));
3789 * Turn off standout mode
3794 if (g_attrPreStandout
)
3796 textattr(g_attrPreStandout
);
3797 g_attrPreStandout
= 0;
3803 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
3806 mch_set_normal_colors(void)
3811 cterm_normal_fg_color
= (g_attrDefault
& 0xf) + 1;
3812 cterm_normal_bg_color
= ((g_attrDefault
>> 4) & 0xf) + 1;
3813 if (T_ME
[0] == ESC
&& T_ME
[1] == '|')
3817 if (*p
== 'm' && n
> 0)
3819 cterm_normal_fg_color
= (n
& 0xf) + 1;
3820 cterm_normal_bg_color
= ((n
>> 4) & 0xf) + 1;
3827 * visual bell: flash the screen
3832 COORD coordOrigin
= {0, 0};
3833 WORD attrFlash
= ~g_attrCurrent
& 0xff;
3836 LPWORD oldattrs
= (LPWORD
)alloc(Rows
* Columns
* sizeof(WORD
));
3838 if (oldattrs
== NULL
)
3840 ReadConsoleOutputAttribute(g_hConOut
, oldattrs
, Rows
* Columns
,
3841 coordOrigin
, &dwDummy
);
3842 FillConsoleOutputAttribute(g_hConOut
, attrFlash
, Rows
* Columns
,
3843 coordOrigin
, &dwDummy
);
3845 Sleep(15); /* wait for 15 msec */
3846 WriteConsoleOutputAttribute(g_hConOut
, oldattrs
, Rows
* Columns
,
3847 coordOrigin
, &dwDummy
);
3853 * Make the cursor visible or invisible
3856 cursor_visible(BOOL fVisible
)
3858 s_cursor_visible
= fVisible
;
3859 #ifdef MCH_CURSOR_SHAPE
3860 mch_update_cursor();
3866 * write `cchToWrite' characters in `pchBuf' to the screen
3867 * Returns the number of characters actually written (at least one).
3874 COORD coord
= g_coord
;
3877 FillConsoleOutputAttribute(g_hConOut
, g_attrCurrent
, cchToWrite
,
3879 /* When writing fails or didn't write a single character, pretend one
3880 * character was written, otherwise we get stuck. */
3881 if (WriteConsoleOutputCharacter(g_hConOut
, pchBuf
, cchToWrite
,
3882 coord
, &written
) == 0
3886 g_coord
.X
+= (SHORT
) written
;
3888 while (g_coord
.X
> g_srScrollRegion
.Right
)
3890 g_coord
.X
-= (SHORT
) Columns
;
3891 if (g_coord
.Y
< g_srScrollRegion
.Bottom
)
3895 gotoxy(g_coord
.X
+ 1, g_coord
.Y
+ 1);
3902 * mch_write(): write the output buffer to the screen, translating ESC
3903 * sequences into calls to console output routines.
3914 write(1, s
, (unsigned)len
);
3918 /* translate ESC | sequences into faked bios calls */
3921 /* optimization: use one single write_chars for runs of text,
3922 * rather than once per character It ain't curses, but it helps. */
3923 DWORD prefix
= (DWORD
)strcspn(s
, "\n\r\b\a\033");
3936 nWritten
= write_chars(s
, prefix
);
3937 #ifdef MCH_WRITE_DUMP
3941 fwrite(s
, sizeof(char_u
), nWritten
, fdDump
);
3942 fputs("<\n", fdDump
);
3945 len
-= (nWritten
- 1);
3948 else if (s
[0] == '\n')
3950 /* \n, newline: go to the beginning of the next line or scroll */
3951 if (g_coord
.Y
== g_srScrollRegion
.Bottom
)
3954 gotoxy(g_srScrollRegion
.Left
+ 1, g_srScrollRegion
.Bottom
+ 1);
3958 gotoxy(g_srScrollRegion
.Left
+ 1, g_coord
.Y
+ 2);
3960 #ifdef MCH_WRITE_DUMP
3962 fputs("\\n\n", fdDump
);
3966 else if (s
[0] == '\r')
3968 /* \r, carriage return: go to beginning of line */
3969 gotoxy(g_srScrollRegion
.Left
+1, g_coord
.Y
+ 1);
3970 #ifdef MCH_WRITE_DUMP
3972 fputs("\\r\n", fdDump
);
3976 else if (s
[0] == '\b')
3978 /* \b, backspace: move cursor one position left */
3979 if (g_coord
.X
> g_srScrollRegion
.Left
)
3981 else if (g_coord
.Y
> g_srScrollRegion
.Top
)
3983 g_coord
.X
= g_srScrollRegion
.Right
;
3986 gotoxy(g_coord
.X
+ 1, g_coord
.Y
+ 1);
3987 #ifdef MCH_WRITE_DUMP
3989 fputs("\\b\n", fdDump
);
3993 else if (s
[0] == '\a')
3996 MessageBeep(0xFFFFFFFF);
3997 #ifdef MCH_WRITE_DUMP
3999 fputs("\\a\n", fdDump
);
4003 else if (s
[0] == ESC
&& len
>= 3-1 && s
[1] == '|')
4005 #ifdef MCH_WRITE_DUMP
4009 int arg1
= 0, arg2
= 0;
4013 /* one or two numeric arguments, separated by ';' */
4015 case '0': case '1': case '2': case '3': case '4':
4016 case '5': case '6': case '7': case '8': case '9':
4018 arg1
= getdigits(&p
); /* no check for length! */
4025 arg2
= getdigits(&p
); /* no check for length! */
4032 set_scroll_region(0, arg1
- 1, Columns
- 1, arg2
- 1);
4036 /* move cursor up arg1 lines in same column */
4037 gotoxy(g_coord
.X
+ 1,
4038 max(g_srScrollRegion
.Top
, g_coord
.Y
- arg1
) + 1);
4042 /* move cursor right arg1 columns in same line */
4043 gotoxy(min(g_srScrollRegion
.Right
, g_coord
.X
+ arg1
) + 1,
4059 textattr((WORD
) arg1
);
4063 textcolor((WORD
) arg1
);
4067 textbackground((WORD
) arg1
);
4074 len
-= (int)(p
- s
);
4079 /* Three-character escape sequences */
4082 /* move cursor up one line in same column */
4083 gotoxy(g_coord
.X
+ 1,
4084 max(g_srScrollRegion
.Top
, g_coord
.Y
- 1) + 1);
4092 /* move cursor right one column in same line */
4093 gotoxy(min(g_srScrollRegion
.Right
, g_coord
.X
+ 1) + 1,
4114 clear_to_end_of_display();
4122 clear_to_end_of_line();
4134 termcap_mode_start();
4138 cursor_visible(TRUE
);
4142 cursor_visible(FALSE
);
4150 #ifdef MCH_WRITE_DUMP
4153 fputs("ESC | ", fdDump
);
4154 fwrite(old_s
+ 2, sizeof(char_u
), s
- old_s
- 2, fdDump
);
4155 fputc('\n', fdDump
);
4161 /* Write a single character */
4164 nWritten
= write_chars(s
, 1);
4165 #ifdef MCH_WRITE_DUMP
4169 fwrite(s
, sizeof(char_u
), nWritten
, fdDump
);
4170 fputs("<\n", fdDump
);
4174 len
-= (nWritten
- 1);
4179 #ifdef MCH_WRITE_DUMP
4185 #endif /* FEAT_GUI_W32 */
4189 * Delay for half a second.
4198 Sleep((int)msec
); /* never wait for input */
4201 # ifdef FEAT_MZSCHEME
4202 if (mzthreads_allowed() && p_mzq
> 0 && msec
> p_mzq
)
4206 /* if msec is large enough, wait by portions in p_mzq */
4209 mzvim_check_threads();
4226 * this version of remove is not scared by a readonly (backup) file
4227 * Return 0 for success, -1 for failure.
4230 mch_remove(char_u
*name
)
4236 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4238 wn
= enc_to_ucs2(name
, NULL
);
4241 SetFileAttributesW(wn
, FILE_ATTRIBUTE_NORMAL
);
4242 n
= DeleteFileW(wn
) ? 0 : -1;
4244 if (n
== 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4246 /* Retry with non-wide function (for Windows 98). */
4250 SetFileAttributes(name
, FILE_ATTRIBUTE_NORMAL
);
4251 return DeleteFile(name
) ? 0 : -1;
4256 * check for an "interrupt signal": CTRL-break or CTRL-C
4259 mch_breakcheck(void)
4261 #ifndef FEAT_GUI_W32 /* never used */
4262 if (g_fCtrlCPressed
|| g_fCBrkPressed
)
4264 g_fCtrlCPressed
= g_fCBrkPressed
= FALSE
;
4272 * How much memory is available?
4273 * Return sum of available physical and page file memory.
4277 mch_avail_mem(int special
)
4281 ms
.dwLength
= sizeof(MEMORYSTATUS
);
4282 GlobalMemoryStatus(&ms
);
4283 return (long_u
) (ms
.dwAvailPhys
+ ms
.dwAvailPageFile
);
4288 * Same code as below, but with wide functions and no comments.
4289 * Return 0 for success, non-zero for failure.
4292 mch_wrename(WCHAR
*wold
, WCHAR
*wnew
)
4296 WCHAR szTempFile
[_MAX_PATH
+ 1];
4297 WCHAR szNewPath
[_MAX_PATH
+ 1];
4300 if (!mch_windows95())
4303 for (i
= 0; wold
[i
] != NUL
; ++i
)
4304 if ((wold
[i
] == '/' || wold
[i
] == '\\' || wold
[i
] == ':')
4305 && wold
[i
+ 1] != 0)
4307 if ((int)(wold
+ i
- p
) < 8 || p
[6] != '~')
4308 return (MoveFileW(wold
, wnew
) == 0);
4311 if (GetFullPathNameW(wnew
, _MAX_PATH
, szNewPath
, &p
) == 0 || p
== NULL
)
4315 if (GetTempFileNameW(szNewPath
, L
"VIM", 0, szTempFile
) == 0)
4318 if (!DeleteFileW(szTempFile
))
4321 if (!MoveFileW(wold
, szTempFile
))
4324 if ((hf
= CreateFileW(wold
, GENERIC_WRITE
, 0, NULL
, CREATE_NEW
,
4325 FILE_ATTRIBUTE_NORMAL
, NULL
)) == INVALID_HANDLE_VALUE
)
4327 if (!CloseHandle(hf
))
4330 if (!MoveFileW(szTempFile
, wnew
))
4332 (void)MoveFileW(szTempFile
, wold
);
4336 DeleteFileW(szTempFile
);
4338 if (!DeleteFileW(wold
))
4347 * mch_rename() works around a bug in rename (aka MoveFile) in
4348 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4349 * file whose short file name is "FOO.BAR" (its long file name will
4350 * be correct: "foo.bar~"). Because a file can be accessed by
4351 * either its SFN or its LFN, "foo.bar" has effectively been
4352 * renamed to "foo.bar", which is not at all what was wanted. This
4353 * seems to happen only when renaming files with three-character
4354 * extensions by appending a suffix that does not include ".".
4355 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4357 * There is another problem, which isn't really a bug but isn't right either:
4358 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
4359 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
4360 * service pack 6. Doesn't seem to happen on Windows 98.
4362 * Like rename(), returns 0 upon success, non-zero upon failure.
4363 * Should probably set errno appropriately when errors occur.
4367 const char *pszOldFile
,
4368 const char *pszNewFile
)
4370 char szTempFile
[_MAX_PATH
+1];
4371 char szNewPath
[_MAX_PATH
+1];
4379 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4381 wold
= enc_to_ucs2((char_u
*)pszOldFile
, NULL
);
4382 wnew
= enc_to_ucs2((char_u
*)pszNewFile
, NULL
);
4383 if (wold
!= NULL
&& wnew
!= NULL
)
4384 retval
= mch_wrename(wold
, wnew
);
4387 if (retval
== 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4389 /* Retry with non-wide function (for Windows 98). */
4394 * No need to play tricks if not running Windows 95, unless the file name
4395 * contains a "~" as the seventh character.
4397 if (!mch_windows95())
4399 pszFilePart
= (char *)gettail((char_u
*)pszOldFile
);
4400 if (STRLEN(pszFilePart
) < 8 || pszFilePart
[6] != '~')
4401 return rename(pszOldFile
, pszNewFile
);
4404 /* Get base path of new file name. Undocumented feature: If pszNewFile is
4405 * a directory, no error is returned and pszFilePart will be NULL. */
4406 if (GetFullPathName(pszNewFile
, _MAX_PATH
, szNewPath
, &pszFilePart
) == 0
4407 || pszFilePart
== NULL
)
4411 /* Get (and create) a unique temporary file name in directory of new file */
4412 if (GetTempFileName(szNewPath
, "VIM", 0, szTempFile
) == 0)
4415 /* blow the temp file away */
4416 if (!DeleteFile(szTempFile
))
4419 /* rename old file to the temp file */
4420 if (!MoveFile(pszOldFile
, szTempFile
))
4423 /* now create an empty file called pszOldFile; this prevents the operating
4424 * system using pszOldFile as an alias (SFN) if we're renaming within the
4425 * same directory. For example, we're editing a file called
4426 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
4427 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
4428 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
4429 * cause all sorts of problems later in buf_write(). So, we create an
4430 * empty file called filena~1.txt and the system will have to find some
4431 * other SFN for filena~1.txt~, such as filena~2.txt
4433 if ((hf
= CreateFile(pszOldFile
, GENERIC_WRITE
, 0, NULL
, CREATE_NEW
,
4434 FILE_ATTRIBUTE_NORMAL
, NULL
)) == INVALID_HANDLE_VALUE
)
4436 if (!CloseHandle(hf
))
4439 /* rename the temp file to the new file */
4440 if (!MoveFile(szTempFile
, pszNewFile
))
4442 /* Renaming failed. Rename the file back to its old name, so that it
4443 * looks like nothing happened. */
4444 (void)MoveFile(szTempFile
, pszOldFile
);
4449 /* Seems to be left around on Novell filesystems */
4450 DeleteFile(szTempFile
);
4452 /* finally, remove the empty old file */
4453 if (!DeleteFile(pszOldFile
))
4456 return 0; /* success */
4460 * Get the default shell for the current hardware platform
4469 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
) /* Windows NT */
4471 else if (g_PlatformId
== VER_PLATFORM_WIN32_WINDOWS
) /* Windows 95 */
4472 psz
= "command.com";
4478 * mch_access() extends access() to do more detailed check on network drives.
4479 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
4482 mch_access(char *n
, int p
)
4486 int retval
= -1; /* default: fail */
4490 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4491 wn
= enc_to_ucs2(n
, NULL
);
4496 char TempName
[_MAX_PATH
+ 16] = "";
4498 WCHAR TempNameW
[_MAX_PATH
+ 16] = L
"";
4503 /* Read check is performed by seeing if we can do a find file on
4504 * the directory for any file. */
4511 for (i
= 0; i
< _MAX_PATH
&& wn
[i
] != 0; ++i
)
4512 TempNameW
[i
] = wn
[i
];
4513 if (TempNameW
[i
- 1] != '\\' && TempNameW
[i
- 1] != '/')
4514 TempNameW
[i
++] = '\\';
4515 TempNameW
[i
++] = '*';
4518 hFile
= FindFirstFileW(TempNameW
, &d
);
4519 if (hFile
== INVALID_HANDLE_VALUE
)
4521 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4524 /* Retry with non-wide function (for Windows 98). */
4529 (void)FindClose(hFile
);
4537 vim_strncpy(TempName
, n
, _MAX_PATH
);
4538 pch
= TempName
+ STRLEN(TempName
) - 1;
4539 if (*pch
!= '\\' && *pch
!= '/')
4544 hFile
= FindFirstFile(TempName
, &d
);
4545 if (hFile
== INVALID_HANDLE_VALUE
)
4547 (void)FindClose(hFile
);
4553 /* Trying to create a temporary file in the directory should catch
4554 * directories on read-only network shares. However, in
4555 * directories whose ACL allows writes but denies deletes will end
4556 * up keeping the temporary file :-(. */
4560 if (!GetTempFileNameW(wn
, L
"VIM", 0, TempNameW
))
4562 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
4565 /* Retry with non-wide function (for Windows 98). */
4570 DeleteFileW(TempNameW
);
4575 if (!GetTempFileName(n
, "VIM", 0, TempName
))
4577 mch_remove((char_u
*)TempName
);
4583 /* Trying to open the file for the required access does ACL, read-only
4584 * network share, and file attribute checks. */
4585 am
= ((p
& W_OK
) ? GENERIC_WRITE
: 0)
4586 | ((p
& R_OK
) ? GENERIC_READ
: 0);
4590 hFile
= CreateFileW(wn
, am
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
4591 if (hFile
== INVALID_HANDLE_VALUE
4592 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
4594 /* Retry with non-wide function (for Windows 98). */
4601 hFile
= CreateFile(n
, am
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
4602 if (hFile
== INVALID_HANDLE_VALUE
)
4607 retval
= 0; /* success */
4615 #if defined(FEAT_MBYTE) || defined(PROTO)
4617 * Version of open() that may use ucs2 file name.
4620 mch_open(char *name
, int flags
, int mode
)
4622 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
4623 # ifndef __BORLANDC__
4627 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
4629 wn
= enc_to_ucs2(name
, NULL
);
4632 f
= _wopen(wn
, flags
, mode
);
4636 /* Retry with non-wide function (for Windows 98). Can't use
4637 * GetLastError() here and it's unclear what errno gets set to if
4638 * the _wopen() fails for missing wide functions. */
4643 return open(name
, flags
, mode
);
4647 * Version of fopen() that may use ucs2 file name.
4650 mch_fopen(char *name
, char *mode
)
4655 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
4656 # ifdef __BORLANDC__
4657 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4658 && g_PlatformId
== VER_PLATFORM_WIN32_NT
4662 wn
= enc_to_ucs2(name
, NULL
);
4663 wm
= enc_to_ucs2(mode
, NULL
);
4664 if (wn
!= NULL
&& wm
!= NULL
)
4665 f
= _wfopen(wn
, wm
);
4670 /* Retry with non-wide function (for Windows 98). Can't use
4671 * GetLastError() here and it's unclear what errno gets set to if
4672 * the _wfopen() fails for missing wide functions. */
4675 return fopen(name
, mode
);
4681 * SUB STREAM (aka info stream) handling:
4683 * NTFS can have sub streams for each file. Normal contents of file is
4684 * stored in the main stream, and extra contents (author information and
4685 * title and so on) can be stored in sub stream. After Windows 2000, user
4686 * can access and store those informations in sub streams via explorer's
4687 * property menuitem in right click menu. Those informations in sub streams
4688 * were lost when copying only the main stream. So we have to copy sub
4691 * Incomplete explanation:
4692 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
4693 * More useful info and an example:
4694 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
4698 * Copy info stream data "substream". Read from the file with BackupRead(sh)
4699 * and write to stream "substream" of file "to".
4700 * Errors are ignored.
4703 copy_substream(HANDLE sh
, void *context
, WCHAR
*to
, WCHAR
*substream
, long len
)
4708 to_name
= malloc((wcslen(to
) + wcslen(substream
) + 1) * sizeof(WCHAR
));
4709 wcscpy(to_name
, to
);
4710 wcscat(to_name
, substream
);
4712 hTo
= CreateFileW(to_name
, GENERIC_WRITE
, 0, NULL
, OPEN_ALWAYS
,
4713 FILE_ATTRIBUTE_NORMAL
, NULL
);
4714 if (hTo
!= INVALID_HANDLE_VALUE
)
4718 DWORD readcnt
, written
;
4721 /* Copy block of bytes at a time. Abort when something goes wrong. */
4722 for (done
= 0; done
< len
; done
+= written
)
4724 /* (size_t) cast for Borland C 5.5 */
4725 todo
= (DWORD
)((size_t)(len
- done
) > sizeof(buf
) ? sizeof(buf
)
4726 : (size_t)(len
- done
));
4727 if (!BackupRead(sh
, (LPBYTE
)buf
, todo
, &readcnt
,
4728 FALSE
, FALSE
, context
)
4730 || !WriteFile(hTo
, buf
, todo
, &written
, NULL
)
4741 * Copy info streams from file "from" to file "to".
4744 copy_infostreams(char_u
*from
, char_u
*to
)
4749 WIN32_STREAM_ID sid
;
4751 WCHAR streamname
[_MAX_PATH
];
4753 void *context
= NULL
;
4757 /* Convert the file names to wide characters. */
4758 fromw
= enc_to_ucs2(from
, NULL
);
4759 tow
= enc_to_ucs2(to
, NULL
);
4760 if (fromw
!= NULL
&& tow
!= NULL
)
4762 /* Open the file for reading. */
4763 sh
= CreateFileW(fromw
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
4764 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4765 if (sh
!= INVALID_HANDLE_VALUE
)
4767 /* Use BackupRead() to find the info streams. Repeat until we
4768 * have done them all.*/
4771 /* Get the header to find the length of the stream name. If
4772 * the "readcount" is zero we have done all info streams. */
4773 ZeroMemory(&sid
, sizeof(WIN32_STREAM_ID
));
4774 headersize
= (int)((char *)&sid
.cStreamName
- (char *)&sid
.dwStreamId
);
4775 if (!BackupRead(sh
, (LPBYTE
)&sid
, headersize
,
4776 &readcount
, FALSE
, FALSE
, &context
)
4780 /* We only deal with streams that have a name. The normal
4781 * file data appears to be without a name, even though docs
4782 * suggest it is called "::$DATA". */
4783 if (sid
.dwStreamNameSize
> 0)
4785 /* Read the stream name. */
4786 if (!BackupRead(sh
, (LPBYTE
)streamname
,
4787 sid
.dwStreamNameSize
,
4788 &readcount
, FALSE
, FALSE
, &context
))
4791 /* Copy an info stream with a name ":anything:$DATA".
4792 * Skip "::$DATA", it has no stream name (examples suggest
4793 * it might be used for the normal file contents).
4794 * Note that BackupRead() counts bytes, but the name is in
4795 * wide characters. */
4796 len
= readcount
/ sizeof(WCHAR
);
4797 streamname
[len
] = 0;
4798 if (len
> 7 && wcsicmp(streamname
+ len
- 6,
4801 streamname
[len
- 6] = 0;
4802 copy_substream(sh
, &context
, tow
, streamname
,
4803 (long)sid
.Size
.u
.LowPart
);
4807 /* Advance to the next stream. We might try seeking too far,
4808 * but BackupSeek() doesn't skip over stream borders, thus
4810 (void)BackupSeek(sh
, sid
.Size
.u
.LowPart
, sid
.Size
.u
.HighPart
,
4811 &lo
, &hi
, &context
);
4814 /* Clear the context. */
4815 (void)BackupRead(sh
, NULL
, 0, &readcount
, TRUE
, FALSE
, &context
);
4826 * Copy file attributes from file "from" to file "to".
4827 * For Windows NT and later we copy info streams.
4828 * Always returns zero, errors are ignored.
4831 mch_copy_file_attribute(char_u
*from
, char_u
*to
)
4834 /* File streams only work on Windows NT and later. */
4836 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
)
4837 copy_infostreams(from
, to
);
4842 #if defined(MYRESETSTKOFLW) || defined(PROTO)
4844 * Recreate a destroyed stack guard page in win32.
4845 * Written by Benjamin Peterson.
4848 /* These magic numbers are from the MS header files */
4849 #define MIN_STACK_WIN9X 17
4850 #define MIN_STACK_WINNT 2
4853 * This function does the same thing as _resetstkoflw(), which is only
4854 * available in DevStudio .net and later.
4855 * Returns 0 for failure, 1 for success.
4858 myresetstkoflw(void)
4863 BYTE
*pLowestPossiblePage
;
4864 MEMORY_BASIC_INFORMATION mbi
;
4869 /* This code will not work on win32s. */
4871 if (g_PlatformId
== VER_PLATFORM_WIN32s
)
4874 /* We need to know the system page size. */
4876 nPageSize
= si
.dwPageSize
;
4878 /* ...and the current stack pointer */
4879 pStackPtr
= (BYTE
*)_alloca(1);
4881 /* ...and the base of the stack. */
4882 if (VirtualQuery(pStackPtr
, &mbi
, sizeof mbi
) == 0)
4884 pStackBase
= (BYTE
*)mbi
.AllocationBase
;
4886 /* ...and the page thats min_stack_req pages away from stack base; this is
4887 * the lowest page we could use. */
4888 pLowestPossiblePage
= pStackBase
+ ((g_PlatformId
== VER_PLATFORM_WIN32_NT
)
4889 ? MIN_STACK_WINNT
: MIN_STACK_WIN9X
) * nPageSize
;
4891 /* On Win95, we want the next page down from the end of the stack. */
4892 if (g_PlatformId
== VER_PLATFORM_WIN32_WINDOWS
)
4894 /* Find the page that's only 1 page down from the page that the stack
4896 pGuardPage
= (BYTE
*)((DWORD
)nPageSize
* (((DWORD
)pStackPtr
4897 / (DWORD
)nPageSize
) - 1));
4898 if (pGuardPage
< pLowestPossiblePage
)
4901 /* Apply the noaccess attribute to the page -- there's no guard
4902 * attribute in win95-type OSes. */
4903 if (!VirtualProtect(pGuardPage
, nPageSize
, PAGE_NOACCESS
, &dummy
))
4908 /* On NT, however, we want the first committed page in the stack Start
4909 * at the stack base and move forward through memory until we find a
4910 * committed block. */
4911 BYTE
*pBlock
= pStackBase
;
4915 if (VirtualQuery(pBlock
, &mbi
, sizeof mbi
) == 0)
4918 pBlock
+= mbi
.RegionSize
;
4920 if (mbi
.State
& MEM_COMMIT
)
4924 /* mbi now describes the first committed block in the stack. */
4925 if (mbi
.Protect
& PAGE_GUARD
)
4928 /* decide where the guard page should start */
4929 if ((long_u
)(mbi
.BaseAddress
) < (long_u
)pLowestPossiblePage
)
4930 pGuardPage
= pLowestPossiblePage
;
4932 pGuardPage
= (BYTE
*)mbi
.BaseAddress
;
4934 /* allocate the guard page */
4935 if (!VirtualAlloc(pGuardPage
, nPageSize
, MEM_COMMIT
, PAGE_READWRITE
))
4938 /* apply the guard attribute to the page */
4939 if (!VirtualProtect(pGuardPage
, nPageSize
, PAGE_READWRITE
| PAGE_GUARD
,
4949 #if defined(FEAT_MBYTE) || defined(PROTO)
4951 * The command line arguments in UCS2
4953 static int nArgsW
= 0;
4954 static LPWSTR
*ArglistW
= NULL
;
4955 static int global_argc
= 0;
4956 static char **global_argv
;
4958 static int used_file_argc
= 0; /* last argument in global_argv[] used
4959 for the argument list. */
4960 static int *used_file_indexes
= NULL
; /* indexes in global_argv[] for
4961 command line arguments added to
4962 the argument list */
4963 static int used_file_count
= 0; /* nr of entries in used_file_indexes */
4964 static int used_file_literal
= FALSE
; /* take file names literally */
4965 static int used_file_full_path
= FALSE
; /* file name was full path */
4966 static int used_file_diff_mode
= FALSE
; /* file name was with diff mode */
4967 static int used_alist_count
= 0;
4971 * Get the command line arguments. Unicode version.
4972 * Returns argc. Zero when something fails.
4975 get_cmd_argsW(char ***argvp
)
4981 ArglistW
= CommandLineToArgvW(GetCommandLineW(), &nArgsW
);
4982 if (ArglistW
!= NULL
)
4984 argv
= malloc((nArgsW
+ 1) * sizeof(char *));
4989 for (i
= 0; i
< argc
; ++i
)
4993 /* Convert each Unicode argument to the current codepage. */
4994 WideCharToMultiByte_alloc(GetACP(), 0,
4995 ArglistW
[i
], (int)wcslen(ArglistW
[i
]) + 1,
4996 (LPSTR
*)&argv
[i
], &len
, 0, 0);
4997 if (argv
[i
] == NULL
)
4999 /* Out of memory, clear everything. */
5012 used_file_indexes
= malloc(argc
* sizeof(int));
5020 free_cmd_argsW(void)
5022 if (ArglistW
!= NULL
)
5024 GlobalFree(ArglistW
);
5030 * Remember "name" is an argument that was added to the argument list.
5031 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5035 used_file_arg(char *name
, int literal
, int full_path
, int diff_mode
)
5039 if (used_file_indexes
== NULL
)
5041 for (i
= used_file_argc
+ 1; i
< global_argc
; ++i
)
5042 if (STRCMP(global_argv
[i
], name
) == 0)
5045 used_file_indexes
[used_file_count
++] = i
;
5048 used_file_literal
= literal
;
5049 used_file_full_path
= full_path
;
5050 used_file_diff_mode
= diff_mode
;
5054 * Remember the length of the argument list as it was. If it changes then we
5055 * leave it alone when 'encoding' is set.
5058 set_alist_count(void)
5060 used_alist_count
= GARGCOUNT
;
5064 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5065 * has been changed while starting up. Use the UCS-2 command line arguments
5066 * and convert them to 'encoding'.
5077 * - if argument count differs between the wide and non-wide argument
5078 * list, something must be wrong.
5079 * - the file name arguments must have been located.
5080 * - the length of the argument list wasn't changed by the user.
5082 if (global_argc
!= nArgsW
5084 || used_file_indexes
== NULL
5085 || used_file_count
== 0
5086 || used_alist_count
!= GARGCOUNT
)
5089 /* Remember the buffer numbers for the arguments. */
5090 fnum_list
= (int *)alloc((int)sizeof(int) * GARGCOUNT
);
5091 if (fnum_list
== NULL
)
5092 return; /* out of memory */
5093 for (i
= 0; i
< GARGCOUNT
; ++i
)
5094 fnum_list
[i
] = GARGLIST
[i
].ae_fnum
;
5096 /* Clear the argument list. Make room for the new arguments. */
5097 alist_clear(&global_alist
);
5098 if (ga_grow(&global_alist
.al_ga
, used_file_count
) == FAIL
)
5099 return; /* out of memory */
5101 for (i
= 0; i
< used_file_count
; ++i
)
5103 idx
= used_file_indexes
[i
];
5104 str
= ucs2_to_enc(ArglistW
[idx
], NULL
);
5108 /* When using diff mode may need to concatenate file name to
5109 * directory name. Just like it's done in main(). */
5110 if (used_file_diff_mode
&& mch_isdir(str
) && GARGCOUNT
> 0
5111 && !mch_isdir(alist_name(&GARGLIST
[0])))
5115 r
= concat_fnames(str
, gettail(alist_name(&GARGLIST
[0])), TRUE
);
5123 /* Re-use the old buffer by renaming it. When not using literal
5124 * names it's done by alist_expand() below. */
5125 if (used_file_literal
)
5126 buf_set_name(fnum_list
[i
], str
);
5128 alist_add(&global_alist
, str
, used_file_literal
? 2 : 0);
5132 if (!used_file_literal
)
5134 /* Now expand wildcards in the arguments. */
5135 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5136 * filename characters but are excluded from 'isfname' to make
5137 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5138 do_cmdline_cmd((char_u
*)":let SaVe_ISF = &isf|set isf+=(,)");
5139 alist_expand(fnum_list
, used_alist_count
);
5140 do_cmdline_cmd((char_u
*)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5143 /* If wildcard expansion failed, we are editing the first file of the
5144 * arglist and there is no file name: Edit the first argument now. */
5145 if (curwin
->w_arg_idx
== 0 && curbuf
->b_fname
== NULL
)
5147 do_cmdline_cmd((char_u
*)":rewind");
5148 if (GARGCOUNT
== 1 && used_file_full_path
)
5149 (void)vim_chdirfile(alist_name(&GARGLIST
[0]));