blob: 88ead6fd637c194757a8f09da85eddabaafc5a83 [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 Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
32#include <process.h>
33
34#undef chdir
35#ifdef __GNUC__
36# ifndef __MINGW32__
37# include <dirent.h>
38# endif
39#else
40# include <direct.h>
41#endif
42
43#if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
44# include <shellapi.h>
45#endif
46
47#ifdef __MINGW32__
48# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
49# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
50# endif
51# ifndef RIGHTMOST_BUTTON_PRESSED
52# define RIGHTMOST_BUTTON_PRESSED 0x0002
53# endif
54# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
55# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
56# endif
57# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
58# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
59# endif
60# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
61# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
62# endif
63
64/*
65 * EventFlags
66 */
67# ifndef MOUSE_MOVED
68# define MOUSE_MOVED 0x0001
69# endif
70# ifndef DOUBLE_CLICK
71# define DOUBLE_CLICK 0x0002
72# endif
73#endif
74
75/* Record all output and all keyboard & mouse input */
76/* #define MCH_WRITE_DUMP */
77
78#ifdef MCH_WRITE_DUMP
79FILE* fdDump = NULL;
80#endif
81
82/*
83 * When generating prototypes for Win32 on Unix, these lines make the syntax
84 * errors disappear. They do not need to be correct.
85 */
86#ifdef PROTO
87#define WINAPI
88#define WINBASEAPI
89typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000090typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000091typedef int ACCESS_MASK;
92typedef int BOOL;
93typedef int COLORREF;
94typedef int CONSOLE_CURSOR_INFO;
95typedef int COORD;
96typedef int DWORD;
97typedef int HANDLE;
98typedef int HDC;
99typedef int HFONT;
100typedef int HICON;
101typedef int HINSTANCE;
102typedef int HWND;
103typedef int INPUT_RECORD;
104typedef int KEY_EVENT_RECORD;
105typedef int LOGFONT;
106typedef int LPBOOL;
107typedef int LPCTSTR;
108typedef int LPDWORD;
109typedef int LPSTR;
110typedef int LPTSTR;
111typedef int LPVOID;
112typedef int MOUSE_EVENT_RECORD;
113typedef int PACL;
114typedef int PDWORD;
115typedef int PHANDLE;
116typedef int PRINTDLG;
117typedef int PSECURITY_DESCRIPTOR;
118typedef int PSID;
119typedef int SECURITY_INFORMATION;
120typedef int SHORT;
121typedef int SMALL_RECT;
122typedef int TEXTMETRIC;
123typedef int TOKEN_INFORMATION_CLASS;
124typedef int TRUSTEE;
125typedef int WORD;
126typedef int WCHAR;
127typedef void VOID;
128#endif
129
130#ifndef FEAT_GUI_W32
131/* Undocumented API in kernel32.dll needed to work around dead key bug in
132 * console-mode applications in NT 4.0. If you switch keyboard layouts
133 * in a console app to a layout that includes dead keys and then hit a
134 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
135 * and Michael Dietrich for helping me figure out this workaround.
136 */
137
138/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
139#ifndef WINBASEAPI
140# define WINBASEAPI __stdcall
141#endif
142#if defined(__BORLANDC__)
143typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
144#else
145typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
146#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000147static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
150#if defined(__BORLANDC__)
151/* Strangely Borland uses a non-standard name. */
152# define wcsicmp(a, b) wcscmpi((a), (b))
153#endif
154
155#ifndef FEAT_GUI_W32
156/* Win32 Console handles for input and output */
157static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
158static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
159
160/* Win32 Screen buffer,coordinate,console I/O information */
161static SMALL_RECT g_srScrollRegion;
162static COORD g_coord; /* 0-based, but external coords are 1-based */
163
164/* The attribute of the screen when the editor was started */
165static WORD g_attrDefault = 7; /* lightgray text on black background */
166static WORD g_attrCurrent;
167
168static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
169static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
170static int g_fForceExit = FALSE; /* set when forcefully exiting */
171
172static void termcap_mode_start(void);
173static void termcap_mode_end(void);
174static void clear_chars(COORD coord, DWORD n);
175static void clear_screen(void);
176static void clear_to_end_of_display(void);
177static void clear_to_end_of_line(void);
178static void scroll(unsigned cLines);
179static void set_scroll_region(unsigned left, unsigned top,
180 unsigned right, unsigned bottom);
181static void insert_lines(unsigned cLines);
182static void delete_lines(unsigned cLines);
183static void gotoxy(unsigned x, unsigned y);
184static void normvideo(void);
185static void textattr(WORD wAttr);
186static void textcolor(WORD wAttr);
187static void textbackground(WORD wAttr);
188static void standout(void);
189static void standend(void);
190static void visual_bell(void);
191static void cursor_visible(BOOL fVisible);
192static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
193static char_u tgetch(int *pmodifiers, char_u *pch2);
194static void create_conin(void);
195static int s_cursor_visible = TRUE;
196static int did_create_conin = FALSE;
197#else
198static int s_dont_use_vimrun = TRUE;
199static int need_vimrun_warning = FALSE;
200static char *vimrun_path = "vimrun ";
201#endif
202
203#ifndef FEAT_GUI_W32
204static int suppress_winsize = 1; /* don't fiddle with console */
205#endif
206
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200207static char_u *exe_path = NULL;
208
Bram Moolenaar071d4272004-06-13 20:20:40 +0000209 static void
210get_exe_name(void)
211{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100212 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
213 * as the maximum length that works (plus a NUL byte). */
214#define MAX_ENV_PATH_LEN 8192
215 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200216 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000217
218 if (exe_name == NULL)
219 {
220 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100221 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000222 if (*temp != NUL)
223 exe_name = FullName_save((char_u *)temp, FALSE);
224 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000225
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200226 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000227 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200228 exe_path = vim_strnsave(exe_name,
229 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200230 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000231 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200232 /* Append our starting directory to $PATH, so that when doing
233 * "!xxd" it's found in our starting directory. Needed because
234 * SearchPath() also looks there. */
235 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100236 if (p == NULL
237 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200238 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100239 if (p == NULL || *p == NUL)
240 temp[0] = NUL;
241 else
242 {
243 STRCPY(temp, p);
244 STRCAT(temp, ";");
245 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200246 STRCAT(temp, exe_path);
247 vim_setenv((char_u *)"PATH", temp);
248 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000249 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000250 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000251}
252
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200253/*
254 * Load library "name".
255 */
256 HINSTANCE
257vimLoadLib(char *name)
258{
259 HINSTANCE dll = NULL;
260 char old_dir[MAXPATHL];
261
262 if (exe_path == NULL)
263 get_exe_name();
264 if (exe_path != NULL && mch_dirname(old_dir, MAXPATHL) == OK)
265 {
266 /* Change directory to where the executable is, both to make sure we
267 * find a .dll there and to avoid looking for a .dll in the current
268 * directory. */
269 mch_chdir(exe_path);
270 dll = LoadLibrary(name);
271 mch_chdir(old_dir);
272 }
273 return dll;
274}
275
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
277# ifndef GETTEXT_DLL
278# define GETTEXT_DLL "libintl.dll"
279# endif
280/* Dummy funcitons */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000281static char *null_libintl_gettext(const char *);
282static char *null_libintl_textdomain(const char *);
283static char *null_libintl_bindtextdomain(const char *, const char *);
284static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000285
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200286static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000287char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
288char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
289char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000290 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000291char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
292 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000293
294 int
295dyn_libintl_init(char *libname)
296{
297 int i;
298 static struct
299 {
300 char *name;
301 FARPROC *ptr;
302 } libintl_entry[] =
303 {
304 {"gettext", (FARPROC*)&dyn_libintl_gettext},
305 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
306 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
307 {NULL, NULL}
308 };
309
310 /* No need to initialize twice. */
311 if (hLibintlDLL)
312 return 1;
313 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200314 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000315 if (!hLibintlDLL)
316 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200317 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000318 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200319 verbose_enter();
320 EMSG2(_(e_loadlib), GETTEXT_DLL);
321 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000322 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200323 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324 }
325 for (i = 0; libintl_entry[i].name != NULL
326 && libintl_entry[i].ptr != NULL; ++i)
327 {
328 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
329 libintl_entry[i].name)) == NULL)
330 {
331 dyn_libintl_end();
332 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000333 {
334 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000335 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000336 verbose_leave();
337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000338 return 0;
339 }
340 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000341
342 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000343 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000344 "bind_textdomain_codeset");
345 if (dyn_libintl_bind_textdomain_codeset == NULL)
346 dyn_libintl_bind_textdomain_codeset =
347 null_libintl_bind_textdomain_codeset;
348
Bram Moolenaar071d4272004-06-13 20:20:40 +0000349 return 1;
350}
351
352 void
353dyn_libintl_end()
354{
355 if (hLibintlDLL)
356 FreeLibrary(hLibintlDLL);
357 hLibintlDLL = NULL;
358 dyn_libintl_gettext = null_libintl_gettext;
359 dyn_libintl_textdomain = null_libintl_textdomain;
360 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000361 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000362}
363
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000364/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000366null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367{
368 return (char*)msgid;
369}
370
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000371/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000372 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000373null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000374{
375 return NULL;
376}
377
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000378/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000379 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000380null_libintl_bind_textdomain_codeset(const char *domainname,
381 const char *codeset)
382{
383 return NULL;
384}
385
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000386/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000387 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000388null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389{
390 return NULL;
391}
392
393#endif /* DYNAMIC_GETTEXT */
394
395/* This symbol is not defined in older versions of the SDK or Visual C++ */
396
397#ifndef VER_PLATFORM_WIN32_WINDOWS
398# define VER_PLATFORM_WIN32_WINDOWS 1
399#endif
400
401DWORD g_PlatformId;
402
403#ifdef HAVE_ACL
404# include <aclapi.h>
405/*
406 * These are needed to dynamically load the ADVAPI DLL, which is not
407 * implemented under Windows 95 (and causes VIM to crash)
408 */
409typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
410 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
411typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
412 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
413 PSECURITY_DESCRIPTOR *);
414
415static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
416static PSNSECINFO pSetNamedSecurityInfo;
417static PGNSECINFO pGetNamedSecurityInfo;
418#endif
419
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200420typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
421
422static BOOL allowPiping = FALSE;
423static PSETHANDLEINFORMATION pSetHandleInformation;
424
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425/*
426 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
427 * VER_PLATFORM_WIN32_WINDOWS (Win95).
428 */
429 void
430PlatformId(void)
431{
432 static int done = FALSE;
433
434 if (!done)
435 {
436 OSVERSIONINFO ovi;
437
438 ovi.dwOSVersionInfoSize = sizeof(ovi);
439 GetVersionEx(&ovi);
440
441 g_PlatformId = ovi.dwPlatformId;
442
443#ifdef HAVE_ACL
444 /*
445 * Load the ADVAPI runtime if we are on anything
446 * other than Windows 95
447 */
448 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
449 {
450 /*
451 * do this load. Problems: Doesn't unload at end of run (this is
452 * theoretically okay, since Windows should unload it when VIM
453 * terminates). Should we be using the 'mch_libcall' routines?
454 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
455 * time we verify security...
456 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200457 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 if (advapi_lib != NULL)
459 {
460 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
461 "SetNamedSecurityInfoA");
462 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
463 "GetNamedSecurityInfoA");
464 if (pSetNamedSecurityInfo == NULL
465 || pGetNamedSecurityInfo == NULL)
466 {
467 /* If we can't get the function addresses, set advapi_lib
468 * to NULL so that we don't use them. */
469 FreeLibrary(advapi_lib);
470 advapi_lib = NULL;
471 }
472 }
473 }
474#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200475 /*
476 * If we are on windows NT, try to load the pipe functions, only
477 * available from Win2K.
478 */
479 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
480 {
481 HANDLE kernel32 = GetModuleHandle("kernel32");
482 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
483 kernel32, "SetHandleInformation");
484
485 allowPiping = pSetHandleInformation != NULL;
486 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000487 done = TRUE;
488 }
489}
490
491/*
492 * Return TRUE when running on Windows 95 (or 98 or ME).
493 * Only to be used after mch_init().
494 */
495 int
496mch_windows95(void)
497{
498 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
499}
500
501#ifdef FEAT_GUI_W32
502/*
503 * Used to work around the "can't do synchronous spawn"
504 * problem on Win32s, without resorting to Universal Thunk.
505 */
506static int old_num_windows;
507static int num_windows;
508
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000509/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510 static BOOL CALLBACK
511win32ssynch_cb(HWND hwnd, LPARAM lparam)
512{
513 num_windows++;
514 return TRUE;
515}
516#endif
517
518#ifndef FEAT_GUI_W32
519
520#define SHIFT (SHIFT_PRESSED)
521#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
522#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
523#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
524
525
526/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
527 * We map function keys to their ANSI terminal equivalents, as produced
528 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
529 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
530 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
531 * combinations of function/arrow/etc keys.
532 */
533
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000534static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535{
536 WORD wVirtKey;
537 BOOL fAnsiKey;
538 int chAlone;
539 int chShift;
540 int chCtrl;
541 int chAlt;
542} VirtKeyMap[] =
543{
544
545/* Key ANSI alone shift ctrl alt */
546 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
547
548 { VK_F1, TRUE, ';', 'T', '^', 'h', },
549 { VK_F2, TRUE, '<', 'U', '_', 'i', },
550 { VK_F3, TRUE, '=', 'V', '`', 'j', },
551 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
552 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
553 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
554 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
555 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
556 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
557 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
558 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
559 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
560
561 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
562 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
563 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
564 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
565 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
566 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
567 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
568 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
569 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
570 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
571
572 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
573
574#if 0
575 /* Most people don't have F13-F20, but what the hell... */
576 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
577 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
578 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
579 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
580 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
581 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
582 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
583 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
584#endif
585 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
586 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
587 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
588 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
589
590 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
591 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
592 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
593 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
594 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
595 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
596 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
597 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
598 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
599 /* Sorry, out of number space! <negri>*/
600 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
601
602};
603
604
605#ifdef _MSC_VER
606// The ToAscii bug destroys several registers. Need to turn off optimization
607// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000608# pragma warning(push)
609# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610# pragma optimize("", off)
611#endif
612
613#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
614# define AChar AsciiChar
615#else
616# define AChar uChar.AsciiChar
617#endif
618
619/* The return code indicates key code size. */
620 static int
621#ifdef __BORLANDC__
622 __stdcall
623#endif
624win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000625 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626{
627 UINT uMods = pker->dwControlKeyState;
628 static int s_iIsDead = 0;
629 static WORD awAnsiCode[2];
630 static BYTE abKeystate[256];
631
632
633 if (s_iIsDead == 2)
634 {
635 pker->AChar = (CHAR) awAnsiCode[1];
636 s_iIsDead = 0;
637 return 1;
638 }
639
640 if (pker->AChar != 0)
641 return 1;
642
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200643 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000644
645 // Should only be non-NULL on NT 4.0
646 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
647 {
648 CHAR szKLID[KL_NAMELENGTH];
649
650 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
651 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
652 }
653
654 /* Clear any pending dead keys */
655 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
656
657 if (uMods & SHIFT_PRESSED)
658 abKeystate[VK_SHIFT] = 0x80;
659 if (uMods & CAPSLOCK_ON)
660 abKeystate[VK_CAPITAL] = 1;
661
662 if ((uMods & ALT_GR) == ALT_GR)
663 {
664 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
665 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
666 }
667
668 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
669 abKeystate, awAnsiCode, 0);
670
671 if (s_iIsDead > 0)
672 pker->AChar = (CHAR) awAnsiCode[0];
673
674 return s_iIsDead;
675}
676
677#ifdef _MSC_VER
678/* MUST switch optimization on again here, otherwise a call to
679 * decode_key_event() may crash (e.g. when hitting caps-lock) */
680# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000681# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682
683# if (_MSC_VER < 1100)
684/* MUST turn off global optimisation for this next function, or
685 * pressing ctrl-minus in insert mode crashes Vim when built with
686 * VC4.1. -- negri. */
687# pragma optimize("g", off)
688# endif
689#endif
690
691static BOOL g_fJustGotFocus = FALSE;
692
693/*
694 * Decode a KEY_EVENT into one or two keystrokes
695 */
696 static BOOL
697decode_key_event(
698 KEY_EVENT_RECORD *pker,
699 char_u *pch,
700 char_u *pch2,
701 int *pmodifiers,
702 BOOL fDoPost)
703{
704 int i;
705 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
706
707 *pch = *pch2 = NUL;
708 g_fJustGotFocus = FALSE;
709
710 /* ignore key up events */
711 if (!pker->bKeyDown)
712 return FALSE;
713
714 /* ignore some keystrokes */
715 switch (pker->wVirtualKeyCode)
716 {
717 /* modifiers */
718 case VK_SHIFT:
719 case VK_CONTROL:
720 case VK_MENU: /* Alt key */
721 return FALSE;
722
723 default:
724 break;
725 }
726
727 /* special cases */
728 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
729 {
730 /* Ctrl-6 is Ctrl-^ */
731 if (pker->wVirtualKeyCode == '6')
732 {
733 *pch = Ctrl_HAT;
734 return TRUE;
735 }
736 /* Ctrl-2 is Ctrl-@ */
737 else if (pker->wVirtualKeyCode == '2')
738 {
739 *pch = NUL;
740 return TRUE;
741 }
742 /* Ctrl-- is Ctrl-_ */
743 else if (pker->wVirtualKeyCode == 0xBD)
744 {
745 *pch = Ctrl__;
746 return TRUE;
747 }
748 }
749
750 /* Shift-TAB */
751 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
752 {
753 *pch = K_NUL;
754 *pch2 = '\017';
755 return TRUE;
756 }
757
758 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
759 {
760 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
761 {
762 if (nModifs == 0)
763 *pch = VirtKeyMap[i].chAlone;
764 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
765 *pch = VirtKeyMap[i].chShift;
766 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
767 *pch = VirtKeyMap[i].chCtrl;
768 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
769 *pch = VirtKeyMap[i].chAlt;
770
771 if (*pch != 0)
772 {
773 if (VirtKeyMap[i].fAnsiKey)
774 {
775 *pch2 = *pch;
776 *pch = K_NUL;
777 }
778
779 return TRUE;
780 }
781 }
782 }
783
784 i = win32_kbd_patch_key(pker);
785
786 if (i < 0)
787 *pch = NUL;
788 else
789 {
790 *pch = (i > 0) ? pker->AChar : NUL;
791
792 if (pmodifiers != NULL)
793 {
794 /* Pass on the ALT key as a modifier, but only when not combined
795 * with CTRL (which is ALTGR). */
796 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
797 *pmodifiers |= MOD_MASK_ALT;
798
799 /* Pass on SHIFT only for special keys, because we don't know when
800 * it's already included with the character. */
801 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
802 *pmodifiers |= MOD_MASK_SHIFT;
803
804 /* Pass on CTRL only for non-special keys, because we don't know
805 * when it's already included with the character. And not when
806 * combined with ALT (which is ALTGR). */
807 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
808 && *pch >= 0x20 && *pch < 0x80)
809 *pmodifiers |= MOD_MASK_CTRL;
810 }
811 }
812
813 return (*pch != NUL);
814}
815
816#ifdef _MSC_VER
817# pragma optimize("", on)
818#endif
819
820#endif /* FEAT_GUI_W32 */
821
822
823#ifdef FEAT_MOUSE
824
825/*
826 * For the GUI the mouse handling is in gui_w32.c.
827 */
828# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000829/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000831mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832{
833}
834# else
835static int g_fMouseAvail = FALSE; /* mouse present */
836static int g_fMouseActive = FALSE; /* mouse enabled */
837static int g_nMouseClick = -1; /* mouse status */
838static int g_xMouse; /* mouse x coordinate */
839static int g_yMouse; /* mouse y coordinate */
840
841/*
842 * Enable or disable mouse input
843 */
844 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000845mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846{
847 DWORD cmodein;
848
849 if (!g_fMouseAvail)
850 return;
851
852 g_fMouseActive = on;
853 GetConsoleMode(g_hConIn, &cmodein);
854
855 if (g_fMouseActive)
856 cmodein |= ENABLE_MOUSE_INPUT;
857 else
858 cmodein &= ~ENABLE_MOUSE_INPUT;
859
860 SetConsoleMode(g_hConIn, cmodein);
861}
862
863
864/*
865 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
866 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
867 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
868 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
869 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
870 * and we return the mouse position in g_xMouse and g_yMouse.
871 *
872 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
873 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
874 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
875 *
876 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
877 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
878 *
879 * Windows will send us MOUSE_MOVED notifications whenever the mouse
880 * moves, even if it stays within the same character cell. We ignore
881 * all MOUSE_MOVED messages if the position hasn't really changed, and
882 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
883 * we're only interested in MOUSE_DRAG).
884 *
885 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
886 * 2-button mouses by pressing the left & right buttons simultaneously.
887 * In practice, it's almost impossible to click both at the same time,
888 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
889 * in such cases, if the user is clicking quickly.
890 */
891 static BOOL
892decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000893 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894{
895 static int s_nOldButton = -1;
896 static int s_nOldMouseClick = -1;
897 static int s_xOldMouse = -1;
898 static int s_yOldMouse = -1;
899 static linenr_T s_old_topline = 0;
900#ifdef FEAT_DIFF
901 static int s_old_topfill = 0;
902#endif
903 static int s_cClicks = 1;
904 static BOOL s_fReleased = TRUE;
905 static DWORD s_dwLastClickTime = 0;
906 static BOOL s_fNextIsMiddle = FALSE;
907
908 static DWORD cButtons = 0; /* number of buttons supported */
909
910 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
911 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
912 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
913 const DWORD LEFT_RIGHT = LEFT | RIGHT;
914
915 int nButton;
916
917 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
918 cButtons = 2;
919
920 if (!g_fMouseAvail || !g_fMouseActive)
921 {
922 g_nMouseClick = -1;
923 return FALSE;
924 }
925
926 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
927 if (g_fJustGotFocus)
928 {
929 g_fJustGotFocus = FALSE;
930 return FALSE;
931 }
932
933 /* unprocessed mouse click? */
934 if (g_nMouseClick != -1)
935 return TRUE;
936
937 nButton = -1;
938 g_xMouse = pmer->dwMousePosition.X;
939 g_yMouse = pmer->dwMousePosition.Y;
940
941 if (pmer->dwEventFlags == MOUSE_MOVED)
942 {
943 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
944 * events even when the mouse moves only within a char cell.) */
945 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
946 return FALSE;
947 }
948
949 /* If no buttons are pressed... */
950 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
951 {
952 /* If the last thing returned was MOUSE_RELEASE, ignore this */
953 if (s_fReleased)
954 return FALSE;
955
956 nButton = MOUSE_RELEASE;
957 s_fReleased = TRUE;
958 }
959 else /* one or more buttons pressed */
960 {
961 /* on a 2-button mouse, hold down left and right buttons
962 * simultaneously to get MIDDLE. */
963
964 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
965 {
966 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
967
968 /* if either left or right button only is pressed, see if the
969 * the next mouse event has both of them pressed */
970 if (dwLR == LEFT || dwLR == RIGHT)
971 {
972 for (;;)
973 {
974 /* wait a short time for next input event */
975 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
976 != WAIT_OBJECT_0)
977 break;
978 else
979 {
980 DWORD cRecords = 0;
981 INPUT_RECORD ir;
982 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
983
984 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
985
986 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
987 || !(pmer2->dwButtonState & LEFT_RIGHT))
988 break;
989 else
990 {
991 if (pmer2->dwEventFlags != MOUSE_MOVED)
992 {
993 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
994
995 return decode_mouse_event(pmer2);
996 }
997 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
998 s_yOldMouse == pmer2->dwMousePosition.Y)
999 {
1000 /* throw away spurious mouse move */
1001 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1002
1003 /* are there any more mouse events in queue? */
1004 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1005
1006 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1007 break;
1008 }
1009 else
1010 break;
1011 }
1012 }
1013 }
1014 }
1015 }
1016
1017 if (s_fNextIsMiddle)
1018 {
1019 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1020 ? MOUSE_DRAG : MOUSE_MIDDLE;
1021 s_fNextIsMiddle = FALSE;
1022 }
1023 else if (cButtons == 2 &&
1024 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1025 {
1026 nButton = MOUSE_MIDDLE;
1027
1028 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1029 {
1030 s_fNextIsMiddle = TRUE;
1031 nButton = MOUSE_RELEASE;
1032 }
1033 }
1034 else if ((pmer->dwButtonState & LEFT) == LEFT)
1035 nButton = MOUSE_LEFT;
1036 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1037 nButton = MOUSE_MIDDLE;
1038 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1039 nButton = MOUSE_RIGHT;
1040
1041 if (! s_fReleased && ! s_fNextIsMiddle
1042 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1043 return FALSE;
1044
1045 s_fReleased = s_fNextIsMiddle;
1046 }
1047
1048 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1049 {
1050 /* button pressed or released, without mouse moving */
1051 if (nButton != -1 && nButton != MOUSE_RELEASE)
1052 {
1053 DWORD dwCurrentTime = GetTickCount();
1054
1055 if (s_xOldMouse != g_xMouse
1056 || s_yOldMouse != g_yMouse
1057 || s_nOldButton != nButton
1058 || s_old_topline != curwin->w_topline
1059#ifdef FEAT_DIFF
1060 || s_old_topfill != curwin->w_topfill
1061#endif
1062 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1063 {
1064 s_cClicks = 1;
1065 }
1066 else if (++s_cClicks > 4)
1067 {
1068 s_cClicks = 1;
1069 }
1070
1071 s_dwLastClickTime = dwCurrentTime;
1072 }
1073 }
1074 else if (pmer->dwEventFlags == MOUSE_MOVED)
1075 {
1076 if (nButton != -1 && nButton != MOUSE_RELEASE)
1077 nButton = MOUSE_DRAG;
1078
1079 s_cClicks = 1;
1080 }
1081
1082 if (nButton == -1)
1083 return FALSE;
1084
1085 if (nButton != MOUSE_RELEASE)
1086 s_nOldButton = nButton;
1087
1088 g_nMouseClick = nButton;
1089
1090 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1091 g_nMouseClick |= MOUSE_SHIFT;
1092 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1093 g_nMouseClick |= MOUSE_CTRL;
1094 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1095 g_nMouseClick |= MOUSE_ALT;
1096
1097 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1098 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1099
1100 /* only pass on interesting (i.e., different) mouse events */
1101 if (s_xOldMouse == g_xMouse
1102 && s_yOldMouse == g_yMouse
1103 && s_nOldMouseClick == g_nMouseClick)
1104 {
1105 g_nMouseClick = -1;
1106 return FALSE;
1107 }
1108
1109 s_xOldMouse = g_xMouse;
1110 s_yOldMouse = g_yMouse;
1111 s_old_topline = curwin->w_topline;
1112#ifdef FEAT_DIFF
1113 s_old_topfill = curwin->w_topfill;
1114#endif
1115 s_nOldMouseClick = g_nMouseClick;
1116
1117 return TRUE;
1118}
1119
1120# endif /* FEAT_GUI_W32 */
1121#endif /* FEAT_MOUSE */
1122
1123
1124#ifdef MCH_CURSOR_SHAPE
1125/*
1126 * Set the shape of the cursor.
1127 * 'thickness' can be from 1 (thin) to 99 (block)
1128 */
1129 static void
1130mch_set_cursor_shape(int thickness)
1131{
1132 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1133 ConsoleCursorInfo.dwSize = thickness;
1134 ConsoleCursorInfo.bVisible = s_cursor_visible;
1135
1136 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1137 if (s_cursor_visible)
1138 SetConsoleCursorPosition(g_hConOut, g_coord);
1139}
1140
1141 void
1142mch_update_cursor(void)
1143{
1144 int idx;
1145 int thickness;
1146
1147 /*
1148 * How the cursor is drawn depends on the current mode.
1149 */
1150 idx = get_shape_idx(FALSE);
1151
1152 if (shape_table[idx].shape == SHAPE_BLOCK)
1153 thickness = 99; /* 100 doesn't work on W95 */
1154 else
1155 thickness = shape_table[idx].percentage;
1156 mch_set_cursor_shape(thickness);
1157}
1158#endif
1159
1160#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1161/*
1162 * Handle FOCUS_EVENT.
1163 */
1164 static void
1165handle_focus_event(INPUT_RECORD ir)
1166{
1167 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1168 ui_focus_change((int)g_fJustGotFocus);
1169}
1170
1171/*
1172 * Wait until console input from keyboard or mouse is available,
1173 * or the time is up.
1174 * Return TRUE if something is available FALSE if not.
1175 */
1176 static int
1177WaitForChar(long msec)
1178{
1179 DWORD dwNow = 0, dwEndTime = 0;
1180 INPUT_RECORD ir;
1181 DWORD cRecords;
1182 char_u ch, ch2;
1183
1184 if (msec > 0)
1185 /* Wait until the specified time has elapsed. */
1186 dwEndTime = GetTickCount() + msec;
1187 else if (msec < 0)
1188 /* Wait forever. */
1189 dwEndTime = INFINITE;
1190
1191 /* We need to loop until the end of the time period, because
1192 * we might get multiple unusable mouse events in that time.
1193 */
1194 for (;;)
1195 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001196#ifdef FEAT_MZSCHEME
1197 mzvim_check_threads();
1198#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001199#ifdef FEAT_CLIENTSERVER
1200 serverProcessPendingMessages();
1201#endif
1202 if (0
1203#ifdef FEAT_MOUSE
1204 || g_nMouseClick != -1
1205#endif
1206#ifdef FEAT_CLIENTSERVER
1207 || input_available()
1208#endif
1209 )
1210 return TRUE;
1211
1212 if (msec > 0)
1213 {
1214 /* If the specified wait time has passed, return. */
1215 dwNow = GetTickCount();
1216 if (dwNow >= dwEndTime)
1217 break;
1218 }
1219 if (msec != 0)
1220 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001221 DWORD dwWaitTime = dwEndTime - dwNow;
1222
1223#ifdef FEAT_MZSCHEME
1224 if (mzthreads_allowed() && p_mzq > 0
1225 && (msec < 0 || (long)dwWaitTime > p_mzq))
1226 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1227#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001228#ifdef FEAT_CLIENTSERVER
1229 /* Wait for either an event on the console input or a message in
1230 * the client-server window. */
1231 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001232 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001234 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235#endif
1236 continue;
1237 }
1238
1239 cRecords = 0;
1240 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1241
1242#ifdef FEAT_MBYTE_IME
1243 if (State & CMDLINE && msg_row == Rows - 1)
1244 {
1245 CONSOLE_SCREEN_BUFFER_INFO csbi;
1246
1247 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1248 {
1249 if (csbi.dwCursorPosition.Y != msg_row)
1250 {
1251 /* The screen is now messed up, must redraw the
1252 * command line and later all the windows. */
1253 redraw_all_later(CLEAR);
1254 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1255 redrawcmd();
1256 }
1257 }
1258 }
1259#endif
1260
1261 if (cRecords > 0)
1262 {
1263 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1264 {
1265#ifdef FEAT_MBYTE_IME
1266 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1267 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1268 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1269 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1270 {
1271 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1272 continue;
1273 }
1274#endif
1275 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1276 NULL, FALSE))
1277 return TRUE;
1278 }
1279
1280 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1281
1282 if (ir.EventType == FOCUS_EVENT)
1283 handle_focus_event(ir);
1284 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1285 shell_resized();
1286#ifdef FEAT_MOUSE
1287 else if (ir.EventType == MOUSE_EVENT
1288 && decode_mouse_event(&ir.Event.MouseEvent))
1289 return TRUE;
1290#endif
1291 }
1292 else if (msec == 0)
1293 break;
1294 }
1295
1296#ifdef FEAT_CLIENTSERVER
1297 /* Something might have been received while we were waiting. */
1298 if (input_available())
1299 return TRUE;
1300#endif
1301 return FALSE;
1302}
1303
1304#ifndef FEAT_GUI_MSWIN
1305/*
1306 * return non-zero if a character is available
1307 */
1308 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001309mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001310{
1311 return WaitForChar(0L);
1312}
1313#endif
1314
1315/*
1316 * Create the console input. Used when reading stdin doesn't work.
1317 */
1318 static void
1319create_conin(void)
1320{
1321 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1322 FILE_SHARE_READ|FILE_SHARE_WRITE,
1323 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001324 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325 did_create_conin = TRUE;
1326}
1327
1328/*
1329 * Get a keystroke or a mouse event
1330 */
1331 static char_u
1332tgetch(int *pmodifiers, char_u *pch2)
1333{
1334 char_u ch;
1335
1336 for (;;)
1337 {
1338 INPUT_RECORD ir;
1339 DWORD cRecords = 0;
1340
1341#ifdef FEAT_CLIENTSERVER
1342 (void)WaitForChar(-1L);
1343 if (input_available())
1344 return 0;
1345# ifdef FEAT_MOUSE
1346 if (g_nMouseClick != -1)
1347 return 0;
1348# endif
1349#endif
1350 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1351 {
1352 if (did_create_conin)
1353 read_error_exit();
1354 create_conin();
1355 continue;
1356 }
1357
1358 if (ir.EventType == KEY_EVENT)
1359 {
1360 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1361 pmodifiers, TRUE))
1362 return ch;
1363 }
1364 else if (ir.EventType == FOCUS_EVENT)
1365 handle_focus_event(ir);
1366 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1367 shell_resized();
1368#ifdef FEAT_MOUSE
1369 else if (ir.EventType == MOUSE_EVENT)
1370 {
1371 if (decode_mouse_event(&ir.Event.MouseEvent))
1372 return 0;
1373 }
1374#endif
1375 }
1376}
1377#endif /* !FEAT_GUI_W32 */
1378
1379
1380/*
1381 * mch_inchar(): low-level input funcion.
1382 * Get one or more characters from the keyboard or the mouse.
1383 * If time == 0, do not wait for characters.
1384 * If time == n, wait a short time for characters.
1385 * If time == -1, wait forever for characters.
1386 * Returns the number of characters read into buf.
1387 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001388/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001389 int
1390mch_inchar(
1391 char_u *buf,
1392 int maxlen,
1393 long time,
1394 int tb_change_cnt)
1395{
1396#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1397
1398 int len;
1399 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001400#define TYPEAHEADLEN 20
1401 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1402 static int typeaheadlen = 0;
1403
1404 /* First use any typeahead that was kept because "buf" was too small. */
1405 if (typeaheadlen > 0)
1406 goto theend;
1407
1408#ifdef FEAT_SNIFF
1409 if (want_sniff_request)
1410 {
1411 if (sniff_request_waiting)
1412 {
1413 /* return K_SNIFF */
1414 typeahead[typeaheadlen++] = CSI;
1415 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1416 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1417 sniff_request_waiting = 0;
1418 want_sniff_request = 0;
1419 goto theend;
1420 }
1421 else if (time < 0 || time > 250)
1422 {
1423 /* don't wait too long, a request might be pending */
1424 time = 250;
1425 }
1426 }
1427#endif
1428
1429 if (time >= 0)
1430 {
1431 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433 }
1434 else /* time == -1, wait forever */
1435 {
1436 mch_set_winsize_now(); /* Allow winsize changes from now on */
1437
Bram Moolenaar3918c952005-03-15 22:34:55 +00001438 /*
1439 * If there is no character available within 2 seconds (default)
1440 * write the autoscript file to disk. Or cause the CursorHold event
1441 * to be triggered.
1442 */
1443 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001444 {
1445#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001446 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001448 buf[0] = K_SPECIAL;
1449 buf[1] = KS_EXTRA;
1450 buf[2] = (int)KE_CURSORHOLD;
1451 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452 }
1453#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001454 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 }
1456 }
1457
1458 /*
1459 * Try to read as many characters as there are, until the buffer is full.
1460 */
1461
1462 /* we will get at least one key. Get more if they are available. */
1463 g_fCBrkPressed = FALSE;
1464
1465#ifdef MCH_WRITE_DUMP
1466 if (fdDump)
1467 fputc('[', fdDump);
1468#endif
1469
1470 /* Keep looping until there is something in the typeahead buffer and more
1471 * to get and still room in the buffer (up to two bytes for a char and
1472 * three bytes for a modifier). */
1473 while ((typeaheadlen == 0 || WaitForChar(0L))
1474 && typeaheadlen + 5 <= TYPEAHEADLEN)
1475 {
1476 if (typebuf_changed(tb_change_cnt))
1477 {
1478 /* "buf" may be invalid now if a client put something in the
1479 * typeahead buffer and "buf" is in the typeahead buffer. */
1480 typeaheadlen = 0;
1481 break;
1482 }
1483#ifdef FEAT_MOUSE
1484 if (g_nMouseClick != -1)
1485 {
1486# ifdef MCH_WRITE_DUMP
1487 if (fdDump)
1488 fprintf(fdDump, "{%02x @ %d, %d}",
1489 g_nMouseClick, g_xMouse, g_yMouse);
1490# endif
1491 typeahead[typeaheadlen++] = ESC + 128;
1492 typeahead[typeaheadlen++] = 'M';
1493 typeahead[typeaheadlen++] = g_nMouseClick;
1494 typeahead[typeaheadlen++] = g_xMouse + '!';
1495 typeahead[typeaheadlen++] = g_yMouse + '!';
1496 g_nMouseClick = -1;
1497 }
1498 else
1499#endif
1500 {
1501 char_u ch2 = NUL;
1502 int modifiers = 0;
1503
1504 c = tgetch(&modifiers, &ch2);
1505
1506 if (typebuf_changed(tb_change_cnt))
1507 {
1508 /* "buf" may be invalid now if a client put something in the
1509 * typeahead buffer and "buf" is in the typeahead buffer. */
1510 typeaheadlen = 0;
1511 break;
1512 }
1513
1514 if (c == Ctrl_C && ctrl_c_interrupts)
1515 {
1516#if defined(FEAT_CLIENTSERVER)
1517 trash_input_buf();
1518#endif
1519 got_int = TRUE;
1520 }
1521
1522#ifdef FEAT_MOUSE
1523 if (g_nMouseClick == -1)
1524#endif
1525 {
1526 int n = 1;
1527
1528 /* A key may have one or two bytes. */
1529 typeahead[typeaheadlen] = c;
1530 if (ch2 != NUL)
1531 {
1532 typeahead[typeaheadlen + 1] = ch2;
1533 ++n;
1534 }
1535#ifdef FEAT_MBYTE
1536 /* Only convert normal characters, not special keys. Need to
1537 * convert before applying ALT, otherwise mapping <M-x> breaks
1538 * when 'tenc' is set. */
1539 if (input_conv.vc_type != CONV_NONE
1540 && (ch2 == NUL || c != K_NUL))
1541 n = convert_input(typeahead + typeaheadlen, n,
1542 TYPEAHEADLEN - typeaheadlen);
1543#endif
1544
1545 /* Use the ALT key to set the 8th bit of the character
1546 * when it's one byte, the 8th bit isn't set yet and not
1547 * using a double-byte encoding (would become a lead
1548 * byte). */
1549 if ((modifiers & MOD_MASK_ALT)
1550 && n == 1
1551 && (typeahead[typeaheadlen] & 0x80) == 0
1552#ifdef FEAT_MBYTE
1553 && !enc_dbcs
1554#endif
1555 )
1556 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001557#ifdef FEAT_MBYTE
1558 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1559 typeahead + typeaheadlen);
1560#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001561 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001562#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 modifiers &= ~MOD_MASK_ALT;
1564 }
1565
1566 if (modifiers != 0)
1567 {
1568 /* Prepend modifiers to the character. */
1569 mch_memmove(typeahead + typeaheadlen + 3,
1570 typeahead + typeaheadlen, n);
1571 typeahead[typeaheadlen++] = K_SPECIAL;
1572 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1573 typeahead[typeaheadlen++] = modifiers;
1574 }
1575
1576 typeaheadlen += n;
1577
1578#ifdef MCH_WRITE_DUMP
1579 if (fdDump)
1580 fputc(c, fdDump);
1581#endif
1582 }
1583 }
1584 }
1585
1586#ifdef MCH_WRITE_DUMP
1587 if (fdDump)
1588 {
1589 fputs("]\n", fdDump);
1590 fflush(fdDump);
1591 }
1592#endif
1593
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594theend:
1595 /* Move typeahead to "buf", as much as fits. */
1596 len = 0;
1597 while (len < maxlen && typeaheadlen > 0)
1598 {
1599 buf[len++] = typeahead[0];
1600 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1601 }
1602 return len;
1603
1604#else /* FEAT_GUI_W32 */
1605 return 0;
1606#endif /* FEAT_GUI_W32 */
1607}
1608
1609#ifndef __MINGW32__
1610# include <shellapi.h> /* required for FindExecutable() */
1611#endif
1612
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001613/*
1614 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001615 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001616 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617 static int
1618executable_exists(char *name)
1619{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001620 char *dum;
1621 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001623#ifdef FEAT_MBYTE
1624 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001626 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001627 WCHAR fnamew[_MAX_PATH];
1628 WCHAR *dumw;
1629 long n;
1630
1631 if (p != NULL)
1632 {
1633 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1634 vim_free(p);
1635 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1636 {
1637 if (n == 0)
1638 return FALSE;
1639 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1640 return FALSE;
1641 return TRUE;
1642 }
1643 /* Retry with non-wide function (for Windows 98). */
1644 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001646#endif
1647 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1648 return FALSE;
1649 if (mch_isdir(fname))
1650 return FALSE;
1651 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652}
1653
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001654#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001655 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001656/*
1657 * Bad parameter handler.
1658 *
1659 * Certain MS CRT functions will intentionally crash when passed invalid
1660 * parameters to highlight possible security holes. Setting this function as
1661 * the bad parameter handler will prevent the crash.
1662 *
1663 * In debug builds the parameters contain CRT information that might help track
1664 * down the source of a problem, but in non-debug builds the arguments are all
1665 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1666 * worth allowing these to make debugging of issues easier.
1667 */
1668 static void
1669bad_param_handler(const wchar_t *expression,
1670 const wchar_t *function,
1671 const wchar_t *file,
1672 unsigned int line,
1673 uintptr_t pReserved)
1674{
1675}
1676
1677# define SET_INVALID_PARAM_HANDLER \
1678 ((void)_set_invalid_parameter_handler(bad_param_handler))
1679#else
1680# define SET_INVALID_PARAM_HANDLER
1681#endif
1682
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683#ifdef FEAT_GUI_W32
1684
1685/*
1686 * GUI version of mch_init().
1687 */
1688 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001689mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690{
1691#ifndef __MINGW32__
1692 extern int _fmode;
1693#endif
1694
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001695 /* Silently handle invalid parameters to CRT functions */
1696 SET_INVALID_PARAM_HANDLER;
1697
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698 /* Let critical errors result in a failure, not in a dialog box. Required
1699 * for the timestamp test to work on removed floppies. */
1700 SetErrorMode(SEM_FAILCRITICALERRORS);
1701
1702 _fmode = O_BINARY; /* we do our own CR-LF translation */
1703
1704 /* Specify window size. Is there a place to get the default from? */
1705 Rows = 25;
1706 Columns = 80;
1707
1708 /* Look for 'vimrun' */
1709 if (!gui_is_win32s())
1710 {
1711 char_u vimrun_location[_MAX_PATH + 4];
1712
1713 /* First try in same directory as gvim.exe */
1714 STRCPY(vimrun_location, exe_name);
1715 STRCPY(gettail(vimrun_location), "vimrun.exe");
1716 if (mch_getperm(vimrun_location) >= 0)
1717 {
1718 if (*skiptowhite(vimrun_location) != NUL)
1719 {
1720 /* Enclose path with white space in double quotes. */
1721 mch_memmove(vimrun_location + 1, vimrun_location,
1722 STRLEN(vimrun_location) + 1);
1723 *vimrun_location = '"';
1724 STRCPY(gettail(vimrun_location), "vimrun\" ");
1725 }
1726 else
1727 STRCPY(gettail(vimrun_location), "vimrun ");
1728
1729 vimrun_path = (char *)vim_strsave(vimrun_location);
1730 s_dont_use_vimrun = FALSE;
1731 }
1732 else if (executable_exists("vimrun.exe"))
1733 s_dont_use_vimrun = FALSE;
1734
1735 /* Don't give the warning for a missing vimrun.exe right now, but only
1736 * when vimrun was supposed to be used. Don't bother people that do
1737 * not need vimrun.exe. */
1738 if (s_dont_use_vimrun)
1739 need_vimrun_warning = TRUE;
1740 }
1741
1742 /*
1743 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1744 * Otherwise the default "findstr /n" is used.
1745 */
1746 if (!executable_exists("findstr.exe"))
1747 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1748
1749#ifdef FEAT_CLIPBOARD
1750 clip_init(TRUE);
1751
1752 /*
Bram Moolenaar7528dd62007-05-06 12:32:12 +00001753 * Vim's own clipboard format recognises whether the text is char, line,
1754 * or rectangular block. Only useful for copying between two Vims.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 * "VimClipboard" was used for previous versions, using the first
1756 * character to specify MCHAR, MLINE or MBLOCK.
1757 */
1758 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1759 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1760#endif
1761}
1762
1763
1764#else /* FEAT_GUI_W32 */
1765
1766#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1767#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1768
1769/*
1770 * ClearConsoleBuffer()
1771 * Description:
1772 * Clears the entire contents of the console screen buffer, using the
1773 * specified attribute.
1774 * Returns:
1775 * TRUE on success
1776 */
1777 static BOOL
1778ClearConsoleBuffer(WORD wAttribute)
1779{
1780 CONSOLE_SCREEN_BUFFER_INFO csbi;
1781 COORD coord;
1782 DWORD NumCells, dummy;
1783
1784 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1785 return FALSE;
1786
1787 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1788 coord.X = 0;
1789 coord.Y = 0;
1790 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1791 coord, &dummy))
1792 {
1793 return FALSE;
1794 }
1795 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1796 coord, &dummy))
1797 {
1798 return FALSE;
1799 }
1800
1801 return TRUE;
1802}
1803
1804/*
1805 * FitConsoleWindow()
1806 * Description:
1807 * Checks if the console window will fit within given buffer dimensions.
1808 * Also, if requested, will shrink the window to fit.
1809 * Returns:
1810 * TRUE on success
1811 */
1812 static BOOL
1813FitConsoleWindow(
1814 COORD dwBufferSize,
1815 BOOL WantAdjust)
1816{
1817 CONSOLE_SCREEN_BUFFER_INFO csbi;
1818 COORD dwWindowSize;
1819 BOOL NeedAdjust = FALSE;
1820
1821 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1822 {
1823 /*
1824 * A buffer resize will fail if the current console window does
1825 * not lie completely within that buffer. To avoid this, we might
1826 * have to move and possibly shrink the window.
1827 */
1828 if (csbi.srWindow.Right >= dwBufferSize.X)
1829 {
1830 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1831 if (dwWindowSize.X > dwBufferSize.X)
1832 dwWindowSize.X = dwBufferSize.X;
1833 csbi.srWindow.Right = dwBufferSize.X - 1;
1834 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1835 NeedAdjust = TRUE;
1836 }
1837 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1838 {
1839 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1840 if (dwWindowSize.Y > dwBufferSize.Y)
1841 dwWindowSize.Y = dwBufferSize.Y;
1842 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1843 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1844 NeedAdjust = TRUE;
1845 }
1846 if (NeedAdjust && WantAdjust)
1847 {
1848 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1849 return FALSE;
1850 }
1851 return TRUE;
1852 }
1853
1854 return FALSE;
1855}
1856
1857typedef struct ConsoleBufferStruct
1858{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001859 BOOL IsValid;
1860 CONSOLE_SCREEN_BUFFER_INFO Info;
1861 PCHAR_INFO Buffer;
1862 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863} ConsoleBuffer;
1864
1865/*
1866 * SaveConsoleBuffer()
1867 * Description:
1868 * Saves important information about the console buffer, including the
1869 * actual buffer contents. The saved information is suitable for later
1870 * restoration by RestoreConsoleBuffer().
1871 * Returns:
1872 * TRUE if all information was saved; FALSE otherwise
1873 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1874 */
1875 static BOOL
1876SaveConsoleBuffer(
1877 ConsoleBuffer *cb)
1878{
1879 DWORD NumCells;
1880 COORD BufferCoord;
1881 SMALL_RECT ReadRegion;
1882 WORD Y, Y_incr;
1883
1884 if (cb == NULL)
1885 return FALSE;
1886
1887 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1888 {
1889 cb->IsValid = FALSE;
1890 return FALSE;
1891 }
1892 cb->IsValid = TRUE;
1893
1894 /*
1895 * Allocate a buffer large enough to hold the entire console screen
1896 * buffer. If this ConsoleBuffer structure has already been initialized
1897 * with a buffer of the correct size, then just use that one.
1898 */
1899 if (!cb->IsValid || cb->Buffer == NULL ||
1900 cb->BufferSize.X != cb->Info.dwSize.X ||
1901 cb->BufferSize.Y != cb->Info.dwSize.Y)
1902 {
1903 cb->BufferSize.X = cb->Info.dwSize.X;
1904 cb->BufferSize.Y = cb->Info.dwSize.Y;
1905 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01001906 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
1908 if (cb->Buffer == NULL)
1909 return FALSE;
1910 }
1911
1912 /*
1913 * We will now copy the console screen buffer into our buffer.
1914 * ReadConsoleOutput() seems to be limited as far as how much you
1915 * can read at a time. Empirically, this number seems to be about
1916 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1917 * in chunks until it is all copied. The chunks will all have the
1918 * same horizontal characteristics, so initialize them now. The
1919 * height of each chunk will be (12000 / width).
1920 */
1921 BufferCoord.X = 0;
1922 ReadRegion.Left = 0;
1923 ReadRegion.Right = cb->Info.dwSize.X - 1;
1924 Y_incr = 12000 / cb->Info.dwSize.X;
1925 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
1926 {
1927 /*
1928 * Read into position (0, Y) in our buffer.
1929 */
1930 BufferCoord.Y = Y;
1931 /*
1932 * Read the region whose top left corner is (0, Y) and whose bottom
1933 * right corner is (width - 1, Y + Y_incr - 1). This should define
1934 * a region of size width by Y_incr. Don't worry if this region is
1935 * too large for the remaining buffer; it will be cropped.
1936 */
1937 ReadRegion.Top = Y;
1938 ReadRegion.Bottom = Y + Y_incr - 1;
1939 if (!ReadConsoleOutput(g_hConOut, /* output handle */
1940 cb->Buffer, /* our buffer */
1941 cb->BufferSize, /* dimensions of our buffer */
1942 BufferCoord, /* offset in our buffer */
1943 &ReadRegion)) /* region to save */
1944 {
1945 vim_free(cb->Buffer);
1946 cb->Buffer = NULL;
1947 return FALSE;
1948 }
1949 }
1950
1951 return TRUE;
1952}
1953
1954/*
1955 * RestoreConsoleBuffer()
1956 * Description:
1957 * Restores important information about the console buffer, including the
1958 * actual buffer contents, if desired. The information to restore is in
1959 * the same format used by SaveConsoleBuffer().
1960 * Returns:
1961 * TRUE on success
1962 */
1963 static BOOL
1964RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001965 ConsoleBuffer *cb,
1966 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967{
1968 COORD BufferCoord;
1969 SMALL_RECT WriteRegion;
1970
1971 if (cb == NULL || !cb->IsValid)
1972 return FALSE;
1973
1974 /*
1975 * Before restoring the buffer contents, clear the current buffer, and
1976 * restore the cursor position and window information. Doing this now
1977 * prevents old buffer contents from "flashing" onto the screen.
1978 */
1979 if (RestoreScreen)
1980 ClearConsoleBuffer(cb->Info.wAttributes);
1981
1982 FitConsoleWindow(cb->Info.dwSize, TRUE);
1983 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
1984 return FALSE;
1985 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
1986 return FALSE;
1987
1988 if (!RestoreScreen)
1989 {
1990 /*
1991 * No need to restore the screen buffer contents, so we're done.
1992 */
1993 return TRUE;
1994 }
1995
1996 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
1997 return FALSE;
1998 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
1999 return FALSE;
2000
2001 /*
2002 * Restore the screen buffer contents.
2003 */
2004 if (cb->Buffer != NULL)
2005 {
2006 BufferCoord.X = 0;
2007 BufferCoord.Y = 0;
2008 WriteRegion.Left = 0;
2009 WriteRegion.Top = 0;
2010 WriteRegion.Right = cb->Info.dwSize.X - 1;
2011 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2012 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2013 cb->Buffer, /* our buffer */
2014 cb->BufferSize, /* dimensions of our buffer */
2015 BufferCoord, /* offset in our buffer */
2016 &WriteRegion)) /* region to restore */
2017 {
2018 return FALSE;
2019 }
2020 }
2021
2022 return TRUE;
2023}
2024
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002025#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026#ifdef FEAT_RESTORE_ORIG_SCREEN
2027static ConsoleBuffer g_cbOrig = { 0 };
2028#endif
2029static ConsoleBuffer g_cbNonTermcap = { 0 };
2030static ConsoleBuffer g_cbTermcap = { 0 };
2031
2032#ifdef FEAT_TITLE
2033#ifdef __BORLANDC__
2034typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2035#else
2036typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2037#endif
2038char g_szOrigTitle[256] = { 0 };
2039HWND g_hWnd = NULL; /* also used in os_mswin.c */
2040static HICON g_hOrigIconSmall = NULL;
2041static HICON g_hOrigIcon = NULL;
2042static HICON g_hVimIcon = NULL;
2043static BOOL g_fCanChangeIcon = FALSE;
2044
2045/* ICON* are not defined in VC++ 4.0 */
2046#ifndef ICON_SMALL
2047#define ICON_SMALL 0
2048#endif
2049#ifndef ICON_BIG
2050#define ICON_BIG 1
2051#endif
2052/*
2053 * GetConsoleIcon()
2054 * Description:
2055 * Attempts to retrieve the small icon and/or the big icon currently in
2056 * use by a given window.
2057 * Returns:
2058 * TRUE on success
2059 */
2060 static BOOL
2061GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002062 HWND hWnd,
2063 HICON *phIconSmall,
2064 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065{
2066 if (hWnd == NULL)
2067 return FALSE;
2068
2069 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002070 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2071 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002073 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2074 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 return TRUE;
2076}
2077
2078/*
2079 * SetConsoleIcon()
2080 * Description:
2081 * Attempts to change the small icon and/or the big icon currently in
2082 * use by a given window.
2083 * Returns:
2084 * TRUE on success
2085 */
2086 static BOOL
2087SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002088 HWND hWnd,
2089 HICON hIconSmall,
2090 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002092 HICON hPrevIconSmall;
2093 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094
2095 if (hWnd == NULL)
2096 return FALSE;
2097
2098 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002099 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2100 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002101 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002102 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2103 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002104 return TRUE;
2105}
2106
2107/*
2108 * SaveConsoleTitleAndIcon()
2109 * Description:
2110 * Saves the current console window title in g_szOrigTitle, for later
2111 * restoration. Also, attempts to obtain a handle to the console window,
2112 * and use it to save the small and big icons currently in use by the
2113 * console window. This is not always possible on some versions of Windows;
2114 * nor is it possible when running Vim remotely using Telnet (since the
2115 * console window the user sees is owned by a remote process).
2116 */
2117 static void
2118SaveConsoleTitleAndIcon(void)
2119{
2120 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2121
2122 /* Save the original title. */
2123 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2124 return;
2125
2126 /*
2127 * Obtain a handle to the console window using GetConsoleWindow() from
2128 * KERNEL32.DLL; we need to handle in order to change the window icon.
2129 * This function only exists on NT-based Windows, starting with Windows
2130 * 2000. On older operating systems, we can't change the window icon
2131 * anyway.
2132 */
2133 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2134 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2135 "GetConsoleWindow")) != NULL)
2136 {
2137 g_hWnd = (*GetConsoleWindowProc)();
2138 }
2139 if (g_hWnd == NULL)
2140 return;
2141
2142 /* Save the original console window icon. */
2143 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2144 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2145 return;
2146
2147 /* Extract the first icon contained in the Vim executable. */
2148 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2149 if (g_hVimIcon != NULL)
2150 g_fCanChangeIcon = TRUE;
2151}
2152#endif
2153
2154static int g_fWindInitCalled = FALSE;
2155static int g_fTermcapMode = FALSE;
2156static CONSOLE_CURSOR_INFO g_cci;
2157static DWORD g_cmodein = 0;
2158static DWORD g_cmodeout = 0;
2159
2160/*
2161 * non-GUI version of mch_init().
2162 */
2163 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002164mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002165{
2166#ifndef FEAT_RESTORE_ORIG_SCREEN
2167 CONSOLE_SCREEN_BUFFER_INFO csbi;
2168#endif
2169#ifndef __MINGW32__
2170 extern int _fmode;
2171#endif
2172
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002173 /* Silently handle invalid parameters to CRT functions */
2174 SET_INVALID_PARAM_HANDLER;
2175
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176 /* Let critical errors result in a failure, not in a dialog box. Required
2177 * for the timestamp test to work on removed floppies. */
2178 SetErrorMode(SEM_FAILCRITICALERRORS);
2179
2180 _fmode = O_BINARY; /* we do our own CR-LF translation */
2181 out_flush();
2182
2183 /* Obtain handles for the standard Console I/O devices */
2184 if (read_cmd_fd == 0)
2185 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2186 else
2187 create_conin();
2188 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2189
2190#ifdef FEAT_RESTORE_ORIG_SCREEN
2191 /* Save the initial console buffer for later restoration */
2192 SaveConsoleBuffer(&g_cbOrig);
2193 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2194#else
2195 /* Get current text attributes */
2196 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2197 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2198#endif
2199 if (cterm_normal_fg_color == 0)
2200 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2201 if (cterm_normal_bg_color == 0)
2202 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2203
2204 /* set termcap codes to current text attributes */
2205 update_tcap(g_attrCurrent);
2206
2207 GetConsoleCursorInfo(g_hConOut, &g_cci);
2208 GetConsoleMode(g_hConIn, &g_cmodein);
2209 GetConsoleMode(g_hConOut, &g_cmodeout);
2210
2211#ifdef FEAT_TITLE
2212 SaveConsoleTitleAndIcon();
2213 /*
2214 * Set both the small and big icons of the console window to Vim's icon.
2215 * Note that Vim presently only has one size of icon (32x32), but it
2216 * automatically gets scaled down to 16x16 when setting the small icon.
2217 */
2218 if (g_fCanChangeIcon)
2219 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2220#endif
2221
2222 ui_get_shellsize();
2223
2224#ifdef MCH_WRITE_DUMP
2225 fdDump = fopen("dump", "wt");
2226
2227 if (fdDump)
2228 {
2229 time_t t;
2230
2231 time(&t);
2232 fputs(ctime(&t), fdDump);
2233 fflush(fdDump);
2234 }
2235#endif
2236
2237 g_fWindInitCalled = TRUE;
2238
2239#ifdef FEAT_MOUSE
2240 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2241#endif
2242
2243#ifdef FEAT_CLIPBOARD
2244 clip_init(TRUE);
2245
2246 /*
2247 * Vim's own clipboard format recognises whether the text is char, line, or
2248 * rectangular block. Only useful for copying between two Vims.
2249 * "VimClipboard" was used for previous versions, using the first
2250 * character to specify MCHAR, MLINE or MBLOCK.
2251 */
2252 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2253 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2254#endif
2255
2256 /* This will be NULL on anything but NT 4.0 */
2257 s_pfnGetConsoleKeyboardLayoutName =
2258 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2259 "GetConsoleKeyboardLayoutNameA");
2260}
2261
2262/*
2263 * non-GUI version of mch_exit().
2264 * Shut down and exit with status `r'
2265 * Careful: mch_exit() may be called before mch_init()!
2266 */
2267 void
2268mch_exit(int r)
2269{
2270 stoptermcap();
2271
2272 if (g_fWindInitCalled)
2273 settmode(TMODE_COOK);
2274
2275 ml_close_all(TRUE); /* remove all memfiles */
2276
2277 if (g_fWindInitCalled)
2278 {
2279#ifdef FEAT_TITLE
2280 mch_restore_title(3);
2281 /*
2282 * Restore both the small and big icons of the console window to
2283 * what they were at startup. Don't do this when the window is
2284 * closed, Vim would hang here.
2285 */
2286 if (g_fCanChangeIcon && !g_fForceExit)
2287 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2288#endif
2289
2290#ifdef MCH_WRITE_DUMP
2291 if (fdDump)
2292 {
2293 time_t t;
2294
2295 time(&t);
2296 fputs(ctime(&t), fdDump);
2297 fclose(fdDump);
2298 }
2299 fdDump = NULL;
2300#endif
2301 }
2302
2303 SetConsoleCursorInfo(g_hConOut, &g_cci);
2304 SetConsoleMode(g_hConIn, g_cmodein);
2305 SetConsoleMode(g_hConOut, g_cmodeout);
2306
2307#ifdef DYNAMIC_GETTEXT
2308 dyn_libintl_end();
2309#endif
2310
2311 exit(r);
2312}
2313#endif /* !FEAT_GUI_W32 */
2314
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315/*
2316 * Do we have an interactive window?
2317 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002318/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 int
2320mch_check_win(
2321 int argc,
2322 char **argv)
2323{
2324 get_exe_name();
2325
2326#ifdef FEAT_GUI_W32
2327 return OK; /* GUI always has a tty */
2328#else
2329 if (isatty(1))
2330 return OK;
2331 return FAIL;
2332#endif
2333}
2334
2335
2336/*
2337 * fname_case(): Set the case of the file name, if it already exists.
2338 * When "len" is > 0, also expand short to long filenames.
2339 */
2340 void
2341fname_case(
2342 char_u *name,
2343 int len)
2344{
2345 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002346 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347 char *ptrue, *ptruePrev;
2348 char *porig, *porigPrev;
2349 int flen;
2350 WIN32_FIND_DATA fb;
2351 HANDLE hFind;
2352 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002353 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002355 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356 if (flen == 0 || flen > _MAX_PATH)
2357 return;
2358
2359 slash_adjust(name);
2360
2361 /* Build the new name in szTrueName[] one component at a time. */
2362 porig = name;
2363 ptrue = szTrueName;
2364
2365 if (isalpha(porig[0]) && porig[1] == ':')
2366 {
2367 /* copy leading drive letter */
2368 *ptrue++ = *porig++;
2369 *ptrue++ = *porig++;
2370 *ptrue = NUL; /* in case nothing follows */
2371 }
2372
2373 while (*porig != NUL)
2374 {
2375 /* copy \ characters */
2376 while (*porig == psepc)
2377 *ptrue++ = *porig++;
2378
2379 ptruePrev = ptrue;
2380 porigPrev = porig;
2381 while (*porig != NUL && *porig != psepc)
2382 {
2383#ifdef FEAT_MBYTE
2384 int l;
2385
2386 if (enc_dbcs)
2387 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002388 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389 while (--l >= 0)
2390 *ptrue++ = *porig++;
2391 }
2392 else
2393#endif
2394 *ptrue++ = *porig++;
2395 }
2396 *ptrue = NUL;
2397
Bram Moolenaar464c9252010-10-13 20:37:41 +02002398 /* To avoid a slow failure append "\*" when searching a directory,
2399 * server or network share. */
2400 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002401 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002402 if (*porig == psepc && slen + 2 < _MAX_PATH)
2403 STRCPY(szTrueNameTemp + slen, "\\*");
2404
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 /* Skip "", "." and "..". */
2406 if (ptrue > ptruePrev
2407 && (ptruePrev[0] != '.'
2408 || (ptruePrev[1] != NUL
2409 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002410 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411 != INVALID_HANDLE_VALUE)
2412 {
2413 c = *porig;
2414 *porig = NUL;
2415
2416 /* Only use the match when it's the same name (ignoring case) or
2417 * expansion is allowed and there is a match with the short name
2418 * and there is enough room. */
2419 if (_stricoll(porigPrev, fb.cFileName) == 0
2420 || (len > 0
2421 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2422 && (int)(ptruePrev - szTrueName)
2423 + (int)strlen(fb.cFileName) < len)))
2424 {
2425 STRCPY(ptruePrev, fb.cFileName);
2426
2427 /* Look for exact match and prefer it if found. Must be a
2428 * long name, otherwise there would be only one match. */
2429 while (FindNextFile(hFind, &fb))
2430 {
2431 if (*fb.cAlternateFileName != NUL
2432 && (strcoll(porigPrev, fb.cFileName) == 0
2433 || (len > 0
2434 && (_stricoll(porigPrev,
2435 fb.cAlternateFileName) == 0
2436 && (int)(ptruePrev - szTrueName)
2437 + (int)strlen(fb.cFileName) < len))))
2438 {
2439 STRCPY(ptruePrev, fb.cFileName);
2440 break;
2441 }
2442 }
2443 }
2444 FindClose(hFind);
2445 *porig = c;
2446 ptrue = ptruePrev + strlen(ptruePrev);
2447 }
2448 }
2449
2450 STRCPY(name, szTrueName);
2451}
2452
2453
2454/*
2455 * Insert user name in s[len].
2456 */
2457 int
2458mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002459 char_u *s,
2460 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002462 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002463 DWORD cch = sizeof szUserName;
2464
2465 if (GetUserName(szUserName, &cch))
2466 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002467 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002468 return OK;
2469 }
2470 s[0] = NUL;
2471 return FAIL;
2472}
2473
2474
2475/*
2476 * Insert host name in s[len].
2477 */
2478 void
2479mch_get_host_name(
2480 char_u *s,
2481 int len)
2482{
2483 DWORD cch = len;
2484
2485 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002486 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487}
2488
2489
2490/*
2491 * return process ID
2492 */
2493 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002494mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495{
2496 return (long)GetCurrentProcessId();
2497}
2498
2499
2500/*
2501 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2502 * Return OK for success, FAIL for failure.
2503 */
2504 int
2505mch_dirname(
2506 char_u *buf,
2507 int len)
2508{
2509 /*
2510 * Originally this was:
2511 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2512 * But the Win32s known bug list says that getcwd() doesn't work
2513 * so use the Win32 system call instead. <Negri>
2514 */
2515#ifdef FEAT_MBYTE
2516 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2517 {
2518 WCHAR wbuf[_MAX_PATH + 1];
2519
2520 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2521 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002522 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523
2524 if (p != NULL)
2525 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002526 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 vim_free(p);
2528 return OK;
2529 }
2530 }
2531 /* Retry with non-wide function (for Windows 98). */
2532 }
2533#endif
2534 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2535}
2536
2537/*
2538 * get file permissions for `name'
2539 * -1 : error
2540 * else FILE_ATTRIBUTE_* defined in winnt.h
2541 */
2542 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002543mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544{
2545#ifdef FEAT_MBYTE
2546 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2547 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002548 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549 long n;
2550
2551 if (p != NULL)
2552 {
2553 n = (long)GetFileAttributesW(p);
2554 vim_free(p);
2555 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2556 return n;
2557 /* Retry with non-wide function (for Windows 98). */
2558 }
2559 }
2560#endif
2561 return (long)GetFileAttributes((char *)name);
2562}
2563
2564
2565/*
2566 * set file permission for `name' to `perm'
2567 */
2568 int
2569mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002570 char_u *name,
2571 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572{
2573 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2574#ifdef FEAT_MBYTE
2575 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2576 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002577 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 long n;
2579
2580 if (p != NULL)
2581 {
2582 n = (long)SetFileAttributesW(p, perm);
2583 vim_free(p);
2584 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2585 return n ? OK : FAIL;
2586 /* Retry with non-wide function (for Windows 98). */
2587 }
2588 }
2589#endif
2590 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2591}
2592
2593/*
2594 * Set hidden flag for "name".
2595 */
2596 void
2597mch_hide(char_u *name)
2598{
2599 int perm;
2600#ifdef FEAT_MBYTE
2601 WCHAR *p = NULL;
2602
2603 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002604 p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605#endif
2606
2607#ifdef FEAT_MBYTE
2608 if (p != NULL)
2609 {
2610 perm = GetFileAttributesW(p);
2611 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2612 {
2613 /* Retry with non-wide function (for Windows 98). */
2614 vim_free(p);
2615 p = NULL;
2616 }
2617 }
2618 if (p == NULL)
2619#endif
2620 perm = GetFileAttributes((char *)name);
2621 if (perm >= 0)
2622 {
2623 perm |= FILE_ATTRIBUTE_HIDDEN;
2624#ifdef FEAT_MBYTE
2625 if (p != NULL)
2626 {
2627 if (SetFileAttributesW(p, perm) == 0
2628 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2629 {
2630 /* Retry with non-wide function (for Windows 98). */
2631 vim_free(p);
2632 p = NULL;
2633 }
2634 }
2635 if (p == NULL)
2636#endif
2637 SetFileAttributes((char *)name, perm);
2638 }
2639#ifdef FEAT_MBYTE
2640 vim_free(p);
2641#endif
2642}
2643
2644/*
2645 * return TRUE if "name" is a directory
2646 * return FALSE if "name" is not a directory or upon error
2647 */
2648 int
2649mch_isdir(char_u *name)
2650{
2651 int f = mch_getperm(name);
2652
2653 if (f == -1)
2654 return FALSE; /* file does not exist at all */
2655
2656 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2657}
2658
2659/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002660 * Create directory "name".
2661 * Return 0 on success, -1 on error.
2662 */
2663 int
2664mch_mkdir(char_u *name)
2665{
2666#ifdef FEAT_MBYTE
2667 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2668 {
2669 WCHAR *p;
2670 int retval;
2671
2672 p = enc_to_utf16(name, NULL);
2673 if (p == NULL)
2674 return -1;
2675 retval = _wmkdir(p);
2676 vim_free(p);
2677 return retval;
2678 }
2679#endif
2680 return _mkdir(name);
2681}
2682
2683/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002684 * Return TRUE if file "fname" has more than one link.
2685 */
2686 int
2687mch_is_linked(char_u *fname)
2688{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002689 BY_HANDLE_FILE_INFORMATION info;
2690
2691 return win32_fileinfo(fname, &info) == FILEINFO_OK
2692 && info.nNumberOfLinks > 1;
2693}
2694
2695/*
2696 * Get the by-handle-file-information for "fname".
2697 * Returns FILEINFO_OK when OK.
2698 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
2699 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
2700 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
2701 */
2702 int
2703win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
2704{
Bram Moolenaar03f48552006-02-28 23:52:23 +00002705 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002706 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002707#ifdef FEAT_MBYTE
2708 WCHAR *wn = NULL;
2709
2710 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002711 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002712 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002713 if (wn == NULL)
2714 res = FILEINFO_ENC_FAIL;
2715 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00002716 if (wn != NULL)
2717 {
2718 hFile = CreateFileW(wn, /* file name */
2719 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002720 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002721 NULL, /* security descriptor */
2722 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002723 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002724 NULL); /* handle to template file */
2725 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002726 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002727 {
2728 /* Retry with non-wide function (for Windows 98). */
2729 vim_free(wn);
2730 wn = NULL;
2731 }
2732 }
2733 if (wn == NULL)
2734#endif
2735 hFile = CreateFile(fname, /* file name */
2736 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002737 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002738 NULL, /* security descriptor */
2739 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002740 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002741 NULL); /* handle to template file */
2742
2743 if (hFile != INVALID_HANDLE_VALUE)
2744 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002745 if (GetFileInformationByHandle(hFile, info) != 0)
2746 res = FILEINFO_OK;
2747 else
2748 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002749 CloseHandle(hFile);
2750 }
2751
2752#ifdef FEAT_MBYTE
2753 vim_free(wn);
2754#endif
2755 return res;
2756}
2757
2758/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002759 * Return TRUE if file or directory "name" is writable (not readonly).
2760 * Strange semantics of Win32: a readonly directory is writable, but you can't
2761 * delete a file. Let's say this means it is writable.
2762 */
2763 int
2764mch_writable(char_u *name)
2765{
2766 int perm = mch_getperm(name);
2767
2768 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2769 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2770}
2771
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772/*
2773 * Return 1 if "name" can be executed, 0 if not.
2774 * Return -1 if unknown.
2775 */
2776 int
2777mch_can_exe(char_u *name)
2778{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002779 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002780 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002781 char_u *p;
2782
2783 if (len >= _MAX_PATH) /* safety check */
2784 return FALSE;
2785
2786 /* If there already is an extension try using the name directly. Also do
2787 * this with a Unix-shell like 'shell'. */
2788 if (vim_strchr(gettail(name), '.') != NULL
2789 || strstr((char *)gettail(p_sh), "sh") != NULL)
2790 if (executable_exists((char *)name))
2791 return TRUE;
2792
2793 /*
2794 * Loop over all extensions in $PATHEXT.
2795 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002796 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002797 p = mch_getenv("PATHEXT");
2798 if (p == NULL)
2799 p = (char_u *)".com;.exe;.bat;.cmd";
2800 while (*p)
2801 {
2802 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2803 {
2804 /* A single "." means no extension is added. */
2805 buf[len] = NUL;
2806 ++p;
2807 if (*p)
2808 ++p;
2809 }
2810 else
2811 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2812 if (executable_exists((char *)buf))
2813 return TRUE;
2814 }
2815 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002816}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817
2818/*
2819 * Check what "name" is:
2820 * NODE_NORMAL: file or directory (or doesn't exist)
2821 * NODE_WRITABLE: writable device, socket, fifo, etc.
2822 * NODE_OTHER: non-writable things
2823 */
2824 int
2825mch_nodetype(char_u *name)
2826{
2827 HANDLE hFile;
2828 int type;
2829
Bram Moolenaar043545e2006-10-10 16:44:07 +00002830 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2831 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2832 * here. */
2833 if (STRNCMP(name, "\\\\.\\", 4) == 0)
2834 return NODE_WRITABLE;
2835
Bram Moolenaar071d4272004-06-13 20:20:40 +00002836 hFile = CreateFile(name, /* file name */
2837 GENERIC_WRITE, /* access mode */
2838 0, /* share mode */
2839 NULL, /* security descriptor */
2840 OPEN_EXISTING, /* creation disposition */
2841 0, /* file attributes */
2842 NULL); /* handle to template file */
2843
2844 if (hFile == INVALID_HANDLE_VALUE)
2845 return NODE_NORMAL;
2846
2847 type = GetFileType(hFile);
2848 CloseHandle(hFile);
2849 if (type == FILE_TYPE_CHAR)
2850 return NODE_WRITABLE;
2851 if (type == FILE_TYPE_DISK)
2852 return NODE_NORMAL;
2853 return NODE_OTHER;
2854}
2855
2856#ifdef HAVE_ACL
2857struct my_acl
2858{
2859 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2860 PSID pSidOwner;
2861 PSID pSidGroup;
2862 PACL pDacl;
2863 PACL pSacl;
2864};
2865#endif
2866
2867/*
2868 * Return a pointer to the ACL of file "fname" in allocated memory.
2869 * Return NULL if the ACL is not available for whatever reason.
2870 */
2871 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002872mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873{
2874#ifndef HAVE_ACL
2875 return (vim_acl_T)NULL;
2876#else
2877 struct my_acl *p = NULL;
2878
2879 /* This only works on Windows NT and 2000. */
2880 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2881 {
2882 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2883 if (p != NULL)
2884 {
2885 if (pGetNamedSecurityInfo(
2886 (LPTSTR)fname, // Abstract filename
2887 SE_FILE_OBJECT, // File Object
2888 // Retrieve the entire security descriptor.
2889 OWNER_SECURITY_INFORMATION |
2890 GROUP_SECURITY_INFORMATION |
2891 DACL_SECURITY_INFORMATION |
2892 SACL_SECURITY_INFORMATION,
2893 &p->pSidOwner, // Ownership information.
2894 &p->pSidGroup, // Group membership.
2895 &p->pDacl, // Discretionary information.
2896 &p->pSacl, // For auditing purposes.
2897 &p->pSecurityDescriptor
2898 ) != ERROR_SUCCESS)
2899 {
2900 mch_free_acl((vim_acl_T)p);
2901 p = NULL;
2902 }
2903 }
2904 }
2905
2906 return (vim_acl_T)p;
2907#endif
2908}
2909
2910/*
2911 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2912 * Errors are ignored.
2913 * This must only be called with "acl" equal to what mch_get_acl() returned.
2914 */
2915 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002916mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917{
2918#ifdef HAVE_ACL
2919 struct my_acl *p = (struct my_acl *)acl;
2920
2921 if (p != NULL && advapi_lib != NULL)
2922 (void)pSetNamedSecurityInfo(
2923 (LPTSTR)fname, // Abstract filename
2924 SE_FILE_OBJECT, // File Object
2925 // Retrieve the entire security descriptor.
2926 OWNER_SECURITY_INFORMATION |
2927 GROUP_SECURITY_INFORMATION |
2928 DACL_SECURITY_INFORMATION |
2929 SACL_SECURITY_INFORMATION,
2930 p->pSidOwner, // Ownership information.
2931 p->pSidGroup, // Group membership.
2932 p->pDacl, // Discretionary information.
2933 p->pSacl // For auditing purposes.
2934 );
2935#endif
2936}
2937
2938 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002939mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940{
2941#ifdef HAVE_ACL
2942 struct my_acl *p = (struct my_acl *)acl;
2943
2944 if (p != NULL)
2945 {
2946 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2947 vim_free(p);
2948 }
2949#endif
2950}
2951
2952#ifndef FEAT_GUI_W32
2953
2954/*
2955 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2956 */
2957 static BOOL WINAPI
2958handler_routine(
2959 DWORD dwCtrlType)
2960{
2961 switch (dwCtrlType)
2962 {
2963 case CTRL_C_EVENT:
2964 if (ctrl_c_interrupts)
2965 g_fCtrlCPressed = TRUE;
2966 return TRUE;
2967
2968 case CTRL_BREAK_EVENT:
2969 g_fCBrkPressed = TRUE;
2970 return TRUE;
2971
2972 /* fatal events: shut down gracefully */
2973 case CTRL_CLOSE_EVENT:
2974 case CTRL_LOGOFF_EVENT:
2975 case CTRL_SHUTDOWN_EVENT:
2976 windgoto((int)Rows - 1, 0);
2977 g_fForceExit = TRUE;
2978
Bram Moolenaar0fde2902008-03-16 13:54:13 +00002979 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980 (dwCtrlType == CTRL_CLOSE_EVENT
2981 ? _("close")
2982 : dwCtrlType == CTRL_LOGOFF_EVENT
2983 ? _("logoff")
2984 : _("shutdown")));
2985#ifdef DEBUG
2986 OutputDebugString(IObuff);
2987#endif
2988
2989 preserve_exit(); /* output IObuff, preserve files and exit */
2990
2991 return TRUE; /* not reached */
2992
2993 default:
2994 return FALSE;
2995 }
2996}
2997
2998
2999/*
3000 * set the tty in (raw) ? "raw" : "cooked" mode
3001 */
3002 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003003mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003004{
3005 DWORD cmodein;
3006 DWORD cmodeout;
3007 BOOL bEnableHandler;
3008
3009 GetConsoleMode(g_hConIn, &cmodein);
3010 GetConsoleMode(g_hConOut, &cmodeout);
3011 if (tmode == TMODE_RAW)
3012 {
3013 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3014 ENABLE_ECHO_INPUT);
3015#ifdef FEAT_MOUSE
3016 if (g_fMouseActive)
3017 cmodein |= ENABLE_MOUSE_INPUT;
3018#endif
3019 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3020 bEnableHandler = TRUE;
3021 }
3022 else /* cooked */
3023 {
3024 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3025 ENABLE_ECHO_INPUT);
3026 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3027 bEnableHandler = FALSE;
3028 }
3029 SetConsoleMode(g_hConIn, cmodein);
3030 SetConsoleMode(g_hConOut, cmodeout);
3031 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3032
3033#ifdef MCH_WRITE_DUMP
3034 if (fdDump)
3035 {
3036 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3037 tmode == TMODE_RAW ? "raw" :
3038 tmode == TMODE_COOK ? "cooked" : "normal",
3039 cmodein, cmodeout);
3040 fflush(fdDump);
3041 }
3042#endif
3043}
3044
3045
3046/*
3047 * Get the size of the current window in `Rows' and `Columns'
3048 * Return OK when size could be determined, FAIL otherwise.
3049 */
3050 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003051mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052{
3053 CONSOLE_SCREEN_BUFFER_INFO csbi;
3054
3055 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3056 {
3057 /*
3058 * For some reason, we are trying to get the screen dimensions
3059 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3060 * variables are really intended to mean the size of Vim screen
3061 * while in termcap mode.
3062 */
3063 Rows = g_cbTermcap.Info.dwSize.Y;
3064 Columns = g_cbTermcap.Info.dwSize.X;
3065 }
3066 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3067 {
3068 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3069 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3070 }
3071 else
3072 {
3073 Rows = 25;
3074 Columns = 80;
3075 }
3076 return OK;
3077}
3078
3079/*
3080 * Set a console window to `xSize' * `ySize'
3081 */
3082 static void
3083ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003084 HANDLE hConsole,
3085 int xSize,
3086 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087{
3088 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3089 SMALL_RECT srWindowRect; /* hold the new console size */
3090 COORD coordScreen;
3091
3092#ifdef MCH_WRITE_DUMP
3093 if (fdDump)
3094 {
3095 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3096 fflush(fdDump);
3097 }
3098#endif
3099
3100 /* get the largest size we can size the console window to */
3101 coordScreen = GetLargestConsoleWindowSize(hConsole);
3102
3103 /* define the new console window size and scroll position */
3104 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3105 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3106 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3107
3108 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3109 {
3110 int sx, sy;
3111
3112 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3113 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3114 if (sy < ySize || sx < xSize)
3115 {
3116 /*
3117 * Increasing number of lines/columns, do buffer first.
3118 * Use the maximal size in x and y direction.
3119 */
3120 if (sy < ySize)
3121 coordScreen.Y = ySize;
3122 else
3123 coordScreen.Y = sy;
3124 if (sx < xSize)
3125 coordScreen.X = xSize;
3126 else
3127 coordScreen.X = sx;
3128 SetConsoleScreenBufferSize(hConsole, coordScreen);
3129 }
3130 }
3131
3132 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3133 {
3134#ifdef MCH_WRITE_DUMP
3135 if (fdDump)
3136 {
3137 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3138 GetLastError());
3139 fflush(fdDump);
3140 }
3141#endif
3142 }
3143
3144 /* define the new console buffer size */
3145 coordScreen.X = xSize;
3146 coordScreen.Y = ySize;
3147
3148 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3149 {
3150#ifdef MCH_WRITE_DUMP
3151 if (fdDump)
3152 {
3153 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3154 GetLastError());
3155 fflush(fdDump);
3156 }
3157#endif
3158 }
3159}
3160
3161
3162/*
3163 * Set the console window to `Rows' * `Columns'
3164 */
3165 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003166mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167{
3168 COORD coordScreen;
3169
3170 /* Don't change window size while still starting up */
3171 if (suppress_winsize != 0)
3172 {
3173 suppress_winsize = 2;
3174 return;
3175 }
3176
3177 if (term_console)
3178 {
3179 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3180
3181 /* Clamp Rows and Columns to reasonable values */
3182 if (Rows > coordScreen.Y)
3183 Rows = coordScreen.Y;
3184 if (Columns > coordScreen.X)
3185 Columns = coordScreen.X;
3186
3187 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3188 }
3189}
3190
3191/*
3192 * Rows and/or Columns has changed.
3193 */
3194 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003195mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196{
3197 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3198}
3199
3200
3201/*
3202 * Called when started up, to set the winsize that was delayed.
3203 */
3204 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003205mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206{
3207 if (suppress_winsize == 2)
3208 {
3209 suppress_winsize = 0;
3210 mch_set_shellsize();
3211 shell_resized();
3212 }
3213 suppress_winsize = 0;
3214}
3215#endif /* FEAT_GUI_W32 */
3216
3217
3218
3219#if defined(FEAT_GUI_W32) || defined(PROTO)
3220
3221/*
3222 * Specialised version of system() for Win32 GUI mode.
3223 * This version proceeds as follows:
3224 * 1. Create a console window for use by the subprocess
3225 * 2. Run the subprocess (it gets the allocated console by default)
3226 * 3. Wait for the subprocess to terminate and get its exit code
3227 * 4. Prompt the user to press a key to close the console window
3228 */
3229 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003230mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231{
3232 STARTUPINFO si;
3233 PROCESS_INFORMATION pi;
3234 DWORD ret = 0;
3235 HWND hwnd = GetFocus();
3236
3237 si.cb = sizeof(si);
3238 si.lpReserved = NULL;
3239 si.lpDesktop = NULL;
3240 si.lpTitle = NULL;
3241 si.dwFlags = STARTF_USESHOWWINDOW;
3242 /*
3243 * It's nicer to run a filter command in a minimized window, but in
3244 * Windows 95 this makes the command MUCH slower. We can't do it under
3245 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003246 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247 */
3248 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003249 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250 else
3251 si.wShowWindow = SW_SHOWNORMAL;
3252 si.cbReserved2 = 0;
3253 si.lpReserved2 = NULL;
3254
3255 /* There is a strange error on Windows 95 when using "c:\\command.com".
3256 * When the "c:\\" is left out it works OK...? */
3257 if (mch_windows95()
3258 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3259 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3260 cmd += 3;
3261
3262 /* Now, run the command */
3263 CreateProcess(NULL, /* Executable name */
3264 cmd, /* Command to execute */
3265 NULL, /* Process security attributes */
3266 NULL, /* Thread security attributes */
3267 FALSE, /* Inherit handles */
3268 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3269 CREATE_NEW_CONSOLE,
3270 NULL, /* Environment */
3271 NULL, /* Current directory */
3272 &si, /* Startup information */
3273 &pi); /* Process information */
3274
3275
3276 /* Wait for the command to terminate before continuing */
3277 if (g_PlatformId != VER_PLATFORM_WIN32s)
3278 {
3279#ifdef FEAT_GUI
3280 int delay = 1;
3281
3282 /* Keep updating the window while waiting for the shell to finish. */
3283 for (;;)
3284 {
3285 MSG msg;
3286
3287 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3288 {
3289 TranslateMessage(&msg);
3290 DispatchMessage(&msg);
3291 }
3292 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3293 break;
3294
3295 /* We start waiting for a very short time and then increase it, so
3296 * that we respond quickly when the process is quick, and don't
3297 * consume too much overhead when it's slow. */
3298 if (delay < 50)
3299 delay += 10;
3300 }
3301#else
3302 WaitForSingleObject(pi.hProcess, INFINITE);
3303#endif
3304
3305 /* Get the command exit code */
3306 GetExitCodeProcess(pi.hProcess, &ret);
3307 }
3308 else
3309 {
3310 /*
3311 * This ugly code is the only quick way of performing
3312 * a synchronous spawn under Win32s. Yuk.
3313 */
3314 num_windows = 0;
3315 EnumWindows(win32ssynch_cb, 0);
3316 old_num_windows = num_windows;
3317 do
3318 {
3319 Sleep(1000);
3320 num_windows = 0;
3321 EnumWindows(win32ssynch_cb, 0);
3322 } while (num_windows == old_num_windows);
3323 ret = 0;
3324 }
3325
3326 /* Close the handles to the subprocess, so that it goes away */
3327 CloseHandle(pi.hThread);
3328 CloseHandle(pi.hProcess);
3329
3330 /* Try to get input focus back. Doesn't always work though. */
3331 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3332
3333 return ret;
3334}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003335
3336/*
3337 * Thread launched by the gui to send the current buffer data to the
3338 * process. This way avoid to hang up vim totally if the children
3339 * process take a long time to process the lines.
3340 */
3341 static DWORD WINAPI
3342sub_process_writer(LPVOID param)
3343{
3344 HANDLE g_hChildStd_IN_Wr = param;
3345 linenr_T lnum = curbuf->b_op_start.lnum;
3346 DWORD len = 0;
3347 DWORD l;
3348 char_u *lp = ml_get(lnum);
3349 char_u *s;
3350 int written = 0;
3351
3352 for (;;)
3353 {
3354 l = (DWORD)STRLEN(lp + written);
3355 if (l == 0)
3356 len = 0;
3357 else if (lp[written] == NL)
3358 {
3359 /* NL -> NUL translation */
3360 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3361 }
3362 else
3363 {
3364 s = vim_strchr(lp + written, NL);
3365 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3366 s == NULL ? l : (DWORD)(s - (lp + written)),
3367 &len, NULL);
3368 }
3369 if (len == (int)l)
3370 {
3371 /* Finished a line, add a NL, unless this line should not have
3372 * one. */
3373 if (lnum != curbuf->b_op_end.lnum
3374 || !curbuf->b_p_bin
3375 || (lnum != curbuf->b_no_eol_lnum
3376 && (lnum != curbuf->b_ml.ml_line_count
3377 || curbuf->b_p_eol)))
3378 {
3379 WriteFile(g_hChildStd_IN_Wr, "\n", 1, &ignored, NULL);
3380 }
3381
3382 ++lnum;
3383 if (lnum > curbuf->b_op_end.lnum)
3384 break;
3385
3386 lp = ml_get(lnum);
3387 written = 0;
3388 }
3389 else if (len > 0)
3390 written += len;
3391 }
3392
3393 /* finished all the lines, close pipe */
3394 CloseHandle(g_hChildStd_IN_Wr);
3395 ExitThread(0);
3396}
3397
3398
3399# define BUFLEN 100 /* length for buffer, stolen from unix version */
3400
3401/*
3402 * This function read from the children's stdout and write the
3403 * data on screen or in the buffer accordingly.
3404 */
3405 static void
3406dump_pipe(int options,
3407 HANDLE g_hChildStd_OUT_Rd,
3408 garray_T *ga,
3409 char_u buffer[],
3410 DWORD *buffer_off)
3411{
3412 DWORD availableBytes = 0;
3413 DWORD i;
3414 int c;
3415 char_u *p;
3416 int ret;
3417 DWORD len;
3418 DWORD toRead;
3419 int repeatCount;
3420
3421 /* we query the pipe to see if there is any data to read
3422 * to avoid to perform a blocking read */
3423 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3424 NULL, /* optional buffer */
3425 0, /* buffe size */
3426 NULL, /* number of read bytes */
3427 &availableBytes, /* available bytes total */
3428 NULL); /* byteLeft */
3429
3430 repeatCount = 0;
3431 /* We got real data in the pipe, read it */
3432 while (ret != 0 && availableBytes > 0 && availableBytes > 0)
3433 {
3434 repeatCount++;
3435 toRead =
3436# ifdef FEAT_MBYTE
3437 (DWORD)(BUFLEN - *buffer_off);
3438# else
3439 (DWORD)BUFLEN;
3440# endif
3441 toRead = availableBytes < toRead ? availableBytes : toRead;
3442 ReadFile(g_hChildStd_OUT_Rd, buffer
3443# ifdef FEAT_MBYTE
3444 + *buffer_off, toRead
3445# else
3446 , toRead
3447# endif
3448 , &len, NULL);
3449
3450 /* If we haven't read anything, there is a problem */
3451 if (len == 0)
3452 break;
3453
3454 availableBytes -= len;
3455
3456 if (options & SHELL_READ)
3457 {
3458 /* Do NUL -> NL translation, append NL separated
3459 * lines to the current buffer. */
3460 for (i = 0; i < len; ++i)
3461 {
3462 if (buffer[i] == NL)
3463 append_ga_line(ga);
3464 else if (buffer[i] == NUL)
3465 ga_append(ga, NL);
3466 else
3467 ga_append(ga, buffer[i]);
3468 }
3469 }
3470# ifdef FEAT_MBYTE
3471 else if (has_mbyte)
3472 {
3473 int l;
3474
3475 len += *buffer_off;
3476 buffer[len] = NUL;
3477
3478 /* Check if the last character in buffer[] is
3479 * incomplete, keep these bytes for the next
3480 * round. */
3481 for (p = buffer; p < buffer + len; p += l)
3482 {
3483 l = mb_cptr2len(p);
3484 if (l == 0)
3485 l = 1; /* NUL byte? */
3486 else if (MB_BYTE2LEN(*p) != l)
3487 break;
3488 }
3489 if (p == buffer) /* no complete character */
3490 {
3491 /* avoid getting stuck at an illegal byte */
3492 if (len >= 12)
3493 ++p;
3494 else
3495 {
3496 *buffer_off = len;
3497 return;
3498 }
3499 }
3500 c = *p;
3501 *p = NUL;
3502 msg_puts(buffer);
3503 if (p < buffer + len)
3504 {
3505 *p = c;
3506 *buffer_off = (DWORD)((buffer + len) - p);
3507 mch_memmove(buffer, p, *buffer_off);
3508 return;
3509 }
3510 *buffer_off = 0;
3511 }
3512# endif /* FEAT_MBYTE */
3513 else
3514 {
3515 buffer[len] = NUL;
3516 msg_puts(buffer);
3517 }
3518
3519 windgoto(msg_row, msg_col);
3520 cursor_on();
3521 out_flush();
3522 }
3523}
3524
3525/*
3526 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
3527 * for communication and doesn't open any new window.
3528 */
3529 static int
3530mch_system_piped(char *cmd, int options)
3531{
3532 STARTUPINFO si;
3533 PROCESS_INFORMATION pi;
3534 DWORD ret = 0;
3535
3536 HANDLE g_hChildStd_IN_Rd = NULL;
3537 HANDLE g_hChildStd_IN_Wr = NULL;
3538 HANDLE g_hChildStd_OUT_Rd = NULL;
3539 HANDLE g_hChildStd_OUT_Wr = NULL;
3540
3541 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
3542 DWORD len;
3543
3544 /* buffer used to receive keys */
3545 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3546 int ta_len = 0; /* valid bytes in ta_buf[] */
3547
3548 DWORD i;
3549 int c;
3550 int noread_cnt = 0;
3551 garray_T ga;
3552 int delay = 1;
3553# ifdef FEAT_MBYTE
3554 DWORD buffer_off = 0; /* valid bytes in buffer[] */
3555# endif
3556
3557 SECURITY_ATTRIBUTES saAttr;
3558
3559 /* Set the bInheritHandle flag so pipe handles are inherited. */
3560 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
3561 saAttr.bInheritHandle = TRUE;
3562 saAttr.lpSecurityDescriptor = NULL;
3563
3564 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
3565 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
3566 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
3567 /* Create a pipe for the child process's STDIN. */
3568 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
3569 /* Ensure the write handle to the pipe for STDIN is not inherited. */
3570 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
3571 {
3572 CloseHandle(g_hChildStd_IN_Rd);
3573 CloseHandle(g_hChildStd_IN_Wr);
3574 CloseHandle(g_hChildStd_OUT_Rd);
3575 CloseHandle(g_hChildStd_OUT_Wr);
3576 MSG_PUTS(_("\nCannot create pipes\n"));
3577 }
3578
3579 si.cb = sizeof(si);
3580 si.lpReserved = NULL;
3581 si.lpDesktop = NULL;
3582 si.lpTitle = NULL;
3583 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
3584
3585 /* set-up our file redirection */
3586 si.hStdError = g_hChildStd_OUT_Wr;
3587 si.hStdOutput = g_hChildStd_OUT_Wr;
3588 si.hStdInput = g_hChildStd_IN_Rd;
3589 si.wShowWindow = SW_HIDE;
3590 si.cbReserved2 = 0;
3591 si.lpReserved2 = NULL;
3592
3593 if (options & SHELL_READ)
3594 ga_init2(&ga, 1, BUFLEN);
3595
3596 /* Now, run the command */
3597 CreateProcess(NULL, /* Executable name */
3598 cmd, /* Command to execute */
3599 NULL, /* Process security attributes */
3600 NULL, /* Thread security attributes */
3601
3602 // this command can be litigeous, handle inheritence was
3603 // deactivated for pending temp file, but, if we deactivate
3604 // it, the pipes don't work for some reason.
3605 TRUE, /* Inherit handles, first deactivated,
3606 * but needed */
3607 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
3608 NULL, /* Environment */
3609 NULL, /* Current directory */
3610 &si, /* Startup information */
3611 &pi); /* Process information */
3612
3613
3614 /* Close our unused side of the pipes */
3615 CloseHandle(g_hChildStd_IN_Rd);
3616 CloseHandle(g_hChildStd_OUT_Wr);
3617
3618 if (options & SHELL_WRITE)
3619 {
3620 HANDLE thread =
3621 CreateThread(NULL, /* security attributes */
3622 0, /* default stack size */
3623 sub_process_writer, /* function to be executed */
3624 g_hChildStd_IN_Wr, /* parameter */
3625 0, /* creation flag, start immediately */
3626 NULL); /* we don't care about thread id */
3627 CloseHandle(thread);
3628 g_hChildStd_IN_Wr = NULL;
3629 }
3630
3631 /* Keep updating the window while waiting for the shell to finish. */
3632 for (;;)
3633 {
3634 MSG msg;
3635
3636 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3637 {
3638 TranslateMessage(&msg);
3639 DispatchMessage(&msg);
3640 }
3641
3642 /* write pipe information in the window */
3643 if ((options & (SHELL_READ|SHELL_WRITE))
3644# ifdef FEAT_GUI
3645 || gui.in_use
3646# endif
3647 )
3648 {
3649 len = 0;
3650 if (!(options & SHELL_EXPAND)
3651 && ((options &
3652 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
3653 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
3654# ifdef FEAT_GUI
3655 || gui.in_use
3656# endif
3657 )
3658 && (ta_len > 0 || noread_cnt > 4))
3659 {
3660 if (ta_len == 0)
3661 {
3662 /* Get extra characters when we don't have any. Reset the
3663 * counter and timer. */
3664 noread_cnt = 0;
3665# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
3666 gettimeofday(&start_tv, NULL);
3667# endif
3668 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
3669 }
3670 if (ta_len > 0 || len > 0)
3671 {
3672 /*
3673 * For pipes: Check for CTRL-C: send interrupt signal to
3674 * child. Check for CTRL-D: EOF, close pipe to child.
3675 */
3676 if (len == 1 && cmd != NULL)
3677 {
3678 if (ta_buf[ta_len] == Ctrl_C)
3679 {
3680 /* Learn what exit code is expected, for
3681 * now put 9 as SIGKILL */
3682 TerminateProcess(pi.hProcess, 9);
3683 }
3684 if (ta_buf[ta_len] == Ctrl_D)
3685 {
3686 CloseHandle(g_hChildStd_IN_Wr);
3687 g_hChildStd_IN_Wr = NULL;
3688 }
3689 }
3690
3691 /* replace K_BS by <BS> and K_DEL by <DEL> */
3692 for (i = ta_len; i < ta_len + len; ++i)
3693 {
3694 if (ta_buf[i] == CSI && len - i > 2)
3695 {
3696 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
3697 if (c == K_DEL || c == K_KDEL || c == K_BS)
3698 {
3699 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
3700 (size_t)(len - i - 2));
3701 if (c == K_DEL || c == K_KDEL)
3702 ta_buf[i] = DEL;
3703 else
3704 ta_buf[i] = Ctrl_H;
3705 len -= 2;
3706 }
3707 }
3708 else if (ta_buf[i] == '\r')
3709 ta_buf[i] = '\n';
3710# ifdef FEAT_MBYTE
3711 if (has_mbyte)
3712 i += (*mb_ptr2len_len)(ta_buf + i,
3713 ta_len + len - i) - 1;
3714# endif
3715 }
3716
3717 /*
3718 * For pipes: echo the typed characters. For a pty this
3719 * does not seem to work.
3720 */
3721 for (i = ta_len; i < ta_len + len; ++i)
3722 {
3723 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
3724 msg_putchar(ta_buf[i]);
3725# ifdef FEAT_MBYTE
3726 else if (has_mbyte)
3727 {
3728 int l = (*mb_ptr2len)(ta_buf + i);
3729
3730 msg_outtrans_len(ta_buf + i, l);
3731 i += l - 1;
3732 }
3733# endif
3734 else
3735 msg_outtrans_len(ta_buf + i, 1);
3736 }
3737 windgoto(msg_row, msg_col);
3738 out_flush();
3739
3740 ta_len += len;
3741
3742 /*
3743 * Write the characters to the child, unless EOF has been
3744 * typed for pipes. Write one character at a time, to
3745 * avoid losing too much typeahead. When writing buffer
3746 * lines, drop the typed characters (only check for
3747 * CTRL-C).
3748 */
3749 if (options & SHELL_WRITE)
3750 ta_len = 0;
3751 else if (g_hChildStd_IN_Wr != NULL)
3752 {
3753 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
3754 1, &len, NULL);
3755 // if we are typing in, we want to keep things reactive
3756 delay = 1;
3757 if (len > 0)
3758 {
3759 ta_len -= len;
3760 mch_memmove(ta_buf, ta_buf + len, ta_len);
3761 }
3762 }
3763 }
3764 }
3765 }
3766
3767 if (ta_len)
3768 ui_inchar_undo(ta_buf, ta_len);
3769
3770 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3771 {
3772 dump_pipe(options, g_hChildStd_OUT_Rd,
3773 &ga, buffer, &buffer_off);
3774 break;
3775 }
3776
3777 ++noread_cnt;
3778 dump_pipe(options, g_hChildStd_OUT_Rd,
3779 &ga, buffer, &buffer_off);
3780
3781 /* We start waiting for a very short time and then increase it, so
3782 * that we respond quickly when the process is quick, and don't
3783 * consume too much overhead when it's slow. */
3784 if (delay < 50)
3785 delay += 10;
3786 }
3787
3788 /* Close the pipe */
3789 CloseHandle(g_hChildStd_OUT_Rd);
3790 if (g_hChildStd_IN_Wr != NULL)
3791 CloseHandle(g_hChildStd_IN_Wr);
3792
3793 WaitForSingleObject(pi.hProcess, INFINITE);
3794
3795 /* Get the command exit code */
3796 GetExitCodeProcess(pi.hProcess, &ret);
3797
3798 if (options & SHELL_READ)
3799 {
3800 if (ga.ga_len > 0)
3801 {
3802 append_ga_line(&ga);
3803 /* remember that the NL was missing */
3804 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
3805 }
3806 else
3807 curbuf->b_no_eol_lnum = 0;
3808 ga_clear(&ga);
3809 }
3810
3811 /* Close the handles to the subprocess, so that it goes away */
3812 CloseHandle(pi.hThread);
3813 CloseHandle(pi.hProcess);
3814
3815 return ret;
3816}
3817
3818 static int
3819mch_system(char *cmd, int options)
3820{
3821 /* if we can pipe and the shelltemp option is off */
3822 if (allowPiping && !p_stmp)
3823 return mch_system_piped(cmd, options);
3824 else
3825 return mch_system_classic(cmd, options);
3826}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827#else
3828
3829# define mch_system(c, o) system(c)
3830
3831#endif
3832
3833/*
3834 * Either execute a command by calling the shell or start a new shell
3835 */
3836 int
3837mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003838 char_u *cmd,
3839 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840{
3841 int x = 0;
3842 int tmode = cur_tmode;
3843#ifdef FEAT_TITLE
3844 char szShellTitle[512];
3845
3846 /* Change the title to reflect that we are in a subshell. */
3847 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3848 {
3849 if (cmd == NULL)
3850 strcat(szShellTitle, " :sh");
3851 else
3852 {
3853 strcat(szShellTitle, " - !");
3854 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3855 strcat(szShellTitle, cmd);
3856 }
3857 mch_settitle(szShellTitle, NULL);
3858 }
3859#endif
3860
3861 out_flush();
3862
3863#ifdef MCH_WRITE_DUMP
3864 if (fdDump)
3865 {
3866 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3867 fflush(fdDump);
3868 }
3869#endif
3870
3871 /*
3872 * Catch all deadly signals while running the external command, because a
3873 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3874 */
3875 signal(SIGINT, SIG_IGN);
3876#if defined(__GNUC__) && !defined(__MINGW32__)
3877 signal(SIGKILL, SIG_IGN);
3878#else
3879 signal(SIGBREAK, SIG_IGN);
3880#endif
3881 signal(SIGILL, SIG_IGN);
3882 signal(SIGFPE, SIG_IGN);
3883 signal(SIGSEGV, SIG_IGN);
3884 signal(SIGTERM, SIG_IGN);
3885 signal(SIGABRT, SIG_IGN);
3886
3887 if (options & SHELL_COOKED)
3888 settmode(TMODE_COOK); /* set to normal mode */
3889
3890 if (cmd == NULL)
3891 {
3892 x = mch_system(p_sh, options);
3893 }
3894 else
3895 {
3896 /* we use "command" or "cmd" to start the shell; slow but easy */
3897 char_u *newcmd;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003898 long_u cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00003899#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003900 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003902 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
3903
3904 newcmd = lalloc(cmdlen, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905 if (newcmd != NULL)
3906 {
3907 char_u *cmdbase = (*cmd == '"' ? cmd + 1 : cmd);
3908
3909 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3910 {
3911 STARTUPINFO si;
3912 PROCESS_INFORMATION pi;
Bram Moolenaarbd8608d2011-05-25 17:06:22 +02003913 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914
3915 si.cb = sizeof(si);
3916 si.lpReserved = NULL;
3917 si.lpDesktop = NULL;
3918 si.lpTitle = NULL;
3919 si.dwFlags = 0;
3920 si.cbReserved2 = 0;
3921 si.lpReserved2 = NULL;
3922
3923 cmdbase = skipwhite(cmdbase + 5);
3924 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3925 && vim_iswhite(cmdbase[4]))
3926 {
3927 cmdbase = skipwhite(cmdbase + 4);
3928 si.dwFlags = STARTF_USESHOWWINDOW;
3929 si.wShowWindow = SW_SHOWMINNOACTIVE;
3930 }
Bram Moolenaarbd8608d2011-05-25 17:06:22 +02003931 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
3932 && vim_iswhite(cmdbase[2]))
3933 {
3934 cmdbase = skipwhite(cmdbase + 2);
3935 flags = CREATE_NO_WINDOW;
3936 si.dwFlags = STARTF_USESTDHANDLES;
3937 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
3938 GENERIC_READ, // Access flags
3939 0, // Share flags
3940 NULL, // Security att.
3941 OPEN_EXISTING, // Open flags
3942 FILE_ATTRIBUTE_NORMAL, // File att.
3943 NULL); // Temp file
3944 si.hStdOutput = si.hStdInput;
3945 si.hStdError = si.hStdInput;
3946 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947
3948 /* When the command is in double quotes, but 'shellxquote' is
3949 * empty, keep the double quotes around the command.
3950 * Otherwise remove the double quotes, they aren't needed
3951 * here, because we don't use a shell to run the command. */
3952 if (*cmd == '"' && *p_sxq == NUL)
3953 {
3954 newcmd[0] = '"';
3955 STRCPY(newcmd + 1, cmdbase);
3956 }
3957 else
3958 {
3959 STRCPY(newcmd, cmdbase);
3960 if (*cmd == '"' && *newcmd != NUL)
3961 newcmd[STRLEN(newcmd) - 1] = NUL;
3962 }
3963
3964 /*
3965 * Now, start the command as a process, so that it doesn't
3966 * inherit our handles which causes unpleasant dangling swap
3967 * files if we exit before the spawned process
3968 */
3969 if (CreateProcess (NULL, // Executable name
3970 newcmd, // Command to execute
3971 NULL, // Process security attributes
3972 NULL, // Thread security attributes
3973 FALSE, // Inherit handles
Bram Moolenaarbd8608d2011-05-25 17:06:22 +02003974 flags, // Creation flags
Bram Moolenaar071d4272004-06-13 20:20:40 +00003975 NULL, // Environment
3976 NULL, // Current directory
3977 &si, // Startup information
3978 &pi)) // Process information
3979 x = 0;
3980 else
3981 {
3982 x = -1;
3983#ifdef FEAT_GUI_W32
3984 EMSG(_("E371: Command not found"));
3985#endif
3986 }
Bram Moolenaarbd8608d2011-05-25 17:06:22 +02003987 if (si.hStdInput != NULL)
3988 {
3989 /* Close the handle to \\.\NUL */
3990 CloseHandle(si.hStdInput);
3991 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003992 /* Close the handles to the subprocess, so that it goes away */
3993 CloseHandle(pi.hThread);
3994 CloseHandle(pi.hProcess);
3995 }
3996 else
3997 {
3998#if defined(FEAT_GUI_W32)
3999 if (need_vimrun_warning)
4000 {
4001 MessageBox(NULL,
4002 _("VIMRUN.EXE not found in your $PATH.\n"
4003 "External commands will not pause after completion.\n"
4004 "See :help win32-vimrun for more information."),
4005 _("Vim Warning"),
4006 MB_ICONWARNING);
4007 need_vimrun_warning = FALSE;
4008 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004009 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004010 /* Use vimrun to execute the command. It opens a console
4011 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004012 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013 vimrun_path,
4014 (msg_silent != 0 || (options & SHELL_DOOUT))
4015 ? "-s " : "",
4016 p_sh, p_shcf, cmd);
4017 else
4018#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004019 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004020 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004021 x = mch_system((char *)newcmd, options);
4022 }
4023 vim_free(newcmd);
4024 }
4025 }
4026
4027 if (tmode == TMODE_RAW)
4028 settmode(TMODE_RAW); /* set to raw mode */
4029
4030 /* Print the return value, unless "vimrun" was used. */
4031 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4032#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004033 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4034 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035#endif
4036 )
4037 {
4038 smsg(_("shell returned %d"), x);
4039 msg_putchar('\n');
4040 }
4041#ifdef FEAT_TITLE
4042 resettitle();
4043#endif
4044
4045 signal(SIGINT, SIG_DFL);
4046#if defined(__GNUC__) && !defined(__MINGW32__)
4047 signal(SIGKILL, SIG_DFL);
4048#else
4049 signal(SIGBREAK, SIG_DFL);
4050#endif
4051 signal(SIGILL, SIG_DFL);
4052 signal(SIGFPE, SIG_DFL);
4053 signal(SIGSEGV, SIG_DFL);
4054 signal(SIGTERM, SIG_DFL);
4055 signal(SIGABRT, SIG_DFL);
4056
4057 return x;
4058}
4059
4060
4061#ifndef FEAT_GUI_W32
4062
4063/*
4064 * Start termcap mode
4065 */
4066 static void
4067termcap_mode_start(void)
4068{
4069 DWORD cmodein;
4070
4071 if (g_fTermcapMode)
4072 return;
4073
4074 SaveConsoleBuffer(&g_cbNonTermcap);
4075
4076 if (g_cbTermcap.IsValid)
4077 {
4078 /*
4079 * We've been in termcap mode before. Restore certain screen
4080 * characteristics, including the buffer size and the window
4081 * size. Since we will be redrawing the screen, we don't need
4082 * to restore the actual contents of the buffer.
4083 */
4084 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4085 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4086 Rows = g_cbTermcap.Info.dwSize.Y;
4087 Columns = g_cbTermcap.Info.dwSize.X;
4088 }
4089 else
4090 {
4091 /*
4092 * This is our first time entering termcap mode. Clear the console
4093 * screen buffer, and resize the buffer to match the current window
4094 * size. We will use this as the size of our editing environment.
4095 */
4096 ClearConsoleBuffer(g_attrCurrent);
4097 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4098 }
4099
4100#ifdef FEAT_TITLE
4101 resettitle();
4102#endif
4103
4104 GetConsoleMode(g_hConIn, &cmodein);
4105#ifdef FEAT_MOUSE
4106 if (g_fMouseActive)
4107 cmodein |= ENABLE_MOUSE_INPUT;
4108 else
4109 cmodein &= ~ENABLE_MOUSE_INPUT;
4110#endif
4111 cmodein |= ENABLE_WINDOW_INPUT;
4112 SetConsoleMode(g_hConIn, cmodein);
4113
4114 redraw_later_clear();
4115 g_fTermcapMode = TRUE;
4116}
4117
4118
4119/*
4120 * End termcap mode
4121 */
4122 static void
4123termcap_mode_end(void)
4124{
4125 DWORD cmodein;
4126 ConsoleBuffer *cb;
4127 COORD coord;
4128 DWORD dwDummy;
4129
4130 if (!g_fTermcapMode)
4131 return;
4132
4133 SaveConsoleBuffer(&g_cbTermcap);
4134
4135 GetConsoleMode(g_hConIn, &cmodein);
4136 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4137 SetConsoleMode(g_hConIn, cmodein);
4138
4139#ifdef FEAT_RESTORE_ORIG_SCREEN
4140 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4141#else
4142 cb = &g_cbNonTermcap;
4143#endif
4144 RestoreConsoleBuffer(cb, p_rs);
4145 SetConsoleCursorInfo(g_hConOut, &g_cci);
4146
4147 if (p_rs || exiting)
4148 {
4149 /*
4150 * Clear anything that happens to be on the current line.
4151 */
4152 coord.X = 0;
4153 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4154 FillConsoleOutputCharacter(g_hConOut, ' ',
4155 cb->Info.dwSize.X, coord, &dwDummy);
4156 /*
4157 * The following is just for aesthetics. If we are exiting without
4158 * restoring the screen, then we want to have a prompt string
4159 * appear at the bottom line. However, the command interpreter
4160 * seems to always advance the cursor one line before displaying
4161 * the prompt string, which causes the screen to scroll. To
4162 * counter this, move the cursor up one line before exiting.
4163 */
4164 if (exiting && !p_rs)
4165 coord.Y--;
4166 /*
4167 * Position the cursor at the leftmost column of the desired row.
4168 */
4169 SetConsoleCursorPosition(g_hConOut, coord);
4170 }
4171
4172 g_fTermcapMode = FALSE;
4173}
4174#endif /* FEAT_GUI_W32 */
4175
4176
4177#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004178/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 void
4180mch_write(
4181 char_u *s,
4182 int len)
4183{
4184 /* never used */
4185}
4186
4187#else
4188
4189/*
4190 * clear `n' chars, starting from `coord'
4191 */
4192 static void
4193clear_chars(
4194 COORD coord,
4195 DWORD n)
4196{
4197 DWORD dwDummy;
4198
4199 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4200 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4201}
4202
4203
4204/*
4205 * Clear the screen
4206 */
4207 static void
4208clear_screen(void)
4209{
4210 g_coord.X = g_coord.Y = 0;
4211 clear_chars(g_coord, Rows * Columns);
4212}
4213
4214
4215/*
4216 * Clear to end of display
4217 */
4218 static void
4219clear_to_end_of_display(void)
4220{
4221 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4222 * Columns + (Columns - g_coord.X));
4223}
4224
4225
4226/*
4227 * Clear to end of line
4228 */
4229 static void
4230clear_to_end_of_line(void)
4231{
4232 clear_chars(g_coord, Columns - g_coord.X);
4233}
4234
4235
4236/*
4237 * Scroll the scroll region up by `cLines' lines
4238 */
4239 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004240scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241{
4242 COORD oldcoord = g_coord;
4243
4244 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4245 delete_lines(cLines);
4246
4247 g_coord = oldcoord;
4248}
4249
4250
4251/*
4252 * Set the scroll region
4253 */
4254 static void
4255set_scroll_region(
4256 unsigned left,
4257 unsigned top,
4258 unsigned right,
4259 unsigned bottom)
4260{
4261 if (left >= right
4262 || top >= bottom
4263 || right > (unsigned) Columns - 1
4264 || bottom > (unsigned) Rows - 1)
4265 return;
4266
4267 g_srScrollRegion.Left = left;
4268 g_srScrollRegion.Top = top;
4269 g_srScrollRegion.Right = right;
4270 g_srScrollRegion.Bottom = bottom;
4271}
4272
4273
4274/*
4275 * Insert `cLines' lines at the current cursor position
4276 */
4277 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004278insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004279{
4280 SMALL_RECT source;
4281 COORD dest;
4282 CHAR_INFO fill;
4283
4284 dest.X = 0;
4285 dest.Y = g_coord.Y + cLines;
4286
4287 source.Left = 0;
4288 source.Top = g_coord.Y;
4289 source.Right = g_srScrollRegion.Right;
4290 source.Bottom = g_srScrollRegion.Bottom - cLines;
4291
4292 fill.Char.AsciiChar = ' ';
4293 fill.Attributes = g_attrCurrent;
4294
4295 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4296
4297 /* Here we have to deal with a win32 console flake: If the scroll
4298 * region looks like abc and we scroll c to a and fill with d we get
4299 * cbd... if we scroll block c one line at a time to a, we get cdd...
4300 * vim expects cdd consistently... So we have to deal with that
4301 * here... (this also occurs scrolling the same way in the other
4302 * direction). */
4303
4304 if (source.Bottom < dest.Y)
4305 {
4306 COORD coord;
4307
4308 coord.X = 0;
4309 coord.Y = source.Bottom;
4310 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4311 }
4312}
4313
4314
4315/*
4316 * Delete `cLines' lines at the current cursor position
4317 */
4318 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004319delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004320{
4321 SMALL_RECT source;
4322 COORD dest;
4323 CHAR_INFO fill;
4324 int nb;
4325
4326 dest.X = 0;
4327 dest.Y = g_coord.Y;
4328
4329 source.Left = 0;
4330 source.Top = g_coord.Y + cLines;
4331 source.Right = g_srScrollRegion.Right;
4332 source.Bottom = g_srScrollRegion.Bottom;
4333
4334 fill.Char.AsciiChar = ' ';
4335 fill.Attributes = g_attrCurrent;
4336
4337 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4338
4339 /* Here we have to deal with a win32 console flake: If the scroll
4340 * region looks like abc and we scroll c to a and fill with d we get
4341 * cbd... if we scroll block c one line at a time to a, we get cdd...
4342 * vim expects cdd consistently... So we have to deal with that
4343 * here... (this also occurs scrolling the same way in the other
4344 * direction). */
4345
4346 nb = dest.Y + (source.Bottom - source.Top) + 1;
4347
4348 if (nb < source.Top)
4349 {
4350 COORD coord;
4351
4352 coord.X = 0;
4353 coord.Y = nb;
4354 clear_chars(coord, Columns * (source.Top - nb));
4355 }
4356}
4357
4358
4359/*
4360 * Set the cursor position
4361 */
4362 static void
4363gotoxy(
4364 unsigned x,
4365 unsigned y)
4366{
4367 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4368 return;
4369
4370 /* external cursor coords are 1-based; internal are 0-based */
4371 g_coord.X = x - 1;
4372 g_coord.Y = y - 1;
4373 SetConsoleCursorPosition(g_hConOut, g_coord);
4374}
4375
4376
4377/*
4378 * Set the current text attribute = (foreground | background)
4379 * See ../doc/os_win32.txt for the numbers.
4380 */
4381 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004382textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383{
4384 g_attrCurrent = wAttr;
4385
4386 SetConsoleTextAttribute(g_hConOut, wAttr);
4387}
4388
4389
4390 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004391textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004392{
4393 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
4394
4395 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4396}
4397
4398
4399 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004400textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004401{
4402 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
4403
4404 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4405}
4406
4407
4408/*
4409 * restore the default text attribute (whatever we started with)
4410 */
4411 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004412normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413{
4414 textattr(g_attrDefault);
4415}
4416
4417
4418static WORD g_attrPreStandout = 0;
4419
4420/*
4421 * Make the text standout, by brightening it
4422 */
4423 static void
4424standout(void)
4425{
4426 g_attrPreStandout = g_attrCurrent;
4427 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
4428}
4429
4430
4431/*
4432 * Turn off standout mode
4433 */
4434 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004435standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004436{
4437 if (g_attrPreStandout)
4438 {
4439 textattr(g_attrPreStandout);
4440 g_attrPreStandout = 0;
4441 }
4442}
4443
4444
4445/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00004446 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004447 */
4448 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004449mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450{
4451 char_u *p;
4452 int n;
4453
4454 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
4455 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
4456 if (T_ME[0] == ESC && T_ME[1] == '|')
4457 {
4458 p = T_ME + 2;
4459 n = getdigits(&p);
4460 if (*p == 'm' && n > 0)
4461 {
4462 cterm_normal_fg_color = (n & 0xf) + 1;
4463 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
4464 }
4465 }
4466}
4467
4468
4469/*
4470 * visual bell: flash the screen
4471 */
4472 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004473visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474{
4475 COORD coordOrigin = {0, 0};
4476 WORD attrFlash = ~g_attrCurrent & 0xff;
4477
4478 DWORD dwDummy;
4479 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
4480
4481 if (oldattrs == NULL)
4482 return;
4483 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4484 coordOrigin, &dwDummy);
4485 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
4486 coordOrigin, &dwDummy);
4487
4488 Sleep(15); /* wait for 15 msec */
4489 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4490 coordOrigin, &dwDummy);
4491 vim_free(oldattrs);
4492}
4493
4494
4495/*
4496 * Make the cursor visible or invisible
4497 */
4498 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004499cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500{
4501 s_cursor_visible = fVisible;
4502#ifdef MCH_CURSOR_SHAPE
4503 mch_update_cursor();
4504#endif
4505}
4506
4507
4508/*
4509 * write `cchToWrite' characters in `pchBuf' to the screen
4510 * Returns the number of characters actually written (at least one).
4511 */
4512 static BOOL
4513write_chars(
4514 LPCSTR pchBuf,
4515 DWORD cchToWrite)
4516{
4517 COORD coord = g_coord;
4518 DWORD written;
4519
4520 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
4521 coord, &written);
4522 /* When writing fails or didn't write a single character, pretend one
4523 * character was written, otherwise we get stuck. */
4524 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
4525 coord, &written) == 0
4526 || written == 0)
4527 written = 1;
4528
4529 g_coord.X += (SHORT) written;
4530
4531 while (g_coord.X > g_srScrollRegion.Right)
4532 {
4533 g_coord.X -= (SHORT) Columns;
4534 if (g_coord.Y < g_srScrollRegion.Bottom)
4535 g_coord.Y++;
4536 }
4537
4538 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4539
4540 return written;
4541}
4542
4543
4544/*
4545 * mch_write(): write the output buffer to the screen, translating ESC
4546 * sequences into calls to console output routines.
4547 */
4548 void
4549mch_write(
4550 char_u *s,
4551 int len)
4552{
4553 s[len] = NUL;
4554
4555 if (!term_console)
4556 {
4557 write(1, s, (unsigned)len);
4558 return;
4559 }
4560
4561 /* translate ESC | sequences into faked bios calls */
4562 while (len--)
4563 {
4564 /* optimization: use one single write_chars for runs of text,
4565 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004566 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567
4568 if (p_wd)
4569 {
4570 WaitForChar(p_wd);
4571 if (prefix != 0)
4572 prefix = 1;
4573 }
4574
4575 if (prefix != 0)
4576 {
4577 DWORD nWritten;
4578
4579 nWritten = write_chars(s, prefix);
4580#ifdef MCH_WRITE_DUMP
4581 if (fdDump)
4582 {
4583 fputc('>', fdDump);
4584 fwrite(s, sizeof(char_u), nWritten, fdDump);
4585 fputs("<\n", fdDump);
4586 }
4587#endif
4588 len -= (nWritten - 1);
4589 s += nWritten;
4590 }
4591 else if (s[0] == '\n')
4592 {
4593 /* \n, newline: go to the beginning of the next line or scroll */
4594 if (g_coord.Y == g_srScrollRegion.Bottom)
4595 {
4596 scroll(1);
4597 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
4598 }
4599 else
4600 {
4601 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
4602 }
4603#ifdef MCH_WRITE_DUMP
4604 if (fdDump)
4605 fputs("\\n\n", fdDump);
4606#endif
4607 s++;
4608 }
4609 else if (s[0] == '\r')
4610 {
4611 /* \r, carriage return: go to beginning of line */
4612 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
4613#ifdef MCH_WRITE_DUMP
4614 if (fdDump)
4615 fputs("\\r\n", fdDump);
4616#endif
4617 s++;
4618 }
4619 else if (s[0] == '\b')
4620 {
4621 /* \b, backspace: move cursor one position left */
4622 if (g_coord.X > g_srScrollRegion.Left)
4623 g_coord.X--;
4624 else if (g_coord.Y > g_srScrollRegion.Top)
4625 {
4626 g_coord.X = g_srScrollRegion.Right;
4627 g_coord.Y--;
4628 }
4629 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4630#ifdef MCH_WRITE_DUMP
4631 if (fdDump)
4632 fputs("\\b\n", fdDump);
4633#endif
4634 s++;
4635 }
4636 else if (s[0] == '\a')
4637 {
4638 /* \a, bell */
4639 MessageBeep(0xFFFFFFFF);
4640#ifdef MCH_WRITE_DUMP
4641 if (fdDump)
4642 fputs("\\a\n", fdDump);
4643#endif
4644 s++;
4645 }
4646 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4647 {
4648#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004649 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004650#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004651 char_u *p;
4652 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004653
4654 switch (s[2])
4655 {
4656 /* one or two numeric arguments, separated by ';' */
4657
4658 case '0': case '1': case '2': case '3': case '4':
4659 case '5': case '6': case '7': case '8': case '9':
4660 p = s + 2;
4661 arg1 = getdigits(&p); /* no check for length! */
4662 if (p > s + len)
4663 break;
4664
4665 if (*p == ';')
4666 {
4667 ++p;
4668 arg2 = getdigits(&p); /* no check for length! */
4669 if (p > s + len)
4670 break;
4671
4672 if (*p == 'H')
4673 gotoxy(arg2, arg1);
4674 else if (*p == 'r')
4675 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4676 }
4677 else if (*p == 'A')
4678 {
4679 /* move cursor up arg1 lines in same column */
4680 gotoxy(g_coord.X + 1,
4681 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4682 }
4683 else if (*p == 'C')
4684 {
4685 /* move cursor right arg1 columns in same line */
4686 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4687 g_coord.Y + 1);
4688 }
4689 else if (*p == 'H')
4690 {
4691 gotoxy(1, arg1);
4692 }
4693 else if (*p == 'L')
4694 {
4695 insert_lines(arg1);
4696 }
4697 else if (*p == 'm')
4698 {
4699 if (arg1 == 0)
4700 normvideo();
4701 else
4702 textattr((WORD) arg1);
4703 }
4704 else if (*p == 'f')
4705 {
4706 textcolor((WORD) arg1);
4707 }
4708 else if (*p == 'b')
4709 {
4710 textbackground((WORD) arg1);
4711 }
4712 else if (*p == 'M')
4713 {
4714 delete_lines(arg1);
4715 }
4716
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004717 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004718 s = p + 1;
4719 break;
4720
4721
4722 /* Three-character escape sequences */
4723
4724 case 'A':
4725 /* move cursor up one line in same column */
4726 gotoxy(g_coord.X + 1,
4727 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4728 goto got3;
4729
4730 case 'B':
4731 visual_bell();
4732 goto got3;
4733
4734 case 'C':
4735 /* move cursor right one column in same line */
4736 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4737 g_coord.Y + 1);
4738 goto got3;
4739
4740 case 'E':
4741 termcap_mode_end();
4742 goto got3;
4743
4744 case 'F':
4745 standout();
4746 goto got3;
4747
4748 case 'f':
4749 standend();
4750 goto got3;
4751
4752 case 'H':
4753 gotoxy(1, 1);
4754 goto got3;
4755
4756 case 'j':
4757 clear_to_end_of_display();
4758 goto got3;
4759
4760 case 'J':
4761 clear_screen();
4762 goto got3;
4763
4764 case 'K':
4765 clear_to_end_of_line();
4766 goto got3;
4767
4768 case 'L':
4769 insert_lines(1);
4770 goto got3;
4771
4772 case 'M':
4773 delete_lines(1);
4774 goto got3;
4775
4776 case 'S':
4777 termcap_mode_start();
4778 goto got3;
4779
4780 case 'V':
4781 cursor_visible(TRUE);
4782 goto got3;
4783
4784 case 'v':
4785 cursor_visible(FALSE);
4786 goto got3;
4787
4788 got3:
4789 s += 3;
4790 len -= 2;
4791 }
4792
4793#ifdef MCH_WRITE_DUMP
4794 if (fdDump)
4795 {
4796 fputs("ESC | ", fdDump);
4797 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4798 fputc('\n', fdDump);
4799 }
4800#endif
4801 }
4802 else
4803 {
4804 /* Write a single character */
4805 DWORD nWritten;
4806
4807 nWritten = write_chars(s, 1);
4808#ifdef MCH_WRITE_DUMP
4809 if (fdDump)
4810 {
4811 fputc('>', fdDump);
4812 fwrite(s, sizeof(char_u), nWritten, fdDump);
4813 fputs("<\n", fdDump);
4814 }
4815#endif
4816
4817 len -= (nWritten - 1);
4818 s += nWritten;
4819 }
4820 }
4821
4822#ifdef MCH_WRITE_DUMP
4823 if (fdDump)
4824 fflush(fdDump);
4825#endif
4826}
4827
4828#endif /* FEAT_GUI_W32 */
4829
4830
4831/*
4832 * Delay for half a second.
4833 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004834/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835 void
4836mch_delay(
4837 long msec,
4838 int ignoreinput)
4839{
4840#ifdef FEAT_GUI_W32
4841 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004842#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004844# ifdef FEAT_MZSCHEME
4845 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4846 {
4847 int towait = p_mzq;
4848
4849 /* if msec is large enough, wait by portions in p_mzq */
4850 while (msec > 0)
4851 {
4852 mzvim_check_threads();
4853 if (msec < towait)
4854 towait = msec;
4855 Sleep(towait);
4856 msec -= towait;
4857 }
4858 }
4859 else
4860# endif
4861 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862 else
4863 WaitForChar(msec);
4864#endif
4865}
4866
4867
4868/*
4869 * this version of remove is not scared by a readonly (backup) file
4870 * Return 0 for success, -1 for failure.
4871 */
4872 int
4873mch_remove(char_u *name)
4874{
4875#ifdef FEAT_MBYTE
4876 WCHAR *wn = NULL;
4877 int n;
4878
4879 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4880 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004881 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 if (wn != NULL)
4883 {
4884 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4885 n = DeleteFileW(wn) ? 0 : -1;
4886 vim_free(wn);
4887 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4888 return n;
4889 /* Retry with non-wide function (for Windows 98). */
4890 }
4891 }
4892#endif
4893 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4894 return DeleteFile(name) ? 0 : -1;
4895}
4896
4897
4898/*
4899 * check for an "interrupt signal": CTRL-break or CTRL-C
4900 */
4901 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004902mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903{
4904#ifndef FEAT_GUI_W32 /* never used */
4905 if (g_fCtrlCPressed || g_fCBrkPressed)
4906 {
4907 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4908 got_int = TRUE;
4909 }
4910#endif
4911}
4912
4913
4914/*
4915 * How much memory is available?
4916 * Return sum of available physical and page file memory.
4917 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004918/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004919 long_u
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004920mch_avail_mem(int special)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921{
4922 MEMORYSTATUS ms;
4923
4924 ms.dwLength = sizeof(MEMORYSTATUS);
4925 GlobalMemoryStatus(&ms);
4926 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
4927}
4928
4929#ifdef FEAT_MBYTE
4930/*
4931 * Same code as below, but with wide functions and no comments.
4932 * Return 0 for success, non-zero for failure.
4933 */
4934 int
4935mch_wrename(WCHAR *wold, WCHAR *wnew)
4936{
4937 WCHAR *p;
4938 int i;
4939 WCHAR szTempFile[_MAX_PATH + 1];
4940 WCHAR szNewPath[_MAX_PATH + 1];
4941 HANDLE hf;
4942
4943 if (!mch_windows95())
4944 {
4945 p = wold;
4946 for (i = 0; wold[i] != NUL; ++i)
4947 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
4948 && wold[i + 1] != 0)
4949 p = wold + i + 1;
4950 if ((int)(wold + i - p) < 8 || p[6] != '~')
4951 return (MoveFileW(wold, wnew) == 0);
4952 }
4953
4954 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
4955 return -1;
4956 *p = NUL;
4957
4958 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
4959 return -2;
4960
4961 if (!DeleteFileW(szTempFile))
4962 return -3;
4963
4964 if (!MoveFileW(wold, szTempFile))
4965 return -4;
4966
4967 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4968 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4969 return -5;
4970 if (!CloseHandle(hf))
4971 return -6;
4972
4973 if (!MoveFileW(szTempFile, wnew))
4974 {
4975 (void)MoveFileW(szTempFile, wold);
4976 return -7;
4977 }
4978
4979 DeleteFileW(szTempFile);
4980
4981 if (!DeleteFileW(wold))
4982 return -8;
4983
4984 return 0;
4985}
4986#endif
4987
4988
4989/*
4990 * mch_rename() works around a bug in rename (aka MoveFile) in
4991 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4992 * file whose short file name is "FOO.BAR" (its long file name will
4993 * be correct: "foo.bar~"). Because a file can be accessed by
4994 * either its SFN or its LFN, "foo.bar" has effectively been
4995 * renamed to "foo.bar", which is not at all what was wanted. This
4996 * seems to happen only when renaming files with three-character
4997 * extensions by appending a suffix that does not include ".".
4998 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4999 *
5000 * There is another problem, which isn't really a bug but isn't right either:
5001 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5002 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5003 * service pack 6. Doesn't seem to happen on Windows 98.
5004 *
5005 * Like rename(), returns 0 upon success, non-zero upon failure.
5006 * Should probably set errno appropriately when errors occur.
5007 */
5008 int
5009mch_rename(
5010 const char *pszOldFile,
5011 const char *pszNewFile)
5012{
5013 char szTempFile[_MAX_PATH+1];
5014 char szNewPath[_MAX_PATH+1];
5015 char *pszFilePart;
5016 HANDLE hf;
5017#ifdef FEAT_MBYTE
5018 WCHAR *wold = NULL;
5019 WCHAR *wnew = NULL;
5020 int retval = -1;
5021
5022 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5023 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005024 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5025 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005026 if (wold != NULL && wnew != NULL)
5027 retval = mch_wrename(wold, wnew);
5028 vim_free(wold);
5029 vim_free(wnew);
5030 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5031 return retval;
5032 /* Retry with non-wide function (for Windows 98). */
5033 }
5034#endif
5035
5036 /*
5037 * No need to play tricks if not running Windows 95, unless the file name
5038 * contains a "~" as the seventh character.
5039 */
5040 if (!mch_windows95())
5041 {
5042 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5043 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5044 return rename(pszOldFile, pszNewFile);
5045 }
5046
5047 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5048 * a directory, no error is returned and pszFilePart will be NULL. */
5049 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5050 || pszFilePart == NULL)
5051 return -1;
5052 *pszFilePart = NUL;
5053
5054 /* Get (and create) a unique temporary file name in directory of new file */
5055 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5056 return -2;
5057
5058 /* blow the temp file away */
5059 if (!DeleteFile(szTempFile))
5060 return -3;
5061
5062 /* rename old file to the temp file */
5063 if (!MoveFile(pszOldFile, szTempFile))
5064 return -4;
5065
5066 /* now create an empty file called pszOldFile; this prevents the operating
5067 * system using pszOldFile as an alias (SFN) if we're renaming within the
5068 * same directory. For example, we're editing a file called
5069 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5070 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5071 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005072 * cause all sorts of problems later in buf_write(). So, we create an
5073 * empty file called filena~1.txt and the system will have to find some
5074 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005075 */
5076 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5077 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5078 return -5;
5079 if (!CloseHandle(hf))
5080 return -6;
5081
5082 /* rename the temp file to the new file */
5083 if (!MoveFile(szTempFile, pszNewFile))
5084 {
5085 /* Renaming failed. Rename the file back to its old name, so that it
5086 * looks like nothing happened. */
5087 (void)MoveFile(szTempFile, pszOldFile);
5088
5089 return -7;
5090 }
5091
5092 /* Seems to be left around on Novell filesystems */
5093 DeleteFile(szTempFile);
5094
5095 /* finally, remove the empty old file */
5096 if (!DeleteFile(pszOldFile))
5097 return -8;
5098
5099 return 0; /* success */
5100}
5101
5102/*
5103 * Get the default shell for the current hardware platform
5104 */
5105 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005106default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005107{
5108 char* psz = NULL;
5109
5110 PlatformId();
5111
5112 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5113 psz = "cmd.exe";
5114 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5115 psz = "command.com";
5116
5117 return psz;
5118}
5119
5120/*
5121 * mch_access() extends access() to do more detailed check on network drives.
5122 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5123 */
5124 int
5125mch_access(char *n, int p)
5126{
5127 HANDLE hFile;
5128 DWORD am;
5129 int retval = -1; /* default: fail */
5130#ifdef FEAT_MBYTE
5131 WCHAR *wn = NULL;
5132
5133 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005134 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005135#endif
5136
5137 if (mch_isdir(n))
5138 {
5139 char TempName[_MAX_PATH + 16] = "";
5140#ifdef FEAT_MBYTE
5141 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5142#endif
5143
5144 if (p & R_OK)
5145 {
5146 /* Read check is performed by seeing if we can do a find file on
5147 * the directory for any file. */
5148#ifdef FEAT_MBYTE
5149 if (wn != NULL)
5150 {
5151 int i;
5152 WIN32_FIND_DATAW d;
5153
5154 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5155 TempNameW[i] = wn[i];
5156 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5157 TempNameW[i++] = '\\';
5158 TempNameW[i++] = '*';
5159 TempNameW[i++] = 0;
5160
5161 hFile = FindFirstFileW(TempNameW, &d);
5162 if (hFile == INVALID_HANDLE_VALUE)
5163 {
5164 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5165 goto getout;
5166
5167 /* Retry with non-wide function (for Windows 98). */
5168 vim_free(wn);
5169 wn = NULL;
5170 }
5171 else
5172 (void)FindClose(hFile);
5173 }
5174 if (wn == NULL)
5175#endif
5176 {
5177 char *pch;
5178 WIN32_FIND_DATA d;
5179
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005180 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005181 pch = TempName + STRLEN(TempName) - 1;
5182 if (*pch != '\\' && *pch != '/')
5183 *++pch = '\\';
5184 *++pch = '*';
5185 *++pch = NUL;
5186
5187 hFile = FindFirstFile(TempName, &d);
5188 if (hFile == INVALID_HANDLE_VALUE)
5189 goto getout;
5190 (void)FindClose(hFile);
5191 }
5192 }
5193
5194 if (p & W_OK)
5195 {
5196 /* Trying to create a temporary file in the directory should catch
5197 * directories on read-only network shares. However, in
5198 * directories whose ACL allows writes but denies deletes will end
5199 * up keeping the temporary file :-(. */
5200#ifdef FEAT_MBYTE
5201 if (wn != NULL)
5202 {
5203 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5204 {
5205 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5206 goto getout;
5207
5208 /* Retry with non-wide function (for Windows 98). */
5209 vim_free(wn);
5210 wn = NULL;
5211 }
5212 else
5213 DeleteFileW(TempNameW);
5214 }
5215 if (wn == NULL)
5216#endif
5217 {
5218 if (!GetTempFileName(n, "VIM", 0, TempName))
5219 goto getout;
5220 mch_remove((char_u *)TempName);
5221 }
5222 }
5223 }
5224 else
5225 {
5226 /* Trying to open the file for the required access does ACL, read-only
5227 * network share, and file attribute checks. */
5228 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5229 | ((p & R_OK) ? GENERIC_READ : 0);
5230#ifdef FEAT_MBYTE
5231 if (wn != NULL)
5232 {
5233 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5234 if (hFile == INVALID_HANDLE_VALUE
5235 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5236 {
5237 /* Retry with non-wide function (for Windows 98). */
5238 vim_free(wn);
5239 wn = NULL;
5240 }
5241 }
5242 if (wn == NULL)
5243#endif
5244 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5245 if (hFile == INVALID_HANDLE_VALUE)
5246 goto getout;
5247 CloseHandle(hFile);
5248 }
5249
5250 retval = 0; /* success */
5251getout:
5252#ifdef FEAT_MBYTE
5253 vim_free(wn);
5254#endif
5255 return retval;
5256}
5257
5258#if defined(FEAT_MBYTE) || defined(PROTO)
5259/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005260 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261 */
5262 int
5263mch_open(char *name, int flags, int mode)
5264{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005265 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5266# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005267 WCHAR *wn;
5268 int f;
5269
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005270 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005271 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005272 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005273 if (wn != NULL)
5274 {
5275 f = _wopen(wn, flags, mode);
5276 vim_free(wn);
5277 if (f >= 0)
5278 return f;
5279 /* Retry with non-wide function (for Windows 98). Can't use
5280 * GetLastError() here and it's unclear what errno gets set to if
5281 * the _wopen() fails for missing wide functions. */
5282 }
5283 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005284# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005285
5286 return open(name, flags, mode);
5287}
5288
5289/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005290 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291 */
5292 FILE *
5293mch_fopen(char *name, char *mode)
5294{
5295 WCHAR *wn, *wm;
5296 FILE *f = NULL;
5297
5298 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5299# ifdef __BORLANDC__
5300 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5301 && g_PlatformId == VER_PLATFORM_WIN32_NT
5302# endif
5303 )
5304 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005305# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005306 /* Work around an annoying assertion in the Microsoft debug CRT
5307 * when mode's text/binary setting doesn't match _get_fmode(). */
5308 char newMode = mode[strlen(mode) - 1];
5309 int oldMode = 0;
5310
5311 _get_fmode(&oldMode);
5312 if (newMode == 't')
5313 _set_fmode(_O_TEXT);
5314 else if (newMode == 'b')
5315 _set_fmode(_O_BINARY);
5316# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005317 wn = enc_to_utf16(name, NULL);
5318 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005319 if (wn != NULL && wm != NULL)
5320 f = _wfopen(wn, wm);
5321 vim_free(wn);
5322 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005323
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005324# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005325 _set_fmode(oldMode);
5326# endif
5327
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328 if (f != NULL)
5329 return f;
5330 /* Retry with non-wide function (for Windows 98). Can't use
5331 * GetLastError() here and it's unclear what errno gets set to if
5332 * the _wfopen() fails for missing wide functions. */
5333 }
5334
5335 return fopen(name, mode);
5336}
5337#endif
5338
5339#ifdef FEAT_MBYTE
5340/*
5341 * SUB STREAM (aka info stream) handling:
5342 *
5343 * NTFS can have sub streams for each file. Normal contents of file is
5344 * stored in the main stream, and extra contents (author information and
5345 * title and so on) can be stored in sub stream. After Windows 2000, user
5346 * can access and store those informations in sub streams via explorer's
5347 * property menuitem in right click menu. Those informations in sub streams
5348 * were lost when copying only the main stream. So we have to copy sub
5349 * streams.
5350 *
5351 * Incomplete explanation:
5352 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5353 * More useful info and an example:
5354 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5355 */
5356
5357/*
5358 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5359 * and write to stream "substream" of file "to".
5360 * Errors are ignored.
5361 */
5362 static void
5363copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5364{
5365 HANDLE hTo;
5366 WCHAR *to_name;
5367
5368 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5369 wcscpy(to_name, to);
5370 wcscat(to_name, substream);
5371
5372 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5373 FILE_ATTRIBUTE_NORMAL, NULL);
5374 if (hTo != INVALID_HANDLE_VALUE)
5375 {
5376 long done;
5377 DWORD todo;
5378 DWORD readcnt, written;
5379 char buf[4096];
5380
5381 /* Copy block of bytes at a time. Abort when something goes wrong. */
5382 for (done = 0; done < len; done += written)
5383 {
5384 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005385 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5386 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005387 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5388 FALSE, FALSE, context)
5389 || readcnt != todo
5390 || !WriteFile(hTo, buf, todo, &written, NULL)
5391 || written != todo)
5392 break;
5393 }
5394 CloseHandle(hTo);
5395 }
5396
5397 free(to_name);
5398}
5399
5400/*
5401 * Copy info streams from file "from" to file "to".
5402 */
5403 static void
5404copy_infostreams(char_u *from, char_u *to)
5405{
5406 WCHAR *fromw;
5407 WCHAR *tow;
5408 HANDLE sh;
5409 WIN32_STREAM_ID sid;
5410 int headersize;
5411 WCHAR streamname[_MAX_PATH];
5412 DWORD readcount;
5413 void *context = NULL;
5414 DWORD lo, hi;
5415 int len;
5416
5417 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005418 fromw = enc_to_utf16(from, NULL);
5419 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005420 if (fromw != NULL && tow != NULL)
5421 {
5422 /* Open the file for reading. */
5423 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
5424 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5425 if (sh != INVALID_HANDLE_VALUE)
5426 {
5427 /* Use BackupRead() to find the info streams. Repeat until we
5428 * have done them all.*/
5429 for (;;)
5430 {
5431 /* Get the header to find the length of the stream name. If
5432 * the "readcount" is zero we have done all info streams. */
5433 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005434 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
5436 &readcount, FALSE, FALSE, &context)
5437 || readcount == 0)
5438 break;
5439
5440 /* We only deal with streams that have a name. The normal
5441 * file data appears to be without a name, even though docs
5442 * suggest it is called "::$DATA". */
5443 if (sid.dwStreamNameSize > 0)
5444 {
5445 /* Read the stream name. */
5446 if (!BackupRead(sh, (LPBYTE)streamname,
5447 sid.dwStreamNameSize,
5448 &readcount, FALSE, FALSE, &context))
5449 break;
5450
5451 /* Copy an info stream with a name ":anything:$DATA".
5452 * Skip "::$DATA", it has no stream name (examples suggest
5453 * it might be used for the normal file contents).
5454 * Note that BackupRead() counts bytes, but the name is in
5455 * wide characters. */
5456 len = readcount / sizeof(WCHAR);
5457 streamname[len] = 0;
5458 if (len > 7 && wcsicmp(streamname + len - 6,
5459 L":$DATA") == 0)
5460 {
5461 streamname[len - 6] = 0;
5462 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00005463 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005464 }
5465 }
5466
5467 /* Advance to the next stream. We might try seeking too far,
5468 * but BackupSeek() doesn't skip over stream borders, thus
5469 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005470 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005471 &lo, &hi, &context);
5472 }
5473
5474 /* Clear the context. */
5475 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
5476
5477 CloseHandle(sh);
5478 }
5479 }
5480 vim_free(fromw);
5481 vim_free(tow);
5482}
5483#endif
5484
5485/*
5486 * Copy file attributes from file "from" to file "to".
5487 * For Windows NT and later we copy info streams.
5488 * Always returns zero, errors are ignored.
5489 */
5490 int
5491mch_copy_file_attribute(char_u *from, char_u *to)
5492{
5493#ifdef FEAT_MBYTE
5494 /* File streams only work on Windows NT and later. */
5495 PlatformId();
5496 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5497 copy_infostreams(from, to);
5498#endif
5499 return 0;
5500}
5501
5502#if defined(MYRESETSTKOFLW) || defined(PROTO)
5503/*
5504 * Recreate a destroyed stack guard page in win32.
5505 * Written by Benjamin Peterson.
5506 */
5507
5508/* These magic numbers are from the MS header files */
5509#define MIN_STACK_WIN9X 17
5510#define MIN_STACK_WINNT 2
5511
5512/*
5513 * This function does the same thing as _resetstkoflw(), which is only
5514 * available in DevStudio .net and later.
5515 * Returns 0 for failure, 1 for success.
5516 */
5517 int
5518myresetstkoflw(void)
5519{
5520 BYTE *pStackPtr;
5521 BYTE *pGuardPage;
5522 BYTE *pStackBase;
5523 BYTE *pLowestPossiblePage;
5524 MEMORY_BASIC_INFORMATION mbi;
5525 SYSTEM_INFO si;
5526 DWORD nPageSize;
5527 DWORD dummy;
5528
5529 /* This code will not work on win32s. */
5530 PlatformId();
5531 if (g_PlatformId == VER_PLATFORM_WIN32s)
5532 return 0;
5533
5534 /* We need to know the system page size. */
5535 GetSystemInfo(&si);
5536 nPageSize = si.dwPageSize;
5537
5538 /* ...and the current stack pointer */
5539 pStackPtr = (BYTE*)_alloca(1);
5540
5541 /* ...and the base of the stack. */
5542 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
5543 return 0;
5544 pStackBase = (BYTE*)mbi.AllocationBase;
5545
5546 /* ...and the page thats min_stack_req pages away from stack base; this is
5547 * the lowest page we could use. */
5548 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
5549 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
5550
5551 /* On Win95, we want the next page down from the end of the stack. */
5552 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
5553 {
5554 /* Find the page that's only 1 page down from the page that the stack
5555 * ptr is in. */
5556 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
5557 / (DWORD)nPageSize) - 1));
5558 if (pGuardPage < pLowestPossiblePage)
5559 return 0;
5560
5561 /* Apply the noaccess attribute to the page -- there's no guard
5562 * attribute in win95-type OSes. */
5563 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
5564 return 0;
5565 }
5566 else
5567 {
5568 /* On NT, however, we want the first committed page in the stack Start
5569 * at the stack base and move forward through memory until we find a
5570 * committed block. */
5571 BYTE *pBlock = pStackBase;
5572
Bram Moolenaara466c992005-07-09 21:03:22 +00005573 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574 {
5575 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
5576 return 0;
5577
5578 pBlock += mbi.RegionSize;
5579
5580 if (mbi.State & MEM_COMMIT)
5581 break;
5582 }
5583
5584 /* mbi now describes the first committed block in the stack. */
5585 if (mbi.Protect & PAGE_GUARD)
5586 return 1;
5587
5588 /* decide where the guard page should start */
5589 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
5590 pGuardPage = pLowestPossiblePage;
5591 else
5592 pGuardPage = (BYTE*)mbi.BaseAddress;
5593
5594 /* allocate the guard page */
5595 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
5596 return 0;
5597
5598 /* apply the guard attribute to the page */
5599 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
5600 &dummy))
5601 return 0;
5602 }
5603
5604 return 1;
5605}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005606#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005608
5609#if defined(FEAT_MBYTE) || defined(PROTO)
5610/*
5611 * The command line arguments in UCS2
5612 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005613static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005614static LPWSTR *ArglistW = NULL;
5615static int global_argc = 0;
5616static char **global_argv;
5617
5618static int used_file_argc = 0; /* last argument in global_argv[] used
5619 for the argument list. */
5620static int *used_file_indexes = NULL; /* indexes in global_argv[] for
5621 command line arguments added to
5622 the argument list */
5623static int used_file_count = 0; /* nr of entries in used_file_indexes */
5624static int used_file_literal = FALSE; /* take file names literally */
5625static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005626static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005627static int used_alist_count = 0;
5628
5629
5630/*
5631 * Get the command line arguments. Unicode version.
5632 * Returns argc. Zero when something fails.
5633 */
5634 int
5635get_cmd_argsW(char ***argvp)
5636{
5637 char **argv = NULL;
5638 int argc = 0;
5639 int i;
5640
5641 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5642 if (ArglistW != NULL)
5643 {
5644 argv = malloc((nArgsW + 1) * sizeof(char *));
5645 if (argv != NULL)
5646 {
5647 argc = nArgsW;
5648 argv[argc] = NULL;
5649 for (i = 0; i < argc; ++i)
5650 {
5651 int len;
5652
5653 /* Convert each Unicode argument to the current codepage. */
5654 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005655 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005656 (LPSTR *)&argv[i], &len, 0, 0);
5657 if (argv[i] == NULL)
5658 {
5659 /* Out of memory, clear everything. */
5660 while (i > 0)
5661 free(argv[--i]);
5662 free(argv);
5663 argc = 0;
5664 }
5665 }
5666 }
5667 }
5668
5669 global_argc = argc;
5670 global_argv = argv;
5671 if (argc > 0)
5672 used_file_indexes = malloc(argc * sizeof(int));
5673
5674 if (argvp != NULL)
5675 *argvp = argv;
5676 return argc;
5677}
5678
5679 void
5680free_cmd_argsW(void)
5681{
5682 if (ArglistW != NULL)
5683 {
5684 GlobalFree(ArglistW);
5685 ArglistW = NULL;
5686 }
5687}
5688
5689/*
5690 * Remember "name" is an argument that was added to the argument list.
5691 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5692 * is called.
5693 */
5694 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005695used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005696{
5697 int i;
5698
5699 if (used_file_indexes == NULL)
5700 return;
5701 for (i = used_file_argc + 1; i < global_argc; ++i)
5702 if (STRCMP(global_argv[i], name) == 0)
5703 {
5704 used_file_argc = i;
5705 used_file_indexes[used_file_count++] = i;
5706 break;
5707 }
5708 used_file_literal = literal;
5709 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005710 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005711}
5712
5713/*
5714 * Remember the length of the argument list as it was. If it changes then we
5715 * leave it alone when 'encoding' is set.
5716 */
5717 void
5718set_alist_count(void)
5719{
5720 used_alist_count = GARGCOUNT;
5721}
5722
5723/*
5724 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5725 * has been changed while starting up. Use the UCS-2 command line arguments
5726 * and convert them to 'encoding'.
5727 */
5728 void
5729fix_arg_enc(void)
5730{
5731 int i;
5732 int idx;
5733 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005734 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005735
5736 /* Safety checks:
5737 * - if argument count differs between the wide and non-wide argument
5738 * list, something must be wrong.
5739 * - the file name arguments must have been located.
5740 * - the length of the argument list wasn't changed by the user.
5741 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005742 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005743 || ArglistW == NULL
5744 || used_file_indexes == NULL
5745 || used_file_count == 0
5746 || used_alist_count != GARGCOUNT)
5747 return;
5748
Bram Moolenaar86b68352004-12-27 21:59:20 +00005749 /* Remember the buffer numbers for the arguments. */
5750 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5751 if (fnum_list == NULL)
5752 return; /* out of memory */
5753 for (i = 0; i < GARGCOUNT; ++i)
5754 fnum_list[i] = GARGLIST[i].ae_fnum;
5755
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005756 /* Clear the argument list. Make room for the new arguments. */
5757 alist_clear(&global_alist);
5758 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005759 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005760
5761 for (i = 0; i < used_file_count; ++i)
5762 {
5763 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005764 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005765 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005766 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005767#ifdef FEAT_DIFF
5768 /* When using diff mode may need to concatenate file name to
5769 * directory name. Just like it's done in main(). */
5770 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5771 && !mch_isdir(alist_name(&GARGLIST[0])))
5772 {
5773 char_u *r;
5774
5775 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5776 if (r != NULL)
5777 {
5778 vim_free(str);
5779 str = r;
5780 }
5781 }
5782#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005783 /* Re-use the old buffer by renaming it. When not using literal
5784 * names it's done by alist_expand() below. */
5785 if (used_file_literal)
5786 buf_set_name(fnum_list[i], str);
5787
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005788 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005789 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005790 }
5791
5792 if (!used_file_literal)
5793 {
5794 /* Now expand wildcards in the arguments. */
5795 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5796 * filename characters but are excluded from 'isfname' to make
5797 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5798 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005799 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005800 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5801 }
5802
5803 /* If wildcard expansion failed, we are editing the first file of the
5804 * arglist and there is no file name: Edit the first argument now. */
5805 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5806 {
5807 do_cmdline_cmd((char_u *)":rewind");
5808 if (GARGCOUNT == 1 && used_file_full_path)
5809 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5810 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005811
5812 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005813}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814#endif