blob: 3fdd41b6dba51827ae877e31479664bca6e08ea4 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
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".
14 *
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.
18 *
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.
21 */
22
Bram Moolenaar362e1a32006-03-06 23:29:24 +000023#include "vimio.h"
Bram Moolenaar071d4272004-06-13 20:20:40 +000024#include "vim.h"
25
Bram Moolenaar325b7a22004-07-05 15:58:32 +000026#ifdef FEAT_MZSCHEME
27# include "if_mzsch.h"
28#endif
29
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <sys/types.h>
31#include <errno.h>
32#include <signal.h>
33#include <limits.h>
34#include <process.h>
35
36#undef chdir
37#ifdef __GNUC__
38# ifndef __MINGW32__
39# include <dirent.h>
40# endif
41#else
42# include <direct.h>
43#endif
44
45#if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
46# include <shellapi.h>
47#endif
48
49#ifdef __MINGW32__
50# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
51# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
52# endif
53# ifndef RIGHTMOST_BUTTON_PRESSED
54# define RIGHTMOST_BUTTON_PRESSED 0x0002
55# endif
56# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
57# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
58# endif
59# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
60# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
61# endif
62# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
63# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
64# endif
65
66/*
67 * EventFlags
68 */
69# ifndef MOUSE_MOVED
70# define MOUSE_MOVED 0x0001
71# endif
72# ifndef DOUBLE_CLICK
73# define DOUBLE_CLICK 0x0002
74# endif
75#endif
76
77/* Record all output and all keyboard & mouse input */
78/* #define MCH_WRITE_DUMP */
79
80#ifdef MCH_WRITE_DUMP
81FILE* fdDump = NULL;
82#endif
83
84/*
85 * When generating prototypes for Win32 on Unix, these lines make the syntax
86 * errors disappear. They do not need to be correct.
87 */
88#ifdef PROTO
89#define WINAPI
90#define WINBASEAPI
91typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000092typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000093typedef int ACCESS_MASK;
94typedef int BOOL;
95typedef int COLORREF;
96typedef int CONSOLE_CURSOR_INFO;
97typedef int COORD;
98typedef int DWORD;
99typedef int HANDLE;
100typedef int HDC;
101typedef int HFONT;
102typedef int HICON;
103typedef int HINSTANCE;
104typedef int HWND;
105typedef int INPUT_RECORD;
106typedef int KEY_EVENT_RECORD;
107typedef int LOGFONT;
108typedef int LPBOOL;
109typedef int LPCTSTR;
110typedef int LPDWORD;
111typedef int LPSTR;
112typedef int LPTSTR;
113typedef int LPVOID;
114typedef int MOUSE_EVENT_RECORD;
115typedef int PACL;
116typedef int PDWORD;
117typedef int PHANDLE;
118typedef int PRINTDLG;
119typedef int PSECURITY_DESCRIPTOR;
120typedef int PSID;
121typedef int SECURITY_INFORMATION;
122typedef int SHORT;
123typedef int SMALL_RECT;
124typedef int TEXTMETRIC;
125typedef int TOKEN_INFORMATION_CLASS;
126typedef int TRUSTEE;
127typedef int WORD;
128typedef int WCHAR;
129typedef void VOID;
130#endif
131
132#ifndef FEAT_GUI_W32
133/* Undocumented API in kernel32.dll needed to work around dead key bug in
134 * console-mode applications in NT 4.0. If you switch keyboard layouts
135 * in a console app to a layout that includes dead keys and then hit a
136 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
137 * and Michael Dietrich for helping me figure out this workaround.
138 */
139
140/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
141#ifndef WINBASEAPI
142# define WINBASEAPI __stdcall
143#endif
144#if defined(__BORLANDC__)
145typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
146#else
147typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
148#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000149static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
152#if defined(__BORLANDC__)
153/* Strangely Borland uses a non-standard name. */
154# define wcsicmp(a, b) wcscmpi((a), (b))
155#endif
156
157#ifndef FEAT_GUI_W32
158/* Win32 Console handles for input and output */
159static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
160static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
161
162/* Win32 Screen buffer,coordinate,console I/O information */
163static SMALL_RECT g_srScrollRegion;
164static COORD g_coord; /* 0-based, but external coords are 1-based */
165
166/* The attribute of the screen when the editor was started */
167static WORD g_attrDefault = 7; /* lightgray text on black background */
168static WORD g_attrCurrent;
169
170static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
171static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
172static int g_fForceExit = FALSE; /* set when forcefully exiting */
173
174static void termcap_mode_start(void);
175static void termcap_mode_end(void);
176static void clear_chars(COORD coord, DWORD n);
177static void clear_screen(void);
178static void clear_to_end_of_display(void);
179static void clear_to_end_of_line(void);
180static void scroll(unsigned cLines);
181static void set_scroll_region(unsigned left, unsigned top,
182 unsigned right, unsigned bottom);
183static void insert_lines(unsigned cLines);
184static void delete_lines(unsigned cLines);
185static void gotoxy(unsigned x, unsigned y);
186static void normvideo(void);
187static void textattr(WORD wAttr);
188static void textcolor(WORD wAttr);
189static void textbackground(WORD wAttr);
190static void standout(void);
191static void standend(void);
192static void visual_bell(void);
193static void cursor_visible(BOOL fVisible);
194static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
195static char_u tgetch(int *pmodifiers, char_u *pch2);
196static void create_conin(void);
197static int s_cursor_visible = TRUE;
198static int did_create_conin = FALSE;
199#else
200static int s_dont_use_vimrun = TRUE;
201static int need_vimrun_warning = FALSE;
202static char *vimrun_path = "vimrun ";
203#endif
204
205#ifndef FEAT_GUI_W32
206static int suppress_winsize = 1; /* don't fiddle with console */
207#endif
208
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200209static char_u *exe_path = NULL;
210
Bram Moolenaar071d4272004-06-13 20:20:40 +0000211 static void
212get_exe_name(void)
213{
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200214 char temp[MAXPATHL];
215 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000216
217 if (exe_name == NULL)
218 {
219 /* store the name of the executable, may be used for $VIM */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200220 GetModuleFileName(NULL, temp, MAXPATHL - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000221 if (*temp != NUL)
222 exe_name = FullName_save((char_u *)temp, FALSE);
223 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000224
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200225 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000226 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200227 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
228 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000229 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200230 /* Append our starting directory to $PATH, so that when doing
231 * "!xxd" it's found in our starting directory. Needed because
232 * SearchPath() also looks there. */
233 p = mch_getenv("PATH");
Bram Moolenaar8bbe9932010-10-24 14:33:43 +0200234 if (STRLEN(p) + STRLEN(exe_path) + 2 < MAXPATHL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235 {
236 STRCPY(temp, p);
237 STRCAT(temp, ";");
238 STRCAT(temp, exe_path);
239 vim_setenv((char_u *)"PATH", temp);
240 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000241 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000242 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243}
244
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200245/*
246 * Load library "name".
247 */
248 HINSTANCE
249vimLoadLib(char *name)
250{
251 HINSTANCE dll = NULL;
252 char old_dir[MAXPATHL];
253
254 if (exe_path == NULL)
255 get_exe_name();
256 if (exe_path != NULL && mch_dirname(old_dir, MAXPATHL) == OK)
257 {
258 /* Change directory to where the executable is, both to make sure we
259 * find a .dll there and to avoid looking for a .dll in the current
260 * directory. */
261 mch_chdir(exe_path);
262 dll = LoadLibrary(name);
263 mch_chdir(old_dir);
264 }
265 return dll;
266}
267
Bram Moolenaar071d4272004-06-13 20:20:40 +0000268#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
269# ifndef GETTEXT_DLL
270# define GETTEXT_DLL "libintl.dll"
271# endif
272/* Dummy funcitons */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000273static char *null_libintl_gettext(const char *);
274static char *null_libintl_textdomain(const char *);
275static char *null_libintl_bindtextdomain(const char *, const char *);
276static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000277
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200278static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000279char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
280char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
281char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000282 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000283char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
284 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000285
286 int
287dyn_libintl_init(char *libname)
288{
289 int i;
290 static struct
291 {
292 char *name;
293 FARPROC *ptr;
294 } libintl_entry[] =
295 {
296 {"gettext", (FARPROC*)&dyn_libintl_gettext},
297 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
298 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
299 {NULL, NULL}
300 };
301
302 /* No need to initialize twice. */
303 if (hLibintlDLL)
304 return 1;
305 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200306 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000307 if (!hLibintlDLL)
308 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200309 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000310 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200311 verbose_enter();
312 EMSG2(_(e_loadlib), GETTEXT_DLL);
313 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000314 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200315 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000316 }
317 for (i = 0; libintl_entry[i].name != NULL
318 && libintl_entry[i].ptr != NULL; ++i)
319 {
320 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
321 libintl_entry[i].name)) == NULL)
322 {
323 dyn_libintl_end();
324 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000325 {
326 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000327 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000328 verbose_leave();
329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000330 return 0;
331 }
332 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000333
334 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000335 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000336 "bind_textdomain_codeset");
337 if (dyn_libintl_bind_textdomain_codeset == NULL)
338 dyn_libintl_bind_textdomain_codeset =
339 null_libintl_bind_textdomain_codeset;
340
Bram Moolenaar071d4272004-06-13 20:20:40 +0000341 return 1;
342}
343
344 void
345dyn_libintl_end()
346{
347 if (hLibintlDLL)
348 FreeLibrary(hLibintlDLL);
349 hLibintlDLL = NULL;
350 dyn_libintl_gettext = null_libintl_gettext;
351 dyn_libintl_textdomain = null_libintl_textdomain;
352 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000353 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000354}
355
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000356/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000357 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000358null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000359{
360 return (char*)msgid;
361}
362
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000363/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000364 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000365null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366{
367 return NULL;
368}
369
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000370/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000372null_libintl_bind_textdomain_codeset(const char *domainname,
373 const char *codeset)
374{
375 return NULL;
376}
377
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000378/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000379 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000380null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000381{
382 return NULL;
383}
384
385#endif /* DYNAMIC_GETTEXT */
386
387/* This symbol is not defined in older versions of the SDK or Visual C++ */
388
389#ifndef VER_PLATFORM_WIN32_WINDOWS
390# define VER_PLATFORM_WIN32_WINDOWS 1
391#endif
392
393DWORD g_PlatformId;
394
395#ifdef HAVE_ACL
396# include <aclapi.h>
397/*
398 * These are needed to dynamically load the ADVAPI DLL, which is not
399 * implemented under Windows 95 (and causes VIM to crash)
400 */
401typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
402 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
403typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
404 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
405 PSECURITY_DESCRIPTOR *);
406
407static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
408static PSNSECINFO pSetNamedSecurityInfo;
409static PGNSECINFO pGetNamedSecurityInfo;
410#endif
411
412/*
413 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
414 * VER_PLATFORM_WIN32_WINDOWS (Win95).
415 */
416 void
417PlatformId(void)
418{
419 static int done = FALSE;
420
421 if (!done)
422 {
423 OSVERSIONINFO ovi;
424
425 ovi.dwOSVersionInfoSize = sizeof(ovi);
426 GetVersionEx(&ovi);
427
428 g_PlatformId = ovi.dwPlatformId;
429
430#ifdef HAVE_ACL
431 /*
432 * Load the ADVAPI runtime if we are on anything
433 * other than Windows 95
434 */
435 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
436 {
437 /*
438 * do this load. Problems: Doesn't unload at end of run (this is
439 * theoretically okay, since Windows should unload it when VIM
440 * terminates). Should we be using the 'mch_libcall' routines?
441 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
442 * time we verify security...
443 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200444 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445 if (advapi_lib != NULL)
446 {
447 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
448 "SetNamedSecurityInfoA");
449 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
450 "GetNamedSecurityInfoA");
451 if (pSetNamedSecurityInfo == NULL
452 || pGetNamedSecurityInfo == NULL)
453 {
454 /* If we can't get the function addresses, set advapi_lib
455 * to NULL so that we don't use them. */
456 FreeLibrary(advapi_lib);
457 advapi_lib = NULL;
458 }
459 }
460 }
461#endif
462 done = TRUE;
463 }
464}
465
466/*
467 * Return TRUE when running on Windows 95 (or 98 or ME).
468 * Only to be used after mch_init().
469 */
470 int
471mch_windows95(void)
472{
473 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
474}
475
476#ifdef FEAT_GUI_W32
477/*
478 * Used to work around the "can't do synchronous spawn"
479 * problem on Win32s, without resorting to Universal Thunk.
480 */
481static int old_num_windows;
482static int num_windows;
483
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000484/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000485 static BOOL CALLBACK
486win32ssynch_cb(HWND hwnd, LPARAM lparam)
487{
488 num_windows++;
489 return TRUE;
490}
491#endif
492
493#ifndef FEAT_GUI_W32
494
495#define SHIFT (SHIFT_PRESSED)
496#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
497#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
498#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
499
500
501/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
502 * We map function keys to their ANSI terminal equivalents, as produced
503 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
504 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
505 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
506 * combinations of function/arrow/etc keys.
507 */
508
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000509static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510{
511 WORD wVirtKey;
512 BOOL fAnsiKey;
513 int chAlone;
514 int chShift;
515 int chCtrl;
516 int chAlt;
517} VirtKeyMap[] =
518{
519
520/* Key ANSI alone shift ctrl alt */
521 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
522
523 { VK_F1, TRUE, ';', 'T', '^', 'h', },
524 { VK_F2, TRUE, '<', 'U', '_', 'i', },
525 { VK_F3, TRUE, '=', 'V', '`', 'j', },
526 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
527 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
528 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
529 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
530 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
531 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
532 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
533 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
534 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
535
536 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
537 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
538 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
539 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
540 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
541 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
542 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
543 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
544 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
545 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
546
547 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
548
549#if 0
550 /* Most people don't have F13-F20, but what the hell... */
551 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
552 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
553 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
554 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
555 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
556 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
557 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
558 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
559#endif
560 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
561 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
562 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
563 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
564
565 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
566 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
567 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
568 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
569 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
570 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
571 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
572 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
573 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
574 /* Sorry, out of number space! <negri>*/
575 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
576
577};
578
579
580#ifdef _MSC_VER
581// The ToAscii bug destroys several registers. Need to turn off optimization
582// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000583# pragma warning(push)
584# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000585# pragma optimize("", off)
586#endif
587
588#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
589# define AChar AsciiChar
590#else
591# define AChar uChar.AsciiChar
592#endif
593
594/* The return code indicates key code size. */
595 static int
596#ifdef __BORLANDC__
597 __stdcall
598#endif
599win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000600 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601{
602 UINT uMods = pker->dwControlKeyState;
603 static int s_iIsDead = 0;
604 static WORD awAnsiCode[2];
605 static BYTE abKeystate[256];
606
607
608 if (s_iIsDead == 2)
609 {
610 pker->AChar = (CHAR) awAnsiCode[1];
611 s_iIsDead = 0;
612 return 1;
613 }
614
615 if (pker->AChar != 0)
616 return 1;
617
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200618 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619
620 // Should only be non-NULL on NT 4.0
621 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
622 {
623 CHAR szKLID[KL_NAMELENGTH];
624
625 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
626 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
627 }
628
629 /* Clear any pending dead keys */
630 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
631
632 if (uMods & SHIFT_PRESSED)
633 abKeystate[VK_SHIFT] = 0x80;
634 if (uMods & CAPSLOCK_ON)
635 abKeystate[VK_CAPITAL] = 1;
636
637 if ((uMods & ALT_GR) == ALT_GR)
638 {
639 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
640 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
641 }
642
643 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
644 abKeystate, awAnsiCode, 0);
645
646 if (s_iIsDead > 0)
647 pker->AChar = (CHAR) awAnsiCode[0];
648
649 return s_iIsDead;
650}
651
652#ifdef _MSC_VER
653/* MUST switch optimization on again here, otherwise a call to
654 * decode_key_event() may crash (e.g. when hitting caps-lock) */
655# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000656# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657
658# if (_MSC_VER < 1100)
659/* MUST turn off global optimisation for this next function, or
660 * pressing ctrl-minus in insert mode crashes Vim when built with
661 * VC4.1. -- negri. */
662# pragma optimize("g", off)
663# endif
664#endif
665
666static BOOL g_fJustGotFocus = FALSE;
667
668/*
669 * Decode a KEY_EVENT into one or two keystrokes
670 */
671 static BOOL
672decode_key_event(
673 KEY_EVENT_RECORD *pker,
674 char_u *pch,
675 char_u *pch2,
676 int *pmodifiers,
677 BOOL fDoPost)
678{
679 int i;
680 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
681
682 *pch = *pch2 = NUL;
683 g_fJustGotFocus = FALSE;
684
685 /* ignore key up events */
686 if (!pker->bKeyDown)
687 return FALSE;
688
689 /* ignore some keystrokes */
690 switch (pker->wVirtualKeyCode)
691 {
692 /* modifiers */
693 case VK_SHIFT:
694 case VK_CONTROL:
695 case VK_MENU: /* Alt key */
696 return FALSE;
697
698 default:
699 break;
700 }
701
702 /* special cases */
703 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
704 {
705 /* Ctrl-6 is Ctrl-^ */
706 if (pker->wVirtualKeyCode == '6')
707 {
708 *pch = Ctrl_HAT;
709 return TRUE;
710 }
711 /* Ctrl-2 is Ctrl-@ */
712 else if (pker->wVirtualKeyCode == '2')
713 {
714 *pch = NUL;
715 return TRUE;
716 }
717 /* Ctrl-- is Ctrl-_ */
718 else if (pker->wVirtualKeyCode == 0xBD)
719 {
720 *pch = Ctrl__;
721 return TRUE;
722 }
723 }
724
725 /* Shift-TAB */
726 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
727 {
728 *pch = K_NUL;
729 *pch2 = '\017';
730 return TRUE;
731 }
732
733 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
734 {
735 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
736 {
737 if (nModifs == 0)
738 *pch = VirtKeyMap[i].chAlone;
739 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
740 *pch = VirtKeyMap[i].chShift;
741 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
742 *pch = VirtKeyMap[i].chCtrl;
743 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
744 *pch = VirtKeyMap[i].chAlt;
745
746 if (*pch != 0)
747 {
748 if (VirtKeyMap[i].fAnsiKey)
749 {
750 *pch2 = *pch;
751 *pch = K_NUL;
752 }
753
754 return TRUE;
755 }
756 }
757 }
758
759 i = win32_kbd_patch_key(pker);
760
761 if (i < 0)
762 *pch = NUL;
763 else
764 {
765 *pch = (i > 0) ? pker->AChar : NUL;
766
767 if (pmodifiers != NULL)
768 {
769 /* Pass on the ALT key as a modifier, but only when not combined
770 * with CTRL (which is ALTGR). */
771 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
772 *pmodifiers |= MOD_MASK_ALT;
773
774 /* Pass on SHIFT only for special keys, because we don't know when
775 * it's already included with the character. */
776 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
777 *pmodifiers |= MOD_MASK_SHIFT;
778
779 /* Pass on CTRL only for non-special keys, because we don't know
780 * when it's already included with the character. And not when
781 * combined with ALT (which is ALTGR). */
782 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
783 && *pch >= 0x20 && *pch < 0x80)
784 *pmodifiers |= MOD_MASK_CTRL;
785 }
786 }
787
788 return (*pch != NUL);
789}
790
791#ifdef _MSC_VER
792# pragma optimize("", on)
793#endif
794
795#endif /* FEAT_GUI_W32 */
796
797
798#ifdef FEAT_MOUSE
799
800/*
801 * For the GUI the mouse handling is in gui_w32.c.
802 */
803# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000804/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000806mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000807{
808}
809# else
810static int g_fMouseAvail = FALSE; /* mouse present */
811static int g_fMouseActive = FALSE; /* mouse enabled */
812static int g_nMouseClick = -1; /* mouse status */
813static int g_xMouse; /* mouse x coordinate */
814static int g_yMouse; /* mouse y coordinate */
815
816/*
817 * Enable or disable mouse input
818 */
819 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000820mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821{
822 DWORD cmodein;
823
824 if (!g_fMouseAvail)
825 return;
826
827 g_fMouseActive = on;
828 GetConsoleMode(g_hConIn, &cmodein);
829
830 if (g_fMouseActive)
831 cmodein |= ENABLE_MOUSE_INPUT;
832 else
833 cmodein &= ~ENABLE_MOUSE_INPUT;
834
835 SetConsoleMode(g_hConIn, cmodein);
836}
837
838
839/*
840 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
841 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
842 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
843 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
844 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
845 * and we return the mouse position in g_xMouse and g_yMouse.
846 *
847 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
848 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
849 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
850 *
851 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
852 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
853 *
854 * Windows will send us MOUSE_MOVED notifications whenever the mouse
855 * moves, even if it stays within the same character cell. We ignore
856 * all MOUSE_MOVED messages if the position hasn't really changed, and
857 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
858 * we're only interested in MOUSE_DRAG).
859 *
860 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
861 * 2-button mouses by pressing the left & right buttons simultaneously.
862 * In practice, it's almost impossible to click both at the same time,
863 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
864 * in such cases, if the user is clicking quickly.
865 */
866 static BOOL
867decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000868 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869{
870 static int s_nOldButton = -1;
871 static int s_nOldMouseClick = -1;
872 static int s_xOldMouse = -1;
873 static int s_yOldMouse = -1;
874 static linenr_T s_old_topline = 0;
875#ifdef FEAT_DIFF
876 static int s_old_topfill = 0;
877#endif
878 static int s_cClicks = 1;
879 static BOOL s_fReleased = TRUE;
880 static DWORD s_dwLastClickTime = 0;
881 static BOOL s_fNextIsMiddle = FALSE;
882
883 static DWORD cButtons = 0; /* number of buttons supported */
884
885 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
886 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
887 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
888 const DWORD LEFT_RIGHT = LEFT | RIGHT;
889
890 int nButton;
891
892 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
893 cButtons = 2;
894
895 if (!g_fMouseAvail || !g_fMouseActive)
896 {
897 g_nMouseClick = -1;
898 return FALSE;
899 }
900
901 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
902 if (g_fJustGotFocus)
903 {
904 g_fJustGotFocus = FALSE;
905 return FALSE;
906 }
907
908 /* unprocessed mouse click? */
909 if (g_nMouseClick != -1)
910 return TRUE;
911
912 nButton = -1;
913 g_xMouse = pmer->dwMousePosition.X;
914 g_yMouse = pmer->dwMousePosition.Y;
915
916 if (pmer->dwEventFlags == MOUSE_MOVED)
917 {
918 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
919 * events even when the mouse moves only within a char cell.) */
920 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
921 return FALSE;
922 }
923
924 /* If no buttons are pressed... */
925 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
926 {
927 /* If the last thing returned was MOUSE_RELEASE, ignore this */
928 if (s_fReleased)
929 return FALSE;
930
931 nButton = MOUSE_RELEASE;
932 s_fReleased = TRUE;
933 }
934 else /* one or more buttons pressed */
935 {
936 /* on a 2-button mouse, hold down left and right buttons
937 * simultaneously to get MIDDLE. */
938
939 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
940 {
941 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
942
943 /* if either left or right button only is pressed, see if the
944 * the next mouse event has both of them pressed */
945 if (dwLR == LEFT || dwLR == RIGHT)
946 {
947 for (;;)
948 {
949 /* wait a short time for next input event */
950 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
951 != WAIT_OBJECT_0)
952 break;
953 else
954 {
955 DWORD cRecords = 0;
956 INPUT_RECORD ir;
957 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
958
959 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
960
961 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
962 || !(pmer2->dwButtonState & LEFT_RIGHT))
963 break;
964 else
965 {
966 if (pmer2->dwEventFlags != MOUSE_MOVED)
967 {
968 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
969
970 return decode_mouse_event(pmer2);
971 }
972 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
973 s_yOldMouse == pmer2->dwMousePosition.Y)
974 {
975 /* throw away spurious mouse move */
976 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
977
978 /* are there any more mouse events in queue? */
979 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
980
981 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
982 break;
983 }
984 else
985 break;
986 }
987 }
988 }
989 }
990 }
991
992 if (s_fNextIsMiddle)
993 {
994 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
995 ? MOUSE_DRAG : MOUSE_MIDDLE;
996 s_fNextIsMiddle = FALSE;
997 }
998 else if (cButtons == 2 &&
999 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1000 {
1001 nButton = MOUSE_MIDDLE;
1002
1003 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1004 {
1005 s_fNextIsMiddle = TRUE;
1006 nButton = MOUSE_RELEASE;
1007 }
1008 }
1009 else if ((pmer->dwButtonState & LEFT) == LEFT)
1010 nButton = MOUSE_LEFT;
1011 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1012 nButton = MOUSE_MIDDLE;
1013 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1014 nButton = MOUSE_RIGHT;
1015
1016 if (! s_fReleased && ! s_fNextIsMiddle
1017 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1018 return FALSE;
1019
1020 s_fReleased = s_fNextIsMiddle;
1021 }
1022
1023 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1024 {
1025 /* button pressed or released, without mouse moving */
1026 if (nButton != -1 && nButton != MOUSE_RELEASE)
1027 {
1028 DWORD dwCurrentTime = GetTickCount();
1029
1030 if (s_xOldMouse != g_xMouse
1031 || s_yOldMouse != g_yMouse
1032 || s_nOldButton != nButton
1033 || s_old_topline != curwin->w_topline
1034#ifdef FEAT_DIFF
1035 || s_old_topfill != curwin->w_topfill
1036#endif
1037 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1038 {
1039 s_cClicks = 1;
1040 }
1041 else if (++s_cClicks > 4)
1042 {
1043 s_cClicks = 1;
1044 }
1045
1046 s_dwLastClickTime = dwCurrentTime;
1047 }
1048 }
1049 else if (pmer->dwEventFlags == MOUSE_MOVED)
1050 {
1051 if (nButton != -1 && nButton != MOUSE_RELEASE)
1052 nButton = MOUSE_DRAG;
1053
1054 s_cClicks = 1;
1055 }
1056
1057 if (nButton == -1)
1058 return FALSE;
1059
1060 if (nButton != MOUSE_RELEASE)
1061 s_nOldButton = nButton;
1062
1063 g_nMouseClick = nButton;
1064
1065 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1066 g_nMouseClick |= MOUSE_SHIFT;
1067 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1068 g_nMouseClick |= MOUSE_CTRL;
1069 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1070 g_nMouseClick |= MOUSE_ALT;
1071
1072 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1073 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1074
1075 /* only pass on interesting (i.e., different) mouse events */
1076 if (s_xOldMouse == g_xMouse
1077 && s_yOldMouse == g_yMouse
1078 && s_nOldMouseClick == g_nMouseClick)
1079 {
1080 g_nMouseClick = -1;
1081 return FALSE;
1082 }
1083
1084 s_xOldMouse = g_xMouse;
1085 s_yOldMouse = g_yMouse;
1086 s_old_topline = curwin->w_topline;
1087#ifdef FEAT_DIFF
1088 s_old_topfill = curwin->w_topfill;
1089#endif
1090 s_nOldMouseClick = g_nMouseClick;
1091
1092 return TRUE;
1093}
1094
1095# endif /* FEAT_GUI_W32 */
1096#endif /* FEAT_MOUSE */
1097
1098
1099#ifdef MCH_CURSOR_SHAPE
1100/*
1101 * Set the shape of the cursor.
1102 * 'thickness' can be from 1 (thin) to 99 (block)
1103 */
1104 static void
1105mch_set_cursor_shape(int thickness)
1106{
1107 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1108 ConsoleCursorInfo.dwSize = thickness;
1109 ConsoleCursorInfo.bVisible = s_cursor_visible;
1110
1111 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1112 if (s_cursor_visible)
1113 SetConsoleCursorPosition(g_hConOut, g_coord);
1114}
1115
1116 void
1117mch_update_cursor(void)
1118{
1119 int idx;
1120 int thickness;
1121
1122 /*
1123 * How the cursor is drawn depends on the current mode.
1124 */
1125 idx = get_shape_idx(FALSE);
1126
1127 if (shape_table[idx].shape == SHAPE_BLOCK)
1128 thickness = 99; /* 100 doesn't work on W95 */
1129 else
1130 thickness = shape_table[idx].percentage;
1131 mch_set_cursor_shape(thickness);
1132}
1133#endif
1134
1135#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1136/*
1137 * Handle FOCUS_EVENT.
1138 */
1139 static void
1140handle_focus_event(INPUT_RECORD ir)
1141{
1142 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1143 ui_focus_change((int)g_fJustGotFocus);
1144}
1145
1146/*
1147 * Wait until console input from keyboard or mouse is available,
1148 * or the time is up.
1149 * Return TRUE if something is available FALSE if not.
1150 */
1151 static int
1152WaitForChar(long msec)
1153{
1154 DWORD dwNow = 0, dwEndTime = 0;
1155 INPUT_RECORD ir;
1156 DWORD cRecords;
1157 char_u ch, ch2;
1158
1159 if (msec > 0)
1160 /* Wait until the specified time has elapsed. */
1161 dwEndTime = GetTickCount() + msec;
1162 else if (msec < 0)
1163 /* Wait forever. */
1164 dwEndTime = INFINITE;
1165
1166 /* We need to loop until the end of the time period, because
1167 * we might get multiple unusable mouse events in that time.
1168 */
1169 for (;;)
1170 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001171#ifdef FEAT_MZSCHEME
1172 mzvim_check_threads();
1173#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001174#ifdef FEAT_CLIENTSERVER
1175 serverProcessPendingMessages();
1176#endif
1177 if (0
1178#ifdef FEAT_MOUSE
1179 || g_nMouseClick != -1
1180#endif
1181#ifdef FEAT_CLIENTSERVER
1182 || input_available()
1183#endif
1184 )
1185 return TRUE;
1186
1187 if (msec > 0)
1188 {
1189 /* If the specified wait time has passed, return. */
1190 dwNow = GetTickCount();
1191 if (dwNow >= dwEndTime)
1192 break;
1193 }
1194 if (msec != 0)
1195 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001196 DWORD dwWaitTime = dwEndTime - dwNow;
1197
1198#ifdef FEAT_MZSCHEME
1199 if (mzthreads_allowed() && p_mzq > 0
1200 && (msec < 0 || (long)dwWaitTime > p_mzq))
1201 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1202#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203#ifdef FEAT_CLIENTSERVER
1204 /* Wait for either an event on the console input or a message in
1205 * the client-server window. */
1206 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001207 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001208#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001209 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210#endif
1211 continue;
1212 }
1213
1214 cRecords = 0;
1215 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1216
1217#ifdef FEAT_MBYTE_IME
1218 if (State & CMDLINE && msg_row == Rows - 1)
1219 {
1220 CONSOLE_SCREEN_BUFFER_INFO csbi;
1221
1222 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1223 {
1224 if (csbi.dwCursorPosition.Y != msg_row)
1225 {
1226 /* The screen is now messed up, must redraw the
1227 * command line and later all the windows. */
1228 redraw_all_later(CLEAR);
1229 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1230 redrawcmd();
1231 }
1232 }
1233 }
1234#endif
1235
1236 if (cRecords > 0)
1237 {
1238 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1239 {
1240#ifdef FEAT_MBYTE_IME
1241 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1242 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1243 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1244 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1245 {
1246 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1247 continue;
1248 }
1249#endif
1250 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1251 NULL, FALSE))
1252 return TRUE;
1253 }
1254
1255 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1256
1257 if (ir.EventType == FOCUS_EVENT)
1258 handle_focus_event(ir);
1259 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1260 shell_resized();
1261#ifdef FEAT_MOUSE
1262 else if (ir.EventType == MOUSE_EVENT
1263 && decode_mouse_event(&ir.Event.MouseEvent))
1264 return TRUE;
1265#endif
1266 }
1267 else if (msec == 0)
1268 break;
1269 }
1270
1271#ifdef FEAT_CLIENTSERVER
1272 /* Something might have been received while we were waiting. */
1273 if (input_available())
1274 return TRUE;
1275#endif
1276 return FALSE;
1277}
1278
1279#ifndef FEAT_GUI_MSWIN
1280/*
1281 * return non-zero if a character is available
1282 */
1283 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001284mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285{
1286 return WaitForChar(0L);
1287}
1288#endif
1289
1290/*
1291 * Create the console input. Used when reading stdin doesn't work.
1292 */
1293 static void
1294create_conin(void)
1295{
1296 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1297 FILE_SHARE_READ|FILE_SHARE_WRITE,
1298 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001299 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001300 did_create_conin = TRUE;
1301}
1302
1303/*
1304 * Get a keystroke or a mouse event
1305 */
1306 static char_u
1307tgetch(int *pmodifiers, char_u *pch2)
1308{
1309 char_u ch;
1310
1311 for (;;)
1312 {
1313 INPUT_RECORD ir;
1314 DWORD cRecords = 0;
1315
1316#ifdef FEAT_CLIENTSERVER
1317 (void)WaitForChar(-1L);
1318 if (input_available())
1319 return 0;
1320# ifdef FEAT_MOUSE
1321 if (g_nMouseClick != -1)
1322 return 0;
1323# endif
1324#endif
1325 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1326 {
1327 if (did_create_conin)
1328 read_error_exit();
1329 create_conin();
1330 continue;
1331 }
1332
1333 if (ir.EventType == KEY_EVENT)
1334 {
1335 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1336 pmodifiers, TRUE))
1337 return ch;
1338 }
1339 else if (ir.EventType == FOCUS_EVENT)
1340 handle_focus_event(ir);
1341 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1342 shell_resized();
1343#ifdef FEAT_MOUSE
1344 else if (ir.EventType == MOUSE_EVENT)
1345 {
1346 if (decode_mouse_event(&ir.Event.MouseEvent))
1347 return 0;
1348 }
1349#endif
1350 }
1351}
1352#endif /* !FEAT_GUI_W32 */
1353
1354
1355/*
1356 * mch_inchar(): low-level input funcion.
1357 * Get one or more characters from the keyboard or the mouse.
1358 * If time == 0, do not wait for characters.
1359 * If time == n, wait a short time for characters.
1360 * If time == -1, wait forever for characters.
1361 * Returns the number of characters read into buf.
1362 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001363/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 int
1365mch_inchar(
1366 char_u *buf,
1367 int maxlen,
1368 long time,
1369 int tb_change_cnt)
1370{
1371#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1372
1373 int len;
1374 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001375#define TYPEAHEADLEN 20
1376 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1377 static int typeaheadlen = 0;
1378
1379 /* First use any typeahead that was kept because "buf" was too small. */
1380 if (typeaheadlen > 0)
1381 goto theend;
1382
1383#ifdef FEAT_SNIFF
1384 if (want_sniff_request)
1385 {
1386 if (sniff_request_waiting)
1387 {
1388 /* return K_SNIFF */
1389 typeahead[typeaheadlen++] = CSI;
1390 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1391 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1392 sniff_request_waiting = 0;
1393 want_sniff_request = 0;
1394 goto theend;
1395 }
1396 else if (time < 0 || time > 250)
1397 {
1398 /* don't wait too long, a request might be pending */
1399 time = 250;
1400 }
1401 }
1402#endif
1403
1404 if (time >= 0)
1405 {
1406 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001407 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408 }
1409 else /* time == -1, wait forever */
1410 {
1411 mch_set_winsize_now(); /* Allow winsize changes from now on */
1412
Bram Moolenaar3918c952005-03-15 22:34:55 +00001413 /*
1414 * If there is no character available within 2 seconds (default)
1415 * write the autoscript file to disk. Or cause the CursorHold event
1416 * to be triggered.
1417 */
1418 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001419 {
1420#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001421 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001422 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001423 buf[0] = K_SPECIAL;
1424 buf[1] = KS_EXTRA;
1425 buf[2] = (int)KE_CURSORHOLD;
1426 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427 }
1428#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001429 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430 }
1431 }
1432
1433 /*
1434 * Try to read as many characters as there are, until the buffer is full.
1435 */
1436
1437 /* we will get at least one key. Get more if they are available. */
1438 g_fCBrkPressed = FALSE;
1439
1440#ifdef MCH_WRITE_DUMP
1441 if (fdDump)
1442 fputc('[', fdDump);
1443#endif
1444
1445 /* Keep looping until there is something in the typeahead buffer and more
1446 * to get and still room in the buffer (up to two bytes for a char and
1447 * three bytes for a modifier). */
1448 while ((typeaheadlen == 0 || WaitForChar(0L))
1449 && typeaheadlen + 5 <= TYPEAHEADLEN)
1450 {
1451 if (typebuf_changed(tb_change_cnt))
1452 {
1453 /* "buf" may be invalid now if a client put something in the
1454 * typeahead buffer and "buf" is in the typeahead buffer. */
1455 typeaheadlen = 0;
1456 break;
1457 }
1458#ifdef FEAT_MOUSE
1459 if (g_nMouseClick != -1)
1460 {
1461# ifdef MCH_WRITE_DUMP
1462 if (fdDump)
1463 fprintf(fdDump, "{%02x @ %d, %d}",
1464 g_nMouseClick, g_xMouse, g_yMouse);
1465# endif
1466 typeahead[typeaheadlen++] = ESC + 128;
1467 typeahead[typeaheadlen++] = 'M';
1468 typeahead[typeaheadlen++] = g_nMouseClick;
1469 typeahead[typeaheadlen++] = g_xMouse + '!';
1470 typeahead[typeaheadlen++] = g_yMouse + '!';
1471 g_nMouseClick = -1;
1472 }
1473 else
1474#endif
1475 {
1476 char_u ch2 = NUL;
1477 int modifiers = 0;
1478
1479 c = tgetch(&modifiers, &ch2);
1480
1481 if (typebuf_changed(tb_change_cnt))
1482 {
1483 /* "buf" may be invalid now if a client put something in the
1484 * typeahead buffer and "buf" is in the typeahead buffer. */
1485 typeaheadlen = 0;
1486 break;
1487 }
1488
1489 if (c == Ctrl_C && ctrl_c_interrupts)
1490 {
1491#if defined(FEAT_CLIENTSERVER)
1492 trash_input_buf();
1493#endif
1494 got_int = TRUE;
1495 }
1496
1497#ifdef FEAT_MOUSE
1498 if (g_nMouseClick == -1)
1499#endif
1500 {
1501 int n = 1;
1502
1503 /* A key may have one or two bytes. */
1504 typeahead[typeaheadlen] = c;
1505 if (ch2 != NUL)
1506 {
1507 typeahead[typeaheadlen + 1] = ch2;
1508 ++n;
1509 }
1510#ifdef FEAT_MBYTE
1511 /* Only convert normal characters, not special keys. Need to
1512 * convert before applying ALT, otherwise mapping <M-x> breaks
1513 * when 'tenc' is set. */
1514 if (input_conv.vc_type != CONV_NONE
1515 && (ch2 == NUL || c != K_NUL))
1516 n = convert_input(typeahead + typeaheadlen, n,
1517 TYPEAHEADLEN - typeaheadlen);
1518#endif
1519
1520 /* Use the ALT key to set the 8th bit of the character
1521 * when it's one byte, the 8th bit isn't set yet and not
1522 * using a double-byte encoding (would become a lead
1523 * byte). */
1524 if ((modifiers & MOD_MASK_ALT)
1525 && n == 1
1526 && (typeahead[typeaheadlen] & 0x80) == 0
1527#ifdef FEAT_MBYTE
1528 && !enc_dbcs
1529#endif
1530 )
1531 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001532#ifdef FEAT_MBYTE
1533 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1534 typeahead + typeaheadlen);
1535#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001537#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538 modifiers &= ~MOD_MASK_ALT;
1539 }
1540
1541 if (modifiers != 0)
1542 {
1543 /* Prepend modifiers to the character. */
1544 mch_memmove(typeahead + typeaheadlen + 3,
1545 typeahead + typeaheadlen, n);
1546 typeahead[typeaheadlen++] = K_SPECIAL;
1547 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1548 typeahead[typeaheadlen++] = modifiers;
1549 }
1550
1551 typeaheadlen += n;
1552
1553#ifdef MCH_WRITE_DUMP
1554 if (fdDump)
1555 fputc(c, fdDump);
1556#endif
1557 }
1558 }
1559 }
1560
1561#ifdef MCH_WRITE_DUMP
1562 if (fdDump)
1563 {
1564 fputs("]\n", fdDump);
1565 fflush(fdDump);
1566 }
1567#endif
1568
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569theend:
1570 /* Move typeahead to "buf", as much as fits. */
1571 len = 0;
1572 while (len < maxlen && typeaheadlen > 0)
1573 {
1574 buf[len++] = typeahead[0];
1575 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1576 }
1577 return len;
1578
1579#else /* FEAT_GUI_W32 */
1580 return 0;
1581#endif /* FEAT_GUI_W32 */
1582}
1583
1584#ifndef __MINGW32__
1585# include <shellapi.h> /* required for FindExecutable() */
1586#endif
1587
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001588/*
1589 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001590 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001591 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 static int
1593executable_exists(char *name)
1594{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001595 char *dum;
1596 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001598#ifdef FEAT_MBYTE
1599 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001601 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001602 WCHAR fnamew[_MAX_PATH];
1603 WCHAR *dumw;
1604 long n;
1605
1606 if (p != NULL)
1607 {
1608 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1609 vim_free(p);
1610 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1611 {
1612 if (n == 0)
1613 return FALSE;
1614 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1615 return FALSE;
1616 return TRUE;
1617 }
1618 /* Retry with non-wide function (for Windows 98). */
1619 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001621#endif
1622 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1623 return FALSE;
1624 if (mch_isdir(fname))
1625 return FALSE;
1626 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627}
1628
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001629#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
1630 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
1631/*
1632 * Bad parameter handler.
1633 *
1634 * Certain MS CRT functions will intentionally crash when passed invalid
1635 * parameters to highlight possible security holes. Setting this function as
1636 * the bad parameter handler will prevent the crash.
1637 *
1638 * In debug builds the parameters contain CRT information that might help track
1639 * down the source of a problem, but in non-debug builds the arguments are all
1640 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1641 * worth allowing these to make debugging of issues easier.
1642 */
1643 static void
1644bad_param_handler(const wchar_t *expression,
1645 const wchar_t *function,
1646 const wchar_t *file,
1647 unsigned int line,
1648 uintptr_t pReserved)
1649{
1650}
1651
1652# define SET_INVALID_PARAM_HANDLER \
1653 ((void)_set_invalid_parameter_handler(bad_param_handler))
1654#else
1655# define SET_INVALID_PARAM_HANDLER
1656#endif
1657
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658#ifdef FEAT_GUI_W32
1659
1660/*
1661 * GUI version of mch_init().
1662 */
1663 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001664mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665{
1666#ifndef __MINGW32__
1667 extern int _fmode;
1668#endif
1669
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001670 /* Silently handle invalid parameters to CRT functions */
1671 SET_INVALID_PARAM_HANDLER;
1672
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673 /* Let critical errors result in a failure, not in a dialog box. Required
1674 * for the timestamp test to work on removed floppies. */
1675 SetErrorMode(SEM_FAILCRITICALERRORS);
1676
1677 _fmode = O_BINARY; /* we do our own CR-LF translation */
1678
1679 /* Specify window size. Is there a place to get the default from? */
1680 Rows = 25;
1681 Columns = 80;
1682
1683 /* Look for 'vimrun' */
1684 if (!gui_is_win32s())
1685 {
1686 char_u vimrun_location[_MAX_PATH + 4];
1687
1688 /* First try in same directory as gvim.exe */
1689 STRCPY(vimrun_location, exe_name);
1690 STRCPY(gettail(vimrun_location), "vimrun.exe");
1691 if (mch_getperm(vimrun_location) >= 0)
1692 {
1693 if (*skiptowhite(vimrun_location) != NUL)
1694 {
1695 /* Enclose path with white space in double quotes. */
1696 mch_memmove(vimrun_location + 1, vimrun_location,
1697 STRLEN(vimrun_location) + 1);
1698 *vimrun_location = '"';
1699 STRCPY(gettail(vimrun_location), "vimrun\" ");
1700 }
1701 else
1702 STRCPY(gettail(vimrun_location), "vimrun ");
1703
1704 vimrun_path = (char *)vim_strsave(vimrun_location);
1705 s_dont_use_vimrun = FALSE;
1706 }
1707 else if (executable_exists("vimrun.exe"))
1708 s_dont_use_vimrun = FALSE;
1709
1710 /* Don't give the warning for a missing vimrun.exe right now, but only
1711 * when vimrun was supposed to be used. Don't bother people that do
1712 * not need vimrun.exe. */
1713 if (s_dont_use_vimrun)
1714 need_vimrun_warning = TRUE;
1715 }
1716
1717 /*
1718 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1719 * Otherwise the default "findstr /n" is used.
1720 */
1721 if (!executable_exists("findstr.exe"))
1722 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1723
1724#ifdef FEAT_CLIPBOARD
1725 clip_init(TRUE);
1726
1727 /*
Bram Moolenaar7528dd62007-05-06 12:32:12 +00001728 * Vim's own clipboard format recognises whether the text is char, line,
1729 * or rectangular block. Only useful for copying between two Vims.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 * "VimClipboard" was used for previous versions, using the first
1731 * character to specify MCHAR, MLINE or MBLOCK.
1732 */
1733 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1734 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1735#endif
1736}
1737
1738
1739#else /* FEAT_GUI_W32 */
1740
1741#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1742#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1743
1744/*
1745 * ClearConsoleBuffer()
1746 * Description:
1747 * Clears the entire contents of the console screen buffer, using the
1748 * specified attribute.
1749 * Returns:
1750 * TRUE on success
1751 */
1752 static BOOL
1753ClearConsoleBuffer(WORD wAttribute)
1754{
1755 CONSOLE_SCREEN_BUFFER_INFO csbi;
1756 COORD coord;
1757 DWORD NumCells, dummy;
1758
1759 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1760 return FALSE;
1761
1762 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1763 coord.X = 0;
1764 coord.Y = 0;
1765 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1766 coord, &dummy))
1767 {
1768 return FALSE;
1769 }
1770 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1771 coord, &dummy))
1772 {
1773 return FALSE;
1774 }
1775
1776 return TRUE;
1777}
1778
1779/*
1780 * FitConsoleWindow()
1781 * Description:
1782 * Checks if the console window will fit within given buffer dimensions.
1783 * Also, if requested, will shrink the window to fit.
1784 * Returns:
1785 * TRUE on success
1786 */
1787 static BOOL
1788FitConsoleWindow(
1789 COORD dwBufferSize,
1790 BOOL WantAdjust)
1791{
1792 CONSOLE_SCREEN_BUFFER_INFO csbi;
1793 COORD dwWindowSize;
1794 BOOL NeedAdjust = FALSE;
1795
1796 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1797 {
1798 /*
1799 * A buffer resize will fail if the current console window does
1800 * not lie completely within that buffer. To avoid this, we might
1801 * have to move and possibly shrink the window.
1802 */
1803 if (csbi.srWindow.Right >= dwBufferSize.X)
1804 {
1805 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1806 if (dwWindowSize.X > dwBufferSize.X)
1807 dwWindowSize.X = dwBufferSize.X;
1808 csbi.srWindow.Right = dwBufferSize.X - 1;
1809 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1810 NeedAdjust = TRUE;
1811 }
1812 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1813 {
1814 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1815 if (dwWindowSize.Y > dwBufferSize.Y)
1816 dwWindowSize.Y = dwBufferSize.Y;
1817 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1818 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1819 NeedAdjust = TRUE;
1820 }
1821 if (NeedAdjust && WantAdjust)
1822 {
1823 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1824 return FALSE;
1825 }
1826 return TRUE;
1827 }
1828
1829 return FALSE;
1830}
1831
1832typedef struct ConsoleBufferStruct
1833{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001834 BOOL IsValid;
1835 CONSOLE_SCREEN_BUFFER_INFO Info;
1836 PCHAR_INFO Buffer;
1837 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838} ConsoleBuffer;
1839
1840/*
1841 * SaveConsoleBuffer()
1842 * Description:
1843 * Saves important information about the console buffer, including the
1844 * actual buffer contents. The saved information is suitable for later
1845 * restoration by RestoreConsoleBuffer().
1846 * Returns:
1847 * TRUE if all information was saved; FALSE otherwise
1848 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1849 */
1850 static BOOL
1851SaveConsoleBuffer(
1852 ConsoleBuffer *cb)
1853{
1854 DWORD NumCells;
1855 COORD BufferCoord;
1856 SMALL_RECT ReadRegion;
1857 WORD Y, Y_incr;
1858
1859 if (cb == NULL)
1860 return FALSE;
1861
1862 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1863 {
1864 cb->IsValid = FALSE;
1865 return FALSE;
1866 }
1867 cb->IsValid = TRUE;
1868
1869 /*
1870 * Allocate a buffer large enough to hold the entire console screen
1871 * buffer. If this ConsoleBuffer structure has already been initialized
1872 * with a buffer of the correct size, then just use that one.
1873 */
1874 if (!cb->IsValid || cb->Buffer == NULL ||
1875 cb->BufferSize.X != cb->Info.dwSize.X ||
1876 cb->BufferSize.Y != cb->Info.dwSize.Y)
1877 {
1878 cb->BufferSize.X = cb->Info.dwSize.X;
1879 cb->BufferSize.Y = cb->Info.dwSize.Y;
1880 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
1881 if (cb->Buffer != NULL)
1882 vim_free(cb->Buffer);
1883 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
1884 if (cb->Buffer == NULL)
1885 return FALSE;
1886 }
1887
1888 /*
1889 * We will now copy the console screen buffer into our buffer.
1890 * ReadConsoleOutput() seems to be limited as far as how much you
1891 * can read at a time. Empirically, this number seems to be about
1892 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1893 * in chunks until it is all copied. The chunks will all have the
1894 * same horizontal characteristics, so initialize them now. The
1895 * height of each chunk will be (12000 / width).
1896 */
1897 BufferCoord.X = 0;
1898 ReadRegion.Left = 0;
1899 ReadRegion.Right = cb->Info.dwSize.X - 1;
1900 Y_incr = 12000 / cb->Info.dwSize.X;
1901 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
1902 {
1903 /*
1904 * Read into position (0, Y) in our buffer.
1905 */
1906 BufferCoord.Y = Y;
1907 /*
1908 * Read the region whose top left corner is (0, Y) and whose bottom
1909 * right corner is (width - 1, Y + Y_incr - 1). This should define
1910 * a region of size width by Y_incr. Don't worry if this region is
1911 * too large for the remaining buffer; it will be cropped.
1912 */
1913 ReadRegion.Top = Y;
1914 ReadRegion.Bottom = Y + Y_incr - 1;
1915 if (!ReadConsoleOutput(g_hConOut, /* output handle */
1916 cb->Buffer, /* our buffer */
1917 cb->BufferSize, /* dimensions of our buffer */
1918 BufferCoord, /* offset in our buffer */
1919 &ReadRegion)) /* region to save */
1920 {
1921 vim_free(cb->Buffer);
1922 cb->Buffer = NULL;
1923 return FALSE;
1924 }
1925 }
1926
1927 return TRUE;
1928}
1929
1930/*
1931 * RestoreConsoleBuffer()
1932 * Description:
1933 * Restores important information about the console buffer, including the
1934 * actual buffer contents, if desired. The information to restore is in
1935 * the same format used by SaveConsoleBuffer().
1936 * Returns:
1937 * TRUE on success
1938 */
1939 static BOOL
1940RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001941 ConsoleBuffer *cb,
1942 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001943{
1944 COORD BufferCoord;
1945 SMALL_RECT WriteRegion;
1946
1947 if (cb == NULL || !cb->IsValid)
1948 return FALSE;
1949
1950 /*
1951 * Before restoring the buffer contents, clear the current buffer, and
1952 * restore the cursor position and window information. Doing this now
1953 * prevents old buffer contents from "flashing" onto the screen.
1954 */
1955 if (RestoreScreen)
1956 ClearConsoleBuffer(cb->Info.wAttributes);
1957
1958 FitConsoleWindow(cb->Info.dwSize, TRUE);
1959 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
1960 return FALSE;
1961 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
1962 return FALSE;
1963
1964 if (!RestoreScreen)
1965 {
1966 /*
1967 * No need to restore the screen buffer contents, so we're done.
1968 */
1969 return TRUE;
1970 }
1971
1972 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
1973 return FALSE;
1974 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
1975 return FALSE;
1976
1977 /*
1978 * Restore the screen buffer contents.
1979 */
1980 if (cb->Buffer != NULL)
1981 {
1982 BufferCoord.X = 0;
1983 BufferCoord.Y = 0;
1984 WriteRegion.Left = 0;
1985 WriteRegion.Top = 0;
1986 WriteRegion.Right = cb->Info.dwSize.X - 1;
1987 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
1988 if (!WriteConsoleOutput(g_hConOut, /* output handle */
1989 cb->Buffer, /* our buffer */
1990 cb->BufferSize, /* dimensions of our buffer */
1991 BufferCoord, /* offset in our buffer */
1992 &WriteRegion)) /* region to restore */
1993 {
1994 return FALSE;
1995 }
1996 }
1997
1998 return TRUE;
1999}
2000
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002001#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002#ifdef FEAT_RESTORE_ORIG_SCREEN
2003static ConsoleBuffer g_cbOrig = { 0 };
2004#endif
2005static ConsoleBuffer g_cbNonTermcap = { 0 };
2006static ConsoleBuffer g_cbTermcap = { 0 };
2007
2008#ifdef FEAT_TITLE
2009#ifdef __BORLANDC__
2010typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2011#else
2012typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2013#endif
2014char g_szOrigTitle[256] = { 0 };
2015HWND g_hWnd = NULL; /* also used in os_mswin.c */
2016static HICON g_hOrigIconSmall = NULL;
2017static HICON g_hOrigIcon = NULL;
2018static HICON g_hVimIcon = NULL;
2019static BOOL g_fCanChangeIcon = FALSE;
2020
2021/* ICON* are not defined in VC++ 4.0 */
2022#ifndef ICON_SMALL
2023#define ICON_SMALL 0
2024#endif
2025#ifndef ICON_BIG
2026#define ICON_BIG 1
2027#endif
2028/*
2029 * GetConsoleIcon()
2030 * Description:
2031 * Attempts to retrieve the small icon and/or the big icon currently in
2032 * use by a given window.
2033 * Returns:
2034 * TRUE on success
2035 */
2036 static BOOL
2037GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002038 HWND hWnd,
2039 HICON *phIconSmall,
2040 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041{
2042 if (hWnd == NULL)
2043 return FALSE;
2044
2045 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002046 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2047 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002049 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2050 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051 return TRUE;
2052}
2053
2054/*
2055 * SetConsoleIcon()
2056 * Description:
2057 * Attempts to change the small icon and/or the big icon currently in
2058 * use by a given window.
2059 * Returns:
2060 * TRUE on success
2061 */
2062 static BOOL
2063SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002064 HWND hWnd,
2065 HICON hIconSmall,
2066 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002068 HICON hPrevIconSmall;
2069 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070
2071 if (hWnd == NULL)
2072 return FALSE;
2073
2074 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002075 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2076 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002078 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2079 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 return TRUE;
2081}
2082
2083/*
2084 * SaveConsoleTitleAndIcon()
2085 * Description:
2086 * Saves the current console window title in g_szOrigTitle, for later
2087 * restoration. Also, attempts to obtain a handle to the console window,
2088 * and use it to save the small and big icons currently in use by the
2089 * console window. This is not always possible on some versions of Windows;
2090 * nor is it possible when running Vim remotely using Telnet (since the
2091 * console window the user sees is owned by a remote process).
2092 */
2093 static void
2094SaveConsoleTitleAndIcon(void)
2095{
2096 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2097
2098 /* Save the original title. */
2099 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2100 return;
2101
2102 /*
2103 * Obtain a handle to the console window using GetConsoleWindow() from
2104 * KERNEL32.DLL; we need to handle in order to change the window icon.
2105 * This function only exists on NT-based Windows, starting with Windows
2106 * 2000. On older operating systems, we can't change the window icon
2107 * anyway.
2108 */
2109 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2110 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2111 "GetConsoleWindow")) != NULL)
2112 {
2113 g_hWnd = (*GetConsoleWindowProc)();
2114 }
2115 if (g_hWnd == NULL)
2116 return;
2117
2118 /* Save the original console window icon. */
2119 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2120 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2121 return;
2122
2123 /* Extract the first icon contained in the Vim executable. */
2124 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2125 if (g_hVimIcon != NULL)
2126 g_fCanChangeIcon = TRUE;
2127}
2128#endif
2129
2130static int g_fWindInitCalled = FALSE;
2131static int g_fTermcapMode = FALSE;
2132static CONSOLE_CURSOR_INFO g_cci;
2133static DWORD g_cmodein = 0;
2134static DWORD g_cmodeout = 0;
2135
2136/*
2137 * non-GUI version of mch_init().
2138 */
2139 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002140mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002141{
2142#ifndef FEAT_RESTORE_ORIG_SCREEN
2143 CONSOLE_SCREEN_BUFFER_INFO csbi;
2144#endif
2145#ifndef __MINGW32__
2146 extern int _fmode;
2147#endif
2148
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002149 /* Silently handle invalid parameters to CRT functions */
2150 SET_INVALID_PARAM_HANDLER;
2151
Bram Moolenaar071d4272004-06-13 20:20:40 +00002152 /* Let critical errors result in a failure, not in a dialog box. Required
2153 * for the timestamp test to work on removed floppies. */
2154 SetErrorMode(SEM_FAILCRITICALERRORS);
2155
2156 _fmode = O_BINARY; /* we do our own CR-LF translation */
2157 out_flush();
2158
2159 /* Obtain handles for the standard Console I/O devices */
2160 if (read_cmd_fd == 0)
2161 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2162 else
2163 create_conin();
2164 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2165
2166#ifdef FEAT_RESTORE_ORIG_SCREEN
2167 /* Save the initial console buffer for later restoration */
2168 SaveConsoleBuffer(&g_cbOrig);
2169 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2170#else
2171 /* Get current text attributes */
2172 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2173 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2174#endif
2175 if (cterm_normal_fg_color == 0)
2176 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2177 if (cterm_normal_bg_color == 0)
2178 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2179
2180 /* set termcap codes to current text attributes */
2181 update_tcap(g_attrCurrent);
2182
2183 GetConsoleCursorInfo(g_hConOut, &g_cci);
2184 GetConsoleMode(g_hConIn, &g_cmodein);
2185 GetConsoleMode(g_hConOut, &g_cmodeout);
2186
2187#ifdef FEAT_TITLE
2188 SaveConsoleTitleAndIcon();
2189 /*
2190 * Set both the small and big icons of the console window to Vim's icon.
2191 * Note that Vim presently only has one size of icon (32x32), but it
2192 * automatically gets scaled down to 16x16 when setting the small icon.
2193 */
2194 if (g_fCanChangeIcon)
2195 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2196#endif
2197
2198 ui_get_shellsize();
2199
2200#ifdef MCH_WRITE_DUMP
2201 fdDump = fopen("dump", "wt");
2202
2203 if (fdDump)
2204 {
2205 time_t t;
2206
2207 time(&t);
2208 fputs(ctime(&t), fdDump);
2209 fflush(fdDump);
2210 }
2211#endif
2212
2213 g_fWindInitCalled = TRUE;
2214
2215#ifdef FEAT_MOUSE
2216 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2217#endif
2218
2219#ifdef FEAT_CLIPBOARD
2220 clip_init(TRUE);
2221
2222 /*
2223 * Vim's own clipboard format recognises whether the text is char, line, or
2224 * rectangular block. Only useful for copying between two Vims.
2225 * "VimClipboard" was used for previous versions, using the first
2226 * character to specify MCHAR, MLINE or MBLOCK.
2227 */
2228 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2229 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2230#endif
2231
2232 /* This will be NULL on anything but NT 4.0 */
2233 s_pfnGetConsoleKeyboardLayoutName =
2234 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2235 "GetConsoleKeyboardLayoutNameA");
2236}
2237
2238/*
2239 * non-GUI version of mch_exit().
2240 * Shut down and exit with status `r'
2241 * Careful: mch_exit() may be called before mch_init()!
2242 */
2243 void
2244mch_exit(int r)
2245{
2246 stoptermcap();
2247
2248 if (g_fWindInitCalled)
2249 settmode(TMODE_COOK);
2250
2251 ml_close_all(TRUE); /* remove all memfiles */
2252
2253 if (g_fWindInitCalled)
2254 {
2255#ifdef FEAT_TITLE
2256 mch_restore_title(3);
2257 /*
2258 * Restore both the small and big icons of the console window to
2259 * what they were at startup. Don't do this when the window is
2260 * closed, Vim would hang here.
2261 */
2262 if (g_fCanChangeIcon && !g_fForceExit)
2263 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2264#endif
2265
2266#ifdef MCH_WRITE_DUMP
2267 if (fdDump)
2268 {
2269 time_t t;
2270
2271 time(&t);
2272 fputs(ctime(&t), fdDump);
2273 fclose(fdDump);
2274 }
2275 fdDump = NULL;
2276#endif
2277 }
2278
2279 SetConsoleCursorInfo(g_hConOut, &g_cci);
2280 SetConsoleMode(g_hConIn, g_cmodein);
2281 SetConsoleMode(g_hConOut, g_cmodeout);
2282
2283#ifdef DYNAMIC_GETTEXT
2284 dyn_libintl_end();
2285#endif
2286
2287 exit(r);
2288}
2289#endif /* !FEAT_GUI_W32 */
2290
Bram Moolenaar071d4272004-06-13 20:20:40 +00002291/*
2292 * Do we have an interactive window?
2293 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002294/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002295 int
2296mch_check_win(
2297 int argc,
2298 char **argv)
2299{
2300 get_exe_name();
2301
2302#ifdef FEAT_GUI_W32
2303 return OK; /* GUI always has a tty */
2304#else
2305 if (isatty(1))
2306 return OK;
2307 return FAIL;
2308#endif
2309}
2310
2311
2312/*
2313 * fname_case(): Set the case of the file name, if it already exists.
2314 * When "len" is > 0, also expand short to long filenames.
2315 */
2316 void
2317fname_case(
2318 char_u *name,
2319 int len)
2320{
2321 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002322 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323 char *ptrue, *ptruePrev;
2324 char *porig, *porigPrev;
2325 int flen;
2326 WIN32_FIND_DATA fb;
2327 HANDLE hFind;
2328 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002329 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002331 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332 if (flen == 0 || flen > _MAX_PATH)
2333 return;
2334
2335 slash_adjust(name);
2336
2337 /* Build the new name in szTrueName[] one component at a time. */
2338 porig = name;
2339 ptrue = szTrueName;
2340
2341 if (isalpha(porig[0]) && porig[1] == ':')
2342 {
2343 /* copy leading drive letter */
2344 *ptrue++ = *porig++;
2345 *ptrue++ = *porig++;
2346 *ptrue = NUL; /* in case nothing follows */
2347 }
2348
2349 while (*porig != NUL)
2350 {
2351 /* copy \ characters */
2352 while (*porig == psepc)
2353 *ptrue++ = *porig++;
2354
2355 ptruePrev = ptrue;
2356 porigPrev = porig;
2357 while (*porig != NUL && *porig != psepc)
2358 {
2359#ifdef FEAT_MBYTE
2360 int l;
2361
2362 if (enc_dbcs)
2363 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002364 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 while (--l >= 0)
2366 *ptrue++ = *porig++;
2367 }
2368 else
2369#endif
2370 *ptrue++ = *porig++;
2371 }
2372 *ptrue = NUL;
2373
Bram Moolenaar464c9252010-10-13 20:37:41 +02002374 /* To avoid a slow failure append "\*" when searching a directory,
2375 * server or network share. */
2376 STRCPY(szTrueNameTemp, szTrueName);
2377 slen = strlen(szTrueNameTemp);
2378 if (*porig == psepc && slen + 2 < _MAX_PATH)
2379 STRCPY(szTrueNameTemp + slen, "\\*");
2380
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 /* Skip "", "." and "..". */
2382 if (ptrue > ptruePrev
2383 && (ptruePrev[0] != '.'
2384 || (ptruePrev[1] != NUL
2385 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002386 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 != INVALID_HANDLE_VALUE)
2388 {
2389 c = *porig;
2390 *porig = NUL;
2391
2392 /* Only use the match when it's the same name (ignoring case) or
2393 * expansion is allowed and there is a match with the short name
2394 * and there is enough room. */
2395 if (_stricoll(porigPrev, fb.cFileName) == 0
2396 || (len > 0
2397 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2398 && (int)(ptruePrev - szTrueName)
2399 + (int)strlen(fb.cFileName) < len)))
2400 {
2401 STRCPY(ptruePrev, fb.cFileName);
2402
2403 /* Look for exact match and prefer it if found. Must be a
2404 * long name, otherwise there would be only one match. */
2405 while (FindNextFile(hFind, &fb))
2406 {
2407 if (*fb.cAlternateFileName != NUL
2408 && (strcoll(porigPrev, fb.cFileName) == 0
2409 || (len > 0
2410 && (_stricoll(porigPrev,
2411 fb.cAlternateFileName) == 0
2412 && (int)(ptruePrev - szTrueName)
2413 + (int)strlen(fb.cFileName) < len))))
2414 {
2415 STRCPY(ptruePrev, fb.cFileName);
2416 break;
2417 }
2418 }
2419 }
2420 FindClose(hFind);
2421 *porig = c;
2422 ptrue = ptruePrev + strlen(ptruePrev);
2423 }
2424 }
2425
2426 STRCPY(name, szTrueName);
2427}
2428
2429
2430/*
2431 * Insert user name in s[len].
2432 */
2433 int
2434mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002435 char_u *s,
2436 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002438 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439 DWORD cch = sizeof szUserName;
2440
2441 if (GetUserName(szUserName, &cch))
2442 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002443 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444 return OK;
2445 }
2446 s[0] = NUL;
2447 return FAIL;
2448}
2449
2450
2451/*
2452 * Insert host name in s[len].
2453 */
2454 void
2455mch_get_host_name(
2456 char_u *s,
2457 int len)
2458{
2459 DWORD cch = len;
2460
2461 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002462 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002463}
2464
2465
2466/*
2467 * return process ID
2468 */
2469 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002470mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471{
2472 return (long)GetCurrentProcessId();
2473}
2474
2475
2476/*
2477 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2478 * Return OK for success, FAIL for failure.
2479 */
2480 int
2481mch_dirname(
2482 char_u *buf,
2483 int len)
2484{
2485 /*
2486 * Originally this was:
2487 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2488 * But the Win32s known bug list says that getcwd() doesn't work
2489 * so use the Win32 system call instead. <Negri>
2490 */
2491#ifdef FEAT_MBYTE
2492 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2493 {
2494 WCHAR wbuf[_MAX_PATH + 1];
2495
2496 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2497 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002498 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499
2500 if (p != NULL)
2501 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002502 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 vim_free(p);
2504 return OK;
2505 }
2506 }
2507 /* Retry with non-wide function (for Windows 98). */
2508 }
2509#endif
2510 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2511}
2512
2513/*
2514 * get file permissions for `name'
2515 * -1 : error
2516 * else FILE_ATTRIBUTE_* defined in winnt.h
2517 */
2518 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002519mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520{
2521#ifdef FEAT_MBYTE
2522 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2523 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002524 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 long n;
2526
2527 if (p != NULL)
2528 {
2529 n = (long)GetFileAttributesW(p);
2530 vim_free(p);
2531 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2532 return n;
2533 /* Retry with non-wide function (for Windows 98). */
2534 }
2535 }
2536#endif
2537 return (long)GetFileAttributes((char *)name);
2538}
2539
2540
2541/*
2542 * set file permission for `name' to `perm'
2543 */
2544 int
2545mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002546 char_u *name,
2547 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548{
2549 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2550#ifdef FEAT_MBYTE
2551 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2552 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002553 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554 long n;
2555
2556 if (p != NULL)
2557 {
2558 n = (long)SetFileAttributesW(p, perm);
2559 vim_free(p);
2560 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2561 return n ? OK : FAIL;
2562 /* Retry with non-wide function (for Windows 98). */
2563 }
2564 }
2565#endif
2566 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2567}
2568
2569/*
2570 * Set hidden flag for "name".
2571 */
2572 void
2573mch_hide(char_u *name)
2574{
2575 int perm;
2576#ifdef FEAT_MBYTE
2577 WCHAR *p = NULL;
2578
2579 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002580 p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581#endif
2582
2583#ifdef FEAT_MBYTE
2584 if (p != NULL)
2585 {
2586 perm = GetFileAttributesW(p);
2587 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2588 {
2589 /* Retry with non-wide function (for Windows 98). */
2590 vim_free(p);
2591 p = NULL;
2592 }
2593 }
2594 if (p == NULL)
2595#endif
2596 perm = GetFileAttributes((char *)name);
2597 if (perm >= 0)
2598 {
2599 perm |= FILE_ATTRIBUTE_HIDDEN;
2600#ifdef FEAT_MBYTE
2601 if (p != NULL)
2602 {
2603 if (SetFileAttributesW(p, perm) == 0
2604 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2605 {
2606 /* Retry with non-wide function (for Windows 98). */
2607 vim_free(p);
2608 p = NULL;
2609 }
2610 }
2611 if (p == NULL)
2612#endif
2613 SetFileAttributes((char *)name, perm);
2614 }
2615#ifdef FEAT_MBYTE
2616 vim_free(p);
2617#endif
2618}
2619
2620/*
2621 * return TRUE if "name" is a directory
2622 * return FALSE if "name" is not a directory or upon error
2623 */
2624 int
2625mch_isdir(char_u *name)
2626{
2627 int f = mch_getperm(name);
2628
2629 if (f == -1)
2630 return FALSE; /* file does not exist at all */
2631
2632 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2633}
2634
2635/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002636 * Return TRUE if file "fname" has more than one link.
2637 */
2638 int
2639mch_is_linked(char_u *fname)
2640{
2641 HANDLE hFile;
2642 int res = 0;
2643 BY_HANDLE_FILE_INFORMATION inf;
2644#ifdef FEAT_MBYTE
2645 WCHAR *wn = NULL;
2646
2647 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002648 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar03f48552006-02-28 23:52:23 +00002649 if (wn != NULL)
2650 {
2651 hFile = CreateFileW(wn, /* file name */
2652 GENERIC_READ, /* access mode */
2653 0, /* share mode */
2654 NULL, /* security descriptor */
2655 OPEN_EXISTING, /* creation disposition */
2656 0, /* file attributes */
2657 NULL); /* handle to template file */
2658 if (hFile == INVALID_HANDLE_VALUE
2659 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2660 {
2661 /* Retry with non-wide function (for Windows 98). */
2662 vim_free(wn);
2663 wn = NULL;
2664 }
2665 }
2666 if (wn == NULL)
2667#endif
2668 hFile = CreateFile(fname, /* file name */
2669 GENERIC_READ, /* access mode */
2670 0, /* share mode */
2671 NULL, /* security descriptor */
2672 OPEN_EXISTING, /* creation disposition */
2673 0, /* file attributes */
2674 NULL); /* handle to template file */
2675
2676 if (hFile != INVALID_HANDLE_VALUE)
2677 {
2678 if (GetFileInformationByHandle(hFile, &inf) != 0
2679 && inf.nNumberOfLinks > 1)
2680 res = 1;
2681 CloseHandle(hFile);
2682 }
2683
2684#ifdef FEAT_MBYTE
2685 vim_free(wn);
2686#endif
2687 return res;
2688}
2689
2690/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002691 * Return TRUE if file or directory "name" is writable (not readonly).
2692 * Strange semantics of Win32: a readonly directory is writable, but you can't
2693 * delete a file. Let's say this means it is writable.
2694 */
2695 int
2696mch_writable(char_u *name)
2697{
2698 int perm = mch_getperm(name);
2699
2700 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2701 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2702}
2703
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704/*
2705 * Return 1 if "name" can be executed, 0 if not.
2706 * Return -1 if unknown.
2707 */
2708 int
2709mch_can_exe(char_u *name)
2710{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002711 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002712 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002713 char_u *p;
2714
2715 if (len >= _MAX_PATH) /* safety check */
2716 return FALSE;
2717
2718 /* If there already is an extension try using the name directly. Also do
2719 * this with a Unix-shell like 'shell'. */
2720 if (vim_strchr(gettail(name), '.') != NULL
2721 || strstr((char *)gettail(p_sh), "sh") != NULL)
2722 if (executable_exists((char *)name))
2723 return TRUE;
2724
2725 /*
2726 * Loop over all extensions in $PATHEXT.
2727 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002728 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002729 p = mch_getenv("PATHEXT");
2730 if (p == NULL)
2731 p = (char_u *)".com;.exe;.bat;.cmd";
2732 while (*p)
2733 {
2734 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2735 {
2736 /* A single "." means no extension is added. */
2737 buf[len] = NUL;
2738 ++p;
2739 if (*p)
2740 ++p;
2741 }
2742 else
2743 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2744 if (executable_exists((char *)buf))
2745 return TRUE;
2746 }
2747 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002748}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749
2750/*
2751 * Check what "name" is:
2752 * NODE_NORMAL: file or directory (or doesn't exist)
2753 * NODE_WRITABLE: writable device, socket, fifo, etc.
2754 * NODE_OTHER: non-writable things
2755 */
2756 int
2757mch_nodetype(char_u *name)
2758{
2759 HANDLE hFile;
2760 int type;
2761
Bram Moolenaar043545e2006-10-10 16:44:07 +00002762 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2763 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2764 * here. */
2765 if (STRNCMP(name, "\\\\.\\", 4) == 0)
2766 return NODE_WRITABLE;
2767
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768 hFile = CreateFile(name, /* file name */
2769 GENERIC_WRITE, /* access mode */
2770 0, /* share mode */
2771 NULL, /* security descriptor */
2772 OPEN_EXISTING, /* creation disposition */
2773 0, /* file attributes */
2774 NULL); /* handle to template file */
2775
2776 if (hFile == INVALID_HANDLE_VALUE)
2777 return NODE_NORMAL;
2778
2779 type = GetFileType(hFile);
2780 CloseHandle(hFile);
2781 if (type == FILE_TYPE_CHAR)
2782 return NODE_WRITABLE;
2783 if (type == FILE_TYPE_DISK)
2784 return NODE_NORMAL;
2785 return NODE_OTHER;
2786}
2787
2788#ifdef HAVE_ACL
2789struct my_acl
2790{
2791 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2792 PSID pSidOwner;
2793 PSID pSidGroup;
2794 PACL pDacl;
2795 PACL pSacl;
2796};
2797#endif
2798
2799/*
2800 * Return a pointer to the ACL of file "fname" in allocated memory.
2801 * Return NULL if the ACL is not available for whatever reason.
2802 */
2803 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002804mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805{
2806#ifndef HAVE_ACL
2807 return (vim_acl_T)NULL;
2808#else
2809 struct my_acl *p = NULL;
2810
2811 /* This only works on Windows NT and 2000. */
2812 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2813 {
2814 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2815 if (p != NULL)
2816 {
2817 if (pGetNamedSecurityInfo(
2818 (LPTSTR)fname, // Abstract filename
2819 SE_FILE_OBJECT, // File Object
2820 // Retrieve the entire security descriptor.
2821 OWNER_SECURITY_INFORMATION |
2822 GROUP_SECURITY_INFORMATION |
2823 DACL_SECURITY_INFORMATION |
2824 SACL_SECURITY_INFORMATION,
2825 &p->pSidOwner, // Ownership information.
2826 &p->pSidGroup, // Group membership.
2827 &p->pDacl, // Discretionary information.
2828 &p->pSacl, // For auditing purposes.
2829 &p->pSecurityDescriptor
2830 ) != ERROR_SUCCESS)
2831 {
2832 mch_free_acl((vim_acl_T)p);
2833 p = NULL;
2834 }
2835 }
2836 }
2837
2838 return (vim_acl_T)p;
2839#endif
2840}
2841
2842/*
2843 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2844 * Errors are ignored.
2845 * This must only be called with "acl" equal to what mch_get_acl() returned.
2846 */
2847 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002848mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849{
2850#ifdef HAVE_ACL
2851 struct my_acl *p = (struct my_acl *)acl;
2852
2853 if (p != NULL && advapi_lib != NULL)
2854 (void)pSetNamedSecurityInfo(
2855 (LPTSTR)fname, // Abstract filename
2856 SE_FILE_OBJECT, // File Object
2857 // Retrieve the entire security descriptor.
2858 OWNER_SECURITY_INFORMATION |
2859 GROUP_SECURITY_INFORMATION |
2860 DACL_SECURITY_INFORMATION |
2861 SACL_SECURITY_INFORMATION,
2862 p->pSidOwner, // Ownership information.
2863 p->pSidGroup, // Group membership.
2864 p->pDacl, // Discretionary information.
2865 p->pSacl // For auditing purposes.
2866 );
2867#endif
2868}
2869
2870 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002871mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872{
2873#ifdef HAVE_ACL
2874 struct my_acl *p = (struct my_acl *)acl;
2875
2876 if (p != NULL)
2877 {
2878 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2879 vim_free(p);
2880 }
2881#endif
2882}
2883
2884#ifndef FEAT_GUI_W32
2885
2886/*
2887 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2888 */
2889 static BOOL WINAPI
2890handler_routine(
2891 DWORD dwCtrlType)
2892{
2893 switch (dwCtrlType)
2894 {
2895 case CTRL_C_EVENT:
2896 if (ctrl_c_interrupts)
2897 g_fCtrlCPressed = TRUE;
2898 return TRUE;
2899
2900 case CTRL_BREAK_EVENT:
2901 g_fCBrkPressed = TRUE;
2902 return TRUE;
2903
2904 /* fatal events: shut down gracefully */
2905 case CTRL_CLOSE_EVENT:
2906 case CTRL_LOGOFF_EVENT:
2907 case CTRL_SHUTDOWN_EVENT:
2908 windgoto((int)Rows - 1, 0);
2909 g_fForceExit = TRUE;
2910
Bram Moolenaar0fde2902008-03-16 13:54:13 +00002911 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912 (dwCtrlType == CTRL_CLOSE_EVENT
2913 ? _("close")
2914 : dwCtrlType == CTRL_LOGOFF_EVENT
2915 ? _("logoff")
2916 : _("shutdown")));
2917#ifdef DEBUG
2918 OutputDebugString(IObuff);
2919#endif
2920
2921 preserve_exit(); /* output IObuff, preserve files and exit */
2922
2923 return TRUE; /* not reached */
2924
2925 default:
2926 return FALSE;
2927 }
2928}
2929
2930
2931/*
2932 * set the tty in (raw) ? "raw" : "cooked" mode
2933 */
2934 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002935mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936{
2937 DWORD cmodein;
2938 DWORD cmodeout;
2939 BOOL bEnableHandler;
2940
2941 GetConsoleMode(g_hConIn, &cmodein);
2942 GetConsoleMode(g_hConOut, &cmodeout);
2943 if (tmode == TMODE_RAW)
2944 {
2945 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2946 ENABLE_ECHO_INPUT);
2947#ifdef FEAT_MOUSE
2948 if (g_fMouseActive)
2949 cmodein |= ENABLE_MOUSE_INPUT;
2950#endif
2951 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2952 bEnableHandler = TRUE;
2953 }
2954 else /* cooked */
2955 {
2956 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2957 ENABLE_ECHO_INPUT);
2958 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2959 bEnableHandler = FALSE;
2960 }
2961 SetConsoleMode(g_hConIn, cmodein);
2962 SetConsoleMode(g_hConOut, cmodeout);
2963 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
2964
2965#ifdef MCH_WRITE_DUMP
2966 if (fdDump)
2967 {
2968 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
2969 tmode == TMODE_RAW ? "raw" :
2970 tmode == TMODE_COOK ? "cooked" : "normal",
2971 cmodein, cmodeout);
2972 fflush(fdDump);
2973 }
2974#endif
2975}
2976
2977
2978/*
2979 * Get the size of the current window in `Rows' and `Columns'
2980 * Return OK when size could be determined, FAIL otherwise.
2981 */
2982 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002983mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984{
2985 CONSOLE_SCREEN_BUFFER_INFO csbi;
2986
2987 if (!g_fTermcapMode && g_cbTermcap.IsValid)
2988 {
2989 /*
2990 * For some reason, we are trying to get the screen dimensions
2991 * even though we are not in termcap mode. The 'Rows' and 'Columns'
2992 * variables are really intended to mean the size of Vim screen
2993 * while in termcap mode.
2994 */
2995 Rows = g_cbTermcap.Info.dwSize.Y;
2996 Columns = g_cbTermcap.Info.dwSize.X;
2997 }
2998 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2999 {
3000 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3001 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3002 }
3003 else
3004 {
3005 Rows = 25;
3006 Columns = 80;
3007 }
3008 return OK;
3009}
3010
3011/*
3012 * Set a console window to `xSize' * `ySize'
3013 */
3014 static void
3015ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003016 HANDLE hConsole,
3017 int xSize,
3018 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019{
3020 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3021 SMALL_RECT srWindowRect; /* hold the new console size */
3022 COORD coordScreen;
3023
3024#ifdef MCH_WRITE_DUMP
3025 if (fdDump)
3026 {
3027 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3028 fflush(fdDump);
3029 }
3030#endif
3031
3032 /* get the largest size we can size the console window to */
3033 coordScreen = GetLargestConsoleWindowSize(hConsole);
3034
3035 /* define the new console window size and scroll position */
3036 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3037 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3038 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3039
3040 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3041 {
3042 int sx, sy;
3043
3044 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3045 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3046 if (sy < ySize || sx < xSize)
3047 {
3048 /*
3049 * Increasing number of lines/columns, do buffer first.
3050 * Use the maximal size in x and y direction.
3051 */
3052 if (sy < ySize)
3053 coordScreen.Y = ySize;
3054 else
3055 coordScreen.Y = sy;
3056 if (sx < xSize)
3057 coordScreen.X = xSize;
3058 else
3059 coordScreen.X = sx;
3060 SetConsoleScreenBufferSize(hConsole, coordScreen);
3061 }
3062 }
3063
3064 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3065 {
3066#ifdef MCH_WRITE_DUMP
3067 if (fdDump)
3068 {
3069 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3070 GetLastError());
3071 fflush(fdDump);
3072 }
3073#endif
3074 }
3075
3076 /* define the new console buffer size */
3077 coordScreen.X = xSize;
3078 coordScreen.Y = ySize;
3079
3080 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3081 {
3082#ifdef MCH_WRITE_DUMP
3083 if (fdDump)
3084 {
3085 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3086 GetLastError());
3087 fflush(fdDump);
3088 }
3089#endif
3090 }
3091}
3092
3093
3094/*
3095 * Set the console window to `Rows' * `Columns'
3096 */
3097 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003098mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099{
3100 COORD coordScreen;
3101
3102 /* Don't change window size while still starting up */
3103 if (suppress_winsize != 0)
3104 {
3105 suppress_winsize = 2;
3106 return;
3107 }
3108
3109 if (term_console)
3110 {
3111 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3112
3113 /* Clamp Rows and Columns to reasonable values */
3114 if (Rows > coordScreen.Y)
3115 Rows = coordScreen.Y;
3116 if (Columns > coordScreen.X)
3117 Columns = coordScreen.X;
3118
3119 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3120 }
3121}
3122
3123/*
3124 * Rows and/or Columns has changed.
3125 */
3126 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003127mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128{
3129 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3130}
3131
3132
3133/*
3134 * Called when started up, to set the winsize that was delayed.
3135 */
3136 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003137mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138{
3139 if (suppress_winsize == 2)
3140 {
3141 suppress_winsize = 0;
3142 mch_set_shellsize();
3143 shell_resized();
3144 }
3145 suppress_winsize = 0;
3146}
3147#endif /* FEAT_GUI_W32 */
3148
3149
3150
3151#if defined(FEAT_GUI_W32) || defined(PROTO)
3152
3153/*
3154 * Specialised version of system() for Win32 GUI mode.
3155 * This version proceeds as follows:
3156 * 1. Create a console window for use by the subprocess
3157 * 2. Run the subprocess (it gets the allocated console by default)
3158 * 3. Wait for the subprocess to terminate and get its exit code
3159 * 4. Prompt the user to press a key to close the console window
3160 */
3161 static int
3162mch_system(char *cmd, int options)
3163{
3164 STARTUPINFO si;
3165 PROCESS_INFORMATION pi;
3166 DWORD ret = 0;
3167 HWND hwnd = GetFocus();
3168
3169 si.cb = sizeof(si);
3170 si.lpReserved = NULL;
3171 si.lpDesktop = NULL;
3172 si.lpTitle = NULL;
3173 si.dwFlags = STARTF_USESHOWWINDOW;
3174 /*
3175 * It's nicer to run a filter command in a minimized window, but in
3176 * Windows 95 this makes the command MUCH slower. We can't do it under
3177 * Win32s either as it stops the synchronous spawn workaround working.
3178 */
3179 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
3180 si.wShowWindow = SW_SHOWMINIMIZED;
3181 else
3182 si.wShowWindow = SW_SHOWNORMAL;
3183 si.cbReserved2 = 0;
3184 si.lpReserved2 = NULL;
3185
3186 /* There is a strange error on Windows 95 when using "c:\\command.com".
3187 * When the "c:\\" is left out it works OK...? */
3188 if (mch_windows95()
3189 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3190 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3191 cmd += 3;
3192
3193 /* Now, run the command */
3194 CreateProcess(NULL, /* Executable name */
3195 cmd, /* Command to execute */
3196 NULL, /* Process security attributes */
3197 NULL, /* Thread security attributes */
3198 FALSE, /* Inherit handles */
3199 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3200 CREATE_NEW_CONSOLE,
3201 NULL, /* Environment */
3202 NULL, /* Current directory */
3203 &si, /* Startup information */
3204 &pi); /* Process information */
3205
3206
3207 /* Wait for the command to terminate before continuing */
3208 if (g_PlatformId != VER_PLATFORM_WIN32s)
3209 {
3210#ifdef FEAT_GUI
3211 int delay = 1;
3212
3213 /* Keep updating the window while waiting for the shell to finish. */
3214 for (;;)
3215 {
3216 MSG msg;
3217
3218 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3219 {
3220 TranslateMessage(&msg);
3221 DispatchMessage(&msg);
3222 }
3223 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3224 break;
3225
3226 /* We start waiting for a very short time and then increase it, so
3227 * that we respond quickly when the process is quick, and don't
3228 * consume too much overhead when it's slow. */
3229 if (delay < 50)
3230 delay += 10;
3231 }
3232#else
3233 WaitForSingleObject(pi.hProcess, INFINITE);
3234#endif
3235
3236 /* Get the command exit code */
3237 GetExitCodeProcess(pi.hProcess, &ret);
3238 }
3239 else
3240 {
3241 /*
3242 * This ugly code is the only quick way of performing
3243 * a synchronous spawn under Win32s. Yuk.
3244 */
3245 num_windows = 0;
3246 EnumWindows(win32ssynch_cb, 0);
3247 old_num_windows = num_windows;
3248 do
3249 {
3250 Sleep(1000);
3251 num_windows = 0;
3252 EnumWindows(win32ssynch_cb, 0);
3253 } while (num_windows == old_num_windows);
3254 ret = 0;
3255 }
3256
3257 /* Close the handles to the subprocess, so that it goes away */
3258 CloseHandle(pi.hThread);
3259 CloseHandle(pi.hProcess);
3260
3261 /* Try to get input focus back. Doesn't always work though. */
3262 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3263
3264 return ret;
3265}
3266#else
3267
3268# define mch_system(c, o) system(c)
3269
3270#endif
3271
3272/*
3273 * Either execute a command by calling the shell or start a new shell
3274 */
3275 int
3276mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003277 char_u *cmd,
3278 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279{
3280 int x = 0;
3281 int tmode = cur_tmode;
3282#ifdef FEAT_TITLE
3283 char szShellTitle[512];
3284
3285 /* Change the title to reflect that we are in a subshell. */
3286 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3287 {
3288 if (cmd == NULL)
3289 strcat(szShellTitle, " :sh");
3290 else
3291 {
3292 strcat(szShellTitle, " - !");
3293 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3294 strcat(szShellTitle, cmd);
3295 }
3296 mch_settitle(szShellTitle, NULL);
3297 }
3298#endif
3299
3300 out_flush();
3301
3302#ifdef MCH_WRITE_DUMP
3303 if (fdDump)
3304 {
3305 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3306 fflush(fdDump);
3307 }
3308#endif
3309
3310 /*
3311 * Catch all deadly signals while running the external command, because a
3312 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3313 */
3314 signal(SIGINT, SIG_IGN);
3315#if defined(__GNUC__) && !defined(__MINGW32__)
3316 signal(SIGKILL, SIG_IGN);
3317#else
3318 signal(SIGBREAK, SIG_IGN);
3319#endif
3320 signal(SIGILL, SIG_IGN);
3321 signal(SIGFPE, SIG_IGN);
3322 signal(SIGSEGV, SIG_IGN);
3323 signal(SIGTERM, SIG_IGN);
3324 signal(SIGABRT, SIG_IGN);
3325
3326 if (options & SHELL_COOKED)
3327 settmode(TMODE_COOK); /* set to normal mode */
3328
3329 if (cmd == NULL)
3330 {
3331 x = mch_system(p_sh, options);
3332 }
3333 else
3334 {
3335 /* we use "command" or "cmd" to start the shell; slow but easy */
3336 char_u *newcmd;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003337 long_u cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338#ifdef FEAT_GUI_W32
3339 STRLEN(vimrun_path) +
3340#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003341 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
3342
3343 newcmd = lalloc(cmdlen, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344 if (newcmd != NULL)
3345 {
3346 char_u *cmdbase = (*cmd == '"' ? cmd + 1 : cmd);
3347
3348 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3349 {
3350 STARTUPINFO si;
3351 PROCESS_INFORMATION pi;
3352
3353 si.cb = sizeof(si);
3354 si.lpReserved = NULL;
3355 si.lpDesktop = NULL;
3356 si.lpTitle = NULL;
3357 si.dwFlags = 0;
3358 si.cbReserved2 = 0;
3359 si.lpReserved2 = NULL;
3360
3361 cmdbase = skipwhite(cmdbase + 5);
3362 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3363 && vim_iswhite(cmdbase[4]))
3364 {
3365 cmdbase = skipwhite(cmdbase + 4);
3366 si.dwFlags = STARTF_USESHOWWINDOW;
3367 si.wShowWindow = SW_SHOWMINNOACTIVE;
3368 }
3369
3370 /* When the command is in double quotes, but 'shellxquote' is
3371 * empty, keep the double quotes around the command.
3372 * Otherwise remove the double quotes, they aren't needed
3373 * here, because we don't use a shell to run the command. */
3374 if (*cmd == '"' && *p_sxq == NUL)
3375 {
3376 newcmd[0] = '"';
3377 STRCPY(newcmd + 1, cmdbase);
3378 }
3379 else
3380 {
3381 STRCPY(newcmd, cmdbase);
3382 if (*cmd == '"' && *newcmd != NUL)
3383 newcmd[STRLEN(newcmd) - 1] = NUL;
3384 }
3385
3386 /*
3387 * Now, start the command as a process, so that it doesn't
3388 * inherit our handles which causes unpleasant dangling swap
3389 * files if we exit before the spawned process
3390 */
3391 if (CreateProcess (NULL, // Executable name
3392 newcmd, // Command to execute
3393 NULL, // Process security attributes
3394 NULL, // Thread security attributes
3395 FALSE, // Inherit handles
3396 CREATE_NEW_CONSOLE, // Creation flags
3397 NULL, // Environment
3398 NULL, // Current directory
3399 &si, // Startup information
3400 &pi)) // Process information
3401 x = 0;
3402 else
3403 {
3404 x = -1;
3405#ifdef FEAT_GUI_W32
3406 EMSG(_("E371: Command not found"));
3407#endif
3408 }
3409 /* Close the handles to the subprocess, so that it goes away */
3410 CloseHandle(pi.hThread);
3411 CloseHandle(pi.hProcess);
3412 }
3413 else
3414 {
3415#if defined(FEAT_GUI_W32)
3416 if (need_vimrun_warning)
3417 {
3418 MessageBox(NULL,
3419 _("VIMRUN.EXE not found in your $PATH.\n"
3420 "External commands will not pause after completion.\n"
3421 "See :help win32-vimrun for more information."),
3422 _("Vim Warning"),
3423 MB_ICONWARNING);
3424 need_vimrun_warning = FALSE;
3425 }
3426 if (!s_dont_use_vimrun)
3427 /* Use vimrun to execute the command. It opens a console
3428 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02003429 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00003430 vimrun_path,
3431 (msg_silent != 0 || (options & SHELL_DOOUT))
3432 ? "-s " : "",
3433 p_sh, p_shcf, cmd);
3434 else
3435#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02003436 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003437 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 x = mch_system((char *)newcmd, options);
3439 }
3440 vim_free(newcmd);
3441 }
3442 }
3443
3444 if (tmode == TMODE_RAW)
3445 settmode(TMODE_RAW); /* set to raw mode */
3446
3447 /* Print the return value, unless "vimrun" was used. */
3448 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
3449#if defined(FEAT_GUI_W32)
3450 && ((options & SHELL_DOOUT) || s_dont_use_vimrun)
3451#endif
3452 )
3453 {
3454 smsg(_("shell returned %d"), x);
3455 msg_putchar('\n');
3456 }
3457#ifdef FEAT_TITLE
3458 resettitle();
3459#endif
3460
3461 signal(SIGINT, SIG_DFL);
3462#if defined(__GNUC__) && !defined(__MINGW32__)
3463 signal(SIGKILL, SIG_DFL);
3464#else
3465 signal(SIGBREAK, SIG_DFL);
3466#endif
3467 signal(SIGILL, SIG_DFL);
3468 signal(SIGFPE, SIG_DFL);
3469 signal(SIGSEGV, SIG_DFL);
3470 signal(SIGTERM, SIG_DFL);
3471 signal(SIGABRT, SIG_DFL);
3472
3473 return x;
3474}
3475
3476
3477#ifndef FEAT_GUI_W32
3478
3479/*
3480 * Start termcap mode
3481 */
3482 static void
3483termcap_mode_start(void)
3484{
3485 DWORD cmodein;
3486
3487 if (g_fTermcapMode)
3488 return;
3489
3490 SaveConsoleBuffer(&g_cbNonTermcap);
3491
3492 if (g_cbTermcap.IsValid)
3493 {
3494 /*
3495 * We've been in termcap mode before. Restore certain screen
3496 * characteristics, including the buffer size and the window
3497 * size. Since we will be redrawing the screen, we don't need
3498 * to restore the actual contents of the buffer.
3499 */
3500 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
3501 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
3502 Rows = g_cbTermcap.Info.dwSize.Y;
3503 Columns = g_cbTermcap.Info.dwSize.X;
3504 }
3505 else
3506 {
3507 /*
3508 * This is our first time entering termcap mode. Clear the console
3509 * screen buffer, and resize the buffer to match the current window
3510 * size. We will use this as the size of our editing environment.
3511 */
3512 ClearConsoleBuffer(g_attrCurrent);
3513 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3514 }
3515
3516#ifdef FEAT_TITLE
3517 resettitle();
3518#endif
3519
3520 GetConsoleMode(g_hConIn, &cmodein);
3521#ifdef FEAT_MOUSE
3522 if (g_fMouseActive)
3523 cmodein |= ENABLE_MOUSE_INPUT;
3524 else
3525 cmodein &= ~ENABLE_MOUSE_INPUT;
3526#endif
3527 cmodein |= ENABLE_WINDOW_INPUT;
3528 SetConsoleMode(g_hConIn, cmodein);
3529
3530 redraw_later_clear();
3531 g_fTermcapMode = TRUE;
3532}
3533
3534
3535/*
3536 * End termcap mode
3537 */
3538 static void
3539termcap_mode_end(void)
3540{
3541 DWORD cmodein;
3542 ConsoleBuffer *cb;
3543 COORD coord;
3544 DWORD dwDummy;
3545
3546 if (!g_fTermcapMode)
3547 return;
3548
3549 SaveConsoleBuffer(&g_cbTermcap);
3550
3551 GetConsoleMode(g_hConIn, &cmodein);
3552 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
3553 SetConsoleMode(g_hConIn, cmodein);
3554
3555#ifdef FEAT_RESTORE_ORIG_SCREEN
3556 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
3557#else
3558 cb = &g_cbNonTermcap;
3559#endif
3560 RestoreConsoleBuffer(cb, p_rs);
3561 SetConsoleCursorInfo(g_hConOut, &g_cci);
3562
3563 if (p_rs || exiting)
3564 {
3565 /*
3566 * Clear anything that happens to be on the current line.
3567 */
3568 coord.X = 0;
3569 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
3570 FillConsoleOutputCharacter(g_hConOut, ' ',
3571 cb->Info.dwSize.X, coord, &dwDummy);
3572 /*
3573 * The following is just for aesthetics. If we are exiting without
3574 * restoring the screen, then we want to have a prompt string
3575 * appear at the bottom line. However, the command interpreter
3576 * seems to always advance the cursor one line before displaying
3577 * the prompt string, which causes the screen to scroll. To
3578 * counter this, move the cursor up one line before exiting.
3579 */
3580 if (exiting && !p_rs)
3581 coord.Y--;
3582 /*
3583 * Position the cursor at the leftmost column of the desired row.
3584 */
3585 SetConsoleCursorPosition(g_hConOut, coord);
3586 }
3587
3588 g_fTermcapMode = FALSE;
3589}
3590#endif /* FEAT_GUI_W32 */
3591
3592
3593#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003594/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 void
3596mch_write(
3597 char_u *s,
3598 int len)
3599{
3600 /* never used */
3601}
3602
3603#else
3604
3605/*
3606 * clear `n' chars, starting from `coord'
3607 */
3608 static void
3609clear_chars(
3610 COORD coord,
3611 DWORD n)
3612{
3613 DWORD dwDummy;
3614
3615 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
3616 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
3617}
3618
3619
3620/*
3621 * Clear the screen
3622 */
3623 static void
3624clear_screen(void)
3625{
3626 g_coord.X = g_coord.Y = 0;
3627 clear_chars(g_coord, Rows * Columns);
3628}
3629
3630
3631/*
3632 * Clear to end of display
3633 */
3634 static void
3635clear_to_end_of_display(void)
3636{
3637 clear_chars(g_coord, (Rows - g_coord.Y - 1)
3638 * Columns + (Columns - g_coord.X));
3639}
3640
3641
3642/*
3643 * Clear to end of line
3644 */
3645 static void
3646clear_to_end_of_line(void)
3647{
3648 clear_chars(g_coord, Columns - g_coord.X);
3649}
3650
3651
3652/*
3653 * Scroll the scroll region up by `cLines' lines
3654 */
3655 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003656scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657{
3658 COORD oldcoord = g_coord;
3659
3660 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
3661 delete_lines(cLines);
3662
3663 g_coord = oldcoord;
3664}
3665
3666
3667/*
3668 * Set the scroll region
3669 */
3670 static void
3671set_scroll_region(
3672 unsigned left,
3673 unsigned top,
3674 unsigned right,
3675 unsigned bottom)
3676{
3677 if (left >= right
3678 || top >= bottom
3679 || right > (unsigned) Columns - 1
3680 || bottom > (unsigned) Rows - 1)
3681 return;
3682
3683 g_srScrollRegion.Left = left;
3684 g_srScrollRegion.Top = top;
3685 g_srScrollRegion.Right = right;
3686 g_srScrollRegion.Bottom = bottom;
3687}
3688
3689
3690/*
3691 * Insert `cLines' lines at the current cursor position
3692 */
3693 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003694insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003695{
3696 SMALL_RECT source;
3697 COORD dest;
3698 CHAR_INFO fill;
3699
3700 dest.X = 0;
3701 dest.Y = g_coord.Y + cLines;
3702
3703 source.Left = 0;
3704 source.Top = g_coord.Y;
3705 source.Right = g_srScrollRegion.Right;
3706 source.Bottom = g_srScrollRegion.Bottom - cLines;
3707
3708 fill.Char.AsciiChar = ' ';
3709 fill.Attributes = g_attrCurrent;
3710
3711 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3712
3713 /* Here we have to deal with a win32 console flake: If the scroll
3714 * region looks like abc and we scroll c to a and fill with d we get
3715 * cbd... if we scroll block c one line at a time to a, we get cdd...
3716 * vim expects cdd consistently... So we have to deal with that
3717 * here... (this also occurs scrolling the same way in the other
3718 * direction). */
3719
3720 if (source.Bottom < dest.Y)
3721 {
3722 COORD coord;
3723
3724 coord.X = 0;
3725 coord.Y = source.Bottom;
3726 clear_chars(coord, Columns * (dest.Y - source.Bottom));
3727 }
3728}
3729
3730
3731/*
3732 * Delete `cLines' lines at the current cursor position
3733 */
3734 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003735delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736{
3737 SMALL_RECT source;
3738 COORD dest;
3739 CHAR_INFO fill;
3740 int nb;
3741
3742 dest.X = 0;
3743 dest.Y = g_coord.Y;
3744
3745 source.Left = 0;
3746 source.Top = g_coord.Y + cLines;
3747 source.Right = g_srScrollRegion.Right;
3748 source.Bottom = g_srScrollRegion.Bottom;
3749
3750 fill.Char.AsciiChar = ' ';
3751 fill.Attributes = g_attrCurrent;
3752
3753 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3754
3755 /* Here we have to deal with a win32 console flake: If the scroll
3756 * region looks like abc and we scroll c to a and fill with d we get
3757 * cbd... if we scroll block c one line at a time to a, we get cdd...
3758 * vim expects cdd consistently... So we have to deal with that
3759 * here... (this also occurs scrolling the same way in the other
3760 * direction). */
3761
3762 nb = dest.Y + (source.Bottom - source.Top) + 1;
3763
3764 if (nb < source.Top)
3765 {
3766 COORD coord;
3767
3768 coord.X = 0;
3769 coord.Y = nb;
3770 clear_chars(coord, Columns * (source.Top - nb));
3771 }
3772}
3773
3774
3775/*
3776 * Set the cursor position
3777 */
3778 static void
3779gotoxy(
3780 unsigned x,
3781 unsigned y)
3782{
3783 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
3784 return;
3785
3786 /* external cursor coords are 1-based; internal are 0-based */
3787 g_coord.X = x - 1;
3788 g_coord.Y = y - 1;
3789 SetConsoleCursorPosition(g_hConOut, g_coord);
3790}
3791
3792
3793/*
3794 * Set the current text attribute = (foreground | background)
3795 * See ../doc/os_win32.txt for the numbers.
3796 */
3797 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003798textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799{
3800 g_attrCurrent = wAttr;
3801
3802 SetConsoleTextAttribute(g_hConOut, wAttr);
3803}
3804
3805
3806 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003807textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808{
3809 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
3810
3811 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3812}
3813
3814
3815 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003816textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817{
3818 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
3819
3820 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3821}
3822
3823
3824/*
3825 * restore the default text attribute (whatever we started with)
3826 */
3827 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003828normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003829{
3830 textattr(g_attrDefault);
3831}
3832
3833
3834static WORD g_attrPreStandout = 0;
3835
3836/*
3837 * Make the text standout, by brightening it
3838 */
3839 static void
3840standout(void)
3841{
3842 g_attrPreStandout = g_attrCurrent;
3843 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
3844}
3845
3846
3847/*
3848 * Turn off standout mode
3849 */
3850 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003851standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852{
3853 if (g_attrPreStandout)
3854 {
3855 textattr(g_attrPreStandout);
3856 g_attrPreStandout = 0;
3857 }
3858}
3859
3860
3861/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00003862 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863 */
3864 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003865mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866{
3867 char_u *p;
3868 int n;
3869
3870 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
3871 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
3872 if (T_ME[0] == ESC && T_ME[1] == '|')
3873 {
3874 p = T_ME + 2;
3875 n = getdigits(&p);
3876 if (*p == 'm' && n > 0)
3877 {
3878 cterm_normal_fg_color = (n & 0xf) + 1;
3879 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
3880 }
3881 }
3882}
3883
3884
3885/*
3886 * visual bell: flash the screen
3887 */
3888 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003889visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890{
3891 COORD coordOrigin = {0, 0};
3892 WORD attrFlash = ~g_attrCurrent & 0xff;
3893
3894 DWORD dwDummy;
3895 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
3896
3897 if (oldattrs == NULL)
3898 return;
3899 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3900 coordOrigin, &dwDummy);
3901 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
3902 coordOrigin, &dwDummy);
3903
3904 Sleep(15); /* wait for 15 msec */
3905 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3906 coordOrigin, &dwDummy);
3907 vim_free(oldattrs);
3908}
3909
3910
3911/*
3912 * Make the cursor visible or invisible
3913 */
3914 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003915cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916{
3917 s_cursor_visible = fVisible;
3918#ifdef MCH_CURSOR_SHAPE
3919 mch_update_cursor();
3920#endif
3921}
3922
3923
3924/*
3925 * write `cchToWrite' characters in `pchBuf' to the screen
3926 * Returns the number of characters actually written (at least one).
3927 */
3928 static BOOL
3929write_chars(
3930 LPCSTR pchBuf,
3931 DWORD cchToWrite)
3932{
3933 COORD coord = g_coord;
3934 DWORD written;
3935
3936 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
3937 coord, &written);
3938 /* When writing fails or didn't write a single character, pretend one
3939 * character was written, otherwise we get stuck. */
3940 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
3941 coord, &written) == 0
3942 || written == 0)
3943 written = 1;
3944
3945 g_coord.X += (SHORT) written;
3946
3947 while (g_coord.X > g_srScrollRegion.Right)
3948 {
3949 g_coord.X -= (SHORT) Columns;
3950 if (g_coord.Y < g_srScrollRegion.Bottom)
3951 g_coord.Y++;
3952 }
3953
3954 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3955
3956 return written;
3957}
3958
3959
3960/*
3961 * mch_write(): write the output buffer to the screen, translating ESC
3962 * sequences into calls to console output routines.
3963 */
3964 void
3965mch_write(
3966 char_u *s,
3967 int len)
3968{
3969 s[len] = NUL;
3970
3971 if (!term_console)
3972 {
3973 write(1, s, (unsigned)len);
3974 return;
3975 }
3976
3977 /* translate ESC | sequences into faked bios calls */
3978 while (len--)
3979 {
3980 /* optimization: use one single write_chars for runs of text,
3981 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003982 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983
3984 if (p_wd)
3985 {
3986 WaitForChar(p_wd);
3987 if (prefix != 0)
3988 prefix = 1;
3989 }
3990
3991 if (prefix != 0)
3992 {
3993 DWORD nWritten;
3994
3995 nWritten = write_chars(s, prefix);
3996#ifdef MCH_WRITE_DUMP
3997 if (fdDump)
3998 {
3999 fputc('>', fdDump);
4000 fwrite(s, sizeof(char_u), nWritten, fdDump);
4001 fputs("<\n", fdDump);
4002 }
4003#endif
4004 len -= (nWritten - 1);
4005 s += nWritten;
4006 }
4007 else if (s[0] == '\n')
4008 {
4009 /* \n, newline: go to the beginning of the next line or scroll */
4010 if (g_coord.Y == g_srScrollRegion.Bottom)
4011 {
4012 scroll(1);
4013 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
4014 }
4015 else
4016 {
4017 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
4018 }
4019#ifdef MCH_WRITE_DUMP
4020 if (fdDump)
4021 fputs("\\n\n", fdDump);
4022#endif
4023 s++;
4024 }
4025 else if (s[0] == '\r')
4026 {
4027 /* \r, carriage return: go to beginning of line */
4028 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
4029#ifdef MCH_WRITE_DUMP
4030 if (fdDump)
4031 fputs("\\r\n", fdDump);
4032#endif
4033 s++;
4034 }
4035 else if (s[0] == '\b')
4036 {
4037 /* \b, backspace: move cursor one position left */
4038 if (g_coord.X > g_srScrollRegion.Left)
4039 g_coord.X--;
4040 else if (g_coord.Y > g_srScrollRegion.Top)
4041 {
4042 g_coord.X = g_srScrollRegion.Right;
4043 g_coord.Y--;
4044 }
4045 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4046#ifdef MCH_WRITE_DUMP
4047 if (fdDump)
4048 fputs("\\b\n", fdDump);
4049#endif
4050 s++;
4051 }
4052 else if (s[0] == '\a')
4053 {
4054 /* \a, bell */
4055 MessageBeep(0xFFFFFFFF);
4056#ifdef MCH_WRITE_DUMP
4057 if (fdDump)
4058 fputs("\\a\n", fdDump);
4059#endif
4060 s++;
4061 }
4062 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4063 {
4064#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004065 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004066#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004067 char_u *p;
4068 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004069
4070 switch (s[2])
4071 {
4072 /* one or two numeric arguments, separated by ';' */
4073
4074 case '0': case '1': case '2': case '3': case '4':
4075 case '5': case '6': case '7': case '8': case '9':
4076 p = s + 2;
4077 arg1 = getdigits(&p); /* no check for length! */
4078 if (p > s + len)
4079 break;
4080
4081 if (*p == ';')
4082 {
4083 ++p;
4084 arg2 = getdigits(&p); /* no check for length! */
4085 if (p > s + len)
4086 break;
4087
4088 if (*p == 'H')
4089 gotoxy(arg2, arg1);
4090 else if (*p == 'r')
4091 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4092 }
4093 else if (*p == 'A')
4094 {
4095 /* move cursor up arg1 lines in same column */
4096 gotoxy(g_coord.X + 1,
4097 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4098 }
4099 else if (*p == 'C')
4100 {
4101 /* move cursor right arg1 columns in same line */
4102 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4103 g_coord.Y + 1);
4104 }
4105 else if (*p == 'H')
4106 {
4107 gotoxy(1, arg1);
4108 }
4109 else if (*p == 'L')
4110 {
4111 insert_lines(arg1);
4112 }
4113 else if (*p == 'm')
4114 {
4115 if (arg1 == 0)
4116 normvideo();
4117 else
4118 textattr((WORD) arg1);
4119 }
4120 else if (*p == 'f')
4121 {
4122 textcolor((WORD) arg1);
4123 }
4124 else if (*p == 'b')
4125 {
4126 textbackground((WORD) arg1);
4127 }
4128 else if (*p == 'M')
4129 {
4130 delete_lines(arg1);
4131 }
4132
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004133 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134 s = p + 1;
4135 break;
4136
4137
4138 /* Three-character escape sequences */
4139
4140 case 'A':
4141 /* move cursor up one line in same column */
4142 gotoxy(g_coord.X + 1,
4143 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4144 goto got3;
4145
4146 case 'B':
4147 visual_bell();
4148 goto got3;
4149
4150 case 'C':
4151 /* move cursor right one column in same line */
4152 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4153 g_coord.Y + 1);
4154 goto got3;
4155
4156 case 'E':
4157 termcap_mode_end();
4158 goto got3;
4159
4160 case 'F':
4161 standout();
4162 goto got3;
4163
4164 case 'f':
4165 standend();
4166 goto got3;
4167
4168 case 'H':
4169 gotoxy(1, 1);
4170 goto got3;
4171
4172 case 'j':
4173 clear_to_end_of_display();
4174 goto got3;
4175
4176 case 'J':
4177 clear_screen();
4178 goto got3;
4179
4180 case 'K':
4181 clear_to_end_of_line();
4182 goto got3;
4183
4184 case 'L':
4185 insert_lines(1);
4186 goto got3;
4187
4188 case 'M':
4189 delete_lines(1);
4190 goto got3;
4191
4192 case 'S':
4193 termcap_mode_start();
4194 goto got3;
4195
4196 case 'V':
4197 cursor_visible(TRUE);
4198 goto got3;
4199
4200 case 'v':
4201 cursor_visible(FALSE);
4202 goto got3;
4203
4204 got3:
4205 s += 3;
4206 len -= 2;
4207 }
4208
4209#ifdef MCH_WRITE_DUMP
4210 if (fdDump)
4211 {
4212 fputs("ESC | ", fdDump);
4213 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4214 fputc('\n', fdDump);
4215 }
4216#endif
4217 }
4218 else
4219 {
4220 /* Write a single character */
4221 DWORD nWritten;
4222
4223 nWritten = write_chars(s, 1);
4224#ifdef MCH_WRITE_DUMP
4225 if (fdDump)
4226 {
4227 fputc('>', fdDump);
4228 fwrite(s, sizeof(char_u), nWritten, fdDump);
4229 fputs("<\n", fdDump);
4230 }
4231#endif
4232
4233 len -= (nWritten - 1);
4234 s += nWritten;
4235 }
4236 }
4237
4238#ifdef MCH_WRITE_DUMP
4239 if (fdDump)
4240 fflush(fdDump);
4241#endif
4242}
4243
4244#endif /* FEAT_GUI_W32 */
4245
4246
4247/*
4248 * Delay for half a second.
4249 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004250/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251 void
4252mch_delay(
4253 long msec,
4254 int ignoreinput)
4255{
4256#ifdef FEAT_GUI_W32
4257 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004258#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004260# ifdef FEAT_MZSCHEME
4261 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4262 {
4263 int towait = p_mzq;
4264
4265 /* if msec is large enough, wait by portions in p_mzq */
4266 while (msec > 0)
4267 {
4268 mzvim_check_threads();
4269 if (msec < towait)
4270 towait = msec;
4271 Sleep(towait);
4272 msec -= towait;
4273 }
4274 }
4275 else
4276# endif
4277 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004278 else
4279 WaitForChar(msec);
4280#endif
4281}
4282
4283
4284/*
4285 * this version of remove is not scared by a readonly (backup) file
4286 * Return 0 for success, -1 for failure.
4287 */
4288 int
4289mch_remove(char_u *name)
4290{
4291#ifdef FEAT_MBYTE
4292 WCHAR *wn = NULL;
4293 int n;
4294
4295 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4296 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004297 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298 if (wn != NULL)
4299 {
4300 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4301 n = DeleteFileW(wn) ? 0 : -1;
4302 vim_free(wn);
4303 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4304 return n;
4305 /* Retry with non-wide function (for Windows 98). */
4306 }
4307 }
4308#endif
4309 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4310 return DeleteFile(name) ? 0 : -1;
4311}
4312
4313
4314/*
4315 * check for an "interrupt signal": CTRL-break or CTRL-C
4316 */
4317 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004318mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319{
4320#ifndef FEAT_GUI_W32 /* never used */
4321 if (g_fCtrlCPressed || g_fCBrkPressed)
4322 {
4323 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4324 got_int = TRUE;
4325 }
4326#endif
4327}
4328
4329
4330/*
4331 * How much memory is available?
4332 * Return sum of available physical and page file memory.
4333 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004334/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004335 long_u
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004336mch_avail_mem(int special)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337{
4338 MEMORYSTATUS ms;
4339
4340 ms.dwLength = sizeof(MEMORYSTATUS);
4341 GlobalMemoryStatus(&ms);
4342 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
4343}
4344
4345#ifdef FEAT_MBYTE
4346/*
4347 * Same code as below, but with wide functions and no comments.
4348 * Return 0 for success, non-zero for failure.
4349 */
4350 int
4351mch_wrename(WCHAR *wold, WCHAR *wnew)
4352{
4353 WCHAR *p;
4354 int i;
4355 WCHAR szTempFile[_MAX_PATH + 1];
4356 WCHAR szNewPath[_MAX_PATH + 1];
4357 HANDLE hf;
4358
4359 if (!mch_windows95())
4360 {
4361 p = wold;
4362 for (i = 0; wold[i] != NUL; ++i)
4363 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
4364 && wold[i + 1] != 0)
4365 p = wold + i + 1;
4366 if ((int)(wold + i - p) < 8 || p[6] != '~')
4367 return (MoveFileW(wold, wnew) == 0);
4368 }
4369
4370 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
4371 return -1;
4372 *p = NUL;
4373
4374 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
4375 return -2;
4376
4377 if (!DeleteFileW(szTempFile))
4378 return -3;
4379
4380 if (!MoveFileW(wold, szTempFile))
4381 return -4;
4382
4383 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4384 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4385 return -5;
4386 if (!CloseHandle(hf))
4387 return -6;
4388
4389 if (!MoveFileW(szTempFile, wnew))
4390 {
4391 (void)MoveFileW(szTempFile, wold);
4392 return -7;
4393 }
4394
4395 DeleteFileW(szTempFile);
4396
4397 if (!DeleteFileW(wold))
4398 return -8;
4399
4400 return 0;
4401}
4402#endif
4403
4404
4405/*
4406 * mch_rename() works around a bug in rename (aka MoveFile) in
4407 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4408 * file whose short file name is "FOO.BAR" (its long file name will
4409 * be correct: "foo.bar~"). Because a file can be accessed by
4410 * either its SFN or its LFN, "foo.bar" has effectively been
4411 * renamed to "foo.bar", which is not at all what was wanted. This
4412 * seems to happen only when renaming files with three-character
4413 * extensions by appending a suffix that does not include ".".
4414 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4415 *
4416 * There is another problem, which isn't really a bug but isn't right either:
4417 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
4418 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
4419 * service pack 6. Doesn't seem to happen on Windows 98.
4420 *
4421 * Like rename(), returns 0 upon success, non-zero upon failure.
4422 * Should probably set errno appropriately when errors occur.
4423 */
4424 int
4425mch_rename(
4426 const char *pszOldFile,
4427 const char *pszNewFile)
4428{
4429 char szTempFile[_MAX_PATH+1];
4430 char szNewPath[_MAX_PATH+1];
4431 char *pszFilePart;
4432 HANDLE hf;
4433#ifdef FEAT_MBYTE
4434 WCHAR *wold = NULL;
4435 WCHAR *wnew = NULL;
4436 int retval = -1;
4437
4438 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4439 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004440 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
4441 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004442 if (wold != NULL && wnew != NULL)
4443 retval = mch_wrename(wold, wnew);
4444 vim_free(wold);
4445 vim_free(wnew);
4446 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4447 return retval;
4448 /* Retry with non-wide function (for Windows 98). */
4449 }
4450#endif
4451
4452 /*
4453 * No need to play tricks if not running Windows 95, unless the file name
4454 * contains a "~" as the seventh character.
4455 */
4456 if (!mch_windows95())
4457 {
4458 pszFilePart = (char *)gettail((char_u *)pszOldFile);
4459 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
4460 return rename(pszOldFile, pszNewFile);
4461 }
4462
4463 /* Get base path of new file name. Undocumented feature: If pszNewFile is
4464 * a directory, no error is returned and pszFilePart will be NULL. */
4465 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
4466 || pszFilePart == NULL)
4467 return -1;
4468 *pszFilePart = NUL;
4469
4470 /* Get (and create) a unique temporary file name in directory of new file */
4471 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
4472 return -2;
4473
4474 /* blow the temp file away */
4475 if (!DeleteFile(szTempFile))
4476 return -3;
4477
4478 /* rename old file to the temp file */
4479 if (!MoveFile(pszOldFile, szTempFile))
4480 return -4;
4481
4482 /* now create an empty file called pszOldFile; this prevents the operating
4483 * system using pszOldFile as an alias (SFN) if we're renaming within the
4484 * same directory. For example, we're editing a file called
4485 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
4486 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
4487 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004488 * cause all sorts of problems later in buf_write(). So, we create an
4489 * empty file called filena~1.txt and the system will have to find some
4490 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00004491 */
4492 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4493 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4494 return -5;
4495 if (!CloseHandle(hf))
4496 return -6;
4497
4498 /* rename the temp file to the new file */
4499 if (!MoveFile(szTempFile, pszNewFile))
4500 {
4501 /* Renaming failed. Rename the file back to its old name, so that it
4502 * looks like nothing happened. */
4503 (void)MoveFile(szTempFile, pszOldFile);
4504
4505 return -7;
4506 }
4507
4508 /* Seems to be left around on Novell filesystems */
4509 DeleteFile(szTempFile);
4510
4511 /* finally, remove the empty old file */
4512 if (!DeleteFile(pszOldFile))
4513 return -8;
4514
4515 return 0; /* success */
4516}
4517
4518/*
4519 * Get the default shell for the current hardware platform
4520 */
4521 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004522default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523{
4524 char* psz = NULL;
4525
4526 PlatformId();
4527
4528 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
4529 psz = "cmd.exe";
4530 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
4531 psz = "command.com";
4532
4533 return psz;
4534}
4535
4536/*
4537 * mch_access() extends access() to do more detailed check on network drives.
4538 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
4539 */
4540 int
4541mch_access(char *n, int p)
4542{
4543 HANDLE hFile;
4544 DWORD am;
4545 int retval = -1; /* default: fail */
4546#ifdef FEAT_MBYTE
4547 WCHAR *wn = NULL;
4548
4549 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004550 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004551#endif
4552
4553 if (mch_isdir(n))
4554 {
4555 char TempName[_MAX_PATH + 16] = "";
4556#ifdef FEAT_MBYTE
4557 WCHAR TempNameW[_MAX_PATH + 16] = L"";
4558#endif
4559
4560 if (p & R_OK)
4561 {
4562 /* Read check is performed by seeing if we can do a find file on
4563 * the directory for any file. */
4564#ifdef FEAT_MBYTE
4565 if (wn != NULL)
4566 {
4567 int i;
4568 WIN32_FIND_DATAW d;
4569
4570 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
4571 TempNameW[i] = wn[i];
4572 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
4573 TempNameW[i++] = '\\';
4574 TempNameW[i++] = '*';
4575 TempNameW[i++] = 0;
4576
4577 hFile = FindFirstFileW(TempNameW, &d);
4578 if (hFile == INVALID_HANDLE_VALUE)
4579 {
4580 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4581 goto getout;
4582
4583 /* Retry with non-wide function (for Windows 98). */
4584 vim_free(wn);
4585 wn = NULL;
4586 }
4587 else
4588 (void)FindClose(hFile);
4589 }
4590 if (wn == NULL)
4591#endif
4592 {
4593 char *pch;
4594 WIN32_FIND_DATA d;
4595
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00004596 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004597 pch = TempName + STRLEN(TempName) - 1;
4598 if (*pch != '\\' && *pch != '/')
4599 *++pch = '\\';
4600 *++pch = '*';
4601 *++pch = NUL;
4602
4603 hFile = FindFirstFile(TempName, &d);
4604 if (hFile == INVALID_HANDLE_VALUE)
4605 goto getout;
4606 (void)FindClose(hFile);
4607 }
4608 }
4609
4610 if (p & W_OK)
4611 {
4612 /* Trying to create a temporary file in the directory should catch
4613 * directories on read-only network shares. However, in
4614 * directories whose ACL allows writes but denies deletes will end
4615 * up keeping the temporary file :-(. */
4616#ifdef FEAT_MBYTE
4617 if (wn != NULL)
4618 {
4619 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
4620 {
4621 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4622 goto getout;
4623
4624 /* Retry with non-wide function (for Windows 98). */
4625 vim_free(wn);
4626 wn = NULL;
4627 }
4628 else
4629 DeleteFileW(TempNameW);
4630 }
4631 if (wn == NULL)
4632#endif
4633 {
4634 if (!GetTempFileName(n, "VIM", 0, TempName))
4635 goto getout;
4636 mch_remove((char_u *)TempName);
4637 }
4638 }
4639 }
4640 else
4641 {
4642 /* Trying to open the file for the required access does ACL, read-only
4643 * network share, and file attribute checks. */
4644 am = ((p & W_OK) ? GENERIC_WRITE : 0)
4645 | ((p & R_OK) ? GENERIC_READ : 0);
4646#ifdef FEAT_MBYTE
4647 if (wn != NULL)
4648 {
4649 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4650 if (hFile == INVALID_HANDLE_VALUE
4651 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4652 {
4653 /* Retry with non-wide function (for Windows 98). */
4654 vim_free(wn);
4655 wn = NULL;
4656 }
4657 }
4658 if (wn == NULL)
4659#endif
4660 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4661 if (hFile == INVALID_HANDLE_VALUE)
4662 goto getout;
4663 CloseHandle(hFile);
4664 }
4665
4666 retval = 0; /* success */
4667getout:
4668#ifdef FEAT_MBYTE
4669 vim_free(wn);
4670#endif
4671 return retval;
4672}
4673
4674#if defined(FEAT_MBYTE) || defined(PROTO)
4675/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004676 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004677 */
4678 int
4679mch_open(char *name, int flags, int mode)
4680{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004681 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
4682# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683 WCHAR *wn;
4684 int f;
4685
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004686 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004688 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004689 if (wn != NULL)
4690 {
4691 f = _wopen(wn, flags, mode);
4692 vim_free(wn);
4693 if (f >= 0)
4694 return f;
4695 /* Retry with non-wide function (for Windows 98). Can't use
4696 * GetLastError() here and it's unclear what errno gets set to if
4697 * the _wopen() fails for missing wide functions. */
4698 }
4699 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004700# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004701
4702 return open(name, flags, mode);
4703}
4704
4705/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004706 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004707 */
4708 FILE *
4709mch_fopen(char *name, char *mode)
4710{
4711 WCHAR *wn, *wm;
4712 FILE *f = NULL;
4713
4714 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
4715# ifdef __BORLANDC__
4716 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4717 && g_PlatformId == VER_PLATFORM_WIN32_NT
4718# endif
4719 )
4720 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00004721# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004722 /* Work around an annoying assertion in the Microsoft debug CRT
4723 * when mode's text/binary setting doesn't match _get_fmode(). */
4724 char newMode = mode[strlen(mode) - 1];
4725 int oldMode = 0;
4726
4727 _get_fmode(&oldMode);
4728 if (newMode == 't')
4729 _set_fmode(_O_TEXT);
4730 else if (newMode == 'b')
4731 _set_fmode(_O_BINARY);
4732# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004733 wn = enc_to_utf16(name, NULL);
4734 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735 if (wn != NULL && wm != NULL)
4736 f = _wfopen(wn, wm);
4737 vim_free(wn);
4738 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004739
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00004740# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004741 _set_fmode(oldMode);
4742# endif
4743
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744 if (f != NULL)
4745 return f;
4746 /* Retry with non-wide function (for Windows 98). Can't use
4747 * GetLastError() here and it's unclear what errno gets set to if
4748 * the _wfopen() fails for missing wide functions. */
4749 }
4750
4751 return fopen(name, mode);
4752}
4753#endif
4754
4755#ifdef FEAT_MBYTE
4756/*
4757 * SUB STREAM (aka info stream) handling:
4758 *
4759 * NTFS can have sub streams for each file. Normal contents of file is
4760 * stored in the main stream, and extra contents (author information and
4761 * title and so on) can be stored in sub stream. After Windows 2000, user
4762 * can access and store those informations in sub streams via explorer's
4763 * property menuitem in right click menu. Those informations in sub streams
4764 * were lost when copying only the main stream. So we have to copy sub
4765 * streams.
4766 *
4767 * Incomplete explanation:
4768 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
4769 * More useful info and an example:
4770 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
4771 */
4772
4773/*
4774 * Copy info stream data "substream". Read from the file with BackupRead(sh)
4775 * and write to stream "substream" of file "to".
4776 * Errors are ignored.
4777 */
4778 static void
4779copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
4780{
4781 HANDLE hTo;
4782 WCHAR *to_name;
4783
4784 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
4785 wcscpy(to_name, to);
4786 wcscat(to_name, substream);
4787
4788 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
4789 FILE_ATTRIBUTE_NORMAL, NULL);
4790 if (hTo != INVALID_HANDLE_VALUE)
4791 {
4792 long done;
4793 DWORD todo;
4794 DWORD readcnt, written;
4795 char buf[4096];
4796
4797 /* Copy block of bytes at a time. Abort when something goes wrong. */
4798 for (done = 0; done < len; done += written)
4799 {
4800 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004801 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
4802 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004803 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
4804 FALSE, FALSE, context)
4805 || readcnt != todo
4806 || !WriteFile(hTo, buf, todo, &written, NULL)
4807 || written != todo)
4808 break;
4809 }
4810 CloseHandle(hTo);
4811 }
4812
4813 free(to_name);
4814}
4815
4816/*
4817 * Copy info streams from file "from" to file "to".
4818 */
4819 static void
4820copy_infostreams(char_u *from, char_u *to)
4821{
4822 WCHAR *fromw;
4823 WCHAR *tow;
4824 HANDLE sh;
4825 WIN32_STREAM_ID sid;
4826 int headersize;
4827 WCHAR streamname[_MAX_PATH];
4828 DWORD readcount;
4829 void *context = NULL;
4830 DWORD lo, hi;
4831 int len;
4832
4833 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004834 fromw = enc_to_utf16(from, NULL);
4835 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836 if (fromw != NULL && tow != NULL)
4837 {
4838 /* Open the file for reading. */
4839 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
4840 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4841 if (sh != INVALID_HANDLE_VALUE)
4842 {
4843 /* Use BackupRead() to find the info streams. Repeat until we
4844 * have done them all.*/
4845 for (;;)
4846 {
4847 /* Get the header to find the length of the stream name. If
4848 * the "readcount" is zero we have done all info streams. */
4849 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004850 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
4852 &readcount, FALSE, FALSE, &context)
4853 || readcount == 0)
4854 break;
4855
4856 /* We only deal with streams that have a name. The normal
4857 * file data appears to be without a name, even though docs
4858 * suggest it is called "::$DATA". */
4859 if (sid.dwStreamNameSize > 0)
4860 {
4861 /* Read the stream name. */
4862 if (!BackupRead(sh, (LPBYTE)streamname,
4863 sid.dwStreamNameSize,
4864 &readcount, FALSE, FALSE, &context))
4865 break;
4866
4867 /* Copy an info stream with a name ":anything:$DATA".
4868 * Skip "::$DATA", it has no stream name (examples suggest
4869 * it might be used for the normal file contents).
4870 * Note that BackupRead() counts bytes, but the name is in
4871 * wide characters. */
4872 len = readcount / sizeof(WCHAR);
4873 streamname[len] = 0;
4874 if (len > 7 && wcsicmp(streamname + len - 6,
4875 L":$DATA") == 0)
4876 {
4877 streamname[len - 6] = 0;
4878 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004879 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004880 }
4881 }
4882
4883 /* Advance to the next stream. We might try seeking too far,
4884 * but BackupSeek() doesn't skip over stream borders, thus
4885 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004886 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004887 &lo, &hi, &context);
4888 }
4889
4890 /* Clear the context. */
4891 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
4892
4893 CloseHandle(sh);
4894 }
4895 }
4896 vim_free(fromw);
4897 vim_free(tow);
4898}
4899#endif
4900
4901/*
4902 * Copy file attributes from file "from" to file "to".
4903 * For Windows NT and later we copy info streams.
4904 * Always returns zero, errors are ignored.
4905 */
4906 int
4907mch_copy_file_attribute(char_u *from, char_u *to)
4908{
4909#ifdef FEAT_MBYTE
4910 /* File streams only work on Windows NT and later. */
4911 PlatformId();
4912 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
4913 copy_infostreams(from, to);
4914#endif
4915 return 0;
4916}
4917
4918#if defined(MYRESETSTKOFLW) || defined(PROTO)
4919/*
4920 * Recreate a destroyed stack guard page in win32.
4921 * Written by Benjamin Peterson.
4922 */
4923
4924/* These magic numbers are from the MS header files */
4925#define MIN_STACK_WIN9X 17
4926#define MIN_STACK_WINNT 2
4927
4928/*
4929 * This function does the same thing as _resetstkoflw(), which is only
4930 * available in DevStudio .net and later.
4931 * Returns 0 for failure, 1 for success.
4932 */
4933 int
4934myresetstkoflw(void)
4935{
4936 BYTE *pStackPtr;
4937 BYTE *pGuardPage;
4938 BYTE *pStackBase;
4939 BYTE *pLowestPossiblePage;
4940 MEMORY_BASIC_INFORMATION mbi;
4941 SYSTEM_INFO si;
4942 DWORD nPageSize;
4943 DWORD dummy;
4944
4945 /* This code will not work on win32s. */
4946 PlatformId();
4947 if (g_PlatformId == VER_PLATFORM_WIN32s)
4948 return 0;
4949
4950 /* We need to know the system page size. */
4951 GetSystemInfo(&si);
4952 nPageSize = si.dwPageSize;
4953
4954 /* ...and the current stack pointer */
4955 pStackPtr = (BYTE*)_alloca(1);
4956
4957 /* ...and the base of the stack. */
4958 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
4959 return 0;
4960 pStackBase = (BYTE*)mbi.AllocationBase;
4961
4962 /* ...and the page thats min_stack_req pages away from stack base; this is
4963 * the lowest page we could use. */
4964 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
4965 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
4966
4967 /* On Win95, we want the next page down from the end of the stack. */
4968 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
4969 {
4970 /* Find the page that's only 1 page down from the page that the stack
4971 * ptr is in. */
4972 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
4973 / (DWORD)nPageSize) - 1));
4974 if (pGuardPage < pLowestPossiblePage)
4975 return 0;
4976
4977 /* Apply the noaccess attribute to the page -- there's no guard
4978 * attribute in win95-type OSes. */
4979 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
4980 return 0;
4981 }
4982 else
4983 {
4984 /* On NT, however, we want the first committed page in the stack Start
4985 * at the stack base and move forward through memory until we find a
4986 * committed block. */
4987 BYTE *pBlock = pStackBase;
4988
Bram Moolenaara466c992005-07-09 21:03:22 +00004989 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004990 {
4991 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
4992 return 0;
4993
4994 pBlock += mbi.RegionSize;
4995
4996 if (mbi.State & MEM_COMMIT)
4997 break;
4998 }
4999
5000 /* mbi now describes the first committed block in the stack. */
5001 if (mbi.Protect & PAGE_GUARD)
5002 return 1;
5003
5004 /* decide where the guard page should start */
5005 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
5006 pGuardPage = pLowestPossiblePage;
5007 else
5008 pGuardPage = (BYTE*)mbi.BaseAddress;
5009
5010 /* allocate the guard page */
5011 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
5012 return 0;
5013
5014 /* apply the guard attribute to the page */
5015 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
5016 &dummy))
5017 return 0;
5018 }
5019
5020 return 1;
5021}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005022#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005024
5025#if defined(FEAT_MBYTE) || defined(PROTO)
5026/*
5027 * The command line arguments in UCS2
5028 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005029static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005030static LPWSTR *ArglistW = NULL;
5031static int global_argc = 0;
5032static char **global_argv;
5033
5034static int used_file_argc = 0; /* last argument in global_argv[] used
5035 for the argument list. */
5036static int *used_file_indexes = NULL; /* indexes in global_argv[] for
5037 command line arguments added to
5038 the argument list */
5039static int used_file_count = 0; /* nr of entries in used_file_indexes */
5040static int used_file_literal = FALSE; /* take file names literally */
5041static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005042static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005043static int used_alist_count = 0;
5044
5045
5046/*
5047 * Get the command line arguments. Unicode version.
5048 * Returns argc. Zero when something fails.
5049 */
5050 int
5051get_cmd_argsW(char ***argvp)
5052{
5053 char **argv = NULL;
5054 int argc = 0;
5055 int i;
5056
5057 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5058 if (ArglistW != NULL)
5059 {
5060 argv = malloc((nArgsW + 1) * sizeof(char *));
5061 if (argv != NULL)
5062 {
5063 argc = nArgsW;
5064 argv[argc] = NULL;
5065 for (i = 0; i < argc; ++i)
5066 {
5067 int len;
5068
5069 /* Convert each Unicode argument to the current codepage. */
5070 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005071 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005072 (LPSTR *)&argv[i], &len, 0, 0);
5073 if (argv[i] == NULL)
5074 {
5075 /* Out of memory, clear everything. */
5076 while (i > 0)
5077 free(argv[--i]);
5078 free(argv);
5079 argc = 0;
5080 }
5081 }
5082 }
5083 }
5084
5085 global_argc = argc;
5086 global_argv = argv;
5087 if (argc > 0)
5088 used_file_indexes = malloc(argc * sizeof(int));
5089
5090 if (argvp != NULL)
5091 *argvp = argv;
5092 return argc;
5093}
5094
5095 void
5096free_cmd_argsW(void)
5097{
5098 if (ArglistW != NULL)
5099 {
5100 GlobalFree(ArglistW);
5101 ArglistW = NULL;
5102 }
5103}
5104
5105/*
5106 * Remember "name" is an argument that was added to the argument list.
5107 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5108 * is called.
5109 */
5110 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005111used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005112{
5113 int i;
5114
5115 if (used_file_indexes == NULL)
5116 return;
5117 for (i = used_file_argc + 1; i < global_argc; ++i)
5118 if (STRCMP(global_argv[i], name) == 0)
5119 {
5120 used_file_argc = i;
5121 used_file_indexes[used_file_count++] = i;
5122 break;
5123 }
5124 used_file_literal = literal;
5125 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005126 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005127}
5128
5129/*
5130 * Remember the length of the argument list as it was. If it changes then we
5131 * leave it alone when 'encoding' is set.
5132 */
5133 void
5134set_alist_count(void)
5135{
5136 used_alist_count = GARGCOUNT;
5137}
5138
5139/*
5140 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5141 * has been changed while starting up. Use the UCS-2 command line arguments
5142 * and convert them to 'encoding'.
5143 */
5144 void
5145fix_arg_enc(void)
5146{
5147 int i;
5148 int idx;
5149 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005150 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005151
5152 /* Safety checks:
5153 * - if argument count differs between the wide and non-wide argument
5154 * list, something must be wrong.
5155 * - the file name arguments must have been located.
5156 * - the length of the argument list wasn't changed by the user.
5157 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005158 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005159 || ArglistW == NULL
5160 || used_file_indexes == NULL
5161 || used_file_count == 0
5162 || used_alist_count != GARGCOUNT)
5163 return;
5164
Bram Moolenaar86b68352004-12-27 21:59:20 +00005165 /* Remember the buffer numbers for the arguments. */
5166 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5167 if (fnum_list == NULL)
5168 return; /* out of memory */
5169 for (i = 0; i < GARGCOUNT; ++i)
5170 fnum_list[i] = GARGLIST[i].ae_fnum;
5171
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005172 /* Clear the argument list. Make room for the new arguments. */
5173 alist_clear(&global_alist);
5174 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005175 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005176
5177 for (i = 0; i < used_file_count; ++i)
5178 {
5179 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005180 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005181 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005182 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005183#ifdef FEAT_DIFF
5184 /* When using diff mode may need to concatenate file name to
5185 * directory name. Just like it's done in main(). */
5186 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5187 && !mch_isdir(alist_name(&GARGLIST[0])))
5188 {
5189 char_u *r;
5190
5191 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5192 if (r != NULL)
5193 {
5194 vim_free(str);
5195 str = r;
5196 }
5197 }
5198#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005199 /* Re-use the old buffer by renaming it. When not using literal
5200 * names it's done by alist_expand() below. */
5201 if (used_file_literal)
5202 buf_set_name(fnum_list[i], str);
5203
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005204 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005205 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005206 }
5207
5208 if (!used_file_literal)
5209 {
5210 /* Now expand wildcards in the arguments. */
5211 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5212 * filename characters but are excluded from 'isfname' to make
5213 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5214 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005215 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005216 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5217 }
5218
5219 /* If wildcard expansion failed, we are editing the first file of the
5220 * arglist and there is no file name: Edit the first argument now. */
5221 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5222 {
5223 do_cmdline_cmd((char_u *)":rewind");
5224 if (GARGCOUNT == 1 && used_file_full_path)
5225 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5226 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005227
5228 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005229}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005230#endif