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