blob: 6bfcc2af5282e821887e06d3e0ebf98cae0e5ca1 [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];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002311 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312 char *ptrue, *ptruePrev;
2313 char *porig, *porigPrev;
2314 int flen;
2315 WIN32_FIND_DATA fb;
2316 HANDLE hFind;
2317 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002318 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002320 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 if (flen == 0 || flen > _MAX_PATH)
2322 return;
2323
2324 slash_adjust(name);
2325
2326 /* Build the new name in szTrueName[] one component at a time. */
2327 porig = name;
2328 ptrue = szTrueName;
2329
2330 if (isalpha(porig[0]) && porig[1] == ':')
2331 {
2332 /* copy leading drive letter */
2333 *ptrue++ = *porig++;
2334 *ptrue++ = *porig++;
2335 *ptrue = NUL; /* in case nothing follows */
2336 }
2337
2338 while (*porig != NUL)
2339 {
2340 /* copy \ characters */
2341 while (*porig == psepc)
2342 *ptrue++ = *porig++;
2343
2344 ptruePrev = ptrue;
2345 porigPrev = porig;
2346 while (*porig != NUL && *porig != psepc)
2347 {
2348#ifdef FEAT_MBYTE
2349 int l;
2350
2351 if (enc_dbcs)
2352 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002353 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354 while (--l >= 0)
2355 *ptrue++ = *porig++;
2356 }
2357 else
2358#endif
2359 *ptrue++ = *porig++;
2360 }
2361 *ptrue = NUL;
2362
Bram Moolenaar464c9252010-10-13 20:37:41 +02002363 /* To avoid a slow failure append "\*" when searching a directory,
2364 * server or network share. */
2365 STRCPY(szTrueNameTemp, szTrueName);
2366 slen = strlen(szTrueNameTemp);
2367 if (*porig == psepc && slen + 2 < _MAX_PATH)
2368 STRCPY(szTrueNameTemp + slen, "\\*");
2369
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 /* Skip "", "." and "..". */
2371 if (ptrue > ptruePrev
2372 && (ptruePrev[0] != '.'
2373 || (ptruePrev[1] != NUL
2374 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002375 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376 != INVALID_HANDLE_VALUE)
2377 {
2378 c = *porig;
2379 *porig = NUL;
2380
2381 /* Only use the match when it's the same name (ignoring case) or
2382 * expansion is allowed and there is a match with the short name
2383 * and there is enough room. */
2384 if (_stricoll(porigPrev, fb.cFileName) == 0
2385 || (len > 0
2386 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2387 && (int)(ptruePrev - szTrueName)
2388 + (int)strlen(fb.cFileName) < len)))
2389 {
2390 STRCPY(ptruePrev, fb.cFileName);
2391
2392 /* Look for exact match and prefer it if found. Must be a
2393 * long name, otherwise there would be only one match. */
2394 while (FindNextFile(hFind, &fb))
2395 {
2396 if (*fb.cAlternateFileName != NUL
2397 && (strcoll(porigPrev, fb.cFileName) == 0
2398 || (len > 0
2399 && (_stricoll(porigPrev,
2400 fb.cAlternateFileName) == 0
2401 && (int)(ptruePrev - szTrueName)
2402 + (int)strlen(fb.cFileName) < len))))
2403 {
2404 STRCPY(ptruePrev, fb.cFileName);
2405 break;
2406 }
2407 }
2408 }
2409 FindClose(hFind);
2410 *porig = c;
2411 ptrue = ptruePrev + strlen(ptruePrev);
2412 }
2413 }
2414
2415 STRCPY(name, szTrueName);
2416}
2417
2418
2419/*
2420 * Insert user name in s[len].
2421 */
2422 int
2423mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002424 char_u *s,
2425 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002427 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428 DWORD cch = sizeof szUserName;
2429
2430 if (GetUserName(szUserName, &cch))
2431 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002432 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 return OK;
2434 }
2435 s[0] = NUL;
2436 return FAIL;
2437}
2438
2439
2440/*
2441 * Insert host name in s[len].
2442 */
2443 void
2444mch_get_host_name(
2445 char_u *s,
2446 int len)
2447{
2448 DWORD cch = len;
2449
2450 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002451 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452}
2453
2454
2455/*
2456 * return process ID
2457 */
2458 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002459mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002460{
2461 return (long)GetCurrentProcessId();
2462}
2463
2464
2465/*
2466 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2467 * Return OK for success, FAIL for failure.
2468 */
2469 int
2470mch_dirname(
2471 char_u *buf,
2472 int len)
2473{
2474 /*
2475 * Originally this was:
2476 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2477 * But the Win32s known bug list says that getcwd() doesn't work
2478 * so use the Win32 system call instead. <Negri>
2479 */
2480#ifdef FEAT_MBYTE
2481 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2482 {
2483 WCHAR wbuf[_MAX_PATH + 1];
2484
2485 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2486 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002487 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488
2489 if (p != NULL)
2490 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002491 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 vim_free(p);
2493 return OK;
2494 }
2495 }
2496 /* Retry with non-wide function (for Windows 98). */
2497 }
2498#endif
2499 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2500}
2501
2502/*
2503 * get file permissions for `name'
2504 * -1 : error
2505 * else FILE_ATTRIBUTE_* defined in winnt.h
2506 */
2507 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002508mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509{
2510#ifdef FEAT_MBYTE
2511 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2512 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002513 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 long n;
2515
2516 if (p != NULL)
2517 {
2518 n = (long)GetFileAttributesW(p);
2519 vim_free(p);
2520 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2521 return n;
2522 /* Retry with non-wide function (for Windows 98). */
2523 }
2524 }
2525#endif
2526 return (long)GetFileAttributes((char *)name);
2527}
2528
2529
2530/*
2531 * set file permission for `name' to `perm'
2532 */
2533 int
2534mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002535 char_u *name,
2536 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537{
2538 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2539#ifdef FEAT_MBYTE
2540 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2541 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002542 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 long n;
2544
2545 if (p != NULL)
2546 {
2547 n = (long)SetFileAttributesW(p, perm);
2548 vim_free(p);
2549 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2550 return n ? OK : FAIL;
2551 /* Retry with non-wide function (for Windows 98). */
2552 }
2553 }
2554#endif
2555 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2556}
2557
2558/*
2559 * Set hidden flag for "name".
2560 */
2561 void
2562mch_hide(char_u *name)
2563{
2564 int perm;
2565#ifdef FEAT_MBYTE
2566 WCHAR *p = NULL;
2567
2568 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002569 p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002570#endif
2571
2572#ifdef FEAT_MBYTE
2573 if (p != NULL)
2574 {
2575 perm = GetFileAttributesW(p);
2576 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2577 {
2578 /* Retry with non-wide function (for Windows 98). */
2579 vim_free(p);
2580 p = NULL;
2581 }
2582 }
2583 if (p == NULL)
2584#endif
2585 perm = GetFileAttributes((char *)name);
2586 if (perm >= 0)
2587 {
2588 perm |= FILE_ATTRIBUTE_HIDDEN;
2589#ifdef FEAT_MBYTE
2590 if (p != NULL)
2591 {
2592 if (SetFileAttributesW(p, perm) == 0
2593 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2594 {
2595 /* Retry with non-wide function (for Windows 98). */
2596 vim_free(p);
2597 p = NULL;
2598 }
2599 }
2600 if (p == NULL)
2601#endif
2602 SetFileAttributes((char *)name, perm);
2603 }
2604#ifdef FEAT_MBYTE
2605 vim_free(p);
2606#endif
2607}
2608
2609/*
2610 * return TRUE if "name" is a directory
2611 * return FALSE if "name" is not a directory or upon error
2612 */
2613 int
2614mch_isdir(char_u *name)
2615{
2616 int f = mch_getperm(name);
2617
2618 if (f == -1)
2619 return FALSE; /* file does not exist at all */
2620
2621 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2622}
2623
2624/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002625 * Return TRUE if file "fname" has more than one link.
2626 */
2627 int
2628mch_is_linked(char_u *fname)
2629{
2630 HANDLE hFile;
2631 int res = 0;
2632 BY_HANDLE_FILE_INFORMATION inf;
2633#ifdef FEAT_MBYTE
2634 WCHAR *wn = NULL;
2635
2636 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002637 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar03f48552006-02-28 23:52:23 +00002638 if (wn != NULL)
2639 {
2640 hFile = CreateFileW(wn, /* file name */
2641 GENERIC_READ, /* access mode */
2642 0, /* share mode */
2643 NULL, /* security descriptor */
2644 OPEN_EXISTING, /* creation disposition */
2645 0, /* file attributes */
2646 NULL); /* handle to template file */
2647 if (hFile == INVALID_HANDLE_VALUE
2648 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2649 {
2650 /* Retry with non-wide function (for Windows 98). */
2651 vim_free(wn);
2652 wn = NULL;
2653 }
2654 }
2655 if (wn == NULL)
2656#endif
2657 hFile = CreateFile(fname, /* file name */
2658 GENERIC_READ, /* access mode */
2659 0, /* share mode */
2660 NULL, /* security descriptor */
2661 OPEN_EXISTING, /* creation disposition */
2662 0, /* file attributes */
2663 NULL); /* handle to template file */
2664
2665 if (hFile != INVALID_HANDLE_VALUE)
2666 {
2667 if (GetFileInformationByHandle(hFile, &inf) != 0
2668 && inf.nNumberOfLinks > 1)
2669 res = 1;
2670 CloseHandle(hFile);
2671 }
2672
2673#ifdef FEAT_MBYTE
2674 vim_free(wn);
2675#endif
2676 return res;
2677}
2678
2679/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680 * Return TRUE if file or directory "name" is writable (not readonly).
2681 * Strange semantics of Win32: a readonly directory is writable, but you can't
2682 * delete a file. Let's say this means it is writable.
2683 */
2684 int
2685mch_writable(char_u *name)
2686{
2687 int perm = mch_getperm(name);
2688
2689 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2690 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2691}
2692
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693/*
2694 * Return 1 if "name" can be executed, 0 if not.
2695 * Return -1 if unknown.
2696 */
2697 int
2698mch_can_exe(char_u *name)
2699{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002700 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002701 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002702 char_u *p;
2703
2704 if (len >= _MAX_PATH) /* safety check */
2705 return FALSE;
2706
2707 /* If there already is an extension try using the name directly. Also do
2708 * this with a Unix-shell like 'shell'. */
2709 if (vim_strchr(gettail(name), '.') != NULL
2710 || strstr((char *)gettail(p_sh), "sh") != NULL)
2711 if (executable_exists((char *)name))
2712 return TRUE;
2713
2714 /*
2715 * Loop over all extensions in $PATHEXT.
2716 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002717 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002718 p = mch_getenv("PATHEXT");
2719 if (p == NULL)
2720 p = (char_u *)".com;.exe;.bat;.cmd";
2721 while (*p)
2722 {
2723 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2724 {
2725 /* A single "." means no extension is added. */
2726 buf[len] = NUL;
2727 ++p;
2728 if (*p)
2729 ++p;
2730 }
2731 else
2732 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2733 if (executable_exists((char *)buf))
2734 return TRUE;
2735 }
2736 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738
2739/*
2740 * Check what "name" is:
2741 * NODE_NORMAL: file or directory (or doesn't exist)
2742 * NODE_WRITABLE: writable device, socket, fifo, etc.
2743 * NODE_OTHER: non-writable things
2744 */
2745 int
2746mch_nodetype(char_u *name)
2747{
2748 HANDLE hFile;
2749 int type;
2750
Bram Moolenaar043545e2006-10-10 16:44:07 +00002751 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2752 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2753 * here. */
2754 if (STRNCMP(name, "\\\\.\\", 4) == 0)
2755 return NODE_WRITABLE;
2756
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757 hFile = CreateFile(name, /* file name */
2758 GENERIC_WRITE, /* access mode */
2759 0, /* share mode */
2760 NULL, /* security descriptor */
2761 OPEN_EXISTING, /* creation disposition */
2762 0, /* file attributes */
2763 NULL); /* handle to template file */
2764
2765 if (hFile == INVALID_HANDLE_VALUE)
2766 return NODE_NORMAL;
2767
2768 type = GetFileType(hFile);
2769 CloseHandle(hFile);
2770 if (type == FILE_TYPE_CHAR)
2771 return NODE_WRITABLE;
2772 if (type == FILE_TYPE_DISK)
2773 return NODE_NORMAL;
2774 return NODE_OTHER;
2775}
2776
2777#ifdef HAVE_ACL
2778struct my_acl
2779{
2780 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2781 PSID pSidOwner;
2782 PSID pSidGroup;
2783 PACL pDacl;
2784 PACL pSacl;
2785};
2786#endif
2787
2788/*
2789 * Return a pointer to the ACL of file "fname" in allocated memory.
2790 * Return NULL if the ACL is not available for whatever reason.
2791 */
2792 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002793mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794{
2795#ifndef HAVE_ACL
2796 return (vim_acl_T)NULL;
2797#else
2798 struct my_acl *p = NULL;
2799
2800 /* This only works on Windows NT and 2000. */
2801 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2802 {
2803 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2804 if (p != NULL)
2805 {
2806 if (pGetNamedSecurityInfo(
2807 (LPTSTR)fname, // Abstract filename
2808 SE_FILE_OBJECT, // File Object
2809 // Retrieve the entire security descriptor.
2810 OWNER_SECURITY_INFORMATION |
2811 GROUP_SECURITY_INFORMATION |
2812 DACL_SECURITY_INFORMATION |
2813 SACL_SECURITY_INFORMATION,
2814 &p->pSidOwner, // Ownership information.
2815 &p->pSidGroup, // Group membership.
2816 &p->pDacl, // Discretionary information.
2817 &p->pSacl, // For auditing purposes.
2818 &p->pSecurityDescriptor
2819 ) != ERROR_SUCCESS)
2820 {
2821 mch_free_acl((vim_acl_T)p);
2822 p = NULL;
2823 }
2824 }
2825 }
2826
2827 return (vim_acl_T)p;
2828#endif
2829}
2830
2831/*
2832 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2833 * Errors are ignored.
2834 * This must only be called with "acl" equal to what mch_get_acl() returned.
2835 */
2836 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002837mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838{
2839#ifdef HAVE_ACL
2840 struct my_acl *p = (struct my_acl *)acl;
2841
2842 if (p != NULL && advapi_lib != NULL)
2843 (void)pSetNamedSecurityInfo(
2844 (LPTSTR)fname, // Abstract filename
2845 SE_FILE_OBJECT, // File Object
2846 // Retrieve the entire security descriptor.
2847 OWNER_SECURITY_INFORMATION |
2848 GROUP_SECURITY_INFORMATION |
2849 DACL_SECURITY_INFORMATION |
2850 SACL_SECURITY_INFORMATION,
2851 p->pSidOwner, // Ownership information.
2852 p->pSidGroup, // Group membership.
2853 p->pDacl, // Discretionary information.
2854 p->pSacl // For auditing purposes.
2855 );
2856#endif
2857}
2858
2859 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002860mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861{
2862#ifdef HAVE_ACL
2863 struct my_acl *p = (struct my_acl *)acl;
2864
2865 if (p != NULL)
2866 {
2867 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2868 vim_free(p);
2869 }
2870#endif
2871}
2872
2873#ifndef FEAT_GUI_W32
2874
2875/*
2876 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2877 */
2878 static BOOL WINAPI
2879handler_routine(
2880 DWORD dwCtrlType)
2881{
2882 switch (dwCtrlType)
2883 {
2884 case CTRL_C_EVENT:
2885 if (ctrl_c_interrupts)
2886 g_fCtrlCPressed = TRUE;
2887 return TRUE;
2888
2889 case CTRL_BREAK_EVENT:
2890 g_fCBrkPressed = TRUE;
2891 return TRUE;
2892
2893 /* fatal events: shut down gracefully */
2894 case CTRL_CLOSE_EVENT:
2895 case CTRL_LOGOFF_EVENT:
2896 case CTRL_SHUTDOWN_EVENT:
2897 windgoto((int)Rows - 1, 0);
2898 g_fForceExit = TRUE;
2899
Bram Moolenaar0fde2902008-03-16 13:54:13 +00002900 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901 (dwCtrlType == CTRL_CLOSE_EVENT
2902 ? _("close")
2903 : dwCtrlType == CTRL_LOGOFF_EVENT
2904 ? _("logoff")
2905 : _("shutdown")));
2906#ifdef DEBUG
2907 OutputDebugString(IObuff);
2908#endif
2909
2910 preserve_exit(); /* output IObuff, preserve files and exit */
2911
2912 return TRUE; /* not reached */
2913
2914 default:
2915 return FALSE;
2916 }
2917}
2918
2919
2920/*
2921 * set the tty in (raw) ? "raw" : "cooked" mode
2922 */
2923 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002924mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925{
2926 DWORD cmodein;
2927 DWORD cmodeout;
2928 BOOL bEnableHandler;
2929
2930 GetConsoleMode(g_hConIn, &cmodein);
2931 GetConsoleMode(g_hConOut, &cmodeout);
2932 if (tmode == TMODE_RAW)
2933 {
2934 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2935 ENABLE_ECHO_INPUT);
2936#ifdef FEAT_MOUSE
2937 if (g_fMouseActive)
2938 cmodein |= ENABLE_MOUSE_INPUT;
2939#endif
2940 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2941 bEnableHandler = TRUE;
2942 }
2943 else /* cooked */
2944 {
2945 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2946 ENABLE_ECHO_INPUT);
2947 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2948 bEnableHandler = FALSE;
2949 }
2950 SetConsoleMode(g_hConIn, cmodein);
2951 SetConsoleMode(g_hConOut, cmodeout);
2952 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
2953
2954#ifdef MCH_WRITE_DUMP
2955 if (fdDump)
2956 {
2957 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
2958 tmode == TMODE_RAW ? "raw" :
2959 tmode == TMODE_COOK ? "cooked" : "normal",
2960 cmodein, cmodeout);
2961 fflush(fdDump);
2962 }
2963#endif
2964}
2965
2966
2967/*
2968 * Get the size of the current window in `Rows' and `Columns'
2969 * Return OK when size could be determined, FAIL otherwise.
2970 */
2971 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002972mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973{
2974 CONSOLE_SCREEN_BUFFER_INFO csbi;
2975
2976 if (!g_fTermcapMode && g_cbTermcap.IsValid)
2977 {
2978 /*
2979 * For some reason, we are trying to get the screen dimensions
2980 * even though we are not in termcap mode. The 'Rows' and 'Columns'
2981 * variables are really intended to mean the size of Vim screen
2982 * while in termcap mode.
2983 */
2984 Rows = g_cbTermcap.Info.dwSize.Y;
2985 Columns = g_cbTermcap.Info.dwSize.X;
2986 }
2987 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2988 {
2989 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2990 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2991 }
2992 else
2993 {
2994 Rows = 25;
2995 Columns = 80;
2996 }
2997 return OK;
2998}
2999
3000/*
3001 * Set a console window to `xSize' * `ySize'
3002 */
3003 static void
3004ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003005 HANDLE hConsole,
3006 int xSize,
3007 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008{
3009 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3010 SMALL_RECT srWindowRect; /* hold the new console size */
3011 COORD coordScreen;
3012
3013#ifdef MCH_WRITE_DUMP
3014 if (fdDump)
3015 {
3016 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3017 fflush(fdDump);
3018 }
3019#endif
3020
3021 /* get the largest size we can size the console window to */
3022 coordScreen = GetLargestConsoleWindowSize(hConsole);
3023
3024 /* define the new console window size and scroll position */
3025 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3026 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3027 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3028
3029 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3030 {
3031 int sx, sy;
3032
3033 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3034 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3035 if (sy < ySize || sx < xSize)
3036 {
3037 /*
3038 * Increasing number of lines/columns, do buffer first.
3039 * Use the maximal size in x and y direction.
3040 */
3041 if (sy < ySize)
3042 coordScreen.Y = ySize;
3043 else
3044 coordScreen.Y = sy;
3045 if (sx < xSize)
3046 coordScreen.X = xSize;
3047 else
3048 coordScreen.X = sx;
3049 SetConsoleScreenBufferSize(hConsole, coordScreen);
3050 }
3051 }
3052
3053 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3054 {
3055#ifdef MCH_WRITE_DUMP
3056 if (fdDump)
3057 {
3058 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3059 GetLastError());
3060 fflush(fdDump);
3061 }
3062#endif
3063 }
3064
3065 /* define the new console buffer size */
3066 coordScreen.X = xSize;
3067 coordScreen.Y = ySize;
3068
3069 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3070 {
3071#ifdef MCH_WRITE_DUMP
3072 if (fdDump)
3073 {
3074 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3075 GetLastError());
3076 fflush(fdDump);
3077 }
3078#endif
3079 }
3080}
3081
3082
3083/*
3084 * Set the console window to `Rows' * `Columns'
3085 */
3086 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003087mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088{
3089 COORD coordScreen;
3090
3091 /* Don't change window size while still starting up */
3092 if (suppress_winsize != 0)
3093 {
3094 suppress_winsize = 2;
3095 return;
3096 }
3097
3098 if (term_console)
3099 {
3100 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3101
3102 /* Clamp Rows and Columns to reasonable values */
3103 if (Rows > coordScreen.Y)
3104 Rows = coordScreen.Y;
3105 if (Columns > coordScreen.X)
3106 Columns = coordScreen.X;
3107
3108 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3109 }
3110}
3111
3112/*
3113 * Rows and/or Columns has changed.
3114 */
3115 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003116mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117{
3118 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3119}
3120
3121
3122/*
3123 * Called when started up, to set the winsize that was delayed.
3124 */
3125 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003126mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127{
3128 if (suppress_winsize == 2)
3129 {
3130 suppress_winsize = 0;
3131 mch_set_shellsize();
3132 shell_resized();
3133 }
3134 suppress_winsize = 0;
3135}
3136#endif /* FEAT_GUI_W32 */
3137
3138
3139
3140#if defined(FEAT_GUI_W32) || defined(PROTO)
3141
3142/*
3143 * Specialised version of system() for Win32 GUI mode.
3144 * This version proceeds as follows:
3145 * 1. Create a console window for use by the subprocess
3146 * 2. Run the subprocess (it gets the allocated console by default)
3147 * 3. Wait for the subprocess to terminate and get its exit code
3148 * 4. Prompt the user to press a key to close the console window
3149 */
3150 static int
3151mch_system(char *cmd, int options)
3152{
3153 STARTUPINFO si;
3154 PROCESS_INFORMATION pi;
3155 DWORD ret = 0;
3156 HWND hwnd = GetFocus();
3157
3158 si.cb = sizeof(si);
3159 si.lpReserved = NULL;
3160 si.lpDesktop = NULL;
3161 si.lpTitle = NULL;
3162 si.dwFlags = STARTF_USESHOWWINDOW;
3163 /*
3164 * It's nicer to run a filter command in a minimized window, but in
3165 * Windows 95 this makes the command MUCH slower. We can't do it under
3166 * Win32s either as it stops the synchronous spawn workaround working.
3167 */
3168 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
3169 si.wShowWindow = SW_SHOWMINIMIZED;
3170 else
3171 si.wShowWindow = SW_SHOWNORMAL;
3172 si.cbReserved2 = 0;
3173 si.lpReserved2 = NULL;
3174
3175 /* There is a strange error on Windows 95 when using "c:\\command.com".
3176 * When the "c:\\" is left out it works OK...? */
3177 if (mch_windows95()
3178 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3179 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3180 cmd += 3;
3181
3182 /* Now, run the command */
3183 CreateProcess(NULL, /* Executable name */
3184 cmd, /* Command to execute */
3185 NULL, /* Process security attributes */
3186 NULL, /* Thread security attributes */
3187 FALSE, /* Inherit handles */
3188 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3189 CREATE_NEW_CONSOLE,
3190 NULL, /* Environment */
3191 NULL, /* Current directory */
3192 &si, /* Startup information */
3193 &pi); /* Process information */
3194
3195
3196 /* Wait for the command to terminate before continuing */
3197 if (g_PlatformId != VER_PLATFORM_WIN32s)
3198 {
3199#ifdef FEAT_GUI
3200 int delay = 1;
3201
3202 /* Keep updating the window while waiting for the shell to finish. */
3203 for (;;)
3204 {
3205 MSG msg;
3206
3207 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3208 {
3209 TranslateMessage(&msg);
3210 DispatchMessage(&msg);
3211 }
3212 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3213 break;
3214
3215 /* We start waiting for a very short time and then increase it, so
3216 * that we respond quickly when the process is quick, and don't
3217 * consume too much overhead when it's slow. */
3218 if (delay < 50)
3219 delay += 10;
3220 }
3221#else
3222 WaitForSingleObject(pi.hProcess, INFINITE);
3223#endif
3224
3225 /* Get the command exit code */
3226 GetExitCodeProcess(pi.hProcess, &ret);
3227 }
3228 else
3229 {
3230 /*
3231 * This ugly code is the only quick way of performing
3232 * a synchronous spawn under Win32s. Yuk.
3233 */
3234 num_windows = 0;
3235 EnumWindows(win32ssynch_cb, 0);
3236 old_num_windows = num_windows;
3237 do
3238 {
3239 Sleep(1000);
3240 num_windows = 0;
3241 EnumWindows(win32ssynch_cb, 0);
3242 } while (num_windows == old_num_windows);
3243 ret = 0;
3244 }
3245
3246 /* Close the handles to the subprocess, so that it goes away */
3247 CloseHandle(pi.hThread);
3248 CloseHandle(pi.hProcess);
3249
3250 /* Try to get input focus back. Doesn't always work though. */
3251 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3252
3253 return ret;
3254}
3255#else
3256
3257# define mch_system(c, o) system(c)
3258
3259#endif
3260
3261/*
3262 * Either execute a command by calling the shell or start a new shell
3263 */
3264 int
3265mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003266 char_u *cmd,
3267 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003268{
3269 int x = 0;
3270 int tmode = cur_tmode;
3271#ifdef FEAT_TITLE
3272 char szShellTitle[512];
3273
3274 /* Change the title to reflect that we are in a subshell. */
3275 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3276 {
3277 if (cmd == NULL)
3278 strcat(szShellTitle, " :sh");
3279 else
3280 {
3281 strcat(szShellTitle, " - !");
3282 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3283 strcat(szShellTitle, cmd);
3284 }
3285 mch_settitle(szShellTitle, NULL);
3286 }
3287#endif
3288
3289 out_flush();
3290
3291#ifdef MCH_WRITE_DUMP
3292 if (fdDump)
3293 {
3294 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3295 fflush(fdDump);
3296 }
3297#endif
3298
3299 /*
3300 * Catch all deadly signals while running the external command, because a
3301 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3302 */
3303 signal(SIGINT, SIG_IGN);
3304#if defined(__GNUC__) && !defined(__MINGW32__)
3305 signal(SIGKILL, SIG_IGN);
3306#else
3307 signal(SIGBREAK, SIG_IGN);
3308#endif
3309 signal(SIGILL, SIG_IGN);
3310 signal(SIGFPE, SIG_IGN);
3311 signal(SIGSEGV, SIG_IGN);
3312 signal(SIGTERM, SIG_IGN);
3313 signal(SIGABRT, SIG_IGN);
3314
3315 if (options & SHELL_COOKED)
3316 settmode(TMODE_COOK); /* set to normal mode */
3317
3318 if (cmd == NULL)
3319 {
3320 x = mch_system(p_sh, options);
3321 }
3322 else
3323 {
3324 /* we use "command" or "cmd" to start the shell; slow but easy */
3325 char_u *newcmd;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003326 long_u cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327#ifdef FEAT_GUI_W32
3328 STRLEN(vimrun_path) +
3329#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003330 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
3331
3332 newcmd = lalloc(cmdlen, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333 if (newcmd != NULL)
3334 {
3335 char_u *cmdbase = (*cmd == '"' ? cmd + 1 : cmd);
3336
3337 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3338 {
3339 STARTUPINFO si;
3340 PROCESS_INFORMATION pi;
3341
3342 si.cb = sizeof(si);
3343 si.lpReserved = NULL;
3344 si.lpDesktop = NULL;
3345 si.lpTitle = NULL;
3346 si.dwFlags = 0;
3347 si.cbReserved2 = 0;
3348 si.lpReserved2 = NULL;
3349
3350 cmdbase = skipwhite(cmdbase + 5);
3351 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3352 && vim_iswhite(cmdbase[4]))
3353 {
3354 cmdbase = skipwhite(cmdbase + 4);
3355 si.dwFlags = STARTF_USESHOWWINDOW;
3356 si.wShowWindow = SW_SHOWMINNOACTIVE;
3357 }
3358
3359 /* When the command is in double quotes, but 'shellxquote' is
3360 * empty, keep the double quotes around the command.
3361 * Otherwise remove the double quotes, they aren't needed
3362 * here, because we don't use a shell to run the command. */
3363 if (*cmd == '"' && *p_sxq == NUL)
3364 {
3365 newcmd[0] = '"';
3366 STRCPY(newcmd + 1, cmdbase);
3367 }
3368 else
3369 {
3370 STRCPY(newcmd, cmdbase);
3371 if (*cmd == '"' && *newcmd != NUL)
3372 newcmd[STRLEN(newcmd) - 1] = NUL;
3373 }
3374
3375 /*
3376 * Now, start the command as a process, so that it doesn't
3377 * inherit our handles which causes unpleasant dangling swap
3378 * files if we exit before the spawned process
3379 */
3380 if (CreateProcess (NULL, // Executable name
3381 newcmd, // Command to execute
3382 NULL, // Process security attributes
3383 NULL, // Thread security attributes
3384 FALSE, // Inherit handles
3385 CREATE_NEW_CONSOLE, // Creation flags
3386 NULL, // Environment
3387 NULL, // Current directory
3388 &si, // Startup information
3389 &pi)) // Process information
3390 x = 0;
3391 else
3392 {
3393 x = -1;
3394#ifdef FEAT_GUI_W32
3395 EMSG(_("E371: Command not found"));
3396#endif
3397 }
3398 /* Close the handles to the subprocess, so that it goes away */
3399 CloseHandle(pi.hThread);
3400 CloseHandle(pi.hProcess);
3401 }
3402 else
3403 {
3404#if defined(FEAT_GUI_W32)
3405 if (need_vimrun_warning)
3406 {
3407 MessageBox(NULL,
3408 _("VIMRUN.EXE not found in your $PATH.\n"
3409 "External commands will not pause after completion.\n"
3410 "See :help win32-vimrun for more information."),
3411 _("Vim Warning"),
3412 MB_ICONWARNING);
3413 need_vimrun_warning = FALSE;
3414 }
3415 if (!s_dont_use_vimrun)
3416 /* Use vimrun to execute the command. It opens a console
3417 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02003418 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00003419 vimrun_path,
3420 (msg_silent != 0 || (options & SHELL_DOOUT))
3421 ? "-s " : "",
3422 p_sh, p_shcf, cmd);
3423 else
3424#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02003425 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003426 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427 x = mch_system((char *)newcmd, options);
3428 }
3429 vim_free(newcmd);
3430 }
3431 }
3432
3433 if (tmode == TMODE_RAW)
3434 settmode(TMODE_RAW); /* set to raw mode */
3435
3436 /* Print the return value, unless "vimrun" was used. */
3437 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
3438#if defined(FEAT_GUI_W32)
3439 && ((options & SHELL_DOOUT) || s_dont_use_vimrun)
3440#endif
3441 )
3442 {
3443 smsg(_("shell returned %d"), x);
3444 msg_putchar('\n');
3445 }
3446#ifdef FEAT_TITLE
3447 resettitle();
3448#endif
3449
3450 signal(SIGINT, SIG_DFL);
3451#if defined(__GNUC__) && !defined(__MINGW32__)
3452 signal(SIGKILL, SIG_DFL);
3453#else
3454 signal(SIGBREAK, SIG_DFL);
3455#endif
3456 signal(SIGILL, SIG_DFL);
3457 signal(SIGFPE, SIG_DFL);
3458 signal(SIGSEGV, SIG_DFL);
3459 signal(SIGTERM, SIG_DFL);
3460 signal(SIGABRT, SIG_DFL);
3461
3462 return x;
3463}
3464
3465
3466#ifndef FEAT_GUI_W32
3467
3468/*
3469 * Start termcap mode
3470 */
3471 static void
3472termcap_mode_start(void)
3473{
3474 DWORD cmodein;
3475
3476 if (g_fTermcapMode)
3477 return;
3478
3479 SaveConsoleBuffer(&g_cbNonTermcap);
3480
3481 if (g_cbTermcap.IsValid)
3482 {
3483 /*
3484 * We've been in termcap mode before. Restore certain screen
3485 * characteristics, including the buffer size and the window
3486 * size. Since we will be redrawing the screen, we don't need
3487 * to restore the actual contents of the buffer.
3488 */
3489 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
3490 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
3491 Rows = g_cbTermcap.Info.dwSize.Y;
3492 Columns = g_cbTermcap.Info.dwSize.X;
3493 }
3494 else
3495 {
3496 /*
3497 * This is our first time entering termcap mode. Clear the console
3498 * screen buffer, and resize the buffer to match the current window
3499 * size. We will use this as the size of our editing environment.
3500 */
3501 ClearConsoleBuffer(g_attrCurrent);
3502 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3503 }
3504
3505#ifdef FEAT_TITLE
3506 resettitle();
3507#endif
3508
3509 GetConsoleMode(g_hConIn, &cmodein);
3510#ifdef FEAT_MOUSE
3511 if (g_fMouseActive)
3512 cmodein |= ENABLE_MOUSE_INPUT;
3513 else
3514 cmodein &= ~ENABLE_MOUSE_INPUT;
3515#endif
3516 cmodein |= ENABLE_WINDOW_INPUT;
3517 SetConsoleMode(g_hConIn, cmodein);
3518
3519 redraw_later_clear();
3520 g_fTermcapMode = TRUE;
3521}
3522
3523
3524/*
3525 * End termcap mode
3526 */
3527 static void
3528termcap_mode_end(void)
3529{
3530 DWORD cmodein;
3531 ConsoleBuffer *cb;
3532 COORD coord;
3533 DWORD dwDummy;
3534
3535 if (!g_fTermcapMode)
3536 return;
3537
3538 SaveConsoleBuffer(&g_cbTermcap);
3539
3540 GetConsoleMode(g_hConIn, &cmodein);
3541 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
3542 SetConsoleMode(g_hConIn, cmodein);
3543
3544#ifdef FEAT_RESTORE_ORIG_SCREEN
3545 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
3546#else
3547 cb = &g_cbNonTermcap;
3548#endif
3549 RestoreConsoleBuffer(cb, p_rs);
3550 SetConsoleCursorInfo(g_hConOut, &g_cci);
3551
3552 if (p_rs || exiting)
3553 {
3554 /*
3555 * Clear anything that happens to be on the current line.
3556 */
3557 coord.X = 0;
3558 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
3559 FillConsoleOutputCharacter(g_hConOut, ' ',
3560 cb->Info.dwSize.X, coord, &dwDummy);
3561 /*
3562 * The following is just for aesthetics. If we are exiting without
3563 * restoring the screen, then we want to have a prompt string
3564 * appear at the bottom line. However, the command interpreter
3565 * seems to always advance the cursor one line before displaying
3566 * the prompt string, which causes the screen to scroll. To
3567 * counter this, move the cursor up one line before exiting.
3568 */
3569 if (exiting && !p_rs)
3570 coord.Y--;
3571 /*
3572 * Position the cursor at the leftmost column of the desired row.
3573 */
3574 SetConsoleCursorPosition(g_hConOut, coord);
3575 }
3576
3577 g_fTermcapMode = FALSE;
3578}
3579#endif /* FEAT_GUI_W32 */
3580
3581
3582#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003583/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584 void
3585mch_write(
3586 char_u *s,
3587 int len)
3588{
3589 /* never used */
3590}
3591
3592#else
3593
3594/*
3595 * clear `n' chars, starting from `coord'
3596 */
3597 static void
3598clear_chars(
3599 COORD coord,
3600 DWORD n)
3601{
3602 DWORD dwDummy;
3603
3604 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
3605 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
3606}
3607
3608
3609/*
3610 * Clear the screen
3611 */
3612 static void
3613clear_screen(void)
3614{
3615 g_coord.X = g_coord.Y = 0;
3616 clear_chars(g_coord, Rows * Columns);
3617}
3618
3619
3620/*
3621 * Clear to end of display
3622 */
3623 static void
3624clear_to_end_of_display(void)
3625{
3626 clear_chars(g_coord, (Rows - g_coord.Y - 1)
3627 * Columns + (Columns - g_coord.X));
3628}
3629
3630
3631/*
3632 * Clear to end of line
3633 */
3634 static void
3635clear_to_end_of_line(void)
3636{
3637 clear_chars(g_coord, Columns - g_coord.X);
3638}
3639
3640
3641/*
3642 * Scroll the scroll region up by `cLines' lines
3643 */
3644 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003645scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003646{
3647 COORD oldcoord = g_coord;
3648
3649 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
3650 delete_lines(cLines);
3651
3652 g_coord = oldcoord;
3653}
3654
3655
3656/*
3657 * Set the scroll region
3658 */
3659 static void
3660set_scroll_region(
3661 unsigned left,
3662 unsigned top,
3663 unsigned right,
3664 unsigned bottom)
3665{
3666 if (left >= right
3667 || top >= bottom
3668 || right > (unsigned) Columns - 1
3669 || bottom > (unsigned) Rows - 1)
3670 return;
3671
3672 g_srScrollRegion.Left = left;
3673 g_srScrollRegion.Top = top;
3674 g_srScrollRegion.Right = right;
3675 g_srScrollRegion.Bottom = bottom;
3676}
3677
3678
3679/*
3680 * Insert `cLines' lines at the current cursor position
3681 */
3682 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003683insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684{
3685 SMALL_RECT source;
3686 COORD dest;
3687 CHAR_INFO fill;
3688
3689 dest.X = 0;
3690 dest.Y = g_coord.Y + cLines;
3691
3692 source.Left = 0;
3693 source.Top = g_coord.Y;
3694 source.Right = g_srScrollRegion.Right;
3695 source.Bottom = g_srScrollRegion.Bottom - cLines;
3696
3697 fill.Char.AsciiChar = ' ';
3698 fill.Attributes = g_attrCurrent;
3699
3700 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3701
3702 /* Here we have to deal with a win32 console flake: If the scroll
3703 * region looks like abc and we scroll c to a and fill with d we get
3704 * cbd... if we scroll block c one line at a time to a, we get cdd...
3705 * vim expects cdd consistently... So we have to deal with that
3706 * here... (this also occurs scrolling the same way in the other
3707 * direction). */
3708
3709 if (source.Bottom < dest.Y)
3710 {
3711 COORD coord;
3712
3713 coord.X = 0;
3714 coord.Y = source.Bottom;
3715 clear_chars(coord, Columns * (dest.Y - source.Bottom));
3716 }
3717}
3718
3719
3720/*
3721 * Delete `cLines' lines at the current cursor position
3722 */
3723 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003724delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003725{
3726 SMALL_RECT source;
3727 COORD dest;
3728 CHAR_INFO fill;
3729 int nb;
3730
3731 dest.X = 0;
3732 dest.Y = g_coord.Y;
3733
3734 source.Left = 0;
3735 source.Top = g_coord.Y + cLines;
3736 source.Right = g_srScrollRegion.Right;
3737 source.Bottom = g_srScrollRegion.Bottom;
3738
3739 fill.Char.AsciiChar = ' ';
3740 fill.Attributes = g_attrCurrent;
3741
3742 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3743
3744 /* Here we have to deal with a win32 console flake: If the scroll
3745 * region looks like abc and we scroll c to a and fill with d we get
3746 * cbd... if we scroll block c one line at a time to a, we get cdd...
3747 * vim expects cdd consistently... So we have to deal with that
3748 * here... (this also occurs scrolling the same way in the other
3749 * direction). */
3750
3751 nb = dest.Y + (source.Bottom - source.Top) + 1;
3752
3753 if (nb < source.Top)
3754 {
3755 COORD coord;
3756
3757 coord.X = 0;
3758 coord.Y = nb;
3759 clear_chars(coord, Columns * (source.Top - nb));
3760 }
3761}
3762
3763
3764/*
3765 * Set the cursor position
3766 */
3767 static void
3768gotoxy(
3769 unsigned x,
3770 unsigned y)
3771{
3772 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
3773 return;
3774
3775 /* external cursor coords are 1-based; internal are 0-based */
3776 g_coord.X = x - 1;
3777 g_coord.Y = y - 1;
3778 SetConsoleCursorPosition(g_hConOut, g_coord);
3779}
3780
3781
3782/*
3783 * Set the current text attribute = (foreground | background)
3784 * See ../doc/os_win32.txt for the numbers.
3785 */
3786 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003787textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788{
3789 g_attrCurrent = wAttr;
3790
3791 SetConsoleTextAttribute(g_hConOut, wAttr);
3792}
3793
3794
3795 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003796textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797{
3798 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
3799
3800 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3801}
3802
3803
3804 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003805textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806{
3807 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
3808
3809 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3810}
3811
3812
3813/*
3814 * restore the default text attribute (whatever we started with)
3815 */
3816 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003817normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818{
3819 textattr(g_attrDefault);
3820}
3821
3822
3823static WORD g_attrPreStandout = 0;
3824
3825/*
3826 * Make the text standout, by brightening it
3827 */
3828 static void
3829standout(void)
3830{
3831 g_attrPreStandout = g_attrCurrent;
3832 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
3833}
3834
3835
3836/*
3837 * Turn off standout mode
3838 */
3839 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003840standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003841{
3842 if (g_attrPreStandout)
3843 {
3844 textattr(g_attrPreStandout);
3845 g_attrPreStandout = 0;
3846 }
3847}
3848
3849
3850/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00003851 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852 */
3853 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003854mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855{
3856 char_u *p;
3857 int n;
3858
3859 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
3860 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
3861 if (T_ME[0] == ESC && T_ME[1] == '|')
3862 {
3863 p = T_ME + 2;
3864 n = getdigits(&p);
3865 if (*p == 'm' && n > 0)
3866 {
3867 cterm_normal_fg_color = (n & 0xf) + 1;
3868 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
3869 }
3870 }
3871}
3872
3873
3874/*
3875 * visual bell: flash the screen
3876 */
3877 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003878visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879{
3880 COORD coordOrigin = {0, 0};
3881 WORD attrFlash = ~g_attrCurrent & 0xff;
3882
3883 DWORD dwDummy;
3884 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
3885
3886 if (oldattrs == NULL)
3887 return;
3888 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3889 coordOrigin, &dwDummy);
3890 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
3891 coordOrigin, &dwDummy);
3892
3893 Sleep(15); /* wait for 15 msec */
3894 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3895 coordOrigin, &dwDummy);
3896 vim_free(oldattrs);
3897}
3898
3899
3900/*
3901 * Make the cursor visible or invisible
3902 */
3903 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003904cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905{
3906 s_cursor_visible = fVisible;
3907#ifdef MCH_CURSOR_SHAPE
3908 mch_update_cursor();
3909#endif
3910}
3911
3912
3913/*
3914 * write `cchToWrite' characters in `pchBuf' to the screen
3915 * Returns the number of characters actually written (at least one).
3916 */
3917 static BOOL
3918write_chars(
3919 LPCSTR pchBuf,
3920 DWORD cchToWrite)
3921{
3922 COORD coord = g_coord;
3923 DWORD written;
3924
3925 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
3926 coord, &written);
3927 /* When writing fails or didn't write a single character, pretend one
3928 * character was written, otherwise we get stuck. */
3929 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
3930 coord, &written) == 0
3931 || written == 0)
3932 written = 1;
3933
3934 g_coord.X += (SHORT) written;
3935
3936 while (g_coord.X > g_srScrollRegion.Right)
3937 {
3938 g_coord.X -= (SHORT) Columns;
3939 if (g_coord.Y < g_srScrollRegion.Bottom)
3940 g_coord.Y++;
3941 }
3942
3943 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3944
3945 return written;
3946}
3947
3948
3949/*
3950 * mch_write(): write the output buffer to the screen, translating ESC
3951 * sequences into calls to console output routines.
3952 */
3953 void
3954mch_write(
3955 char_u *s,
3956 int len)
3957{
3958 s[len] = NUL;
3959
3960 if (!term_console)
3961 {
3962 write(1, s, (unsigned)len);
3963 return;
3964 }
3965
3966 /* translate ESC | sequences into faked bios calls */
3967 while (len--)
3968 {
3969 /* optimization: use one single write_chars for runs of text,
3970 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003971 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003972
3973 if (p_wd)
3974 {
3975 WaitForChar(p_wd);
3976 if (prefix != 0)
3977 prefix = 1;
3978 }
3979
3980 if (prefix != 0)
3981 {
3982 DWORD nWritten;
3983
3984 nWritten = write_chars(s, prefix);
3985#ifdef MCH_WRITE_DUMP
3986 if (fdDump)
3987 {
3988 fputc('>', fdDump);
3989 fwrite(s, sizeof(char_u), nWritten, fdDump);
3990 fputs("<\n", fdDump);
3991 }
3992#endif
3993 len -= (nWritten - 1);
3994 s += nWritten;
3995 }
3996 else if (s[0] == '\n')
3997 {
3998 /* \n, newline: go to the beginning of the next line or scroll */
3999 if (g_coord.Y == g_srScrollRegion.Bottom)
4000 {
4001 scroll(1);
4002 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
4003 }
4004 else
4005 {
4006 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
4007 }
4008#ifdef MCH_WRITE_DUMP
4009 if (fdDump)
4010 fputs("\\n\n", fdDump);
4011#endif
4012 s++;
4013 }
4014 else if (s[0] == '\r')
4015 {
4016 /* \r, carriage return: go to beginning of line */
4017 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
4018#ifdef MCH_WRITE_DUMP
4019 if (fdDump)
4020 fputs("\\r\n", fdDump);
4021#endif
4022 s++;
4023 }
4024 else if (s[0] == '\b')
4025 {
4026 /* \b, backspace: move cursor one position left */
4027 if (g_coord.X > g_srScrollRegion.Left)
4028 g_coord.X--;
4029 else if (g_coord.Y > g_srScrollRegion.Top)
4030 {
4031 g_coord.X = g_srScrollRegion.Right;
4032 g_coord.Y--;
4033 }
4034 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4035#ifdef MCH_WRITE_DUMP
4036 if (fdDump)
4037 fputs("\\b\n", fdDump);
4038#endif
4039 s++;
4040 }
4041 else if (s[0] == '\a')
4042 {
4043 /* \a, bell */
4044 MessageBeep(0xFFFFFFFF);
4045#ifdef MCH_WRITE_DUMP
4046 if (fdDump)
4047 fputs("\\a\n", fdDump);
4048#endif
4049 s++;
4050 }
4051 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4052 {
4053#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004054 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004056 char_u *p;
4057 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058
4059 switch (s[2])
4060 {
4061 /* one or two numeric arguments, separated by ';' */
4062
4063 case '0': case '1': case '2': case '3': case '4':
4064 case '5': case '6': case '7': case '8': case '9':
4065 p = s + 2;
4066 arg1 = getdigits(&p); /* no check for length! */
4067 if (p > s + len)
4068 break;
4069
4070 if (*p == ';')
4071 {
4072 ++p;
4073 arg2 = getdigits(&p); /* no check for length! */
4074 if (p > s + len)
4075 break;
4076
4077 if (*p == 'H')
4078 gotoxy(arg2, arg1);
4079 else if (*p == 'r')
4080 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4081 }
4082 else if (*p == 'A')
4083 {
4084 /* move cursor up arg1 lines in same column */
4085 gotoxy(g_coord.X + 1,
4086 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4087 }
4088 else if (*p == 'C')
4089 {
4090 /* move cursor right arg1 columns in same line */
4091 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4092 g_coord.Y + 1);
4093 }
4094 else if (*p == 'H')
4095 {
4096 gotoxy(1, arg1);
4097 }
4098 else if (*p == 'L')
4099 {
4100 insert_lines(arg1);
4101 }
4102 else if (*p == 'm')
4103 {
4104 if (arg1 == 0)
4105 normvideo();
4106 else
4107 textattr((WORD) arg1);
4108 }
4109 else if (*p == 'f')
4110 {
4111 textcolor((WORD) arg1);
4112 }
4113 else if (*p == 'b')
4114 {
4115 textbackground((WORD) arg1);
4116 }
4117 else if (*p == 'M')
4118 {
4119 delete_lines(arg1);
4120 }
4121
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004122 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123 s = p + 1;
4124 break;
4125
4126
4127 /* Three-character escape sequences */
4128
4129 case 'A':
4130 /* move cursor up one line in same column */
4131 gotoxy(g_coord.X + 1,
4132 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4133 goto got3;
4134
4135 case 'B':
4136 visual_bell();
4137 goto got3;
4138
4139 case 'C':
4140 /* move cursor right one column in same line */
4141 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4142 g_coord.Y + 1);
4143 goto got3;
4144
4145 case 'E':
4146 termcap_mode_end();
4147 goto got3;
4148
4149 case 'F':
4150 standout();
4151 goto got3;
4152
4153 case 'f':
4154 standend();
4155 goto got3;
4156
4157 case 'H':
4158 gotoxy(1, 1);
4159 goto got3;
4160
4161 case 'j':
4162 clear_to_end_of_display();
4163 goto got3;
4164
4165 case 'J':
4166 clear_screen();
4167 goto got3;
4168
4169 case 'K':
4170 clear_to_end_of_line();
4171 goto got3;
4172
4173 case 'L':
4174 insert_lines(1);
4175 goto got3;
4176
4177 case 'M':
4178 delete_lines(1);
4179 goto got3;
4180
4181 case 'S':
4182 termcap_mode_start();
4183 goto got3;
4184
4185 case 'V':
4186 cursor_visible(TRUE);
4187 goto got3;
4188
4189 case 'v':
4190 cursor_visible(FALSE);
4191 goto got3;
4192
4193 got3:
4194 s += 3;
4195 len -= 2;
4196 }
4197
4198#ifdef MCH_WRITE_DUMP
4199 if (fdDump)
4200 {
4201 fputs("ESC | ", fdDump);
4202 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4203 fputc('\n', fdDump);
4204 }
4205#endif
4206 }
4207 else
4208 {
4209 /* Write a single character */
4210 DWORD nWritten;
4211
4212 nWritten = write_chars(s, 1);
4213#ifdef MCH_WRITE_DUMP
4214 if (fdDump)
4215 {
4216 fputc('>', fdDump);
4217 fwrite(s, sizeof(char_u), nWritten, fdDump);
4218 fputs("<\n", fdDump);
4219 }
4220#endif
4221
4222 len -= (nWritten - 1);
4223 s += nWritten;
4224 }
4225 }
4226
4227#ifdef MCH_WRITE_DUMP
4228 if (fdDump)
4229 fflush(fdDump);
4230#endif
4231}
4232
4233#endif /* FEAT_GUI_W32 */
4234
4235
4236/*
4237 * Delay for half a second.
4238 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004239/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004240 void
4241mch_delay(
4242 long msec,
4243 int ignoreinput)
4244{
4245#ifdef FEAT_GUI_W32
4246 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004247#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004248 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004249# ifdef FEAT_MZSCHEME
4250 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4251 {
4252 int towait = p_mzq;
4253
4254 /* if msec is large enough, wait by portions in p_mzq */
4255 while (msec > 0)
4256 {
4257 mzvim_check_threads();
4258 if (msec < towait)
4259 towait = msec;
4260 Sleep(towait);
4261 msec -= towait;
4262 }
4263 }
4264 else
4265# endif
4266 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004267 else
4268 WaitForChar(msec);
4269#endif
4270}
4271
4272
4273/*
4274 * this version of remove is not scared by a readonly (backup) file
4275 * Return 0 for success, -1 for failure.
4276 */
4277 int
4278mch_remove(char_u *name)
4279{
4280#ifdef FEAT_MBYTE
4281 WCHAR *wn = NULL;
4282 int n;
4283
4284 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4285 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004286 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287 if (wn != NULL)
4288 {
4289 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4290 n = DeleteFileW(wn) ? 0 : -1;
4291 vim_free(wn);
4292 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4293 return n;
4294 /* Retry with non-wide function (for Windows 98). */
4295 }
4296 }
4297#endif
4298 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4299 return DeleteFile(name) ? 0 : -1;
4300}
4301
4302
4303/*
4304 * check for an "interrupt signal": CTRL-break or CTRL-C
4305 */
4306 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004307mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004308{
4309#ifndef FEAT_GUI_W32 /* never used */
4310 if (g_fCtrlCPressed || g_fCBrkPressed)
4311 {
4312 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4313 got_int = TRUE;
4314 }
4315#endif
4316}
4317
4318
4319/*
4320 * How much memory is available?
4321 * Return sum of available physical and page file memory.
4322 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004323/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324 long_u
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004325mch_avail_mem(int special)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004326{
4327 MEMORYSTATUS ms;
4328
4329 ms.dwLength = sizeof(MEMORYSTATUS);
4330 GlobalMemoryStatus(&ms);
4331 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
4332}
4333
4334#ifdef FEAT_MBYTE
4335/*
4336 * Same code as below, but with wide functions and no comments.
4337 * Return 0 for success, non-zero for failure.
4338 */
4339 int
4340mch_wrename(WCHAR *wold, WCHAR *wnew)
4341{
4342 WCHAR *p;
4343 int i;
4344 WCHAR szTempFile[_MAX_PATH + 1];
4345 WCHAR szNewPath[_MAX_PATH + 1];
4346 HANDLE hf;
4347
4348 if (!mch_windows95())
4349 {
4350 p = wold;
4351 for (i = 0; wold[i] != NUL; ++i)
4352 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
4353 && wold[i + 1] != 0)
4354 p = wold + i + 1;
4355 if ((int)(wold + i - p) < 8 || p[6] != '~')
4356 return (MoveFileW(wold, wnew) == 0);
4357 }
4358
4359 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
4360 return -1;
4361 *p = NUL;
4362
4363 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
4364 return -2;
4365
4366 if (!DeleteFileW(szTempFile))
4367 return -3;
4368
4369 if (!MoveFileW(wold, szTempFile))
4370 return -4;
4371
4372 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4373 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4374 return -5;
4375 if (!CloseHandle(hf))
4376 return -6;
4377
4378 if (!MoveFileW(szTempFile, wnew))
4379 {
4380 (void)MoveFileW(szTempFile, wold);
4381 return -7;
4382 }
4383
4384 DeleteFileW(szTempFile);
4385
4386 if (!DeleteFileW(wold))
4387 return -8;
4388
4389 return 0;
4390}
4391#endif
4392
4393
4394/*
4395 * mch_rename() works around a bug in rename (aka MoveFile) in
4396 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4397 * file whose short file name is "FOO.BAR" (its long file name will
4398 * be correct: "foo.bar~"). Because a file can be accessed by
4399 * either its SFN or its LFN, "foo.bar" has effectively been
4400 * renamed to "foo.bar", which is not at all what was wanted. This
4401 * seems to happen only when renaming files with three-character
4402 * extensions by appending a suffix that does not include ".".
4403 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4404 *
4405 * There is another problem, which isn't really a bug but isn't right either:
4406 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
4407 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
4408 * service pack 6. Doesn't seem to happen on Windows 98.
4409 *
4410 * Like rename(), returns 0 upon success, non-zero upon failure.
4411 * Should probably set errno appropriately when errors occur.
4412 */
4413 int
4414mch_rename(
4415 const char *pszOldFile,
4416 const char *pszNewFile)
4417{
4418 char szTempFile[_MAX_PATH+1];
4419 char szNewPath[_MAX_PATH+1];
4420 char *pszFilePart;
4421 HANDLE hf;
4422#ifdef FEAT_MBYTE
4423 WCHAR *wold = NULL;
4424 WCHAR *wnew = NULL;
4425 int retval = -1;
4426
4427 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4428 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004429 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
4430 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431 if (wold != NULL && wnew != NULL)
4432 retval = mch_wrename(wold, wnew);
4433 vim_free(wold);
4434 vim_free(wnew);
4435 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4436 return retval;
4437 /* Retry with non-wide function (for Windows 98). */
4438 }
4439#endif
4440
4441 /*
4442 * No need to play tricks if not running Windows 95, unless the file name
4443 * contains a "~" as the seventh character.
4444 */
4445 if (!mch_windows95())
4446 {
4447 pszFilePart = (char *)gettail((char_u *)pszOldFile);
4448 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
4449 return rename(pszOldFile, pszNewFile);
4450 }
4451
4452 /* Get base path of new file name. Undocumented feature: If pszNewFile is
4453 * a directory, no error is returned and pszFilePart will be NULL. */
4454 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
4455 || pszFilePart == NULL)
4456 return -1;
4457 *pszFilePart = NUL;
4458
4459 /* Get (and create) a unique temporary file name in directory of new file */
4460 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
4461 return -2;
4462
4463 /* blow the temp file away */
4464 if (!DeleteFile(szTempFile))
4465 return -3;
4466
4467 /* rename old file to the temp file */
4468 if (!MoveFile(pszOldFile, szTempFile))
4469 return -4;
4470
4471 /* now create an empty file called pszOldFile; this prevents the operating
4472 * system using pszOldFile as an alias (SFN) if we're renaming within the
4473 * same directory. For example, we're editing a file called
4474 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
4475 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
4476 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004477 * cause all sorts of problems later in buf_write(). So, we create an
4478 * empty file called filena~1.txt and the system will have to find some
4479 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480 */
4481 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4482 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4483 return -5;
4484 if (!CloseHandle(hf))
4485 return -6;
4486
4487 /* rename the temp file to the new file */
4488 if (!MoveFile(szTempFile, pszNewFile))
4489 {
4490 /* Renaming failed. Rename the file back to its old name, so that it
4491 * looks like nothing happened. */
4492 (void)MoveFile(szTempFile, pszOldFile);
4493
4494 return -7;
4495 }
4496
4497 /* Seems to be left around on Novell filesystems */
4498 DeleteFile(szTempFile);
4499
4500 /* finally, remove the empty old file */
4501 if (!DeleteFile(pszOldFile))
4502 return -8;
4503
4504 return 0; /* success */
4505}
4506
4507/*
4508 * Get the default shell for the current hardware platform
4509 */
4510 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004511default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004512{
4513 char* psz = NULL;
4514
4515 PlatformId();
4516
4517 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
4518 psz = "cmd.exe";
4519 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
4520 psz = "command.com";
4521
4522 return psz;
4523}
4524
4525/*
4526 * mch_access() extends access() to do more detailed check on network drives.
4527 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
4528 */
4529 int
4530mch_access(char *n, int p)
4531{
4532 HANDLE hFile;
4533 DWORD am;
4534 int retval = -1; /* default: fail */
4535#ifdef FEAT_MBYTE
4536 WCHAR *wn = NULL;
4537
4538 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004539 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004540#endif
4541
4542 if (mch_isdir(n))
4543 {
4544 char TempName[_MAX_PATH + 16] = "";
4545#ifdef FEAT_MBYTE
4546 WCHAR TempNameW[_MAX_PATH + 16] = L"";
4547#endif
4548
4549 if (p & R_OK)
4550 {
4551 /* Read check is performed by seeing if we can do a find file on
4552 * the directory for any file. */
4553#ifdef FEAT_MBYTE
4554 if (wn != NULL)
4555 {
4556 int i;
4557 WIN32_FIND_DATAW d;
4558
4559 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
4560 TempNameW[i] = wn[i];
4561 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
4562 TempNameW[i++] = '\\';
4563 TempNameW[i++] = '*';
4564 TempNameW[i++] = 0;
4565
4566 hFile = FindFirstFileW(TempNameW, &d);
4567 if (hFile == INVALID_HANDLE_VALUE)
4568 {
4569 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4570 goto getout;
4571
4572 /* Retry with non-wide function (for Windows 98). */
4573 vim_free(wn);
4574 wn = NULL;
4575 }
4576 else
4577 (void)FindClose(hFile);
4578 }
4579 if (wn == NULL)
4580#endif
4581 {
4582 char *pch;
4583 WIN32_FIND_DATA d;
4584
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00004585 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004586 pch = TempName + STRLEN(TempName) - 1;
4587 if (*pch != '\\' && *pch != '/')
4588 *++pch = '\\';
4589 *++pch = '*';
4590 *++pch = NUL;
4591
4592 hFile = FindFirstFile(TempName, &d);
4593 if (hFile == INVALID_HANDLE_VALUE)
4594 goto getout;
4595 (void)FindClose(hFile);
4596 }
4597 }
4598
4599 if (p & W_OK)
4600 {
4601 /* Trying to create a temporary file in the directory should catch
4602 * directories on read-only network shares. However, in
4603 * directories whose ACL allows writes but denies deletes will end
4604 * up keeping the temporary file :-(. */
4605#ifdef FEAT_MBYTE
4606 if (wn != NULL)
4607 {
4608 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
4609 {
4610 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4611 goto getout;
4612
4613 /* Retry with non-wide function (for Windows 98). */
4614 vim_free(wn);
4615 wn = NULL;
4616 }
4617 else
4618 DeleteFileW(TempNameW);
4619 }
4620 if (wn == NULL)
4621#endif
4622 {
4623 if (!GetTempFileName(n, "VIM", 0, TempName))
4624 goto getout;
4625 mch_remove((char_u *)TempName);
4626 }
4627 }
4628 }
4629 else
4630 {
4631 /* Trying to open the file for the required access does ACL, read-only
4632 * network share, and file attribute checks. */
4633 am = ((p & W_OK) ? GENERIC_WRITE : 0)
4634 | ((p & R_OK) ? GENERIC_READ : 0);
4635#ifdef FEAT_MBYTE
4636 if (wn != NULL)
4637 {
4638 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4639 if (hFile == INVALID_HANDLE_VALUE
4640 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4641 {
4642 /* Retry with non-wide function (for Windows 98). */
4643 vim_free(wn);
4644 wn = NULL;
4645 }
4646 }
4647 if (wn == NULL)
4648#endif
4649 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4650 if (hFile == INVALID_HANDLE_VALUE)
4651 goto getout;
4652 CloseHandle(hFile);
4653 }
4654
4655 retval = 0; /* success */
4656getout:
4657#ifdef FEAT_MBYTE
4658 vim_free(wn);
4659#endif
4660 return retval;
4661}
4662
4663#if defined(FEAT_MBYTE) || defined(PROTO)
4664/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004665 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004666 */
4667 int
4668mch_open(char *name, int flags, int mode)
4669{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004670 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
4671# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672 WCHAR *wn;
4673 int f;
4674
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004675 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004676 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004677 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678 if (wn != NULL)
4679 {
4680 f = _wopen(wn, flags, mode);
4681 vim_free(wn);
4682 if (f >= 0)
4683 return f;
4684 /* Retry with non-wide function (for Windows 98). Can't use
4685 * GetLastError() here and it's unclear what errno gets set to if
4686 * the _wopen() fails for missing wide functions. */
4687 }
4688 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004689# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004690
4691 return open(name, flags, mode);
4692}
4693
4694/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004695 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004696 */
4697 FILE *
4698mch_fopen(char *name, char *mode)
4699{
4700 WCHAR *wn, *wm;
4701 FILE *f = NULL;
4702
4703 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
4704# ifdef __BORLANDC__
4705 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4706 && g_PlatformId == VER_PLATFORM_WIN32_NT
4707# endif
4708 )
4709 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00004710# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004711 /* Work around an annoying assertion in the Microsoft debug CRT
4712 * when mode's text/binary setting doesn't match _get_fmode(). */
4713 char newMode = mode[strlen(mode) - 1];
4714 int oldMode = 0;
4715
4716 _get_fmode(&oldMode);
4717 if (newMode == 't')
4718 _set_fmode(_O_TEXT);
4719 else if (newMode == 'b')
4720 _set_fmode(_O_BINARY);
4721# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004722 wn = enc_to_utf16(name, NULL);
4723 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 if (wn != NULL && wm != NULL)
4725 f = _wfopen(wn, wm);
4726 vim_free(wn);
4727 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004728
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00004729# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004730 _set_fmode(oldMode);
4731# endif
4732
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733 if (f != NULL)
4734 return f;
4735 /* Retry with non-wide function (for Windows 98). Can't use
4736 * GetLastError() here and it's unclear what errno gets set to if
4737 * the _wfopen() fails for missing wide functions. */
4738 }
4739
4740 return fopen(name, mode);
4741}
4742#endif
4743
4744#ifdef FEAT_MBYTE
4745/*
4746 * SUB STREAM (aka info stream) handling:
4747 *
4748 * NTFS can have sub streams for each file. Normal contents of file is
4749 * stored in the main stream, and extra contents (author information and
4750 * title and so on) can be stored in sub stream. After Windows 2000, user
4751 * can access and store those informations in sub streams via explorer's
4752 * property menuitem in right click menu. Those informations in sub streams
4753 * were lost when copying only the main stream. So we have to copy sub
4754 * streams.
4755 *
4756 * Incomplete explanation:
4757 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
4758 * More useful info and an example:
4759 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
4760 */
4761
4762/*
4763 * Copy info stream data "substream". Read from the file with BackupRead(sh)
4764 * and write to stream "substream" of file "to".
4765 * Errors are ignored.
4766 */
4767 static void
4768copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
4769{
4770 HANDLE hTo;
4771 WCHAR *to_name;
4772
4773 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
4774 wcscpy(to_name, to);
4775 wcscat(to_name, substream);
4776
4777 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
4778 FILE_ATTRIBUTE_NORMAL, NULL);
4779 if (hTo != INVALID_HANDLE_VALUE)
4780 {
4781 long done;
4782 DWORD todo;
4783 DWORD readcnt, written;
4784 char buf[4096];
4785
4786 /* Copy block of bytes at a time. Abort when something goes wrong. */
4787 for (done = 0; done < len; done += written)
4788 {
4789 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004790 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
4791 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
4793 FALSE, FALSE, context)
4794 || readcnt != todo
4795 || !WriteFile(hTo, buf, todo, &written, NULL)
4796 || written != todo)
4797 break;
4798 }
4799 CloseHandle(hTo);
4800 }
4801
4802 free(to_name);
4803}
4804
4805/*
4806 * Copy info streams from file "from" to file "to".
4807 */
4808 static void
4809copy_infostreams(char_u *from, char_u *to)
4810{
4811 WCHAR *fromw;
4812 WCHAR *tow;
4813 HANDLE sh;
4814 WIN32_STREAM_ID sid;
4815 int headersize;
4816 WCHAR streamname[_MAX_PATH];
4817 DWORD readcount;
4818 void *context = NULL;
4819 DWORD lo, hi;
4820 int len;
4821
4822 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004823 fromw = enc_to_utf16(from, NULL);
4824 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825 if (fromw != NULL && tow != NULL)
4826 {
4827 /* Open the file for reading. */
4828 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
4829 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4830 if (sh != INVALID_HANDLE_VALUE)
4831 {
4832 /* Use BackupRead() to find the info streams. Repeat until we
4833 * have done them all.*/
4834 for (;;)
4835 {
4836 /* Get the header to find the length of the stream name. If
4837 * the "readcount" is zero we have done all info streams. */
4838 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004839 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004840 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
4841 &readcount, FALSE, FALSE, &context)
4842 || readcount == 0)
4843 break;
4844
4845 /* We only deal with streams that have a name. The normal
4846 * file data appears to be without a name, even though docs
4847 * suggest it is called "::$DATA". */
4848 if (sid.dwStreamNameSize > 0)
4849 {
4850 /* Read the stream name. */
4851 if (!BackupRead(sh, (LPBYTE)streamname,
4852 sid.dwStreamNameSize,
4853 &readcount, FALSE, FALSE, &context))
4854 break;
4855
4856 /* Copy an info stream with a name ":anything:$DATA".
4857 * Skip "::$DATA", it has no stream name (examples suggest
4858 * it might be used for the normal file contents).
4859 * Note that BackupRead() counts bytes, but the name is in
4860 * wide characters. */
4861 len = readcount / sizeof(WCHAR);
4862 streamname[len] = 0;
4863 if (len > 7 && wcsicmp(streamname + len - 6,
4864 L":$DATA") == 0)
4865 {
4866 streamname[len - 6] = 0;
4867 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004868 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004869 }
4870 }
4871
4872 /* Advance to the next stream. We might try seeking too far,
4873 * but BackupSeek() doesn't skip over stream borders, thus
4874 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004875 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004876 &lo, &hi, &context);
4877 }
4878
4879 /* Clear the context. */
4880 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
4881
4882 CloseHandle(sh);
4883 }
4884 }
4885 vim_free(fromw);
4886 vim_free(tow);
4887}
4888#endif
4889
4890/*
4891 * Copy file attributes from file "from" to file "to".
4892 * For Windows NT and later we copy info streams.
4893 * Always returns zero, errors are ignored.
4894 */
4895 int
4896mch_copy_file_attribute(char_u *from, char_u *to)
4897{
4898#ifdef FEAT_MBYTE
4899 /* File streams only work on Windows NT and later. */
4900 PlatformId();
4901 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
4902 copy_infostreams(from, to);
4903#endif
4904 return 0;
4905}
4906
4907#if defined(MYRESETSTKOFLW) || defined(PROTO)
4908/*
4909 * Recreate a destroyed stack guard page in win32.
4910 * Written by Benjamin Peterson.
4911 */
4912
4913/* These magic numbers are from the MS header files */
4914#define MIN_STACK_WIN9X 17
4915#define MIN_STACK_WINNT 2
4916
4917/*
4918 * This function does the same thing as _resetstkoflw(), which is only
4919 * available in DevStudio .net and later.
4920 * Returns 0 for failure, 1 for success.
4921 */
4922 int
4923myresetstkoflw(void)
4924{
4925 BYTE *pStackPtr;
4926 BYTE *pGuardPage;
4927 BYTE *pStackBase;
4928 BYTE *pLowestPossiblePage;
4929 MEMORY_BASIC_INFORMATION mbi;
4930 SYSTEM_INFO si;
4931 DWORD nPageSize;
4932 DWORD dummy;
4933
4934 /* This code will not work on win32s. */
4935 PlatformId();
4936 if (g_PlatformId == VER_PLATFORM_WIN32s)
4937 return 0;
4938
4939 /* We need to know the system page size. */
4940 GetSystemInfo(&si);
4941 nPageSize = si.dwPageSize;
4942
4943 /* ...and the current stack pointer */
4944 pStackPtr = (BYTE*)_alloca(1);
4945
4946 /* ...and the base of the stack. */
4947 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
4948 return 0;
4949 pStackBase = (BYTE*)mbi.AllocationBase;
4950
4951 /* ...and the page thats min_stack_req pages away from stack base; this is
4952 * the lowest page we could use. */
4953 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
4954 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
4955
4956 /* On Win95, we want the next page down from the end of the stack. */
4957 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
4958 {
4959 /* Find the page that's only 1 page down from the page that the stack
4960 * ptr is in. */
4961 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
4962 / (DWORD)nPageSize) - 1));
4963 if (pGuardPage < pLowestPossiblePage)
4964 return 0;
4965
4966 /* Apply the noaccess attribute to the page -- there's no guard
4967 * attribute in win95-type OSes. */
4968 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
4969 return 0;
4970 }
4971 else
4972 {
4973 /* On NT, however, we want the first committed page in the stack Start
4974 * at the stack base and move forward through memory until we find a
4975 * committed block. */
4976 BYTE *pBlock = pStackBase;
4977
Bram Moolenaara466c992005-07-09 21:03:22 +00004978 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979 {
4980 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
4981 return 0;
4982
4983 pBlock += mbi.RegionSize;
4984
4985 if (mbi.State & MEM_COMMIT)
4986 break;
4987 }
4988
4989 /* mbi now describes the first committed block in the stack. */
4990 if (mbi.Protect & PAGE_GUARD)
4991 return 1;
4992
4993 /* decide where the guard page should start */
4994 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
4995 pGuardPage = pLowestPossiblePage;
4996 else
4997 pGuardPage = (BYTE*)mbi.BaseAddress;
4998
4999 /* allocate the guard page */
5000 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
5001 return 0;
5002
5003 /* apply the guard attribute to the page */
5004 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
5005 &dummy))
5006 return 0;
5007 }
5008
5009 return 1;
5010}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005011#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005012
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005013
5014#if defined(FEAT_MBYTE) || defined(PROTO)
5015/*
5016 * The command line arguments in UCS2
5017 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005018static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005019static LPWSTR *ArglistW = NULL;
5020static int global_argc = 0;
5021static char **global_argv;
5022
5023static int used_file_argc = 0; /* last argument in global_argv[] used
5024 for the argument list. */
5025static int *used_file_indexes = NULL; /* indexes in global_argv[] for
5026 command line arguments added to
5027 the argument list */
5028static int used_file_count = 0; /* nr of entries in used_file_indexes */
5029static int used_file_literal = FALSE; /* take file names literally */
5030static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005031static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005032static int used_alist_count = 0;
5033
5034
5035/*
5036 * Get the command line arguments. Unicode version.
5037 * Returns argc. Zero when something fails.
5038 */
5039 int
5040get_cmd_argsW(char ***argvp)
5041{
5042 char **argv = NULL;
5043 int argc = 0;
5044 int i;
5045
5046 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5047 if (ArglistW != NULL)
5048 {
5049 argv = malloc((nArgsW + 1) * sizeof(char *));
5050 if (argv != NULL)
5051 {
5052 argc = nArgsW;
5053 argv[argc] = NULL;
5054 for (i = 0; i < argc; ++i)
5055 {
5056 int len;
5057
5058 /* Convert each Unicode argument to the current codepage. */
5059 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005060 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005061 (LPSTR *)&argv[i], &len, 0, 0);
5062 if (argv[i] == NULL)
5063 {
5064 /* Out of memory, clear everything. */
5065 while (i > 0)
5066 free(argv[--i]);
5067 free(argv);
5068 argc = 0;
5069 }
5070 }
5071 }
5072 }
5073
5074 global_argc = argc;
5075 global_argv = argv;
5076 if (argc > 0)
5077 used_file_indexes = malloc(argc * sizeof(int));
5078
5079 if (argvp != NULL)
5080 *argvp = argv;
5081 return argc;
5082}
5083
5084 void
5085free_cmd_argsW(void)
5086{
5087 if (ArglistW != NULL)
5088 {
5089 GlobalFree(ArglistW);
5090 ArglistW = NULL;
5091 }
5092}
5093
5094/*
5095 * Remember "name" is an argument that was added to the argument list.
5096 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5097 * is called.
5098 */
5099 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005100used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005101{
5102 int i;
5103
5104 if (used_file_indexes == NULL)
5105 return;
5106 for (i = used_file_argc + 1; i < global_argc; ++i)
5107 if (STRCMP(global_argv[i], name) == 0)
5108 {
5109 used_file_argc = i;
5110 used_file_indexes[used_file_count++] = i;
5111 break;
5112 }
5113 used_file_literal = literal;
5114 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005115 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005116}
5117
5118/*
5119 * Remember the length of the argument list as it was. If it changes then we
5120 * leave it alone when 'encoding' is set.
5121 */
5122 void
5123set_alist_count(void)
5124{
5125 used_alist_count = GARGCOUNT;
5126}
5127
5128/*
5129 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5130 * has been changed while starting up. Use the UCS-2 command line arguments
5131 * and convert them to 'encoding'.
5132 */
5133 void
5134fix_arg_enc(void)
5135{
5136 int i;
5137 int idx;
5138 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005139 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005140
5141 /* Safety checks:
5142 * - if argument count differs between the wide and non-wide argument
5143 * list, something must be wrong.
5144 * - the file name arguments must have been located.
5145 * - the length of the argument list wasn't changed by the user.
5146 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005147 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005148 || ArglistW == NULL
5149 || used_file_indexes == NULL
5150 || used_file_count == 0
5151 || used_alist_count != GARGCOUNT)
5152 return;
5153
Bram Moolenaar86b68352004-12-27 21:59:20 +00005154 /* Remember the buffer numbers for the arguments. */
5155 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5156 if (fnum_list == NULL)
5157 return; /* out of memory */
5158 for (i = 0; i < GARGCOUNT; ++i)
5159 fnum_list[i] = GARGLIST[i].ae_fnum;
5160
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005161 /* Clear the argument list. Make room for the new arguments. */
5162 alist_clear(&global_alist);
5163 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005164 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005165
5166 for (i = 0; i < used_file_count; ++i)
5167 {
5168 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005169 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005170 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005171 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005172#ifdef FEAT_DIFF
5173 /* When using diff mode may need to concatenate file name to
5174 * directory name. Just like it's done in main(). */
5175 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5176 && !mch_isdir(alist_name(&GARGLIST[0])))
5177 {
5178 char_u *r;
5179
5180 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5181 if (r != NULL)
5182 {
5183 vim_free(str);
5184 str = r;
5185 }
5186 }
5187#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005188 /* Re-use the old buffer by renaming it. When not using literal
5189 * names it's done by alist_expand() below. */
5190 if (used_file_literal)
5191 buf_set_name(fnum_list[i], str);
5192
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005193 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005194 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005195 }
5196
5197 if (!used_file_literal)
5198 {
5199 /* Now expand wildcards in the arguments. */
5200 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5201 * filename characters but are excluded from 'isfname' to make
5202 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5203 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005204 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005205 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5206 }
5207
5208 /* If wildcard expansion failed, we are editing the first file of the
5209 * arglist and there is no file name: Edit the first argument now. */
5210 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5211 {
5212 do_cmdline_cmd((char_u *)":rewind");
5213 if (GARGCOUNT == 1 && used_file_full_path)
5214 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5215 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005216
5217 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005218}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219#endif