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