blob: f4d43442d85e77647c9990bb75e5cec54b022442 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
53#ifdef __MINGW32__
54# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
55# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
56# endif
57# ifndef RIGHTMOST_BUTTON_PRESSED
58# define RIGHTMOST_BUTTON_PRESSED 0x0002
59# endif
60# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
61# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
62# endif
63# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
64# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
65# endif
66# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
67# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
68# endif
69
70/*
71 * EventFlags
72 */
73# ifndef MOUSE_MOVED
74# define MOUSE_MOVED 0x0001
75# endif
76# ifndef DOUBLE_CLICK
77# define DOUBLE_CLICK 0x0002
78# endif
79#endif
80
81/* Record all output and all keyboard & mouse input */
82/* #define MCH_WRITE_DUMP */
83
84#ifdef MCH_WRITE_DUMP
85FILE* fdDump = NULL;
86#endif
87
88/*
89 * When generating prototypes for Win32 on Unix, these lines make the syntax
90 * errors disappear. They do not need to be correct.
91 */
92#ifdef PROTO
93#define WINAPI
94#define WINBASEAPI
95typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000096typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000097typedef int ACCESS_MASK;
98typedef int BOOL;
99typedef int COLORREF;
100typedef int CONSOLE_CURSOR_INFO;
101typedef int COORD;
102typedef int DWORD;
103typedef int HANDLE;
104typedef int HDC;
105typedef int HFONT;
106typedef int HICON;
107typedef int HINSTANCE;
108typedef int HWND;
109typedef int INPUT_RECORD;
110typedef int KEY_EVENT_RECORD;
111typedef int LOGFONT;
112typedef int LPBOOL;
113typedef int LPCTSTR;
114typedef int LPDWORD;
115typedef int LPSTR;
116typedef int LPTSTR;
117typedef int LPVOID;
118typedef int MOUSE_EVENT_RECORD;
119typedef int PACL;
120typedef int PDWORD;
121typedef int PHANDLE;
122typedef int PRINTDLG;
123typedef int PSECURITY_DESCRIPTOR;
124typedef int PSID;
125typedef int SECURITY_INFORMATION;
126typedef int SHORT;
127typedef int SMALL_RECT;
128typedef int TEXTMETRIC;
129typedef int TOKEN_INFORMATION_CLASS;
130typedef int TRUSTEE;
131typedef int WORD;
132typedef int WCHAR;
133typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100134typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200135typedef int SE_OBJECT_TYPE;
136typedef int PSNSECINFO;
137typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100138typedef int STARTUPINFO;
139typedef int PROCESS_INFORMATION;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140#endif
141
142#ifndef FEAT_GUI_W32
143/* Undocumented API in kernel32.dll needed to work around dead key bug in
144 * console-mode applications in NT 4.0. If you switch keyboard layouts
145 * in a console app to a layout that includes dead keys and then hit a
146 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
147 * and Michael Dietrich for helping me figure out this workaround.
148 */
149
150/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
151#ifndef WINBASEAPI
152# define WINBASEAPI __stdcall
153#endif
154#if defined(__BORLANDC__)
155typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
156#else
157typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
158#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000159static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160#endif
161
162#if defined(__BORLANDC__)
163/* Strangely Borland uses a non-standard name. */
164# define wcsicmp(a, b) wcscmpi((a), (b))
165#endif
166
Bram Moolenaar82881492012-11-20 16:53:39 +0100167#ifndef PROTO
168
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200169/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200170#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100171LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200172BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
173BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
174BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
175#endif
176
Bram Moolenaar82881492012-11-20 16:53:39 +0100177#endif /* PROTO */
178
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179#ifndef FEAT_GUI_W32
180/* Win32 Console handles for input and output */
181static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
182static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
183
184/* Win32 Screen buffer,coordinate,console I/O information */
185static SMALL_RECT g_srScrollRegion;
186static COORD g_coord; /* 0-based, but external coords are 1-based */
187
188/* The attribute of the screen when the editor was started */
189static WORD g_attrDefault = 7; /* lightgray text on black background */
190static WORD g_attrCurrent;
191
192static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
193static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
194static int g_fForceExit = FALSE; /* set when forcefully exiting */
195
196static void termcap_mode_start(void);
197static void termcap_mode_end(void);
198static void clear_chars(COORD coord, DWORD n);
199static void clear_screen(void);
200static void clear_to_end_of_display(void);
201static void clear_to_end_of_line(void);
202static void scroll(unsigned cLines);
203static void set_scroll_region(unsigned left, unsigned top,
204 unsigned right, unsigned bottom);
205static void insert_lines(unsigned cLines);
206static void delete_lines(unsigned cLines);
207static void gotoxy(unsigned x, unsigned y);
208static void normvideo(void);
209static void textattr(WORD wAttr);
210static void textcolor(WORD wAttr);
211static void textbackground(WORD wAttr);
212static void standout(void);
213static void standend(void);
214static void visual_bell(void);
215static void cursor_visible(BOOL fVisible);
216static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
217static char_u tgetch(int *pmodifiers, char_u *pch2);
218static void create_conin(void);
219static int s_cursor_visible = TRUE;
220static int did_create_conin = FALSE;
221#else
222static int s_dont_use_vimrun = TRUE;
223static int need_vimrun_warning = FALSE;
224static char *vimrun_path = "vimrun ";
225#endif
226
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200227static int win32_getattrs(char_u *name);
228static int win32_setattrs(char_u *name, int attrs);
229static int win32_set_archive(char_u *name);
230
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231#ifndef FEAT_GUI_W32
232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100239/*
240 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100241 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100242 */
243 static BOOL
244read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100245 HANDLE hInput,
246 INPUT_RECORD *lpBuffer,
247 DWORD nLength,
248 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100249{
250 enum
251 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100252 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100253 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100254 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100255 static DWORD s_dwIndex = 0;
256 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100257 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100258 int head;
259 int tail;
260 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100261
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100262 if (!win8_or_later)
263 {
264 if (nLength == -1)
265 return PeekConsoleInput(hInput, lpBuffer, 1, lpEvents);
266 return ReadConsoleInput(hInput, lpBuffer, 1, &dwEvents);
267 }
268
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100269 if (s_dwMax == 0)
270 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100271 if (nLength == -1)
272 return PeekConsoleInput(hInput, lpBuffer, 1, lpEvents);
273 if (!ReadConsoleInput(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100274 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100275 s_dwIndex = 0;
276 s_dwMax = dwEvents;
277 if (dwEvents == 0)
278 {
279 *lpEvents = 0;
280 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100281 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100282
283 if (s_dwMax > 1)
284 {
285 head = 0;
286 tail = s_dwMax - 1;
287 while (head != tail)
288 {
289 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
290 && s_irCache[head + 1].EventType
291 == WINDOW_BUFFER_SIZE_EVENT)
292 {
293 /* Remove duplicate event to avoid flicker. */
294 for (i = head; i < tail; ++i)
295 s_irCache[i] = s_irCache[i + 1];
296 --tail;
297 continue;
298 }
299 head++;
300 }
301 s_dwMax = tail + 1;
302 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100303 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100304
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100305 *lpBuffer = s_irCache[s_dwIndex];
306 if (nLength != -1 && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100307 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100308 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100309 return TRUE;
310}
311
312/*
313 * Version of PeekConsoleInput() that works with IME.
314 */
315 static BOOL
316peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100317 HANDLE hInput,
318 INPUT_RECORD *lpBuffer,
319 DWORD nLength,
320 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100322 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100323}
324
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325 static void
326get_exe_name(void)
327{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100328 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
329 * as the maximum length that works (plus a NUL byte). */
330#define MAX_ENV_PATH_LEN 8192
331 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200332 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000333
334 if (exe_name == NULL)
335 {
336 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100337 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000338 if (*temp != NUL)
339 exe_name = FullName_save((char_u *)temp, FALSE);
340 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000341
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200342 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000343 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200344 exe_path = vim_strnsave(exe_name,
345 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200346 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000347 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200348 /* Append our starting directory to $PATH, so that when doing
349 * "!xxd" it's found in our starting directory. Needed because
350 * SearchPath() also looks there. */
351 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100352 if (p == NULL
353 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200354 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100355 if (p == NULL || *p == NUL)
356 temp[0] = NUL;
357 else
358 {
359 STRCPY(temp, p);
360 STRCAT(temp, ";");
361 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200362 STRCAT(temp, exe_path);
363 vim_setenv((char_u *)"PATH", temp);
364 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000365 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000366 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367}
368
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200369/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100370 * Unescape characters in "p" that appear in "escaped".
371 */
372 static void
373unescape_shellxquote(char_u *p, char_u *escaped)
374{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100375 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100376 int n;
377
378 while (*p != NUL)
379 {
380 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
381 mch_memmove(p, p + 1, l--);
382#ifdef FEAT_MBYTE
383 n = (*mb_ptr2len)(p);
384#else
385 n = 1;
386#endif
387 p += n;
388 l -= n;
389 }
390}
391
392/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200393 * Load library "name".
394 */
395 HINSTANCE
396vimLoadLib(char *name)
397{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200398 HINSTANCE dll = NULL;
399 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200400
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200401 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
402 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200403 if (exe_path == NULL)
404 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200405 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200406 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200407#ifdef FEAT_MBYTE
408 WCHAR old_dirw[MAXPATHL];
409
410 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
411 {
412 /* Change directory to where the executable is, both to make
413 * sure we find a .dll there and to avoid looking for a .dll
414 * in the current directory. */
415 SetCurrentDirectory(exe_path);
416 dll = LoadLibrary(name);
417 SetCurrentDirectoryW(old_dirw);
418 return dll;
419 }
420 /* Retry with non-wide function (for Windows 98). */
421 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
422#endif
423 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
424 {
425 /* Change directory to where the executable is, both to make
426 * sure we find a .dll there and to avoid looking for a .dll
427 * in the current directory. */
428 SetCurrentDirectory(exe_path);
429 dll = LoadLibrary(name);
430 SetCurrentDirectory(old_dir);
431 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200432 }
433 return dll;
434}
435
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
437# ifndef GETTEXT_DLL
438# define GETTEXT_DLL "libintl.dll"
439# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200440/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000441static char *null_libintl_gettext(const char *);
442static char *null_libintl_textdomain(const char *);
443static char *null_libintl_bindtextdomain(const char *, const char *);
444static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200446static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000447char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
448char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
449char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000451char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
452 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000453
454 int
455dyn_libintl_init(char *libname)
456{
457 int i;
458 static struct
459 {
460 char *name;
461 FARPROC *ptr;
462 } libintl_entry[] =
463 {
464 {"gettext", (FARPROC*)&dyn_libintl_gettext},
465 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
466 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
467 {NULL, NULL}
468 };
469
470 /* No need to initialize twice. */
471 if (hLibintlDLL)
472 return 1;
473 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 if (!hLibintlDLL)
476 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 verbose_enter();
480 EMSG2(_(e_loadlib), GETTEXT_DLL);
481 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200483 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 }
485 for (i = 0; libintl_entry[i].name != NULL
486 && libintl_entry[i].ptr != NULL; ++i)
487 {
488 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
489 libintl_entry[i].name)) == NULL)
490 {
491 dyn_libintl_end();
492 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000493 {
494 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000496 verbose_leave();
497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498 return 0;
499 }
500 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000501
502 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000503 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000504 "bind_textdomain_codeset");
505 if (dyn_libintl_bind_textdomain_codeset == NULL)
506 dyn_libintl_bind_textdomain_codeset =
507 null_libintl_bind_textdomain_codeset;
508
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 return 1;
510}
511
512 void
513dyn_libintl_end()
514{
515 if (hLibintlDLL)
516 FreeLibrary(hLibintlDLL);
517 hLibintlDLL = NULL;
518 dyn_libintl_gettext = null_libintl_gettext;
519 dyn_libintl_textdomain = null_libintl_textdomain;
520 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000521 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522}
523
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000524/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000526null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000527{
528 return (char*)msgid;
529}
530
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000531/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000533null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000534{
535 return NULL;
536}
537
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000538/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000539 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000540null_libintl_bind_textdomain_codeset(const char *domainname,
541 const char *codeset)
542{
543 return NULL;
544}
545
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000546/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000547 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000548null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549{
550 return NULL;
551}
552
553#endif /* DYNAMIC_GETTEXT */
554
555/* This symbol is not defined in older versions of the SDK or Visual C++ */
556
557#ifndef VER_PLATFORM_WIN32_WINDOWS
558# define VER_PLATFORM_WIN32_WINDOWS 1
559#endif
560
561DWORD g_PlatformId;
562
563#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100564# ifndef PROTO
565# include <aclapi.h>
566# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200567# ifndef PROTECTED_DACL_SECURITY_INFORMATION
568# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
569# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100570
Bram Moolenaar071d4272004-06-13 20:20:40 +0000571/*
572 * These are needed to dynamically load the ADVAPI DLL, which is not
573 * implemented under Windows 95 (and causes VIM to crash)
574 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200575typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200577typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
579 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200580# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200581typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200582 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200583typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200584 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
585 PSECURITY_DESCRIPTOR *);
586# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587
588static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
589static PSNSECINFO pSetNamedSecurityInfo;
590static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200591# ifdef FEAT_MBYTE
592static PSNSECINFOW pSetNamedSecurityInfoW;
593static PGNSECINFOW pGetNamedSecurityInfoW;
594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000595#endif
596
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200597typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
598
599static BOOL allowPiping = FALSE;
600static PSETHANDLEINFORMATION pSetHandleInformation;
601
Bram Moolenaar27515922013-06-29 15:36:26 +0200602#ifdef HAVE_ACL
603/*
604 * Enables or disables the specified privilege.
605 */
606 static BOOL
607win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
608{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100609 BOOL bResult;
610 LUID luid;
611 HANDLE hToken;
612 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200613
614 if (!OpenProcessToken(GetCurrentProcess(),
615 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
616 return FALSE;
617
618 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
619 {
620 CloseHandle(hToken);
621 return FALSE;
622 }
623
Bram Moolenaar45500912014-07-09 20:51:07 +0200624 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200625 tokenPrivileges.Privileges[0].Luid = luid;
626 tokenPrivileges.Privileges[0].Attributes = bEnable ?
627 SE_PRIVILEGE_ENABLED : 0;
628
629 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
630 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
631
632 CloseHandle(hToken);
633
634 return bResult && GetLastError() == ERROR_SUCCESS;
635}
636#endif
637
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638/*
639 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
640 * VER_PLATFORM_WIN32_WINDOWS (Win95).
641 */
642 void
643PlatformId(void)
644{
645 static int done = FALSE;
646
647 if (!done)
648 {
649 OSVERSIONINFO ovi;
650
651 ovi.dwOSVersionInfoSize = sizeof(ovi);
652 GetVersionEx(&ovi);
653
654 g_PlatformId = ovi.dwPlatformId;
655
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100656 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
657 || ovi.dwMajorVersion > 6)
658 win8_or_later = TRUE;
659
Bram Moolenaar071d4272004-06-13 20:20:40 +0000660#ifdef HAVE_ACL
661 /*
662 * Load the ADVAPI runtime if we are on anything
663 * other than Windows 95
664 */
665 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
666 {
667 /*
668 * do this load. Problems: Doesn't unload at end of run (this is
669 * theoretically okay, since Windows should unload it when VIM
670 * terminates). Should we be using the 'mch_libcall' routines?
671 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
672 * time we verify security...
673 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200674 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675 if (advapi_lib != NULL)
676 {
677 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
678 "SetNamedSecurityInfoA");
679 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
680 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200681# ifdef FEAT_MBYTE
682 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
683 "SetNamedSecurityInfoW");
684 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
685 "GetNamedSecurityInfoW");
686# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200688 || pGetNamedSecurityInfo == NULL
689# ifdef FEAT_MBYTE
690 || pSetNamedSecurityInfoW == NULL
691 || pGetNamedSecurityInfoW == NULL
692# endif
693 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694 {
695 /* If we can't get the function addresses, set advapi_lib
696 * to NULL so that we don't use them. */
697 FreeLibrary(advapi_lib);
698 advapi_lib = NULL;
699 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200700 /* Enable privilege for getting or setting SACLs. */
701 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702 }
703 }
704#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200705 /*
706 * If we are on windows NT, try to load the pipe functions, only
707 * available from Win2K.
708 */
709 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
710 {
711 HANDLE kernel32 = GetModuleHandle("kernel32");
712 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
713 kernel32, "SetHandleInformation");
714
715 allowPiping = pSetHandleInformation != NULL;
716 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 done = TRUE;
718 }
719}
720
721/*
722 * Return TRUE when running on Windows 95 (or 98 or ME).
723 * Only to be used after mch_init().
724 */
725 int
726mch_windows95(void)
727{
728 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
729}
730
731#ifdef FEAT_GUI_W32
732/*
733 * Used to work around the "can't do synchronous spawn"
734 * problem on Win32s, without resorting to Universal Thunk.
735 */
736static int old_num_windows;
737static int num_windows;
738
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000739/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 static BOOL CALLBACK
741win32ssynch_cb(HWND hwnd, LPARAM lparam)
742{
743 num_windows++;
744 return TRUE;
745}
746#endif
747
748#ifndef FEAT_GUI_W32
749
750#define SHIFT (SHIFT_PRESSED)
751#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
752#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
753#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
754
755
756/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
757 * We map function keys to their ANSI terminal equivalents, as produced
758 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
759 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
760 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
761 * combinations of function/arrow/etc keys.
762 */
763
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000764static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765{
766 WORD wVirtKey;
767 BOOL fAnsiKey;
768 int chAlone;
769 int chShift;
770 int chCtrl;
771 int chAlt;
772} VirtKeyMap[] =
773{
774
775/* Key ANSI alone shift ctrl alt */
776 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
777
778 { VK_F1, TRUE, ';', 'T', '^', 'h', },
779 { VK_F2, TRUE, '<', 'U', '_', 'i', },
780 { VK_F3, TRUE, '=', 'V', '`', 'j', },
781 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
782 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
783 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
784 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
785 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
786 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
787 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
788 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
789 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
790
791 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
792 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
793 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
794 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
795 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
796 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
797 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
798 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
799 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
800 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
801
802 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
803
804#if 0
805 /* Most people don't have F13-F20, but what the hell... */
806 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
807 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
808 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
809 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
810 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
811 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
812 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
813 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
814#endif
815 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
816 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
817 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
818 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
819
820 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
821 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
822 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
823 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
824 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
825 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
826 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
827 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
828 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
829 /* Sorry, out of number space! <negri>*/
830 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
831
832};
833
834
835#ifdef _MSC_VER
836// The ToAscii bug destroys several registers. Need to turn off optimization
837// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000838# pragma warning(push)
839# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840# pragma optimize("", off)
841#endif
842
843#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
844# define AChar AsciiChar
845#else
846# define AChar uChar.AsciiChar
847#endif
848
849/* The return code indicates key code size. */
850 static int
851#ifdef __BORLANDC__
852 __stdcall
853#endif
854win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000855 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856{
857 UINT uMods = pker->dwControlKeyState;
858 static int s_iIsDead = 0;
859 static WORD awAnsiCode[2];
860 static BYTE abKeystate[256];
861
862
863 if (s_iIsDead == 2)
864 {
865 pker->AChar = (CHAR) awAnsiCode[1];
866 s_iIsDead = 0;
867 return 1;
868 }
869
870 if (pker->AChar != 0)
871 return 1;
872
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200873 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874
875 // Should only be non-NULL on NT 4.0
876 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
877 {
878 CHAR szKLID[KL_NAMELENGTH];
879
880 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
881 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
882 }
883
884 /* Clear any pending dead keys */
885 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
886
887 if (uMods & SHIFT_PRESSED)
888 abKeystate[VK_SHIFT] = 0x80;
889 if (uMods & CAPSLOCK_ON)
890 abKeystate[VK_CAPITAL] = 1;
891
892 if ((uMods & ALT_GR) == ALT_GR)
893 {
894 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
895 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
896 }
897
898 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
899 abKeystate, awAnsiCode, 0);
900
901 if (s_iIsDead > 0)
902 pker->AChar = (CHAR) awAnsiCode[0];
903
904 return s_iIsDead;
905}
906
907#ifdef _MSC_VER
908/* MUST switch optimization on again here, otherwise a call to
909 * decode_key_event() may crash (e.g. when hitting caps-lock) */
910# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000911# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912
913# if (_MSC_VER < 1100)
914/* MUST turn off global optimisation for this next function, or
915 * pressing ctrl-minus in insert mode crashes Vim when built with
916 * VC4.1. -- negri. */
917# pragma optimize("g", off)
918# endif
919#endif
920
921static BOOL g_fJustGotFocus = FALSE;
922
923/*
924 * Decode a KEY_EVENT into one or two keystrokes
925 */
926 static BOOL
927decode_key_event(
928 KEY_EVENT_RECORD *pker,
929 char_u *pch,
930 char_u *pch2,
931 int *pmodifiers,
932 BOOL fDoPost)
933{
934 int i;
935 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
936
937 *pch = *pch2 = NUL;
938 g_fJustGotFocus = FALSE;
939
940 /* ignore key up events */
941 if (!pker->bKeyDown)
942 return FALSE;
943
944 /* ignore some keystrokes */
945 switch (pker->wVirtualKeyCode)
946 {
947 /* modifiers */
948 case VK_SHIFT:
949 case VK_CONTROL:
950 case VK_MENU: /* Alt key */
951 return FALSE;
952
953 default:
954 break;
955 }
956
957 /* special cases */
958 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
959 {
960 /* Ctrl-6 is Ctrl-^ */
961 if (pker->wVirtualKeyCode == '6')
962 {
963 *pch = Ctrl_HAT;
964 return TRUE;
965 }
966 /* Ctrl-2 is Ctrl-@ */
967 else if (pker->wVirtualKeyCode == '2')
968 {
969 *pch = NUL;
970 return TRUE;
971 }
972 /* Ctrl-- is Ctrl-_ */
973 else if (pker->wVirtualKeyCode == 0xBD)
974 {
975 *pch = Ctrl__;
976 return TRUE;
977 }
978 }
979
980 /* Shift-TAB */
981 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
982 {
983 *pch = K_NUL;
984 *pch2 = '\017';
985 return TRUE;
986 }
987
988 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
989 {
990 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
991 {
992 if (nModifs == 0)
993 *pch = VirtKeyMap[i].chAlone;
994 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
995 *pch = VirtKeyMap[i].chShift;
996 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
997 *pch = VirtKeyMap[i].chCtrl;
998 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
999 *pch = VirtKeyMap[i].chAlt;
1000
1001 if (*pch != 0)
1002 {
1003 if (VirtKeyMap[i].fAnsiKey)
1004 {
1005 *pch2 = *pch;
1006 *pch = K_NUL;
1007 }
1008
1009 return TRUE;
1010 }
1011 }
1012 }
1013
1014 i = win32_kbd_patch_key(pker);
1015
1016 if (i < 0)
1017 *pch = NUL;
1018 else
1019 {
1020 *pch = (i > 0) ? pker->AChar : NUL;
1021
1022 if (pmodifiers != NULL)
1023 {
1024 /* Pass on the ALT key as a modifier, but only when not combined
1025 * with CTRL (which is ALTGR). */
1026 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1027 *pmodifiers |= MOD_MASK_ALT;
1028
1029 /* Pass on SHIFT only for special keys, because we don't know when
1030 * it's already included with the character. */
1031 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1032 *pmodifiers |= MOD_MASK_SHIFT;
1033
1034 /* Pass on CTRL only for non-special keys, because we don't know
1035 * when it's already included with the character. And not when
1036 * combined with ALT (which is ALTGR). */
1037 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1038 && *pch >= 0x20 && *pch < 0x80)
1039 *pmodifiers |= MOD_MASK_CTRL;
1040 }
1041 }
1042
1043 return (*pch != NUL);
1044}
1045
1046#ifdef _MSC_VER
1047# pragma optimize("", on)
1048#endif
1049
1050#endif /* FEAT_GUI_W32 */
1051
1052
1053#ifdef FEAT_MOUSE
1054
1055/*
1056 * For the GUI the mouse handling is in gui_w32.c.
1057 */
1058# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001059/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001060 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001061mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001062{
1063}
1064# else
1065static int g_fMouseAvail = FALSE; /* mouse present */
1066static int g_fMouseActive = FALSE; /* mouse enabled */
1067static int g_nMouseClick = -1; /* mouse status */
1068static int g_xMouse; /* mouse x coordinate */
1069static int g_yMouse; /* mouse y coordinate */
1070
1071/*
1072 * Enable or disable mouse input
1073 */
1074 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001075mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076{
1077 DWORD cmodein;
1078
1079 if (!g_fMouseAvail)
1080 return;
1081
1082 g_fMouseActive = on;
1083 GetConsoleMode(g_hConIn, &cmodein);
1084
1085 if (g_fMouseActive)
1086 cmodein |= ENABLE_MOUSE_INPUT;
1087 else
1088 cmodein &= ~ENABLE_MOUSE_INPUT;
1089
1090 SetConsoleMode(g_hConIn, cmodein);
1091}
1092
1093
1094/*
1095 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1096 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1097 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1098 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1099 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1100 * and we return the mouse position in g_xMouse and g_yMouse.
1101 *
1102 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1103 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1104 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1105 *
1106 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1107 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1108 *
1109 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1110 * moves, even if it stays within the same character cell. We ignore
1111 * all MOUSE_MOVED messages if the position hasn't really changed, and
1112 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1113 * we're only interested in MOUSE_DRAG).
1114 *
1115 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1116 * 2-button mouses by pressing the left & right buttons simultaneously.
1117 * In practice, it's almost impossible to click both at the same time,
1118 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1119 * in such cases, if the user is clicking quickly.
1120 */
1121 static BOOL
1122decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001123 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124{
1125 static int s_nOldButton = -1;
1126 static int s_nOldMouseClick = -1;
1127 static int s_xOldMouse = -1;
1128 static int s_yOldMouse = -1;
1129 static linenr_T s_old_topline = 0;
1130#ifdef FEAT_DIFF
1131 static int s_old_topfill = 0;
1132#endif
1133 static int s_cClicks = 1;
1134 static BOOL s_fReleased = TRUE;
1135 static DWORD s_dwLastClickTime = 0;
1136 static BOOL s_fNextIsMiddle = FALSE;
1137
1138 static DWORD cButtons = 0; /* number of buttons supported */
1139
1140 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1141 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1142 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1143 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1144
1145 int nButton;
1146
1147 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1148 cButtons = 2;
1149
1150 if (!g_fMouseAvail || !g_fMouseActive)
1151 {
1152 g_nMouseClick = -1;
1153 return FALSE;
1154 }
1155
1156 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1157 if (g_fJustGotFocus)
1158 {
1159 g_fJustGotFocus = FALSE;
1160 return FALSE;
1161 }
1162
1163 /* unprocessed mouse click? */
1164 if (g_nMouseClick != -1)
1165 return TRUE;
1166
1167 nButton = -1;
1168 g_xMouse = pmer->dwMousePosition.X;
1169 g_yMouse = pmer->dwMousePosition.Y;
1170
1171 if (pmer->dwEventFlags == MOUSE_MOVED)
1172 {
1173 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1174 * events even when the mouse moves only within a char cell.) */
1175 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1176 return FALSE;
1177 }
1178
1179 /* If no buttons are pressed... */
1180 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1181 {
1182 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1183 if (s_fReleased)
1184 return FALSE;
1185
1186 nButton = MOUSE_RELEASE;
1187 s_fReleased = TRUE;
1188 }
1189 else /* one or more buttons pressed */
1190 {
1191 /* on a 2-button mouse, hold down left and right buttons
1192 * simultaneously to get MIDDLE. */
1193
1194 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1195 {
1196 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1197
1198 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001199 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200 if (dwLR == LEFT || dwLR == RIGHT)
1201 {
1202 for (;;)
1203 {
1204 /* wait a short time for next input event */
1205 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1206 != WAIT_OBJECT_0)
1207 break;
1208 else
1209 {
1210 DWORD cRecords = 0;
1211 INPUT_RECORD ir;
1212 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1213
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001214 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215
1216 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1217 || !(pmer2->dwButtonState & LEFT_RIGHT))
1218 break;
1219 else
1220 {
1221 if (pmer2->dwEventFlags != MOUSE_MOVED)
1222 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001223 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001224
1225 return decode_mouse_event(pmer2);
1226 }
1227 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1228 s_yOldMouse == pmer2->dwMousePosition.Y)
1229 {
1230 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001231 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232
1233 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001234 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235
1236 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1237 break;
1238 }
1239 else
1240 break;
1241 }
1242 }
1243 }
1244 }
1245 }
1246
1247 if (s_fNextIsMiddle)
1248 {
1249 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1250 ? MOUSE_DRAG : MOUSE_MIDDLE;
1251 s_fNextIsMiddle = FALSE;
1252 }
1253 else if (cButtons == 2 &&
1254 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1255 {
1256 nButton = MOUSE_MIDDLE;
1257
1258 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1259 {
1260 s_fNextIsMiddle = TRUE;
1261 nButton = MOUSE_RELEASE;
1262 }
1263 }
1264 else if ((pmer->dwButtonState & LEFT) == LEFT)
1265 nButton = MOUSE_LEFT;
1266 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1267 nButton = MOUSE_MIDDLE;
1268 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1269 nButton = MOUSE_RIGHT;
1270
1271 if (! s_fReleased && ! s_fNextIsMiddle
1272 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1273 return FALSE;
1274
1275 s_fReleased = s_fNextIsMiddle;
1276 }
1277
1278 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1279 {
1280 /* button pressed or released, without mouse moving */
1281 if (nButton != -1 && nButton != MOUSE_RELEASE)
1282 {
1283 DWORD dwCurrentTime = GetTickCount();
1284
1285 if (s_xOldMouse != g_xMouse
1286 || s_yOldMouse != g_yMouse
1287 || s_nOldButton != nButton
1288 || s_old_topline != curwin->w_topline
1289#ifdef FEAT_DIFF
1290 || s_old_topfill != curwin->w_topfill
1291#endif
1292 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1293 {
1294 s_cClicks = 1;
1295 }
1296 else if (++s_cClicks > 4)
1297 {
1298 s_cClicks = 1;
1299 }
1300
1301 s_dwLastClickTime = dwCurrentTime;
1302 }
1303 }
1304 else if (pmer->dwEventFlags == MOUSE_MOVED)
1305 {
1306 if (nButton != -1 && nButton != MOUSE_RELEASE)
1307 nButton = MOUSE_DRAG;
1308
1309 s_cClicks = 1;
1310 }
1311
1312 if (nButton == -1)
1313 return FALSE;
1314
1315 if (nButton != MOUSE_RELEASE)
1316 s_nOldButton = nButton;
1317
1318 g_nMouseClick = nButton;
1319
1320 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1321 g_nMouseClick |= MOUSE_SHIFT;
1322 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1323 g_nMouseClick |= MOUSE_CTRL;
1324 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1325 g_nMouseClick |= MOUSE_ALT;
1326
1327 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1328 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1329
1330 /* only pass on interesting (i.e., different) mouse events */
1331 if (s_xOldMouse == g_xMouse
1332 && s_yOldMouse == g_yMouse
1333 && s_nOldMouseClick == g_nMouseClick)
1334 {
1335 g_nMouseClick = -1;
1336 return FALSE;
1337 }
1338
1339 s_xOldMouse = g_xMouse;
1340 s_yOldMouse = g_yMouse;
1341 s_old_topline = curwin->w_topline;
1342#ifdef FEAT_DIFF
1343 s_old_topfill = curwin->w_topfill;
1344#endif
1345 s_nOldMouseClick = g_nMouseClick;
1346
1347 return TRUE;
1348}
1349
1350# endif /* FEAT_GUI_W32 */
1351#endif /* FEAT_MOUSE */
1352
1353
1354#ifdef MCH_CURSOR_SHAPE
1355/*
1356 * Set the shape of the cursor.
1357 * 'thickness' can be from 1 (thin) to 99 (block)
1358 */
1359 static void
1360mch_set_cursor_shape(int thickness)
1361{
1362 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1363 ConsoleCursorInfo.dwSize = thickness;
1364 ConsoleCursorInfo.bVisible = s_cursor_visible;
1365
1366 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1367 if (s_cursor_visible)
1368 SetConsoleCursorPosition(g_hConOut, g_coord);
1369}
1370
1371 void
1372mch_update_cursor(void)
1373{
1374 int idx;
1375 int thickness;
1376
1377 /*
1378 * How the cursor is drawn depends on the current mode.
1379 */
1380 idx = get_shape_idx(FALSE);
1381
1382 if (shape_table[idx].shape == SHAPE_BLOCK)
1383 thickness = 99; /* 100 doesn't work on W95 */
1384 else
1385 thickness = shape_table[idx].percentage;
1386 mch_set_cursor_shape(thickness);
1387}
1388#endif
1389
1390#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1391/*
1392 * Handle FOCUS_EVENT.
1393 */
1394 static void
1395handle_focus_event(INPUT_RECORD ir)
1396{
1397 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1398 ui_focus_change((int)g_fJustGotFocus);
1399}
1400
1401/*
1402 * Wait until console input from keyboard or mouse is available,
1403 * or the time is up.
1404 * Return TRUE if something is available FALSE if not.
1405 */
1406 static int
1407WaitForChar(long msec)
1408{
1409 DWORD dwNow = 0, dwEndTime = 0;
1410 INPUT_RECORD ir;
1411 DWORD cRecords;
1412 char_u ch, ch2;
1413
1414 if (msec > 0)
1415 /* Wait until the specified time has elapsed. */
1416 dwEndTime = GetTickCount() + msec;
1417 else if (msec < 0)
1418 /* Wait forever. */
1419 dwEndTime = INFINITE;
1420
1421 /* We need to loop until the end of the time period, because
1422 * we might get multiple unusable mouse events in that time.
1423 */
1424 for (;;)
1425 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001426#ifdef FEAT_MZSCHEME
1427 mzvim_check_threads();
1428#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001429#ifdef FEAT_CLIENTSERVER
1430 serverProcessPendingMessages();
1431#endif
1432 if (0
1433#ifdef FEAT_MOUSE
1434 || g_nMouseClick != -1
1435#endif
1436#ifdef FEAT_CLIENTSERVER
1437 || input_available()
1438#endif
1439 )
1440 return TRUE;
1441
1442 if (msec > 0)
1443 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001444 /* If the specified wait time has passed, return. Beware that
1445 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001446 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001447 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448 break;
1449 }
1450 if (msec != 0)
1451 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001452 DWORD dwWaitTime = dwEndTime - dwNow;
1453
1454#ifdef FEAT_MZSCHEME
1455 if (mzthreads_allowed() && p_mzq > 0
1456 && (msec < 0 || (long)dwWaitTime > p_mzq))
1457 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1458#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459#ifdef FEAT_CLIENTSERVER
1460 /* Wait for either an event on the console input or a message in
1461 * the client-server window. */
1462 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001463 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001464#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001465 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466#endif
1467 continue;
1468 }
1469
1470 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001471 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472
1473#ifdef FEAT_MBYTE_IME
1474 if (State & CMDLINE && msg_row == Rows - 1)
1475 {
1476 CONSOLE_SCREEN_BUFFER_INFO csbi;
1477
1478 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1479 {
1480 if (csbi.dwCursorPosition.Y != msg_row)
1481 {
1482 /* The screen is now messed up, must redraw the
1483 * command line and later all the windows. */
1484 redraw_all_later(CLEAR);
1485 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1486 redrawcmd();
1487 }
1488 }
1489 }
1490#endif
1491
1492 if (cRecords > 0)
1493 {
1494 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1495 {
1496#ifdef FEAT_MBYTE_IME
1497 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1498 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1499 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1500 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1501 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001502 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503 continue;
1504 }
1505#endif
1506 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1507 NULL, FALSE))
1508 return TRUE;
1509 }
1510
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001511 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512
1513 if (ir.EventType == FOCUS_EVENT)
1514 handle_focus_event(ir);
1515 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1516 shell_resized();
1517#ifdef FEAT_MOUSE
1518 else if (ir.EventType == MOUSE_EVENT
1519 && decode_mouse_event(&ir.Event.MouseEvent))
1520 return TRUE;
1521#endif
1522 }
1523 else if (msec == 0)
1524 break;
1525 }
1526
1527#ifdef FEAT_CLIENTSERVER
1528 /* Something might have been received while we were waiting. */
1529 if (input_available())
1530 return TRUE;
1531#endif
1532 return FALSE;
1533}
1534
1535#ifndef FEAT_GUI_MSWIN
1536/*
1537 * return non-zero if a character is available
1538 */
1539 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001540mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541{
1542 return WaitForChar(0L);
1543}
1544#endif
1545
1546/*
1547 * Create the console input. Used when reading stdin doesn't work.
1548 */
1549 static void
1550create_conin(void)
1551{
1552 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1553 FILE_SHARE_READ|FILE_SHARE_WRITE,
1554 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001555 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001556 did_create_conin = TRUE;
1557}
1558
1559/*
1560 * Get a keystroke or a mouse event
1561 */
1562 static char_u
1563tgetch(int *pmodifiers, char_u *pch2)
1564{
1565 char_u ch;
1566
1567 for (;;)
1568 {
1569 INPUT_RECORD ir;
1570 DWORD cRecords = 0;
1571
1572#ifdef FEAT_CLIENTSERVER
1573 (void)WaitForChar(-1L);
1574 if (input_available())
1575 return 0;
1576# ifdef FEAT_MOUSE
1577 if (g_nMouseClick != -1)
1578 return 0;
1579# endif
1580#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001581 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 {
1583 if (did_create_conin)
1584 read_error_exit();
1585 create_conin();
1586 continue;
1587 }
1588
1589 if (ir.EventType == KEY_EVENT)
1590 {
1591 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1592 pmodifiers, TRUE))
1593 return ch;
1594 }
1595 else if (ir.EventType == FOCUS_EVENT)
1596 handle_focus_event(ir);
1597 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1598 shell_resized();
1599#ifdef FEAT_MOUSE
1600 else if (ir.EventType == MOUSE_EVENT)
1601 {
1602 if (decode_mouse_event(&ir.Event.MouseEvent))
1603 return 0;
1604 }
1605#endif
1606 }
1607}
1608#endif /* !FEAT_GUI_W32 */
1609
1610
1611/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001612 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 * Get one or more characters from the keyboard or the mouse.
1614 * If time == 0, do not wait for characters.
1615 * If time == n, wait a short time for characters.
1616 * If time == -1, wait forever for characters.
1617 * Returns the number of characters read into buf.
1618 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001619/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 int
1621mch_inchar(
1622 char_u *buf,
1623 int maxlen,
1624 long time,
1625 int tb_change_cnt)
1626{
1627#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1628
1629 int len;
1630 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001631#define TYPEAHEADLEN 20
1632 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1633 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001634#ifdef FEAT_MBYTE
1635 static char_u *rest = NULL; /* unconverted rest of previous read */
1636 static int restlen = 0;
1637 int unconverted;
1638#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639
1640 /* First use any typeahead that was kept because "buf" was too small. */
1641 if (typeaheadlen > 0)
1642 goto theend;
1643
1644#ifdef FEAT_SNIFF
1645 if (want_sniff_request)
1646 {
1647 if (sniff_request_waiting)
1648 {
1649 /* return K_SNIFF */
1650 typeahead[typeaheadlen++] = CSI;
1651 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1652 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1653 sniff_request_waiting = 0;
1654 want_sniff_request = 0;
1655 goto theend;
1656 }
1657 else if (time < 0 || time > 250)
1658 {
1659 /* don't wait too long, a request might be pending */
1660 time = 250;
1661 }
1662 }
1663#endif
1664
1665 if (time >= 0)
1666 {
1667 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 }
1670 else /* time == -1, wait forever */
1671 {
1672 mch_set_winsize_now(); /* Allow winsize changes from now on */
1673
Bram Moolenaar3918c952005-03-15 22:34:55 +00001674 /*
1675 * If there is no character available within 2 seconds (default)
1676 * write the autoscript file to disk. Or cause the CursorHold event
1677 * to be triggered.
1678 */
1679 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680 {
1681#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001682 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001684 buf[0] = K_SPECIAL;
1685 buf[1] = KS_EXTRA;
1686 buf[2] = (int)KE_CURSORHOLD;
1687 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 }
1689#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001690 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 }
1692 }
1693
1694 /*
1695 * Try to read as many characters as there are, until the buffer is full.
1696 */
1697
1698 /* we will get at least one key. Get more if they are available. */
1699 g_fCBrkPressed = FALSE;
1700
1701#ifdef MCH_WRITE_DUMP
1702 if (fdDump)
1703 fputc('[', fdDump);
1704#endif
1705
1706 /* Keep looping until there is something in the typeahead buffer and more
1707 * to get and still room in the buffer (up to two bytes for a char and
1708 * three bytes for a modifier). */
1709 while ((typeaheadlen == 0 || WaitForChar(0L))
1710 && typeaheadlen + 5 <= TYPEAHEADLEN)
1711 {
1712 if (typebuf_changed(tb_change_cnt))
1713 {
1714 /* "buf" may be invalid now if a client put something in the
1715 * typeahead buffer and "buf" is in the typeahead buffer. */
1716 typeaheadlen = 0;
1717 break;
1718 }
1719#ifdef FEAT_MOUSE
1720 if (g_nMouseClick != -1)
1721 {
1722# ifdef MCH_WRITE_DUMP
1723 if (fdDump)
1724 fprintf(fdDump, "{%02x @ %d, %d}",
1725 g_nMouseClick, g_xMouse, g_yMouse);
1726# endif
1727 typeahead[typeaheadlen++] = ESC + 128;
1728 typeahead[typeaheadlen++] = 'M';
1729 typeahead[typeaheadlen++] = g_nMouseClick;
1730 typeahead[typeaheadlen++] = g_xMouse + '!';
1731 typeahead[typeaheadlen++] = g_yMouse + '!';
1732 g_nMouseClick = -1;
1733 }
1734 else
1735#endif
1736 {
1737 char_u ch2 = NUL;
1738 int modifiers = 0;
1739
1740 c = tgetch(&modifiers, &ch2);
1741
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001742#ifdef FEAT_MBYTE
1743 /* stolen from fill_input_buf() in ui.c */
1744 if (rest != NULL)
1745 {
1746 /* Use remainder of previous call, starts with an invalid
1747 * character that may become valid when reading more. */
1748 if (restlen > TYPEAHEADLEN - typeaheadlen)
1749 unconverted = TYPEAHEADLEN - typeaheadlen;
1750 else
1751 unconverted = restlen;
1752 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1753 if (unconverted == restlen)
1754 {
1755 vim_free(rest);
1756 rest = NULL;
1757 }
1758 else
1759 {
1760 restlen -= unconverted;
1761 mch_memmove(rest, rest + unconverted, restlen);
1762 }
1763 typeaheadlen += unconverted;
1764 }
1765 else
1766 unconverted = 0;
1767#endif
1768
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 if (typebuf_changed(tb_change_cnt))
1770 {
1771 /* "buf" may be invalid now if a client put something in the
1772 * typeahead buffer and "buf" is in the typeahead buffer. */
1773 typeaheadlen = 0;
1774 break;
1775 }
1776
1777 if (c == Ctrl_C && ctrl_c_interrupts)
1778 {
1779#if defined(FEAT_CLIENTSERVER)
1780 trash_input_buf();
1781#endif
1782 got_int = TRUE;
1783 }
1784
1785#ifdef FEAT_MOUSE
1786 if (g_nMouseClick == -1)
1787#endif
1788 {
1789 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001790 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 typeahead[typeaheadlen] = c;
1793 if (ch2 != NUL)
1794 {
Bram Moolenaar45500912014-07-09 20:51:07 +02001795 typeahead[typeaheadlen + 1] = 3;
1796 typeahead[typeaheadlen + 2] = ch2;
1797 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 }
1799#ifdef FEAT_MBYTE
1800 /* Only convert normal characters, not special keys. Need to
1801 * convert before applying ALT, otherwise mapping <M-x> breaks
1802 * when 'tenc' is set. */
1803 if (input_conv.vc_type != CONV_NONE
1804 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001805 {
Bram Moolenaar45500912014-07-09 20:51:07 +02001806 conv = TRUE;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001807 typeaheadlen -= unconverted;
1808 n = convert_input_safe(typeahead + typeaheadlen,
1809 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1810 rest == NULL ? &rest : NULL, &restlen);
1811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812#endif
1813
Bram Moolenaar45500912014-07-09 20:51:07 +02001814 if (conv)
1815 {
1816 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001817
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001818 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001819 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001820 char_u *e = typeahead + TYPEAHEADLEN;
1821
1822 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001823 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001824 if (*p == K_NUL)
1825 {
1826 ++p;
1827 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1828 *p = 3;
1829 ++n;
1830 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001831 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001832 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001833 }
1834 }
1835
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 /* Use the ALT key to set the 8th bit of the character
1837 * when it's one byte, the 8th bit isn't set yet and not
1838 * using a double-byte encoding (would become a lead
1839 * byte). */
1840 if ((modifiers & MOD_MASK_ALT)
1841 && n == 1
1842 && (typeahead[typeaheadlen] & 0x80) == 0
1843#ifdef FEAT_MBYTE
1844 && !enc_dbcs
1845#endif
1846 )
1847 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001848#ifdef FEAT_MBYTE
1849 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1850 typeahead + typeaheadlen);
1851#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001853#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 modifiers &= ~MOD_MASK_ALT;
1855 }
1856
1857 if (modifiers != 0)
1858 {
1859 /* Prepend modifiers to the character. */
1860 mch_memmove(typeahead + typeaheadlen + 3,
1861 typeahead + typeaheadlen, n);
1862 typeahead[typeaheadlen++] = K_SPECIAL;
1863 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1864 typeahead[typeaheadlen++] = modifiers;
1865 }
1866
1867 typeaheadlen += n;
1868
1869#ifdef MCH_WRITE_DUMP
1870 if (fdDump)
1871 fputc(c, fdDump);
1872#endif
1873 }
1874 }
1875 }
1876
1877#ifdef MCH_WRITE_DUMP
1878 if (fdDump)
1879 {
1880 fputs("]\n", fdDump);
1881 fflush(fdDump);
1882 }
1883#endif
1884
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885theend:
1886 /* Move typeahead to "buf", as much as fits. */
1887 len = 0;
1888 while (len < maxlen && typeaheadlen > 0)
1889 {
1890 buf[len++] = typeahead[0];
1891 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1892 }
1893 return len;
1894
1895#else /* FEAT_GUI_W32 */
1896 return 0;
1897#endif /* FEAT_GUI_W32 */
1898}
1899
Bram Moolenaar82881492012-11-20 16:53:39 +01001900#ifndef PROTO
1901# ifndef __MINGW32__
1902# include <shellapi.h> /* required for FindExecutable() */
1903# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904#endif
1905
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001906/*
1907 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001908 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001909 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001911executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001913 char *dum;
1914 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001915 char *curpath, *newpath;
1916 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001918#ifdef FEAT_MBYTE
1919 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001921 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001922 WCHAR fnamew[_MAX_PATH];
1923 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001924 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001925
1926 if (p != NULL)
1927 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001928 wcurpath = _wgetenv(L"PATH");
1929 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1930 * sizeof(WCHAR));
1931 if (wnewpath == NULL)
1932 return FALSE;
1933 wcscpy(wnewpath, L".;");
1934 wcscat(wnewpath, wcurpath);
1935 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1936 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001937 vim_free(p);
1938 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1939 {
1940 if (n == 0)
1941 return FALSE;
1942 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1943 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001944 if (path != NULL)
1945 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001946 return TRUE;
1947 }
1948 /* Retry with non-wide function (for Windows 98). */
1949 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001951#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001952
1953 curpath = getenv("PATH");
1954 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1955 if (newpath == NULL)
1956 return FALSE;
1957 STRCPY(newpath, ".;");
1958 STRCAT(newpath, curpath);
1959 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1960 vim_free(newpath);
1961 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001962 return FALSE;
1963 if (mch_isdir(fname))
1964 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001965 if (path != NULL)
1966 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001967 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001968}
1969
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001970#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001971 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001972/*
1973 * Bad parameter handler.
1974 *
1975 * Certain MS CRT functions will intentionally crash when passed invalid
1976 * parameters to highlight possible security holes. Setting this function as
1977 * the bad parameter handler will prevent the crash.
1978 *
1979 * In debug builds the parameters contain CRT information that might help track
1980 * down the source of a problem, but in non-debug builds the arguments are all
1981 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1982 * worth allowing these to make debugging of issues easier.
1983 */
1984 static void
1985bad_param_handler(const wchar_t *expression,
1986 const wchar_t *function,
1987 const wchar_t *file,
1988 unsigned int line,
1989 uintptr_t pReserved)
1990{
1991}
1992
1993# define SET_INVALID_PARAM_HANDLER \
1994 ((void)_set_invalid_parameter_handler(bad_param_handler))
1995#else
1996# define SET_INVALID_PARAM_HANDLER
1997#endif
1998
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999#ifdef FEAT_GUI_W32
2000
2001/*
2002 * GUI version of mch_init().
2003 */
2004 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002005mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006{
2007#ifndef __MINGW32__
2008 extern int _fmode;
2009#endif
2010
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002011 /* Silently handle invalid parameters to CRT functions */
2012 SET_INVALID_PARAM_HANDLER;
2013
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014 /* Let critical errors result in a failure, not in a dialog box. Required
2015 * for the timestamp test to work on removed floppies. */
2016 SetErrorMode(SEM_FAILCRITICALERRORS);
2017
2018 _fmode = O_BINARY; /* we do our own CR-LF translation */
2019
2020 /* Specify window size. Is there a place to get the default from? */
2021 Rows = 25;
2022 Columns = 80;
2023
2024 /* Look for 'vimrun' */
2025 if (!gui_is_win32s())
2026 {
2027 char_u vimrun_location[_MAX_PATH + 4];
2028
2029 /* First try in same directory as gvim.exe */
2030 STRCPY(vimrun_location, exe_name);
2031 STRCPY(gettail(vimrun_location), "vimrun.exe");
2032 if (mch_getperm(vimrun_location) >= 0)
2033 {
2034 if (*skiptowhite(vimrun_location) != NUL)
2035 {
2036 /* Enclose path with white space in double quotes. */
2037 mch_memmove(vimrun_location + 1, vimrun_location,
2038 STRLEN(vimrun_location) + 1);
2039 *vimrun_location = '"';
2040 STRCPY(gettail(vimrun_location), "vimrun\" ");
2041 }
2042 else
2043 STRCPY(gettail(vimrun_location), "vimrun ");
2044
2045 vimrun_path = (char *)vim_strsave(vimrun_location);
2046 s_dont_use_vimrun = FALSE;
2047 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002048 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 s_dont_use_vimrun = FALSE;
2050
2051 /* Don't give the warning for a missing vimrun.exe right now, but only
2052 * when vimrun was supposed to be used. Don't bother people that do
2053 * not need vimrun.exe. */
2054 if (s_dont_use_vimrun)
2055 need_vimrun_warning = TRUE;
2056 }
2057
2058 /*
2059 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2060 * Otherwise the default "findstr /n" is used.
2061 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002062 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2064
2065#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002066 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067#endif
2068}
2069
2070
2071#else /* FEAT_GUI_W32 */
2072
2073#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2074#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2075
2076/*
2077 * ClearConsoleBuffer()
2078 * Description:
2079 * Clears the entire contents of the console screen buffer, using the
2080 * specified attribute.
2081 * Returns:
2082 * TRUE on success
2083 */
2084 static BOOL
2085ClearConsoleBuffer(WORD wAttribute)
2086{
2087 CONSOLE_SCREEN_BUFFER_INFO csbi;
2088 COORD coord;
2089 DWORD NumCells, dummy;
2090
2091 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2092 return FALSE;
2093
2094 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2095 coord.X = 0;
2096 coord.Y = 0;
2097 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2098 coord, &dummy))
2099 {
2100 return FALSE;
2101 }
2102 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2103 coord, &dummy))
2104 {
2105 return FALSE;
2106 }
2107
2108 return TRUE;
2109}
2110
2111/*
2112 * FitConsoleWindow()
2113 * Description:
2114 * Checks if the console window will fit within given buffer dimensions.
2115 * Also, if requested, will shrink the window to fit.
2116 * Returns:
2117 * TRUE on success
2118 */
2119 static BOOL
2120FitConsoleWindow(
2121 COORD dwBufferSize,
2122 BOOL WantAdjust)
2123{
2124 CONSOLE_SCREEN_BUFFER_INFO csbi;
2125 COORD dwWindowSize;
2126 BOOL NeedAdjust = FALSE;
2127
2128 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2129 {
2130 /*
2131 * A buffer resize will fail if the current console window does
2132 * not lie completely within that buffer. To avoid this, we might
2133 * have to move and possibly shrink the window.
2134 */
2135 if (csbi.srWindow.Right >= dwBufferSize.X)
2136 {
2137 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2138 if (dwWindowSize.X > dwBufferSize.X)
2139 dwWindowSize.X = dwBufferSize.X;
2140 csbi.srWindow.Right = dwBufferSize.X - 1;
2141 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2142 NeedAdjust = TRUE;
2143 }
2144 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2145 {
2146 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2147 if (dwWindowSize.Y > dwBufferSize.Y)
2148 dwWindowSize.Y = dwBufferSize.Y;
2149 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2150 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2151 NeedAdjust = TRUE;
2152 }
2153 if (NeedAdjust && WantAdjust)
2154 {
2155 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2156 return FALSE;
2157 }
2158 return TRUE;
2159 }
2160
2161 return FALSE;
2162}
2163
2164typedef struct ConsoleBufferStruct
2165{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002166 BOOL IsValid;
2167 CONSOLE_SCREEN_BUFFER_INFO Info;
2168 PCHAR_INFO Buffer;
2169 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002170} ConsoleBuffer;
2171
2172/*
2173 * SaveConsoleBuffer()
2174 * Description:
2175 * Saves important information about the console buffer, including the
2176 * actual buffer contents. The saved information is suitable for later
2177 * restoration by RestoreConsoleBuffer().
2178 * Returns:
2179 * TRUE if all information was saved; FALSE otherwise
2180 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2181 */
2182 static BOOL
2183SaveConsoleBuffer(
2184 ConsoleBuffer *cb)
2185{
2186 DWORD NumCells;
2187 COORD BufferCoord;
2188 SMALL_RECT ReadRegion;
2189 WORD Y, Y_incr;
2190
2191 if (cb == NULL)
2192 return FALSE;
2193
2194 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2195 {
2196 cb->IsValid = FALSE;
2197 return FALSE;
2198 }
2199 cb->IsValid = TRUE;
2200
2201 /*
2202 * Allocate a buffer large enough to hold the entire console screen
2203 * buffer. If this ConsoleBuffer structure has already been initialized
2204 * with a buffer of the correct size, then just use that one.
2205 */
2206 if (!cb->IsValid || cb->Buffer == NULL ||
2207 cb->BufferSize.X != cb->Info.dwSize.X ||
2208 cb->BufferSize.Y != cb->Info.dwSize.Y)
2209 {
2210 cb->BufferSize.X = cb->Info.dwSize.X;
2211 cb->BufferSize.Y = cb->Info.dwSize.Y;
2212 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002213 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2215 if (cb->Buffer == NULL)
2216 return FALSE;
2217 }
2218
2219 /*
2220 * We will now copy the console screen buffer into our buffer.
2221 * ReadConsoleOutput() seems to be limited as far as how much you
2222 * can read at a time. Empirically, this number seems to be about
2223 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2224 * in chunks until it is all copied. The chunks will all have the
2225 * same horizontal characteristics, so initialize them now. The
2226 * height of each chunk will be (12000 / width).
2227 */
2228 BufferCoord.X = 0;
2229 ReadRegion.Left = 0;
2230 ReadRegion.Right = cb->Info.dwSize.X - 1;
2231 Y_incr = 12000 / cb->Info.dwSize.X;
2232 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2233 {
2234 /*
2235 * Read into position (0, Y) in our buffer.
2236 */
2237 BufferCoord.Y = Y;
2238 /*
2239 * Read the region whose top left corner is (0, Y) and whose bottom
2240 * right corner is (width - 1, Y + Y_incr - 1). This should define
2241 * a region of size width by Y_incr. Don't worry if this region is
2242 * too large for the remaining buffer; it will be cropped.
2243 */
2244 ReadRegion.Top = Y;
2245 ReadRegion.Bottom = Y + Y_incr - 1;
2246 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2247 cb->Buffer, /* our buffer */
2248 cb->BufferSize, /* dimensions of our buffer */
2249 BufferCoord, /* offset in our buffer */
2250 &ReadRegion)) /* region to save */
2251 {
2252 vim_free(cb->Buffer);
2253 cb->Buffer = NULL;
2254 return FALSE;
2255 }
2256 }
2257
2258 return TRUE;
2259}
2260
2261/*
2262 * RestoreConsoleBuffer()
2263 * Description:
2264 * Restores important information about the console buffer, including the
2265 * actual buffer contents, if desired. The information to restore is in
2266 * the same format used by SaveConsoleBuffer().
2267 * Returns:
2268 * TRUE on success
2269 */
2270 static BOOL
2271RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002272 ConsoleBuffer *cb,
2273 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274{
2275 COORD BufferCoord;
2276 SMALL_RECT WriteRegion;
2277
2278 if (cb == NULL || !cb->IsValid)
2279 return FALSE;
2280
2281 /*
2282 * Before restoring the buffer contents, clear the current buffer, and
2283 * restore the cursor position and window information. Doing this now
2284 * prevents old buffer contents from "flashing" onto the screen.
2285 */
2286 if (RestoreScreen)
2287 ClearConsoleBuffer(cb->Info.wAttributes);
2288
2289 FitConsoleWindow(cb->Info.dwSize, TRUE);
2290 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2291 return FALSE;
2292 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2293 return FALSE;
2294
2295 if (!RestoreScreen)
2296 {
2297 /*
2298 * No need to restore the screen buffer contents, so we're done.
2299 */
2300 return TRUE;
2301 }
2302
2303 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2304 return FALSE;
2305 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2306 return FALSE;
2307
2308 /*
2309 * Restore the screen buffer contents.
2310 */
2311 if (cb->Buffer != NULL)
2312 {
2313 BufferCoord.X = 0;
2314 BufferCoord.Y = 0;
2315 WriteRegion.Left = 0;
2316 WriteRegion.Top = 0;
2317 WriteRegion.Right = cb->Info.dwSize.X - 1;
2318 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2319 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2320 cb->Buffer, /* our buffer */
2321 cb->BufferSize, /* dimensions of our buffer */
2322 BufferCoord, /* offset in our buffer */
2323 &WriteRegion)) /* region to restore */
2324 {
2325 return FALSE;
2326 }
2327 }
2328
2329 return TRUE;
2330}
2331
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002332#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333#ifdef FEAT_RESTORE_ORIG_SCREEN
2334static ConsoleBuffer g_cbOrig = { 0 };
2335#endif
2336static ConsoleBuffer g_cbNonTermcap = { 0 };
2337static ConsoleBuffer g_cbTermcap = { 0 };
2338
2339#ifdef FEAT_TITLE
2340#ifdef __BORLANDC__
2341typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2342#else
2343typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2344#endif
2345char g_szOrigTitle[256] = { 0 };
2346HWND g_hWnd = NULL; /* also used in os_mswin.c */
2347static HICON g_hOrigIconSmall = NULL;
2348static HICON g_hOrigIcon = NULL;
2349static HICON g_hVimIcon = NULL;
2350static BOOL g_fCanChangeIcon = FALSE;
2351
2352/* ICON* are not defined in VC++ 4.0 */
2353#ifndef ICON_SMALL
2354#define ICON_SMALL 0
2355#endif
2356#ifndef ICON_BIG
2357#define ICON_BIG 1
2358#endif
2359/*
2360 * GetConsoleIcon()
2361 * Description:
2362 * Attempts to retrieve the small icon and/or the big icon currently in
2363 * use by a given window.
2364 * Returns:
2365 * TRUE on success
2366 */
2367 static BOOL
2368GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002369 HWND hWnd,
2370 HICON *phIconSmall,
2371 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372{
2373 if (hWnd == NULL)
2374 return FALSE;
2375
2376 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002377 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2378 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002380 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2381 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 return TRUE;
2383}
2384
2385/*
2386 * SetConsoleIcon()
2387 * Description:
2388 * Attempts to change the small icon and/or the big icon currently in
2389 * use by a given window.
2390 * Returns:
2391 * TRUE on success
2392 */
2393 static BOOL
2394SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002395 HWND hWnd,
2396 HICON hIconSmall,
2397 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002399 HICON hPrevIconSmall;
2400 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401
2402 if (hWnd == NULL)
2403 return FALSE;
2404
2405 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002406 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2407 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002409 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2410 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411 return TRUE;
2412}
2413
2414/*
2415 * SaveConsoleTitleAndIcon()
2416 * Description:
2417 * Saves the current console window title in g_szOrigTitle, for later
2418 * restoration. Also, attempts to obtain a handle to the console window,
2419 * and use it to save the small and big icons currently in use by the
2420 * console window. This is not always possible on some versions of Windows;
2421 * nor is it possible when running Vim remotely using Telnet (since the
2422 * console window the user sees is owned by a remote process).
2423 */
2424 static void
2425SaveConsoleTitleAndIcon(void)
2426{
2427 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2428
2429 /* Save the original title. */
2430 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2431 return;
2432
2433 /*
2434 * Obtain a handle to the console window using GetConsoleWindow() from
2435 * KERNEL32.DLL; we need to handle in order to change the window icon.
2436 * This function only exists on NT-based Windows, starting with Windows
2437 * 2000. On older operating systems, we can't change the window icon
2438 * anyway.
2439 */
2440 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2441 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2442 "GetConsoleWindow")) != NULL)
2443 {
2444 g_hWnd = (*GetConsoleWindowProc)();
2445 }
2446 if (g_hWnd == NULL)
2447 return;
2448
2449 /* Save the original console window icon. */
2450 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2451 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2452 return;
2453
2454 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002455 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2456 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 if (g_hVimIcon != NULL)
2458 g_fCanChangeIcon = TRUE;
2459}
2460#endif
2461
2462static int g_fWindInitCalled = FALSE;
2463static int g_fTermcapMode = FALSE;
2464static CONSOLE_CURSOR_INFO g_cci;
2465static DWORD g_cmodein = 0;
2466static DWORD g_cmodeout = 0;
2467
2468/*
2469 * non-GUI version of mch_init().
2470 */
2471 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002472mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473{
2474#ifndef FEAT_RESTORE_ORIG_SCREEN
2475 CONSOLE_SCREEN_BUFFER_INFO csbi;
2476#endif
2477#ifndef __MINGW32__
2478 extern int _fmode;
2479#endif
2480
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002481 /* Silently handle invalid parameters to CRT functions */
2482 SET_INVALID_PARAM_HANDLER;
2483
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484 /* Let critical errors result in a failure, not in a dialog box. Required
2485 * for the timestamp test to work on removed floppies. */
2486 SetErrorMode(SEM_FAILCRITICALERRORS);
2487
2488 _fmode = O_BINARY; /* we do our own CR-LF translation */
2489 out_flush();
2490
2491 /* Obtain handles for the standard Console I/O devices */
2492 if (read_cmd_fd == 0)
2493 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2494 else
2495 create_conin();
2496 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2497
2498#ifdef FEAT_RESTORE_ORIG_SCREEN
2499 /* Save the initial console buffer for later restoration */
2500 SaveConsoleBuffer(&g_cbOrig);
2501 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2502#else
2503 /* Get current text attributes */
2504 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2505 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2506#endif
2507 if (cterm_normal_fg_color == 0)
2508 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2509 if (cterm_normal_bg_color == 0)
2510 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2511
2512 /* set termcap codes to current text attributes */
2513 update_tcap(g_attrCurrent);
2514
2515 GetConsoleCursorInfo(g_hConOut, &g_cci);
2516 GetConsoleMode(g_hConIn, &g_cmodein);
2517 GetConsoleMode(g_hConOut, &g_cmodeout);
2518
2519#ifdef FEAT_TITLE
2520 SaveConsoleTitleAndIcon();
2521 /*
2522 * Set both the small and big icons of the console window to Vim's icon.
2523 * Note that Vim presently only has one size of icon (32x32), but it
2524 * automatically gets scaled down to 16x16 when setting the small icon.
2525 */
2526 if (g_fCanChangeIcon)
2527 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2528#endif
2529
2530 ui_get_shellsize();
2531
2532#ifdef MCH_WRITE_DUMP
2533 fdDump = fopen("dump", "wt");
2534
2535 if (fdDump)
2536 {
2537 time_t t;
2538
2539 time(&t);
2540 fputs(ctime(&t), fdDump);
2541 fflush(fdDump);
2542 }
2543#endif
2544
2545 g_fWindInitCalled = TRUE;
2546
2547#ifdef FEAT_MOUSE
2548 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2549#endif
2550
2551#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002552 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553#endif
2554
2555 /* This will be NULL on anything but NT 4.0 */
2556 s_pfnGetConsoleKeyboardLayoutName =
2557 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2558 "GetConsoleKeyboardLayoutNameA");
2559}
2560
2561/*
2562 * non-GUI version of mch_exit().
2563 * Shut down and exit with status `r'
2564 * Careful: mch_exit() may be called before mch_init()!
2565 */
2566 void
2567mch_exit(int r)
2568{
2569 stoptermcap();
2570
2571 if (g_fWindInitCalled)
2572 settmode(TMODE_COOK);
2573
2574 ml_close_all(TRUE); /* remove all memfiles */
2575
2576 if (g_fWindInitCalled)
2577 {
2578#ifdef FEAT_TITLE
2579 mch_restore_title(3);
2580 /*
2581 * Restore both the small and big icons of the console window to
2582 * what they were at startup. Don't do this when the window is
2583 * closed, Vim would hang here.
2584 */
2585 if (g_fCanChangeIcon && !g_fForceExit)
2586 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2587#endif
2588
2589#ifdef MCH_WRITE_DUMP
2590 if (fdDump)
2591 {
2592 time_t t;
2593
2594 time(&t);
2595 fputs(ctime(&t), fdDump);
2596 fclose(fdDump);
2597 }
2598 fdDump = NULL;
2599#endif
2600 }
2601
2602 SetConsoleCursorInfo(g_hConOut, &g_cci);
2603 SetConsoleMode(g_hConIn, g_cmodein);
2604 SetConsoleMode(g_hConOut, g_cmodeout);
2605
2606#ifdef DYNAMIC_GETTEXT
2607 dyn_libintl_end();
2608#endif
2609
2610 exit(r);
2611}
2612#endif /* !FEAT_GUI_W32 */
2613
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614/*
2615 * Do we have an interactive window?
2616 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002617/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 int
2619mch_check_win(
2620 int argc,
2621 char **argv)
2622{
2623 get_exe_name();
2624
2625#ifdef FEAT_GUI_W32
2626 return OK; /* GUI always has a tty */
2627#else
2628 if (isatty(1))
2629 return OK;
2630 return FAIL;
2631#endif
2632}
2633
2634
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002635#ifdef FEAT_MBYTE
2636/*
2637 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2638 * if it already exists. When "len" is > 0, also expand short to long
2639 * filenames.
2640 * Return FAIL if wide functions are not available, OK otherwise.
2641 * NOTE: much of this is identical to fname_case(), keep in sync!
2642 */
2643 static int
2644fname_casew(
2645 WCHAR *name,
2646 int len)
2647{
2648 WCHAR szTrueName[_MAX_PATH + 2];
2649 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2650 WCHAR *ptrue, *ptruePrev;
2651 WCHAR *porig, *porigPrev;
2652 int flen;
2653 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002654 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002655 int c;
2656 int slen;
2657
2658 flen = (int)wcslen(name);
2659 if (flen > _MAX_PATH)
2660 return OK;
2661
2662 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2663
2664 /* Build the new name in szTrueName[] one component at a time. */
2665 porig = name;
2666 ptrue = szTrueName;
2667
2668 if (iswalpha(porig[0]) && porig[1] == L':')
2669 {
2670 /* copy leading drive letter */
2671 *ptrue++ = *porig++;
2672 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002673 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002674 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002675
2676 while (*porig != NUL)
2677 {
2678 /* copy \ characters */
2679 while (*porig == psepc)
2680 *ptrue++ = *porig++;
2681
2682 ptruePrev = ptrue;
2683 porigPrev = porig;
2684 while (*porig != NUL && *porig != psepc)
2685 {
2686 *ptrue++ = *porig++;
2687 }
2688 *ptrue = NUL;
2689
2690 /* To avoid a slow failure append "\*" when searching a directory,
2691 * server or network share. */
2692 wcscpy(szTrueNameTemp, szTrueName);
2693 slen = (int)wcslen(szTrueNameTemp);
2694 if (*porig == psepc && slen + 2 < _MAX_PATH)
2695 wcscpy(szTrueNameTemp + slen, L"\\*");
2696
2697 /* Skip "", "." and "..". */
2698 if (ptrue > ptruePrev
2699 && (ptruePrev[0] != L'.'
2700 || (ptruePrev[1] != NUL
2701 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2702 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2703 != INVALID_HANDLE_VALUE)
2704 {
2705 c = *porig;
2706 *porig = NUL;
2707
2708 /* Only use the match when it's the same name (ignoring case) or
2709 * expansion is allowed and there is a match with the short name
2710 * and there is enough room. */
2711 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2712 || (len > 0
2713 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2714 && (int)(ptruePrev - szTrueName)
2715 + (int)wcslen(fb.cFileName) < len)))
2716 {
2717 wcscpy(ptruePrev, fb.cFileName);
2718
2719 /* Look for exact match and prefer it if found. Must be a
2720 * long name, otherwise there would be only one match. */
2721 while (FindNextFileW(hFind, &fb))
2722 {
2723 if (*fb.cAlternateFileName != NUL
2724 && (wcscoll(porigPrev, fb.cFileName) == 0
2725 || (len > 0
2726 && (_wcsicoll(porigPrev,
2727 fb.cAlternateFileName) == 0
2728 && (int)(ptruePrev - szTrueName)
2729 + (int)wcslen(fb.cFileName) < len))))
2730 {
2731 wcscpy(ptruePrev, fb.cFileName);
2732 break;
2733 }
2734 }
2735 }
2736 FindClose(hFind);
2737 *porig = c;
2738 ptrue = ptruePrev + wcslen(ptruePrev);
2739 }
2740 else if (hFind == INVALID_HANDLE_VALUE
2741 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2742 return FAIL;
2743 }
2744
2745 wcscpy(name, szTrueName);
2746 return OK;
2747}
2748#endif
2749
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750/*
2751 * fname_case(): Set the case of the file name, if it already exists.
2752 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002753 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754 */
2755 void
2756fname_case(
2757 char_u *name,
2758 int len)
2759{
2760 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002761 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002762 char *ptrue, *ptruePrev;
2763 char *porig, *porigPrev;
2764 int flen;
2765 WIN32_FIND_DATA fb;
2766 HANDLE hFind;
2767 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002768 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002769
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002770 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002771 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772 return;
2773
2774 slash_adjust(name);
2775
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002776#ifdef FEAT_MBYTE
2777 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2778 {
2779 WCHAR *p = enc_to_utf16(name, NULL);
2780
2781 if (p != NULL)
2782 {
2783 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002784 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002785
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002786 wcsncpy(buf, p, _MAX_PATH);
2787 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002788 vim_free(p);
2789
2790 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2791 {
2792 q = utf16_to_enc(buf, NULL);
2793 if (q != NULL)
2794 {
2795 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2796 vim_free(q);
2797 return;
2798 }
2799 }
2800 }
2801 /* Retry with non-wide function (for Windows 98). */
2802 }
2803#endif
2804
2805 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2806 * So we should check this after calling wide function. */
2807 if (flen > _MAX_PATH)
2808 return;
2809
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810 /* Build the new name in szTrueName[] one component at a time. */
2811 porig = name;
2812 ptrue = szTrueName;
2813
2814 if (isalpha(porig[0]) && porig[1] == ':')
2815 {
2816 /* copy leading drive letter */
2817 *ptrue++ = *porig++;
2818 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002819 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002820 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002821
2822 while (*porig != NUL)
2823 {
2824 /* copy \ characters */
2825 while (*porig == psepc)
2826 *ptrue++ = *porig++;
2827
2828 ptruePrev = ptrue;
2829 porigPrev = porig;
2830 while (*porig != NUL && *porig != psepc)
2831 {
2832#ifdef FEAT_MBYTE
2833 int l;
2834
2835 if (enc_dbcs)
2836 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002837 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838 while (--l >= 0)
2839 *ptrue++ = *porig++;
2840 }
2841 else
2842#endif
2843 *ptrue++ = *porig++;
2844 }
2845 *ptrue = NUL;
2846
Bram Moolenaar464c9252010-10-13 20:37:41 +02002847 /* To avoid a slow failure append "\*" when searching a directory,
2848 * server or network share. */
2849 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002850 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002851 if (*porig == psepc && slen + 2 < _MAX_PATH)
2852 STRCPY(szTrueNameTemp + slen, "\\*");
2853
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854 /* Skip "", "." and "..". */
2855 if (ptrue > ptruePrev
2856 && (ptruePrev[0] != '.'
2857 || (ptruePrev[1] != NUL
2858 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002859 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860 != INVALID_HANDLE_VALUE)
2861 {
2862 c = *porig;
2863 *porig = NUL;
2864
2865 /* Only use the match when it's the same name (ignoring case) or
2866 * expansion is allowed and there is a match with the short name
2867 * and there is enough room. */
2868 if (_stricoll(porigPrev, fb.cFileName) == 0
2869 || (len > 0
2870 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2871 && (int)(ptruePrev - szTrueName)
2872 + (int)strlen(fb.cFileName) < len)))
2873 {
2874 STRCPY(ptruePrev, fb.cFileName);
2875
2876 /* Look for exact match and prefer it if found. Must be a
2877 * long name, otherwise there would be only one match. */
2878 while (FindNextFile(hFind, &fb))
2879 {
2880 if (*fb.cAlternateFileName != NUL
2881 && (strcoll(porigPrev, fb.cFileName) == 0
2882 || (len > 0
2883 && (_stricoll(porigPrev,
2884 fb.cAlternateFileName) == 0
2885 && (int)(ptruePrev - szTrueName)
2886 + (int)strlen(fb.cFileName) < len))))
2887 {
2888 STRCPY(ptruePrev, fb.cFileName);
2889 break;
2890 }
2891 }
2892 }
2893 FindClose(hFind);
2894 *porig = c;
2895 ptrue = ptruePrev + strlen(ptruePrev);
2896 }
2897 }
2898
2899 STRCPY(name, szTrueName);
2900}
2901
2902
2903/*
2904 * Insert user name in s[len].
2905 */
2906 int
2907mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002908 char_u *s,
2909 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002911 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912 DWORD cch = sizeof szUserName;
2913
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002914#ifdef FEAT_MBYTE
2915 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2916 {
2917 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2918 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2919
2920 if (GetUserNameW(wszUserName, &wcch))
2921 {
2922 char_u *p = utf16_to_enc(wszUserName, NULL);
2923
2924 if (p != NULL)
2925 {
2926 vim_strncpy(s, p, len - 1);
2927 vim_free(p);
2928 return OK;
2929 }
2930 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002931 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2932 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002933 /* Retry with non-wide function (for Windows 98). */
2934 }
2935#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936 if (GetUserName(szUserName, &cch))
2937 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002938 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 return OK;
2940 }
2941 s[0] = NUL;
2942 return FAIL;
2943}
2944
2945
2946/*
2947 * Insert host name in s[len].
2948 */
2949 void
2950mch_get_host_name(
2951 char_u *s,
2952 int len)
2953{
2954 DWORD cch = len;
2955
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002956#ifdef FEAT_MBYTE
2957 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2958 {
2959 WCHAR wszHostName[256 + 1];
2960 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2961
2962 if (GetComputerNameW(wszHostName, &wcch))
2963 {
2964 char_u *p = utf16_to_enc(wszHostName, NULL);
2965
2966 if (p != NULL)
2967 {
2968 vim_strncpy(s, p, len - 1);
2969 vim_free(p);
2970 return;
2971 }
2972 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002973 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2974 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002975 /* Retry with non-wide function (for Windows 98). */
2976 }
2977#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002979 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980}
2981
2982
2983/*
2984 * return process ID
2985 */
2986 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002987mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988{
2989 return (long)GetCurrentProcessId();
2990}
2991
2992
2993/*
2994 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2995 * Return OK for success, FAIL for failure.
2996 */
2997 int
2998mch_dirname(
2999 char_u *buf,
3000 int len)
3001{
3002 /*
3003 * Originally this was:
3004 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3005 * But the Win32s known bug list says that getcwd() doesn't work
3006 * so use the Win32 system call instead. <Negri>
3007 */
3008#ifdef FEAT_MBYTE
3009 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3010 {
3011 WCHAR wbuf[_MAX_PATH + 1];
3012
3013 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3014 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003015 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016
3017 if (p != NULL)
3018 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003019 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 vim_free(p);
3021 return OK;
3022 }
3023 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003024 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3025 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026 /* Retry with non-wide function (for Windows 98). */
3027 }
3028#endif
3029 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3030}
3031
3032/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003033 * Get file permissions for "name".
3034 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 */
3036 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003037mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003039 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003040 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003042 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003043 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044}
3045
3046
3047/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003048 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003049 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003050 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 */
3052 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003053mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003055 long n = -1;
3056
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057#ifdef FEAT_MBYTE
3058 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3059 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003060 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061
3062 if (p != NULL)
3063 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003064 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003066 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003067 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068 /* Retry with non-wide function (for Windows 98). */
3069 }
3070 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003071 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003073 n = _chmod(name, perm);
3074 if (n == -1)
3075 return FAIL;
3076
3077 win32_set_archive(name);
3078
3079 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080}
3081
3082/*
3083 * Set hidden flag for "name".
3084 */
3085 void
3086mch_hide(char_u *name)
3087{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003088 int attrs = win32_getattrs(name);
3089 if (attrs == -1)
3090 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003092 attrs |= FILE_ATTRIBUTE_HIDDEN;
3093 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094}
3095
3096/*
3097 * return TRUE if "name" is a directory
3098 * return FALSE if "name" is not a directory or upon error
3099 */
3100 int
3101mch_isdir(char_u *name)
3102{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003103 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104
3105 if (f == -1)
3106 return FALSE; /* file does not exist at all */
3107
3108 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3109}
3110
3111/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003112 * Create directory "name".
3113 * Return 0 on success, -1 on error.
3114 */
3115 int
3116mch_mkdir(char_u *name)
3117{
3118#ifdef FEAT_MBYTE
3119 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3120 {
3121 WCHAR *p;
3122 int retval;
3123
3124 p = enc_to_utf16(name, NULL);
3125 if (p == NULL)
3126 return -1;
3127 retval = _wmkdir(p);
3128 vim_free(p);
3129 return retval;
3130 }
3131#endif
3132 return _mkdir(name);
3133}
3134
3135/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003136 * Return TRUE if file "fname" has more than one link.
3137 */
3138 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003139mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003140{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003141 BY_HANDLE_FILE_INFORMATION info;
3142
3143 return win32_fileinfo(fname, &info) == FILEINFO_OK
3144 && info.nNumberOfLinks > 1;
3145}
3146
3147/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003148 * Return TRUE if file "fname" is a symbolic link.
3149 */
3150 int
3151mch_is_symbolic_link(char_u *fname)
3152{
3153 HANDLE hFind;
3154 int res = FALSE;
3155 WIN32_FIND_DATAA findDataA;
3156 DWORD fileFlags = 0, reparseTag = 0;
3157#ifdef FEAT_MBYTE
3158 WCHAR *wn = NULL;
3159 WIN32_FIND_DATAW findDataW;
3160
3161 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3162 wn = enc_to_utf16(fname, NULL);
3163 if (wn != NULL)
3164 {
3165 hFind = FindFirstFileW(wn, &findDataW);
3166 vim_free(wn);
3167 if (hFind == INVALID_HANDLE_VALUE
3168 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3169 {
3170 /* Retry with non-wide function (for Windows 98). */
3171 hFind = FindFirstFile(fname, &findDataA);
3172 if (hFind != INVALID_HANDLE_VALUE)
3173 {
3174 fileFlags = findDataA.dwFileAttributes;
3175 reparseTag = findDataA.dwReserved0;
3176 }
3177 }
3178 else
3179 {
3180 fileFlags = findDataW.dwFileAttributes;
3181 reparseTag = findDataW.dwReserved0;
3182 }
3183 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003184 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003185#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003186 {
3187 hFind = FindFirstFile(fname, &findDataA);
3188 if (hFind != INVALID_HANDLE_VALUE)
3189 {
3190 fileFlags = findDataA.dwFileAttributes;
3191 reparseTag = findDataA.dwReserved0;
3192 }
3193 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003194
3195 if (hFind != INVALID_HANDLE_VALUE)
3196 FindClose(hFind);
3197
3198 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3199 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3200 res = TRUE;
3201
3202 return res;
3203}
3204
3205/*
3206 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3207 * link.
3208 */
3209 int
3210mch_is_linked(char_u *fname)
3211{
3212 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3213 return TRUE;
3214 return FALSE;
3215}
3216
3217/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003218 * Get the by-handle-file-information for "fname".
3219 * Returns FILEINFO_OK when OK.
3220 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3221 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3222 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3223 */
3224 int
3225win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3226{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003227 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003228 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003229#ifdef FEAT_MBYTE
3230 WCHAR *wn = NULL;
3231
3232 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003233 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003234 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003235 if (wn == NULL)
3236 res = FILEINFO_ENC_FAIL;
3237 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003238 if (wn != NULL)
3239 {
3240 hFile = CreateFileW(wn, /* file name */
3241 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003242 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003243 NULL, /* security descriptor */
3244 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003245 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003246 NULL); /* handle to template file */
3247 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003248 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003249 {
3250 /* Retry with non-wide function (for Windows 98). */
3251 vim_free(wn);
3252 wn = NULL;
3253 }
3254 }
3255 if (wn == NULL)
3256#endif
3257 hFile = CreateFile(fname, /* file name */
3258 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003259 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003260 NULL, /* security descriptor */
3261 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003262 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003263 NULL); /* handle to template file */
3264
3265 if (hFile != INVALID_HANDLE_VALUE)
3266 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003267 if (GetFileInformationByHandle(hFile, info) != 0)
3268 res = FILEINFO_OK;
3269 else
3270 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003271 CloseHandle(hFile);
3272 }
3273
3274#ifdef FEAT_MBYTE
3275 vim_free(wn);
3276#endif
3277 return res;
3278}
3279
3280/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003281 * get file attributes for `name'
3282 * -1 : error
3283 * else FILE_ATTRIBUTE_* defined in winnt.h
3284 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003285 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003286win32_getattrs(char_u *name)
3287{
3288 int attr;
3289#ifdef FEAT_MBYTE
3290 WCHAR *p = NULL;
3291
3292 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3293 p = enc_to_utf16(name, NULL);
3294
3295 if (p != NULL)
3296 {
3297 attr = GetFileAttributesW(p);
3298 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3299 {
3300 /* Retry with non-wide function (for Windows 98). */
3301 vim_free(p);
3302 p = NULL;
3303 }
3304 }
3305 if (p == NULL)
3306#endif
3307 attr = GetFileAttributes((char *)name);
3308#ifdef FEAT_MBYTE
3309 vim_free(p);
3310#endif
3311 return attr;
3312}
3313
3314/*
3315 * set file attributes for `name' to `attrs'
3316 *
3317 * return -1 for failure, 0 otherwise
3318 */
3319 static
3320 int
3321win32_setattrs(char_u *name, int attrs)
3322{
3323 int res;
3324#ifdef FEAT_MBYTE
3325 WCHAR *p = NULL;
3326
3327 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3328 p = enc_to_utf16(name, NULL);
3329
3330 if (p != NULL)
3331 {
3332 res = SetFileAttributesW(p, attrs);
3333 if (res == FALSE
3334 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3335 {
3336 /* Retry with non-wide function (for Windows 98). */
3337 vim_free(p);
3338 p = NULL;
3339 }
3340 }
3341 if (p == NULL)
3342#endif
3343 res = SetFileAttributes((char *)name, attrs);
3344#ifdef FEAT_MBYTE
3345 vim_free(p);
3346#endif
3347 return res ? 0 : -1;
3348}
3349
3350/*
3351 * Set archive flag for "name".
3352 */
3353 static
3354 int
3355win32_set_archive(char_u *name)
3356{
3357 int attrs = win32_getattrs(name);
3358 if (attrs == -1)
3359 return -1;
3360
3361 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3362 return win32_setattrs(name, attrs);
3363}
3364
3365/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 * Return TRUE if file or directory "name" is writable (not readonly).
3367 * Strange semantics of Win32: a readonly directory is writable, but you can't
3368 * delete a file. Let's say this means it is writable.
3369 */
3370 int
3371mch_writable(char_u *name)
3372{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003373 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003375 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3376 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003377}
3378
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379/*
3380 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003381 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382 * Return -1 if unknown.
3383 */
3384 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003385mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003387 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003388 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003389 char_u *p;
3390
3391 if (len >= _MAX_PATH) /* safety check */
3392 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003393 if (!use_path)
3394 {
3395 /* TODO: check if file is really executable. */
3396 return mch_getperm(name) != -1 && !mch_isdir(name);
3397 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003398
3399 /* If there already is an extension try using the name directly. Also do
3400 * this with a Unix-shell like 'shell'. */
3401 if (vim_strchr(gettail(name), '.') != NULL
3402 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003403 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003404 return TRUE;
3405
3406 /*
3407 * Loop over all extensions in $PATHEXT.
3408 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003409 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003410 p = mch_getenv("PATHEXT");
3411 if (p == NULL)
3412 p = (char_u *)".com;.exe;.bat;.cmd";
3413 while (*p)
3414 {
3415 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3416 {
3417 /* A single "." means no extension is added. */
3418 buf[len] = NUL;
3419 ++p;
3420 if (*p)
3421 ++p;
3422 }
3423 else
3424 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003425 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003426 return TRUE;
3427 }
3428 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003430
3431/*
3432 * Check what "name" is:
3433 * NODE_NORMAL: file or directory (or doesn't exist)
3434 * NODE_WRITABLE: writable device, socket, fifo, etc.
3435 * NODE_OTHER: non-writable things
3436 */
3437 int
3438mch_nodetype(char_u *name)
3439{
3440 HANDLE hFile;
3441 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003442#ifdef FEAT_MBYTE
3443 WCHAR *wn = NULL;
3444#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445
Bram Moolenaar043545e2006-10-10 16:44:07 +00003446 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3447 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3448 * here. */
3449 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3450 return NODE_WRITABLE;
3451
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003452#ifdef FEAT_MBYTE
3453 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3454 {
3455 wn = enc_to_utf16(name, NULL);
3456 if (wn != NULL)
3457 {
3458 hFile = CreateFileW(wn, /* file name */
3459 GENERIC_WRITE, /* access mode */
3460 0, /* share mode */
3461 NULL, /* security descriptor */
3462 OPEN_EXISTING, /* creation disposition */
3463 0, /* file attributes */
3464 NULL); /* handle to template file */
3465 if (hFile == INVALID_HANDLE_VALUE
3466 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3467 {
3468 /* Retry with non-wide function (for Windows 98). */
3469 vim_free(wn);
3470 wn = NULL;
3471 }
3472 }
3473 }
3474 if (wn == NULL)
3475#endif
3476 hFile = CreateFile(name, /* file name */
3477 GENERIC_WRITE, /* access mode */
3478 0, /* share mode */
3479 NULL, /* security descriptor */
3480 OPEN_EXISTING, /* creation disposition */
3481 0, /* file attributes */
3482 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003484#ifdef FEAT_MBYTE
3485 vim_free(wn);
3486#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487 if (hFile == INVALID_HANDLE_VALUE)
3488 return NODE_NORMAL;
3489
3490 type = GetFileType(hFile);
3491 CloseHandle(hFile);
3492 if (type == FILE_TYPE_CHAR)
3493 return NODE_WRITABLE;
3494 if (type == FILE_TYPE_DISK)
3495 return NODE_NORMAL;
3496 return NODE_OTHER;
3497}
3498
3499#ifdef HAVE_ACL
3500struct my_acl
3501{
3502 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3503 PSID pSidOwner;
3504 PSID pSidGroup;
3505 PACL pDacl;
3506 PACL pSacl;
3507};
3508#endif
3509
3510/*
3511 * Return a pointer to the ACL of file "fname" in allocated memory.
3512 * Return NULL if the ACL is not available for whatever reason.
3513 */
3514 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003515mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516{
3517#ifndef HAVE_ACL
3518 return (vim_acl_T)NULL;
3519#else
3520 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003521 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522
3523 /* This only works on Windows NT and 2000. */
3524 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3525 {
3526 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3527 if (p != NULL)
3528 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003529# ifdef FEAT_MBYTE
3530 WCHAR *wn = NULL;
3531
3532 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3533 wn = enc_to_utf16(fname, NULL);
3534 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003536 /* Try to retrieve the entire security descriptor. */
3537 err = pGetNamedSecurityInfoW(
3538 wn, // Abstract filename
3539 SE_FILE_OBJECT, // File Object
3540 OWNER_SECURITY_INFORMATION |
3541 GROUP_SECURITY_INFORMATION |
3542 DACL_SECURITY_INFORMATION |
3543 SACL_SECURITY_INFORMATION,
3544 &p->pSidOwner, // Ownership information.
3545 &p->pSidGroup, // Group membership.
3546 &p->pDacl, // Discretionary information.
3547 &p->pSacl, // For auditing purposes.
3548 &p->pSecurityDescriptor);
3549 if (err == ERROR_ACCESS_DENIED ||
3550 err == ERROR_PRIVILEGE_NOT_HELD)
3551 {
3552 /* Retrieve only DACL. */
3553 (void)pGetNamedSecurityInfoW(
3554 wn,
3555 SE_FILE_OBJECT,
3556 DACL_SECURITY_INFORMATION,
3557 NULL,
3558 NULL,
3559 &p->pDacl,
3560 NULL,
3561 &p->pSecurityDescriptor);
3562 }
3563 if (p->pSecurityDescriptor == NULL)
3564 {
3565 mch_free_acl((vim_acl_T)p);
3566 p = NULL;
3567 }
3568 vim_free(wn);
3569 }
3570 else
3571# endif
3572 {
3573 /* Try to retrieve the entire security descriptor. */
3574 err = pGetNamedSecurityInfo(
3575 (LPSTR)fname, // Abstract filename
3576 SE_FILE_OBJECT, // File Object
3577 OWNER_SECURITY_INFORMATION |
3578 GROUP_SECURITY_INFORMATION |
3579 DACL_SECURITY_INFORMATION |
3580 SACL_SECURITY_INFORMATION,
3581 &p->pSidOwner, // Ownership information.
3582 &p->pSidGroup, // Group membership.
3583 &p->pDacl, // Discretionary information.
3584 &p->pSacl, // For auditing purposes.
3585 &p->pSecurityDescriptor);
3586 if (err == ERROR_ACCESS_DENIED ||
3587 err == ERROR_PRIVILEGE_NOT_HELD)
3588 {
3589 /* Retrieve only DACL. */
3590 (void)pGetNamedSecurityInfo(
3591 (LPSTR)fname,
3592 SE_FILE_OBJECT,
3593 DACL_SECURITY_INFORMATION,
3594 NULL,
3595 NULL,
3596 &p->pDacl,
3597 NULL,
3598 &p->pSecurityDescriptor);
3599 }
3600 if (p->pSecurityDescriptor == NULL)
3601 {
3602 mch_free_acl((vim_acl_T)p);
3603 p = NULL;
3604 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 }
3606 }
3607 }
3608
3609 return (vim_acl_T)p;
3610#endif
3611}
3612
Bram Moolenaar27515922013-06-29 15:36:26 +02003613#ifdef HAVE_ACL
3614/*
3615 * Check if "acl" contains inherited ACE.
3616 */
3617 static BOOL
3618is_acl_inherited(PACL acl)
3619{
3620 DWORD i;
3621 ACL_SIZE_INFORMATION acl_info;
3622 PACCESS_ALLOWED_ACE ace;
3623
3624 acl_info.AceCount = 0;
3625 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3626 for (i = 0; i < acl_info.AceCount; i++)
3627 {
3628 GetAce(acl, i, (LPVOID *)&ace);
3629 if (ace->Header.AceFlags & INHERITED_ACE)
3630 return TRUE;
3631 }
3632 return FALSE;
3633}
3634#endif
3635
Bram Moolenaar071d4272004-06-13 20:20:40 +00003636/*
3637 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3638 * Errors are ignored.
3639 * This must only be called with "acl" equal to what mch_get_acl() returned.
3640 */
3641 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003642mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003643{
3644#ifdef HAVE_ACL
3645 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003646 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647
3648 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003649 {
3650# ifdef FEAT_MBYTE
3651 WCHAR *wn = NULL;
3652# endif
3653
3654 /* Set security flags */
3655 if (p->pSidOwner)
3656 sec_info |= OWNER_SECURITY_INFORMATION;
3657 if (p->pSidGroup)
3658 sec_info |= GROUP_SECURITY_INFORMATION;
3659 if (p->pDacl)
3660 {
3661 sec_info |= DACL_SECURITY_INFORMATION;
3662 /* Do not inherit its parent's DACL.
3663 * If the DACL is inherited, Cygwin permissions would be changed.
3664 */
3665 if (!is_acl_inherited(p->pDacl))
3666 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3667 }
3668 if (p->pSacl)
3669 sec_info |= SACL_SECURITY_INFORMATION;
3670
3671# ifdef FEAT_MBYTE
3672 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3673 wn = enc_to_utf16(fname, NULL);
3674 if (wn != NULL)
3675 {
3676 (void)pSetNamedSecurityInfoW(
3677 wn, // Abstract filename
3678 SE_FILE_OBJECT, // File Object
3679 sec_info,
3680 p->pSidOwner, // Ownership information.
3681 p->pSidGroup, // Group membership.
3682 p->pDacl, // Discretionary information.
3683 p->pSacl // For auditing purposes.
3684 );
3685 vim_free(wn);
3686 }
3687 else
3688# endif
3689 {
3690 (void)pSetNamedSecurityInfo(
3691 (LPSTR)fname, // Abstract filename
3692 SE_FILE_OBJECT, // File Object
3693 sec_info,
3694 p->pSidOwner, // Ownership information.
3695 p->pSidGroup, // Group membership.
3696 p->pDacl, // Discretionary information.
3697 p->pSacl // For auditing purposes.
3698 );
3699 }
3700 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701#endif
3702}
3703
3704 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003705mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706{
3707#ifdef HAVE_ACL
3708 struct my_acl *p = (struct my_acl *)acl;
3709
3710 if (p != NULL)
3711 {
3712 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3713 vim_free(p);
3714 }
3715#endif
3716}
3717
3718#ifndef FEAT_GUI_W32
3719
3720/*
3721 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3722 */
3723 static BOOL WINAPI
3724handler_routine(
3725 DWORD dwCtrlType)
3726{
3727 switch (dwCtrlType)
3728 {
3729 case CTRL_C_EVENT:
3730 if (ctrl_c_interrupts)
3731 g_fCtrlCPressed = TRUE;
3732 return TRUE;
3733
3734 case CTRL_BREAK_EVENT:
3735 g_fCBrkPressed = TRUE;
3736 return TRUE;
3737
3738 /* fatal events: shut down gracefully */
3739 case CTRL_CLOSE_EVENT:
3740 case CTRL_LOGOFF_EVENT:
3741 case CTRL_SHUTDOWN_EVENT:
3742 windgoto((int)Rows - 1, 0);
3743 g_fForceExit = TRUE;
3744
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003745 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 (dwCtrlType == CTRL_CLOSE_EVENT
3747 ? _("close")
3748 : dwCtrlType == CTRL_LOGOFF_EVENT
3749 ? _("logoff")
3750 : _("shutdown")));
3751#ifdef DEBUG
3752 OutputDebugString(IObuff);
3753#endif
3754
3755 preserve_exit(); /* output IObuff, preserve files and exit */
3756
3757 return TRUE; /* not reached */
3758
3759 default:
3760 return FALSE;
3761 }
3762}
3763
3764
3765/*
3766 * set the tty in (raw) ? "raw" : "cooked" mode
3767 */
3768 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003769mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770{
3771 DWORD cmodein;
3772 DWORD cmodeout;
3773 BOOL bEnableHandler;
3774
3775 GetConsoleMode(g_hConIn, &cmodein);
3776 GetConsoleMode(g_hConOut, &cmodeout);
3777 if (tmode == TMODE_RAW)
3778 {
3779 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3780 ENABLE_ECHO_INPUT);
3781#ifdef FEAT_MOUSE
3782 if (g_fMouseActive)
3783 cmodein |= ENABLE_MOUSE_INPUT;
3784#endif
3785 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3786 bEnableHandler = TRUE;
3787 }
3788 else /* cooked */
3789 {
3790 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3791 ENABLE_ECHO_INPUT);
3792 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3793 bEnableHandler = FALSE;
3794 }
3795 SetConsoleMode(g_hConIn, cmodein);
3796 SetConsoleMode(g_hConOut, cmodeout);
3797 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3798
3799#ifdef MCH_WRITE_DUMP
3800 if (fdDump)
3801 {
3802 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3803 tmode == TMODE_RAW ? "raw" :
3804 tmode == TMODE_COOK ? "cooked" : "normal",
3805 cmodein, cmodeout);
3806 fflush(fdDump);
3807 }
3808#endif
3809}
3810
3811
3812/*
3813 * Get the size of the current window in `Rows' and `Columns'
3814 * Return OK when size could be determined, FAIL otherwise.
3815 */
3816 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003817mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818{
3819 CONSOLE_SCREEN_BUFFER_INFO csbi;
3820
3821 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3822 {
3823 /*
3824 * For some reason, we are trying to get the screen dimensions
3825 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3826 * variables are really intended to mean the size of Vim screen
3827 * while in termcap mode.
3828 */
3829 Rows = g_cbTermcap.Info.dwSize.Y;
3830 Columns = g_cbTermcap.Info.dwSize.X;
3831 }
3832 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3833 {
3834 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3835 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3836 }
3837 else
3838 {
3839 Rows = 25;
3840 Columns = 80;
3841 }
3842 return OK;
3843}
3844
3845/*
3846 * Set a console window to `xSize' * `ySize'
3847 */
3848 static void
3849ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003850 HANDLE hConsole,
3851 int xSize,
3852 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003853{
3854 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3855 SMALL_RECT srWindowRect; /* hold the new console size */
3856 COORD coordScreen;
3857
3858#ifdef MCH_WRITE_DUMP
3859 if (fdDump)
3860 {
3861 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3862 fflush(fdDump);
3863 }
3864#endif
3865
3866 /* get the largest size we can size the console window to */
3867 coordScreen = GetLargestConsoleWindowSize(hConsole);
3868
3869 /* define the new console window size and scroll position */
3870 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3871 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3872 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3873
3874 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3875 {
3876 int sx, sy;
3877
3878 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3879 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3880 if (sy < ySize || sx < xSize)
3881 {
3882 /*
3883 * Increasing number of lines/columns, do buffer first.
3884 * Use the maximal size in x and y direction.
3885 */
3886 if (sy < ySize)
3887 coordScreen.Y = ySize;
3888 else
3889 coordScreen.Y = sy;
3890 if (sx < xSize)
3891 coordScreen.X = xSize;
3892 else
3893 coordScreen.X = sx;
3894 SetConsoleScreenBufferSize(hConsole, coordScreen);
3895 }
3896 }
3897
3898 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3899 {
3900#ifdef MCH_WRITE_DUMP
3901 if (fdDump)
3902 {
3903 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3904 GetLastError());
3905 fflush(fdDump);
3906 }
3907#endif
3908 }
3909
3910 /* define the new console buffer size */
3911 coordScreen.X = xSize;
3912 coordScreen.Y = ySize;
3913
3914 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3915 {
3916#ifdef MCH_WRITE_DUMP
3917 if (fdDump)
3918 {
3919 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3920 GetLastError());
3921 fflush(fdDump);
3922 }
3923#endif
3924 }
3925}
3926
3927
3928/*
3929 * Set the console window to `Rows' * `Columns'
3930 */
3931 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003932mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933{
3934 COORD coordScreen;
3935
3936 /* Don't change window size while still starting up */
3937 if (suppress_winsize != 0)
3938 {
3939 suppress_winsize = 2;
3940 return;
3941 }
3942
3943 if (term_console)
3944 {
3945 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3946
3947 /* Clamp Rows and Columns to reasonable values */
3948 if (Rows > coordScreen.Y)
3949 Rows = coordScreen.Y;
3950 if (Columns > coordScreen.X)
3951 Columns = coordScreen.X;
3952
3953 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3954 }
3955}
3956
3957/*
3958 * Rows and/or Columns has changed.
3959 */
3960 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003961mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962{
3963 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3964}
3965
3966
3967/*
3968 * Called when started up, to set the winsize that was delayed.
3969 */
3970 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003971mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003972{
3973 if (suppress_winsize == 2)
3974 {
3975 suppress_winsize = 0;
3976 mch_set_shellsize();
3977 shell_resized();
3978 }
3979 suppress_winsize = 0;
3980}
3981#endif /* FEAT_GUI_W32 */
3982
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003983 static BOOL
3984vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003985 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003986 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003987 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003988 STARTUPINFO *si,
3989 PROCESS_INFORMATION *pi)
3990{
3991# ifdef FEAT_MBYTE
3992 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3993 {
3994 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
3995
3996 if (wcmd != NULL)
3997 {
3998 BOOL ret;
3999 ret = CreateProcessW(
4000 NULL, /* Executable name */
4001 wcmd, /* Command to execute */
4002 NULL, /* Process security attributes */
4003 NULL, /* Thread security attributes */
4004 inherit_handles, /* Inherit handles */
4005 flags, /* Creation flags */
4006 NULL, /* Environment */
4007 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004008 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004009 pi); /* Process information */
4010 vim_free(wcmd);
4011 return ret;
4012 }
4013 }
4014#endif
4015 return CreateProcess(
4016 NULL, /* Executable name */
4017 cmd, /* Command to execute */
4018 NULL, /* Process security attributes */
4019 NULL, /* Thread security attributes */
4020 inherit_handles, /* Inherit handles */
4021 flags, /* Creation flags */
4022 NULL, /* Environment */
4023 NULL, /* Current directory */
4024 si, /* Startup information */
4025 pi); /* Process information */
4026}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004027
4028
4029#if defined(FEAT_GUI_W32) || defined(PROTO)
4030
4031/*
4032 * Specialised version of system() for Win32 GUI mode.
4033 * This version proceeds as follows:
4034 * 1. Create a console window for use by the subprocess
4035 * 2. Run the subprocess (it gets the allocated console by default)
4036 * 3. Wait for the subprocess to terminate and get its exit code
4037 * 4. Prompt the user to press a key to close the console window
4038 */
4039 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004040mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041{
4042 STARTUPINFO si;
4043 PROCESS_INFORMATION pi;
4044 DWORD ret = 0;
4045 HWND hwnd = GetFocus();
4046
4047 si.cb = sizeof(si);
4048 si.lpReserved = NULL;
4049 si.lpDesktop = NULL;
4050 si.lpTitle = NULL;
4051 si.dwFlags = STARTF_USESHOWWINDOW;
4052 /*
4053 * It's nicer to run a filter command in a minimized window, but in
4054 * Windows 95 this makes the command MUCH slower. We can't do it under
4055 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004056 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 */
4058 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004059 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004060 else
4061 si.wShowWindow = SW_SHOWNORMAL;
4062 si.cbReserved2 = 0;
4063 si.lpReserved2 = NULL;
4064
4065 /* There is a strange error on Windows 95 when using "c:\\command.com".
4066 * When the "c:\\" is left out it works OK...? */
4067 if (mch_windows95()
4068 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4069 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4070 cmd += 3;
4071
4072 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004073 vim_create_process(cmd, FALSE,
4074 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004075
4076 /* Wait for the command to terminate before continuing */
4077 if (g_PlatformId != VER_PLATFORM_WIN32s)
4078 {
4079#ifdef FEAT_GUI
4080 int delay = 1;
4081
4082 /* Keep updating the window while waiting for the shell to finish. */
4083 for (;;)
4084 {
4085 MSG msg;
4086
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004087 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088 {
4089 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004090 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004091 delay = 1;
4092 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093 }
4094 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4095 break;
4096
4097 /* We start waiting for a very short time and then increase it, so
4098 * that we respond quickly when the process is quick, and don't
4099 * consume too much overhead when it's slow. */
4100 if (delay < 50)
4101 delay += 10;
4102 }
4103#else
4104 WaitForSingleObject(pi.hProcess, INFINITE);
4105#endif
4106
4107 /* Get the command exit code */
4108 GetExitCodeProcess(pi.hProcess, &ret);
4109 }
4110 else
4111 {
4112 /*
4113 * This ugly code is the only quick way of performing
4114 * a synchronous spawn under Win32s. Yuk.
4115 */
4116 num_windows = 0;
4117 EnumWindows(win32ssynch_cb, 0);
4118 old_num_windows = num_windows;
4119 do
4120 {
4121 Sleep(1000);
4122 num_windows = 0;
4123 EnumWindows(win32ssynch_cb, 0);
4124 } while (num_windows == old_num_windows);
4125 ret = 0;
4126 }
4127
4128 /* Close the handles to the subprocess, so that it goes away */
4129 CloseHandle(pi.hThread);
4130 CloseHandle(pi.hProcess);
4131
4132 /* Try to get input focus back. Doesn't always work though. */
4133 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4134
4135 return ret;
4136}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004137
4138/*
4139 * Thread launched by the gui to send the current buffer data to the
4140 * process. This way avoid to hang up vim totally if the children
4141 * process take a long time to process the lines.
4142 */
4143 static DWORD WINAPI
4144sub_process_writer(LPVOID param)
4145{
4146 HANDLE g_hChildStd_IN_Wr = param;
4147 linenr_T lnum = curbuf->b_op_start.lnum;
4148 DWORD len = 0;
4149 DWORD l;
4150 char_u *lp = ml_get(lnum);
4151 char_u *s;
4152 int written = 0;
4153
4154 for (;;)
4155 {
4156 l = (DWORD)STRLEN(lp + written);
4157 if (l == 0)
4158 len = 0;
4159 else if (lp[written] == NL)
4160 {
4161 /* NL -> NUL translation */
4162 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4163 }
4164 else
4165 {
4166 s = vim_strchr(lp + written, NL);
4167 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4168 s == NULL ? l : (DWORD)(s - (lp + written)),
4169 &len, NULL);
4170 }
4171 if (len == (int)l)
4172 {
4173 /* Finished a line, add a NL, unless this line should not have
4174 * one. */
4175 if (lnum != curbuf->b_op_end.lnum
4176 || !curbuf->b_p_bin
4177 || (lnum != curbuf->b_no_eol_lnum
4178 && (lnum != curbuf->b_ml.ml_line_count
4179 || curbuf->b_p_eol)))
4180 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004181 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004182 }
4183
4184 ++lnum;
4185 if (lnum > curbuf->b_op_end.lnum)
4186 break;
4187
4188 lp = ml_get(lnum);
4189 written = 0;
4190 }
4191 else if (len > 0)
4192 written += len;
4193 }
4194
4195 /* finished all the lines, close pipe */
4196 CloseHandle(g_hChildStd_IN_Wr);
4197 ExitThread(0);
4198}
4199
4200
4201# define BUFLEN 100 /* length for buffer, stolen from unix version */
4202
4203/*
4204 * This function read from the children's stdout and write the
4205 * data on screen or in the buffer accordingly.
4206 */
4207 static void
4208dump_pipe(int options,
4209 HANDLE g_hChildStd_OUT_Rd,
4210 garray_T *ga,
4211 char_u buffer[],
4212 DWORD *buffer_off)
4213{
4214 DWORD availableBytes = 0;
4215 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004216 int ret;
4217 DWORD len;
4218 DWORD toRead;
4219 int repeatCount;
4220
4221 /* we query the pipe to see if there is any data to read
4222 * to avoid to perform a blocking read */
4223 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4224 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004225 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004226 NULL, /* number of read bytes */
4227 &availableBytes, /* available bytes total */
4228 NULL); /* byteLeft */
4229
4230 repeatCount = 0;
4231 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004232 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004233 {
4234 repeatCount++;
4235 toRead =
4236# ifdef FEAT_MBYTE
4237 (DWORD)(BUFLEN - *buffer_off);
4238# else
4239 (DWORD)BUFLEN;
4240# endif
4241 toRead = availableBytes < toRead ? availableBytes : toRead;
4242 ReadFile(g_hChildStd_OUT_Rd, buffer
4243# ifdef FEAT_MBYTE
4244 + *buffer_off, toRead
4245# else
4246 , toRead
4247# endif
4248 , &len, NULL);
4249
4250 /* If we haven't read anything, there is a problem */
4251 if (len == 0)
4252 break;
4253
4254 availableBytes -= len;
4255
4256 if (options & SHELL_READ)
4257 {
4258 /* Do NUL -> NL translation, append NL separated
4259 * lines to the current buffer. */
4260 for (i = 0; i < len; ++i)
4261 {
4262 if (buffer[i] == NL)
4263 append_ga_line(ga);
4264 else if (buffer[i] == NUL)
4265 ga_append(ga, NL);
4266 else
4267 ga_append(ga, buffer[i]);
4268 }
4269 }
4270# ifdef FEAT_MBYTE
4271 else if (has_mbyte)
4272 {
4273 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004274 int c;
4275 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004276
4277 len += *buffer_off;
4278 buffer[len] = NUL;
4279
4280 /* Check if the last character in buffer[] is
4281 * incomplete, keep these bytes for the next
4282 * round. */
4283 for (p = buffer; p < buffer + len; p += l)
4284 {
4285 l = mb_cptr2len(p);
4286 if (l == 0)
4287 l = 1; /* NUL byte? */
4288 else if (MB_BYTE2LEN(*p) != l)
4289 break;
4290 }
4291 if (p == buffer) /* no complete character */
4292 {
4293 /* avoid getting stuck at an illegal byte */
4294 if (len >= 12)
4295 ++p;
4296 else
4297 {
4298 *buffer_off = len;
4299 return;
4300 }
4301 }
4302 c = *p;
4303 *p = NUL;
4304 msg_puts(buffer);
4305 if (p < buffer + len)
4306 {
4307 *p = c;
4308 *buffer_off = (DWORD)((buffer + len) - p);
4309 mch_memmove(buffer, p, *buffer_off);
4310 return;
4311 }
4312 *buffer_off = 0;
4313 }
4314# endif /* FEAT_MBYTE */
4315 else
4316 {
4317 buffer[len] = NUL;
4318 msg_puts(buffer);
4319 }
4320
4321 windgoto(msg_row, msg_col);
4322 cursor_on();
4323 out_flush();
4324 }
4325}
4326
4327/*
4328 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4329 * for communication and doesn't open any new window.
4330 */
4331 static int
4332mch_system_piped(char *cmd, int options)
4333{
4334 STARTUPINFO si;
4335 PROCESS_INFORMATION pi;
4336 DWORD ret = 0;
4337
4338 HANDLE g_hChildStd_IN_Rd = NULL;
4339 HANDLE g_hChildStd_IN_Wr = NULL;
4340 HANDLE g_hChildStd_OUT_Rd = NULL;
4341 HANDLE g_hChildStd_OUT_Wr = NULL;
4342
4343 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4344 DWORD len;
4345
4346 /* buffer used to receive keys */
4347 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4348 int ta_len = 0; /* valid bytes in ta_buf[] */
4349
4350 DWORD i;
4351 int c;
4352 int noread_cnt = 0;
4353 garray_T ga;
4354 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004355 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004356 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004357
4358 SECURITY_ATTRIBUTES saAttr;
4359
4360 /* Set the bInheritHandle flag so pipe handles are inherited. */
4361 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4362 saAttr.bInheritHandle = TRUE;
4363 saAttr.lpSecurityDescriptor = NULL;
4364
4365 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4366 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4367 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4368 /* Create a pipe for the child process's STDIN. */
4369 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4370 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4371 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4372 {
4373 CloseHandle(g_hChildStd_IN_Rd);
4374 CloseHandle(g_hChildStd_IN_Wr);
4375 CloseHandle(g_hChildStd_OUT_Rd);
4376 CloseHandle(g_hChildStd_OUT_Wr);
4377 MSG_PUTS(_("\nCannot create pipes\n"));
4378 }
4379
4380 si.cb = sizeof(si);
4381 si.lpReserved = NULL;
4382 si.lpDesktop = NULL;
4383 si.lpTitle = NULL;
4384 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4385
4386 /* set-up our file redirection */
4387 si.hStdError = g_hChildStd_OUT_Wr;
4388 si.hStdOutput = g_hChildStd_OUT_Wr;
4389 si.hStdInput = g_hChildStd_IN_Rd;
4390 si.wShowWindow = SW_HIDE;
4391 si.cbReserved2 = 0;
4392 si.lpReserved2 = NULL;
4393
4394 if (options & SHELL_READ)
4395 ga_init2(&ga, 1, BUFLEN);
4396
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004397 if (cmd != NULL)
4398 {
4399 p = (char *)vim_strsave((char_u *)cmd);
4400 if (p != NULL)
4401 unescape_shellxquote((char_u *)p, p_sxe);
4402 else
4403 p = cmd;
4404 }
4405
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004406 /* Now, run the command.
4407 * About "Inherit handles" being TRUE: this command can be litigious,
4408 * handle inheritance was deactivated for pending temp file, but, if we
4409 * deactivate it, the pipes don't work for some reason. */
4410 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004411
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004412 if (p != cmd)
4413 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004414
4415 /* Close our unused side of the pipes */
4416 CloseHandle(g_hChildStd_IN_Rd);
4417 CloseHandle(g_hChildStd_OUT_Wr);
4418
4419 if (options & SHELL_WRITE)
4420 {
4421 HANDLE thread =
4422 CreateThread(NULL, /* security attributes */
4423 0, /* default stack size */
4424 sub_process_writer, /* function to be executed */
4425 g_hChildStd_IN_Wr, /* parameter */
4426 0, /* creation flag, start immediately */
4427 NULL); /* we don't care about thread id */
4428 CloseHandle(thread);
4429 g_hChildStd_IN_Wr = NULL;
4430 }
4431
4432 /* Keep updating the window while waiting for the shell to finish. */
4433 for (;;)
4434 {
4435 MSG msg;
4436
Bram Moolenaar175d0702013-12-11 18:36:33 +01004437 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004438 {
4439 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004440 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004441 }
4442
4443 /* write pipe information in the window */
4444 if ((options & (SHELL_READ|SHELL_WRITE))
4445# ifdef FEAT_GUI
4446 || gui.in_use
4447# endif
4448 )
4449 {
4450 len = 0;
4451 if (!(options & SHELL_EXPAND)
4452 && ((options &
4453 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4454 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4455# ifdef FEAT_GUI
4456 || gui.in_use
4457# endif
4458 )
4459 && (ta_len > 0 || noread_cnt > 4))
4460 {
4461 if (ta_len == 0)
4462 {
4463 /* Get extra characters when we don't have any. Reset the
4464 * counter and timer. */
4465 noread_cnt = 0;
4466# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4467 gettimeofday(&start_tv, NULL);
4468# endif
4469 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4470 }
4471 if (ta_len > 0 || len > 0)
4472 {
4473 /*
4474 * For pipes: Check for CTRL-C: send interrupt signal to
4475 * child. Check for CTRL-D: EOF, close pipe to child.
4476 */
4477 if (len == 1 && cmd != NULL)
4478 {
4479 if (ta_buf[ta_len] == Ctrl_C)
4480 {
4481 /* Learn what exit code is expected, for
4482 * now put 9 as SIGKILL */
4483 TerminateProcess(pi.hProcess, 9);
4484 }
4485 if (ta_buf[ta_len] == Ctrl_D)
4486 {
4487 CloseHandle(g_hChildStd_IN_Wr);
4488 g_hChildStd_IN_Wr = NULL;
4489 }
4490 }
4491
4492 /* replace K_BS by <BS> and K_DEL by <DEL> */
4493 for (i = ta_len; i < ta_len + len; ++i)
4494 {
4495 if (ta_buf[i] == CSI && len - i > 2)
4496 {
4497 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4498 if (c == K_DEL || c == K_KDEL || c == K_BS)
4499 {
4500 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4501 (size_t)(len - i - 2));
4502 if (c == K_DEL || c == K_KDEL)
4503 ta_buf[i] = DEL;
4504 else
4505 ta_buf[i] = Ctrl_H;
4506 len -= 2;
4507 }
4508 }
4509 else if (ta_buf[i] == '\r')
4510 ta_buf[i] = '\n';
4511# ifdef FEAT_MBYTE
4512 if (has_mbyte)
4513 i += (*mb_ptr2len_len)(ta_buf + i,
4514 ta_len + len - i) - 1;
4515# endif
4516 }
4517
4518 /*
4519 * For pipes: echo the typed characters. For a pty this
4520 * does not seem to work.
4521 */
4522 for (i = ta_len; i < ta_len + len; ++i)
4523 {
4524 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4525 msg_putchar(ta_buf[i]);
4526# ifdef FEAT_MBYTE
4527 else if (has_mbyte)
4528 {
4529 int l = (*mb_ptr2len)(ta_buf + i);
4530
4531 msg_outtrans_len(ta_buf + i, l);
4532 i += l - 1;
4533 }
4534# endif
4535 else
4536 msg_outtrans_len(ta_buf + i, 1);
4537 }
4538 windgoto(msg_row, msg_col);
4539 out_flush();
4540
4541 ta_len += len;
4542
4543 /*
4544 * Write the characters to the child, unless EOF has been
4545 * typed for pipes. Write one character at a time, to
4546 * avoid losing too much typeahead. When writing buffer
4547 * lines, drop the typed characters (only check for
4548 * CTRL-C).
4549 */
4550 if (options & SHELL_WRITE)
4551 ta_len = 0;
4552 else if (g_hChildStd_IN_Wr != NULL)
4553 {
4554 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4555 1, &len, NULL);
4556 // if we are typing in, we want to keep things reactive
4557 delay = 1;
4558 if (len > 0)
4559 {
4560 ta_len -= len;
4561 mch_memmove(ta_buf, ta_buf + len, ta_len);
4562 }
4563 }
4564 }
4565 }
4566 }
4567
4568 if (ta_len)
4569 ui_inchar_undo(ta_buf, ta_len);
4570
4571 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4572 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004573 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004574 break;
4575 }
4576
4577 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004578 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004579
4580 /* We start waiting for a very short time and then increase it, so
4581 * that we respond quickly when the process is quick, and don't
4582 * consume too much overhead when it's slow. */
4583 if (delay < 50)
4584 delay += 10;
4585 }
4586
4587 /* Close the pipe */
4588 CloseHandle(g_hChildStd_OUT_Rd);
4589 if (g_hChildStd_IN_Wr != NULL)
4590 CloseHandle(g_hChildStd_IN_Wr);
4591
4592 WaitForSingleObject(pi.hProcess, INFINITE);
4593
4594 /* Get the command exit code */
4595 GetExitCodeProcess(pi.hProcess, &ret);
4596
4597 if (options & SHELL_READ)
4598 {
4599 if (ga.ga_len > 0)
4600 {
4601 append_ga_line(&ga);
4602 /* remember that the NL was missing */
4603 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4604 }
4605 else
4606 curbuf->b_no_eol_lnum = 0;
4607 ga_clear(&ga);
4608 }
4609
4610 /* Close the handles to the subprocess, so that it goes away */
4611 CloseHandle(pi.hThread);
4612 CloseHandle(pi.hProcess);
4613
4614 return ret;
4615}
4616
4617 static int
4618mch_system(char *cmd, int options)
4619{
4620 /* if we can pipe and the shelltemp option is off */
4621 if (allowPiping && !p_stmp)
4622 return mch_system_piped(cmd, options);
4623 else
4624 return mch_system_classic(cmd, options);
4625}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626#else
4627
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004628# ifdef FEAT_MBYTE
4629 static int
4630mch_system(char *cmd, int options)
4631{
4632 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4633 {
4634 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4635 if (wcmd != NULL)
4636 {
4637 int ret = _wsystem(wcmd);
4638 vim_free(wcmd);
4639 return ret;
4640 }
4641 }
4642 return system(cmd);
4643}
4644# else
4645# define mch_system(c, o) system(c)
4646# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647
4648#endif
4649
4650/*
4651 * Either execute a command by calling the shell or start a new shell
4652 */
4653 int
4654mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004655 char_u *cmd,
4656 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004657{
4658 int x = 0;
4659 int tmode = cur_tmode;
4660#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004661 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004662# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004663 int did_set_title = FALSE;
4664
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004665 /* Change the title to reflect that we are in a subshell. */
4666 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4667 {
4668 WCHAR szShellTitle[512];
4669
4670 if (GetConsoleTitleW(szShellTitle,
4671 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4672 {
4673 if (cmd == NULL)
4674 wcscat(szShellTitle, L" :sh");
4675 else
4676 {
4677 WCHAR *wn = enc_to_utf16(cmd, NULL);
4678
4679 if (wn != NULL)
4680 {
4681 wcscat(szShellTitle, L" - !");
4682 if ((wcslen(szShellTitle) + wcslen(wn) <
4683 sizeof(szShellTitle)/sizeof(WCHAR)))
4684 wcscat(szShellTitle, wn);
4685 SetConsoleTitleW(szShellTitle);
4686 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004687 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004688 }
4689 }
4690 }
4691 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004692 if (!did_set_title)
4693# endif
4694 /* Change the title to reflect that we are in a subshell. */
4695 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004696 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004697 if (cmd == NULL)
4698 strcat(szShellTitle, " :sh");
4699 else
4700 {
4701 strcat(szShellTitle, " - !");
4702 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4703 strcat(szShellTitle, cmd);
4704 }
4705 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004707#endif
4708
4709 out_flush();
4710
4711#ifdef MCH_WRITE_DUMP
4712 if (fdDump)
4713 {
4714 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4715 fflush(fdDump);
4716 }
4717#endif
4718
4719 /*
4720 * Catch all deadly signals while running the external command, because a
4721 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4722 */
4723 signal(SIGINT, SIG_IGN);
4724#if defined(__GNUC__) && !defined(__MINGW32__)
4725 signal(SIGKILL, SIG_IGN);
4726#else
4727 signal(SIGBREAK, SIG_IGN);
4728#endif
4729 signal(SIGILL, SIG_IGN);
4730 signal(SIGFPE, SIG_IGN);
4731 signal(SIGSEGV, SIG_IGN);
4732 signal(SIGTERM, SIG_IGN);
4733 signal(SIGABRT, SIG_IGN);
4734
4735 if (options & SHELL_COOKED)
4736 settmode(TMODE_COOK); /* set to normal mode */
4737
4738 if (cmd == NULL)
4739 {
4740 x = mch_system(p_sh, options);
4741 }
4742 else
4743 {
4744 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004745 char_u *newcmd = NULL;
4746 char_u *cmdbase = cmd;
4747 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004748
4749 /* Skip a leading ", ( and "(. */
4750 if (*cmdbase == '"' )
4751 ++cmdbase;
4752 if (*cmdbase == '(')
4753 ++cmdbase;
4754
4755 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4756 {
4757 STARTUPINFO si;
4758 PROCESS_INFORMATION pi;
4759 DWORD flags = CREATE_NEW_CONSOLE;
4760 char_u *p;
4761
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004762 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004763 si.cb = sizeof(si);
4764 si.lpReserved = NULL;
4765 si.lpDesktop = NULL;
4766 si.lpTitle = NULL;
4767 si.dwFlags = 0;
4768 si.cbReserved2 = 0;
4769 si.lpReserved2 = NULL;
4770
4771 cmdbase = skipwhite(cmdbase + 5);
4772 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4773 && vim_iswhite(cmdbase[4]))
4774 {
4775 cmdbase = skipwhite(cmdbase + 4);
4776 si.dwFlags = STARTF_USESHOWWINDOW;
4777 si.wShowWindow = SW_SHOWMINNOACTIVE;
4778 }
4779 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4780 && vim_iswhite(cmdbase[2]))
4781 {
4782 cmdbase = skipwhite(cmdbase + 2);
4783 flags = CREATE_NO_WINDOW;
4784 si.dwFlags = STARTF_USESTDHANDLES;
4785 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004786 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004787 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004788 NULL, // Security att.
4789 OPEN_EXISTING, // Open flags
4790 FILE_ATTRIBUTE_NORMAL, // File att.
4791 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004792 si.hStdOutput = si.hStdInput;
4793 si.hStdError = si.hStdInput;
4794 }
4795
4796 /* Remove a trailing ", ) and )" if they have a match
4797 * at the start of the command. */
4798 if (cmdbase > cmd)
4799 {
4800 p = cmdbase + STRLEN(cmdbase);
4801 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4802 *--p = NUL;
4803 if (p > cmdbase && p[-1] == ')'
4804 && (*cmd =='(' || cmd[1] == '('))
4805 *--p = NUL;
4806 }
4807
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004808 newcmd = cmdbase;
4809 unescape_shellxquote(cmdbase, p_sxe);
4810
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004811 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004812 * If creating new console, arguments are passed to the
4813 * 'cmd.exe' as-is. If it's not, arguments are not treated
4814 * correctly for current 'cmd.exe'. So unescape characters in
4815 * shellxescape except '|' for avoiding to be treated as
4816 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004817 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004818 if (flags != CREATE_NEW_CONSOLE)
4819 {
4820 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004821 char_u *cmd_shell = mch_getenv("COMSPEC");
4822
4823 if (cmd_shell == NULL || *cmd_shell == NUL)
4824 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004825
4826 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4827 if (subcmd != NULL)
4828 {
4829 /* make "cmd.exe /c arguments" */
4830 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004831 newcmd = lalloc(cmdlen, TRUE);
4832 if (newcmd != NULL)
4833 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004834 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004835 else
4836 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004837 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004838 }
4839 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004840
4841 /*
4842 * Now, start the command as a process, so that it doesn't
4843 * inherit our handles which causes unpleasant dangling swap
4844 * files if we exit before the spawned process
4845 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004846 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004847 x = 0;
4848 else
4849 {
4850 x = -1;
4851#ifdef FEAT_GUI_W32
4852 EMSG(_("E371: Command not found"));
4853#endif
4854 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004855
4856 if (newcmd != cmdbase)
4857 vim_free(newcmd);
4858
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004859 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004860 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004861 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004862 CloseHandle(si.hStdInput);
4863 }
4864 /* Close the handles to the subprocess, so that it goes away */
4865 CloseHandle(pi.hThread);
4866 CloseHandle(pi.hProcess);
4867 }
4868 else
4869 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004870 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004872 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004874 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4875
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004876 newcmd = lalloc(cmdlen, TRUE);
4877 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004878 {
4879#if defined(FEAT_GUI_W32)
4880 if (need_vimrun_warning)
4881 {
4882 MessageBox(NULL,
4883 _("VIMRUN.EXE not found in your $PATH.\n"
4884 "External commands will not pause after completion.\n"
4885 "See :help win32-vimrun for more information."),
4886 _("Vim Warning"),
4887 MB_ICONWARNING);
4888 need_vimrun_warning = FALSE;
4889 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004890 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004891 /* Use vimrun to execute the command. It opens a console
4892 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004893 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894 vimrun_path,
4895 (msg_silent != 0 || (options & SHELL_DOOUT))
4896 ? "-s " : "",
4897 p_sh, p_shcf, cmd);
4898 else
4899#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004900 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004901 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004902 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004903 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004905 }
4906 }
4907
4908 if (tmode == TMODE_RAW)
4909 settmode(TMODE_RAW); /* set to raw mode */
4910
4911 /* Print the return value, unless "vimrun" was used. */
4912 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4913#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004914 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4915 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916#endif
4917 )
4918 {
4919 smsg(_("shell returned %d"), x);
4920 msg_putchar('\n');
4921 }
4922#ifdef FEAT_TITLE
4923 resettitle();
4924#endif
4925
4926 signal(SIGINT, SIG_DFL);
4927#if defined(__GNUC__) && !defined(__MINGW32__)
4928 signal(SIGKILL, SIG_DFL);
4929#else
4930 signal(SIGBREAK, SIG_DFL);
4931#endif
4932 signal(SIGILL, SIG_DFL);
4933 signal(SIGFPE, SIG_DFL);
4934 signal(SIGSEGV, SIG_DFL);
4935 signal(SIGTERM, SIG_DFL);
4936 signal(SIGABRT, SIG_DFL);
4937
4938 return x;
4939}
4940
4941
4942#ifndef FEAT_GUI_W32
4943
4944/*
4945 * Start termcap mode
4946 */
4947 static void
4948termcap_mode_start(void)
4949{
4950 DWORD cmodein;
4951
4952 if (g_fTermcapMode)
4953 return;
4954
4955 SaveConsoleBuffer(&g_cbNonTermcap);
4956
4957 if (g_cbTermcap.IsValid)
4958 {
4959 /*
4960 * We've been in termcap mode before. Restore certain screen
4961 * characteristics, including the buffer size and the window
4962 * size. Since we will be redrawing the screen, we don't need
4963 * to restore the actual contents of the buffer.
4964 */
4965 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4966 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4967 Rows = g_cbTermcap.Info.dwSize.Y;
4968 Columns = g_cbTermcap.Info.dwSize.X;
4969 }
4970 else
4971 {
4972 /*
4973 * This is our first time entering termcap mode. Clear the console
4974 * screen buffer, and resize the buffer to match the current window
4975 * size. We will use this as the size of our editing environment.
4976 */
4977 ClearConsoleBuffer(g_attrCurrent);
4978 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4979 }
4980
4981#ifdef FEAT_TITLE
4982 resettitle();
4983#endif
4984
4985 GetConsoleMode(g_hConIn, &cmodein);
4986#ifdef FEAT_MOUSE
4987 if (g_fMouseActive)
4988 cmodein |= ENABLE_MOUSE_INPUT;
4989 else
4990 cmodein &= ~ENABLE_MOUSE_INPUT;
4991#endif
4992 cmodein |= ENABLE_WINDOW_INPUT;
4993 SetConsoleMode(g_hConIn, cmodein);
4994
4995 redraw_later_clear();
4996 g_fTermcapMode = TRUE;
4997}
4998
4999
5000/*
5001 * End termcap mode
5002 */
5003 static void
5004termcap_mode_end(void)
5005{
5006 DWORD cmodein;
5007 ConsoleBuffer *cb;
5008 COORD coord;
5009 DWORD dwDummy;
5010
5011 if (!g_fTermcapMode)
5012 return;
5013
5014 SaveConsoleBuffer(&g_cbTermcap);
5015
5016 GetConsoleMode(g_hConIn, &cmodein);
5017 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5018 SetConsoleMode(g_hConIn, cmodein);
5019
5020#ifdef FEAT_RESTORE_ORIG_SCREEN
5021 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5022#else
5023 cb = &g_cbNonTermcap;
5024#endif
5025 RestoreConsoleBuffer(cb, p_rs);
5026 SetConsoleCursorInfo(g_hConOut, &g_cci);
5027
5028 if (p_rs || exiting)
5029 {
5030 /*
5031 * Clear anything that happens to be on the current line.
5032 */
5033 coord.X = 0;
5034 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5035 FillConsoleOutputCharacter(g_hConOut, ' ',
5036 cb->Info.dwSize.X, coord, &dwDummy);
5037 /*
5038 * The following is just for aesthetics. If we are exiting without
5039 * restoring the screen, then we want to have a prompt string
5040 * appear at the bottom line. However, the command interpreter
5041 * seems to always advance the cursor one line before displaying
5042 * the prompt string, which causes the screen to scroll. To
5043 * counter this, move the cursor up one line before exiting.
5044 */
5045 if (exiting && !p_rs)
5046 coord.Y--;
5047 /*
5048 * Position the cursor at the leftmost column of the desired row.
5049 */
5050 SetConsoleCursorPosition(g_hConOut, coord);
5051 }
5052
5053 g_fTermcapMode = FALSE;
5054}
5055#endif /* FEAT_GUI_W32 */
5056
5057
5058#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005059/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005060 void
5061mch_write(
5062 char_u *s,
5063 int len)
5064{
5065 /* never used */
5066}
5067
5068#else
5069
5070/*
5071 * clear `n' chars, starting from `coord'
5072 */
5073 static void
5074clear_chars(
5075 COORD coord,
5076 DWORD n)
5077{
5078 DWORD dwDummy;
5079
5080 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5081 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5082}
5083
5084
5085/*
5086 * Clear the screen
5087 */
5088 static void
5089clear_screen(void)
5090{
5091 g_coord.X = g_coord.Y = 0;
5092 clear_chars(g_coord, Rows * Columns);
5093}
5094
5095
5096/*
5097 * Clear to end of display
5098 */
5099 static void
5100clear_to_end_of_display(void)
5101{
5102 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5103 * Columns + (Columns - g_coord.X));
5104}
5105
5106
5107/*
5108 * Clear to end of line
5109 */
5110 static void
5111clear_to_end_of_line(void)
5112{
5113 clear_chars(g_coord, Columns - g_coord.X);
5114}
5115
5116
5117/*
5118 * Scroll the scroll region up by `cLines' lines
5119 */
5120 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005121scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005122{
5123 COORD oldcoord = g_coord;
5124
5125 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5126 delete_lines(cLines);
5127
5128 g_coord = oldcoord;
5129}
5130
5131
5132/*
5133 * Set the scroll region
5134 */
5135 static void
5136set_scroll_region(
5137 unsigned left,
5138 unsigned top,
5139 unsigned right,
5140 unsigned bottom)
5141{
5142 if (left >= right
5143 || top >= bottom
5144 || right > (unsigned) Columns - 1
5145 || bottom > (unsigned) Rows - 1)
5146 return;
5147
5148 g_srScrollRegion.Left = left;
5149 g_srScrollRegion.Top = top;
5150 g_srScrollRegion.Right = right;
5151 g_srScrollRegion.Bottom = bottom;
5152}
5153
5154
5155/*
5156 * Insert `cLines' lines at the current cursor position
5157 */
5158 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005159insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005160{
5161 SMALL_RECT source;
5162 COORD dest;
5163 CHAR_INFO fill;
5164
5165 dest.X = 0;
5166 dest.Y = g_coord.Y + cLines;
5167
5168 source.Left = 0;
5169 source.Top = g_coord.Y;
5170 source.Right = g_srScrollRegion.Right;
5171 source.Bottom = g_srScrollRegion.Bottom - cLines;
5172
5173 fill.Char.AsciiChar = ' ';
5174 fill.Attributes = g_attrCurrent;
5175
5176 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5177
5178 /* Here we have to deal with a win32 console flake: If the scroll
5179 * region looks like abc and we scroll c to a and fill with d we get
5180 * cbd... if we scroll block c one line at a time to a, we get cdd...
5181 * vim expects cdd consistently... So we have to deal with that
5182 * here... (this also occurs scrolling the same way in the other
5183 * direction). */
5184
5185 if (source.Bottom < dest.Y)
5186 {
5187 COORD coord;
5188
5189 coord.X = 0;
5190 coord.Y = source.Bottom;
5191 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5192 }
5193}
5194
5195
5196/*
5197 * Delete `cLines' lines at the current cursor position
5198 */
5199 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005200delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005201{
5202 SMALL_RECT source;
5203 COORD dest;
5204 CHAR_INFO fill;
5205 int nb;
5206
5207 dest.X = 0;
5208 dest.Y = g_coord.Y;
5209
5210 source.Left = 0;
5211 source.Top = g_coord.Y + cLines;
5212 source.Right = g_srScrollRegion.Right;
5213 source.Bottom = g_srScrollRegion.Bottom;
5214
5215 fill.Char.AsciiChar = ' ';
5216 fill.Attributes = g_attrCurrent;
5217
5218 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5219
5220 /* Here we have to deal with a win32 console flake: If the scroll
5221 * region looks like abc and we scroll c to a and fill with d we get
5222 * cbd... if we scroll block c one line at a time to a, we get cdd...
5223 * vim expects cdd consistently... So we have to deal with that
5224 * here... (this also occurs scrolling the same way in the other
5225 * direction). */
5226
5227 nb = dest.Y + (source.Bottom - source.Top) + 1;
5228
5229 if (nb < source.Top)
5230 {
5231 COORD coord;
5232
5233 coord.X = 0;
5234 coord.Y = nb;
5235 clear_chars(coord, Columns * (source.Top - nb));
5236 }
5237}
5238
5239
5240/*
5241 * Set the cursor position
5242 */
5243 static void
5244gotoxy(
5245 unsigned x,
5246 unsigned y)
5247{
5248 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5249 return;
5250
5251 /* external cursor coords are 1-based; internal are 0-based */
5252 g_coord.X = x - 1;
5253 g_coord.Y = y - 1;
5254 SetConsoleCursorPosition(g_hConOut, g_coord);
5255}
5256
5257
5258/*
5259 * Set the current text attribute = (foreground | background)
5260 * See ../doc/os_win32.txt for the numbers.
5261 */
5262 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005263textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005264{
5265 g_attrCurrent = wAttr;
5266
5267 SetConsoleTextAttribute(g_hConOut, wAttr);
5268}
5269
5270
5271 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005272textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005273{
5274 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
5275
5276 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5277}
5278
5279
5280 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005281textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005282{
5283 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
5284
5285 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5286}
5287
5288
5289/*
5290 * restore the default text attribute (whatever we started with)
5291 */
5292 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005293normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005294{
5295 textattr(g_attrDefault);
5296}
5297
5298
5299static WORD g_attrPreStandout = 0;
5300
5301/*
5302 * Make the text standout, by brightening it
5303 */
5304 static void
5305standout(void)
5306{
5307 g_attrPreStandout = g_attrCurrent;
5308 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5309}
5310
5311
5312/*
5313 * Turn off standout mode
5314 */
5315 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005316standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005317{
5318 if (g_attrPreStandout)
5319 {
5320 textattr(g_attrPreStandout);
5321 g_attrPreStandout = 0;
5322 }
5323}
5324
5325
5326/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005327 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328 */
5329 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005330mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005331{
5332 char_u *p;
5333 int n;
5334
5335 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5336 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5337 if (T_ME[0] == ESC && T_ME[1] == '|')
5338 {
5339 p = T_ME + 2;
5340 n = getdigits(&p);
5341 if (*p == 'm' && n > 0)
5342 {
5343 cterm_normal_fg_color = (n & 0xf) + 1;
5344 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5345 }
5346 }
5347}
5348
5349
5350/*
5351 * visual bell: flash the screen
5352 */
5353 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005354visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005355{
5356 COORD coordOrigin = {0, 0};
5357 WORD attrFlash = ~g_attrCurrent & 0xff;
5358
5359 DWORD dwDummy;
5360 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5361
5362 if (oldattrs == NULL)
5363 return;
5364 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5365 coordOrigin, &dwDummy);
5366 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5367 coordOrigin, &dwDummy);
5368
5369 Sleep(15); /* wait for 15 msec */
5370 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5371 coordOrigin, &dwDummy);
5372 vim_free(oldattrs);
5373}
5374
5375
5376/*
5377 * Make the cursor visible or invisible
5378 */
5379 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005380cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005381{
5382 s_cursor_visible = fVisible;
5383#ifdef MCH_CURSOR_SHAPE
5384 mch_update_cursor();
5385#endif
5386}
5387
5388
5389/*
5390 * write `cchToWrite' characters in `pchBuf' to the screen
5391 * Returns the number of characters actually written (at least one).
5392 */
5393 static BOOL
5394write_chars(
5395 LPCSTR pchBuf,
5396 DWORD cchToWrite)
5397{
5398 COORD coord = g_coord;
5399 DWORD written;
5400
5401 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
5402 coord, &written);
5403 /* When writing fails or didn't write a single character, pretend one
5404 * character was written, otherwise we get stuck. */
5405 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
5406 coord, &written) == 0
5407 || written == 0)
5408 written = 1;
5409
5410 g_coord.X += (SHORT) written;
5411
5412 while (g_coord.X > g_srScrollRegion.Right)
5413 {
5414 g_coord.X -= (SHORT) Columns;
5415 if (g_coord.Y < g_srScrollRegion.Bottom)
5416 g_coord.Y++;
5417 }
5418
5419 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5420
5421 return written;
5422}
5423
5424
5425/*
5426 * mch_write(): write the output buffer to the screen, translating ESC
5427 * sequences into calls to console output routines.
5428 */
5429 void
5430mch_write(
5431 char_u *s,
5432 int len)
5433{
5434 s[len] = NUL;
5435
5436 if (!term_console)
5437 {
5438 write(1, s, (unsigned)len);
5439 return;
5440 }
5441
5442 /* translate ESC | sequences into faked bios calls */
5443 while (len--)
5444 {
5445 /* optimization: use one single write_chars for runs of text,
5446 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005447 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005448
5449 if (p_wd)
5450 {
5451 WaitForChar(p_wd);
5452 if (prefix != 0)
5453 prefix = 1;
5454 }
5455
5456 if (prefix != 0)
5457 {
5458 DWORD nWritten;
5459
5460 nWritten = write_chars(s, prefix);
5461#ifdef MCH_WRITE_DUMP
5462 if (fdDump)
5463 {
5464 fputc('>', fdDump);
5465 fwrite(s, sizeof(char_u), nWritten, fdDump);
5466 fputs("<\n", fdDump);
5467 }
5468#endif
5469 len -= (nWritten - 1);
5470 s += nWritten;
5471 }
5472 else if (s[0] == '\n')
5473 {
5474 /* \n, newline: go to the beginning of the next line or scroll */
5475 if (g_coord.Y == g_srScrollRegion.Bottom)
5476 {
5477 scroll(1);
5478 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5479 }
5480 else
5481 {
5482 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5483 }
5484#ifdef MCH_WRITE_DUMP
5485 if (fdDump)
5486 fputs("\\n\n", fdDump);
5487#endif
5488 s++;
5489 }
5490 else if (s[0] == '\r')
5491 {
5492 /* \r, carriage return: go to beginning of line */
5493 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5494#ifdef MCH_WRITE_DUMP
5495 if (fdDump)
5496 fputs("\\r\n", fdDump);
5497#endif
5498 s++;
5499 }
5500 else if (s[0] == '\b')
5501 {
5502 /* \b, backspace: move cursor one position left */
5503 if (g_coord.X > g_srScrollRegion.Left)
5504 g_coord.X--;
5505 else if (g_coord.Y > g_srScrollRegion.Top)
5506 {
5507 g_coord.X = g_srScrollRegion.Right;
5508 g_coord.Y--;
5509 }
5510 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5511#ifdef MCH_WRITE_DUMP
5512 if (fdDump)
5513 fputs("\\b\n", fdDump);
5514#endif
5515 s++;
5516 }
5517 else if (s[0] == '\a')
5518 {
5519 /* \a, bell */
5520 MessageBeep(0xFFFFFFFF);
5521#ifdef MCH_WRITE_DUMP
5522 if (fdDump)
5523 fputs("\\a\n", fdDump);
5524#endif
5525 s++;
5526 }
5527 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5528 {
5529#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005530 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005532 char_u *p;
5533 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005534
5535 switch (s[2])
5536 {
5537 /* one or two numeric arguments, separated by ';' */
5538
5539 case '0': case '1': case '2': case '3': case '4':
5540 case '5': case '6': case '7': case '8': case '9':
5541 p = s + 2;
5542 arg1 = getdigits(&p); /* no check for length! */
5543 if (p > s + len)
5544 break;
5545
5546 if (*p == ';')
5547 {
5548 ++p;
5549 arg2 = getdigits(&p); /* no check for length! */
5550 if (p > s + len)
5551 break;
5552
5553 if (*p == 'H')
5554 gotoxy(arg2, arg1);
5555 else if (*p == 'r')
5556 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5557 }
5558 else if (*p == 'A')
5559 {
5560 /* move cursor up arg1 lines in same column */
5561 gotoxy(g_coord.X + 1,
5562 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5563 }
5564 else if (*p == 'C')
5565 {
5566 /* move cursor right arg1 columns in same line */
5567 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5568 g_coord.Y + 1);
5569 }
5570 else if (*p == 'H')
5571 {
5572 gotoxy(1, arg1);
5573 }
5574 else if (*p == 'L')
5575 {
5576 insert_lines(arg1);
5577 }
5578 else if (*p == 'm')
5579 {
5580 if (arg1 == 0)
5581 normvideo();
5582 else
5583 textattr((WORD) arg1);
5584 }
5585 else if (*p == 'f')
5586 {
5587 textcolor((WORD) arg1);
5588 }
5589 else if (*p == 'b')
5590 {
5591 textbackground((WORD) arg1);
5592 }
5593 else if (*p == 'M')
5594 {
5595 delete_lines(arg1);
5596 }
5597
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005598 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005599 s = p + 1;
5600 break;
5601
5602
5603 /* Three-character escape sequences */
5604
5605 case 'A':
5606 /* move cursor up one line in same column */
5607 gotoxy(g_coord.X + 1,
5608 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5609 goto got3;
5610
5611 case 'B':
5612 visual_bell();
5613 goto got3;
5614
5615 case 'C':
5616 /* move cursor right one column in same line */
5617 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5618 g_coord.Y + 1);
5619 goto got3;
5620
5621 case 'E':
5622 termcap_mode_end();
5623 goto got3;
5624
5625 case 'F':
5626 standout();
5627 goto got3;
5628
5629 case 'f':
5630 standend();
5631 goto got3;
5632
5633 case 'H':
5634 gotoxy(1, 1);
5635 goto got3;
5636
5637 case 'j':
5638 clear_to_end_of_display();
5639 goto got3;
5640
5641 case 'J':
5642 clear_screen();
5643 goto got3;
5644
5645 case 'K':
5646 clear_to_end_of_line();
5647 goto got3;
5648
5649 case 'L':
5650 insert_lines(1);
5651 goto got3;
5652
5653 case 'M':
5654 delete_lines(1);
5655 goto got3;
5656
5657 case 'S':
5658 termcap_mode_start();
5659 goto got3;
5660
5661 case 'V':
5662 cursor_visible(TRUE);
5663 goto got3;
5664
5665 case 'v':
5666 cursor_visible(FALSE);
5667 goto got3;
5668
5669 got3:
5670 s += 3;
5671 len -= 2;
5672 }
5673
5674#ifdef MCH_WRITE_DUMP
5675 if (fdDump)
5676 {
5677 fputs("ESC | ", fdDump);
5678 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5679 fputc('\n', fdDump);
5680 }
5681#endif
5682 }
5683 else
5684 {
5685 /* Write a single character */
5686 DWORD nWritten;
5687
5688 nWritten = write_chars(s, 1);
5689#ifdef MCH_WRITE_DUMP
5690 if (fdDump)
5691 {
5692 fputc('>', fdDump);
5693 fwrite(s, sizeof(char_u), nWritten, fdDump);
5694 fputs("<\n", fdDump);
5695 }
5696#endif
5697
5698 len -= (nWritten - 1);
5699 s += nWritten;
5700 }
5701 }
5702
5703#ifdef MCH_WRITE_DUMP
5704 if (fdDump)
5705 fflush(fdDump);
5706#endif
5707}
5708
5709#endif /* FEAT_GUI_W32 */
5710
5711
5712/*
5713 * Delay for half a second.
5714 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005715/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005716 void
5717mch_delay(
5718 long msec,
5719 int ignoreinput)
5720{
5721#ifdef FEAT_GUI_W32
5722 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005723#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005725# ifdef FEAT_MZSCHEME
5726 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5727 {
5728 int towait = p_mzq;
5729
5730 /* if msec is large enough, wait by portions in p_mzq */
5731 while (msec > 0)
5732 {
5733 mzvim_check_threads();
5734 if (msec < towait)
5735 towait = msec;
5736 Sleep(towait);
5737 msec -= towait;
5738 }
5739 }
5740 else
5741# endif
5742 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743 else
5744 WaitForChar(msec);
5745#endif
5746}
5747
5748
5749/*
5750 * this version of remove is not scared by a readonly (backup) file
5751 * Return 0 for success, -1 for failure.
5752 */
5753 int
5754mch_remove(char_u *name)
5755{
5756#ifdef FEAT_MBYTE
5757 WCHAR *wn = NULL;
5758 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005759#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005760
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005761 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5762
5763#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005764 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5765 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005766 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767 if (wn != NULL)
5768 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769 n = DeleteFileW(wn) ? 0 : -1;
5770 vim_free(wn);
5771 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5772 return n;
5773 /* Retry with non-wide function (for Windows 98). */
5774 }
5775 }
5776#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777 return DeleteFile(name) ? 0 : -1;
5778}
5779
5780
5781/*
5782 * check for an "interrupt signal": CTRL-break or CTRL-C
5783 */
5784 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005785mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786{
5787#ifndef FEAT_GUI_W32 /* never used */
5788 if (g_fCtrlCPressed || g_fCBrkPressed)
5789 {
5790 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5791 got_int = TRUE;
5792 }
5793#endif
5794}
5795
5796
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797#ifdef FEAT_MBYTE
5798/*
5799 * Same code as below, but with wide functions and no comments.
5800 * Return 0 for success, non-zero for failure.
5801 */
5802 int
5803mch_wrename(WCHAR *wold, WCHAR *wnew)
5804{
5805 WCHAR *p;
5806 int i;
5807 WCHAR szTempFile[_MAX_PATH + 1];
5808 WCHAR szNewPath[_MAX_PATH + 1];
5809 HANDLE hf;
5810
5811 if (!mch_windows95())
5812 {
5813 p = wold;
5814 for (i = 0; wold[i] != NUL; ++i)
5815 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5816 && wold[i + 1] != 0)
5817 p = wold + i + 1;
5818 if ((int)(wold + i - p) < 8 || p[6] != '~')
5819 return (MoveFileW(wold, wnew) == 0);
5820 }
5821
5822 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5823 return -1;
5824 *p = NUL;
5825
5826 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5827 return -2;
5828
5829 if (!DeleteFileW(szTempFile))
5830 return -3;
5831
5832 if (!MoveFileW(wold, szTempFile))
5833 return -4;
5834
5835 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5836 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5837 return -5;
5838 if (!CloseHandle(hf))
5839 return -6;
5840
5841 if (!MoveFileW(szTempFile, wnew))
5842 {
5843 (void)MoveFileW(szTempFile, wold);
5844 return -7;
5845 }
5846
5847 DeleteFileW(szTempFile);
5848
5849 if (!DeleteFileW(wold))
5850 return -8;
5851
5852 return 0;
5853}
5854#endif
5855
5856
5857/*
5858 * mch_rename() works around a bug in rename (aka MoveFile) in
5859 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5860 * file whose short file name is "FOO.BAR" (its long file name will
5861 * be correct: "foo.bar~"). Because a file can be accessed by
5862 * either its SFN or its LFN, "foo.bar" has effectively been
5863 * renamed to "foo.bar", which is not at all what was wanted. This
5864 * seems to happen only when renaming files with three-character
5865 * extensions by appending a suffix that does not include ".".
5866 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5867 *
5868 * There is another problem, which isn't really a bug but isn't right either:
5869 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5870 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5871 * service pack 6. Doesn't seem to happen on Windows 98.
5872 *
5873 * Like rename(), returns 0 upon success, non-zero upon failure.
5874 * Should probably set errno appropriately when errors occur.
5875 */
5876 int
5877mch_rename(
5878 const char *pszOldFile,
5879 const char *pszNewFile)
5880{
5881 char szTempFile[_MAX_PATH+1];
5882 char szNewPath[_MAX_PATH+1];
5883 char *pszFilePart;
5884 HANDLE hf;
5885#ifdef FEAT_MBYTE
5886 WCHAR *wold = NULL;
5887 WCHAR *wnew = NULL;
5888 int retval = -1;
5889
5890 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5891 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005892 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5893 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894 if (wold != NULL && wnew != NULL)
5895 retval = mch_wrename(wold, wnew);
5896 vim_free(wold);
5897 vim_free(wnew);
5898 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5899 return retval;
5900 /* Retry with non-wide function (for Windows 98). */
5901 }
5902#endif
5903
5904 /*
5905 * No need to play tricks if not running Windows 95, unless the file name
5906 * contains a "~" as the seventh character.
5907 */
5908 if (!mch_windows95())
5909 {
5910 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5911 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5912 return rename(pszOldFile, pszNewFile);
5913 }
5914
5915 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5916 * a directory, no error is returned and pszFilePart will be NULL. */
5917 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5918 || pszFilePart == NULL)
5919 return -1;
5920 *pszFilePart = NUL;
5921
5922 /* Get (and create) a unique temporary file name in directory of new file */
5923 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5924 return -2;
5925
5926 /* blow the temp file away */
5927 if (!DeleteFile(szTempFile))
5928 return -3;
5929
5930 /* rename old file to the temp file */
5931 if (!MoveFile(pszOldFile, szTempFile))
5932 return -4;
5933
5934 /* now create an empty file called pszOldFile; this prevents the operating
5935 * system using pszOldFile as an alias (SFN) if we're renaming within the
5936 * same directory. For example, we're editing a file called
5937 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5938 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5939 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005940 * cause all sorts of problems later in buf_write(). So, we create an
5941 * empty file called filena~1.txt and the system will have to find some
5942 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943 */
5944 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5945 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5946 return -5;
5947 if (!CloseHandle(hf))
5948 return -6;
5949
5950 /* rename the temp file to the new file */
5951 if (!MoveFile(szTempFile, pszNewFile))
5952 {
5953 /* Renaming failed. Rename the file back to its old name, so that it
5954 * looks like nothing happened. */
5955 (void)MoveFile(szTempFile, pszOldFile);
5956
5957 return -7;
5958 }
5959
5960 /* Seems to be left around on Novell filesystems */
5961 DeleteFile(szTempFile);
5962
5963 /* finally, remove the empty old file */
5964 if (!DeleteFile(pszOldFile))
5965 return -8;
5966
5967 return 0; /* success */
5968}
5969
5970/*
5971 * Get the default shell for the current hardware platform
5972 */
5973 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005974default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975{
5976 char* psz = NULL;
5977
5978 PlatformId();
5979
5980 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5981 psz = "cmd.exe";
5982 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5983 psz = "command.com";
5984
5985 return psz;
5986}
5987
5988/*
5989 * mch_access() extends access() to do more detailed check on network drives.
5990 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5991 */
5992 int
5993mch_access(char *n, int p)
5994{
5995 HANDLE hFile;
5996 DWORD am;
5997 int retval = -1; /* default: fail */
5998#ifdef FEAT_MBYTE
5999 WCHAR *wn = NULL;
6000
6001 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006002 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006003#endif
6004
6005 if (mch_isdir(n))
6006 {
6007 char TempName[_MAX_PATH + 16] = "";
6008#ifdef FEAT_MBYTE
6009 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6010#endif
6011
6012 if (p & R_OK)
6013 {
6014 /* Read check is performed by seeing if we can do a find file on
6015 * the directory for any file. */
6016#ifdef FEAT_MBYTE
6017 if (wn != NULL)
6018 {
6019 int i;
6020 WIN32_FIND_DATAW d;
6021
6022 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6023 TempNameW[i] = wn[i];
6024 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6025 TempNameW[i++] = '\\';
6026 TempNameW[i++] = '*';
6027 TempNameW[i++] = 0;
6028
6029 hFile = FindFirstFileW(TempNameW, &d);
6030 if (hFile == INVALID_HANDLE_VALUE)
6031 {
6032 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6033 goto getout;
6034
6035 /* Retry with non-wide function (for Windows 98). */
6036 vim_free(wn);
6037 wn = NULL;
6038 }
6039 else
6040 (void)FindClose(hFile);
6041 }
6042 if (wn == NULL)
6043#endif
6044 {
6045 char *pch;
6046 WIN32_FIND_DATA d;
6047
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006048 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049 pch = TempName + STRLEN(TempName) - 1;
6050 if (*pch != '\\' && *pch != '/')
6051 *++pch = '\\';
6052 *++pch = '*';
6053 *++pch = NUL;
6054
6055 hFile = FindFirstFile(TempName, &d);
6056 if (hFile == INVALID_HANDLE_VALUE)
6057 goto getout;
6058 (void)FindClose(hFile);
6059 }
6060 }
6061
6062 if (p & W_OK)
6063 {
6064 /* Trying to create a temporary file in the directory should catch
6065 * directories on read-only network shares. However, in
6066 * directories whose ACL allows writes but denies deletes will end
6067 * up keeping the temporary file :-(. */
6068#ifdef FEAT_MBYTE
6069 if (wn != NULL)
6070 {
6071 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6072 {
6073 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6074 goto getout;
6075
6076 /* Retry with non-wide function (for Windows 98). */
6077 vim_free(wn);
6078 wn = NULL;
6079 }
6080 else
6081 DeleteFileW(TempNameW);
6082 }
6083 if (wn == NULL)
6084#endif
6085 {
6086 if (!GetTempFileName(n, "VIM", 0, TempName))
6087 goto getout;
6088 mch_remove((char_u *)TempName);
6089 }
6090 }
6091 }
6092 else
6093 {
6094 /* Trying to open the file for the required access does ACL, read-only
6095 * network share, and file attribute checks. */
6096 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6097 | ((p & R_OK) ? GENERIC_READ : 0);
6098#ifdef FEAT_MBYTE
6099 if (wn != NULL)
6100 {
6101 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6102 if (hFile == INVALID_HANDLE_VALUE
6103 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6104 {
6105 /* Retry with non-wide function (for Windows 98). */
6106 vim_free(wn);
6107 wn = NULL;
6108 }
6109 }
6110 if (wn == NULL)
6111#endif
6112 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6113 if (hFile == INVALID_HANDLE_VALUE)
6114 goto getout;
6115 CloseHandle(hFile);
6116 }
6117
6118 retval = 0; /* success */
6119getout:
6120#ifdef FEAT_MBYTE
6121 vim_free(wn);
6122#endif
6123 return retval;
6124}
6125
6126#if defined(FEAT_MBYTE) || defined(PROTO)
6127/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006128 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129 */
6130 int
6131mch_open(char *name, int flags, int mode)
6132{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006133 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6134# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006135 WCHAR *wn;
6136 int f;
6137
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006138 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006140 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141 if (wn != NULL)
6142 {
6143 f = _wopen(wn, flags, mode);
6144 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006145 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006146 return f;
6147 /* Retry with non-wide function (for Windows 98). Can't use
6148 * GetLastError() here and it's unclear what errno gets set to if
6149 * the _wopen() fails for missing wide functions. */
6150 }
6151 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006152# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006153
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006154 /* open() can open a file which name is longer than _MAX_PATH bytes
6155 * and shorter than _MAX_PATH characters successfully, but sometimes it
6156 * causes unexpected error in another part. We make it an error explicitly
6157 * here. */
6158 if (strlen(name) >= _MAX_PATH)
6159 return -1;
6160
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 return open(name, flags, mode);
6162}
6163
6164/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006165 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166 */
6167 FILE *
6168mch_fopen(char *name, char *mode)
6169{
6170 WCHAR *wn, *wm;
6171 FILE *f = NULL;
6172
6173 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6174# ifdef __BORLANDC__
6175 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6176 && g_PlatformId == VER_PLATFORM_WIN32_NT
6177# endif
6178 )
6179 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006180# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006181 /* Work around an annoying assertion in the Microsoft debug CRT
6182 * when mode's text/binary setting doesn't match _get_fmode(). */
6183 char newMode = mode[strlen(mode) - 1];
6184 int oldMode = 0;
6185
6186 _get_fmode(&oldMode);
6187 if (newMode == 't')
6188 _set_fmode(_O_TEXT);
6189 else if (newMode == 'b')
6190 _set_fmode(_O_BINARY);
6191# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006192 wn = enc_to_utf16(name, NULL);
6193 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006194 if (wn != NULL && wm != NULL)
6195 f = _wfopen(wn, wm);
6196 vim_free(wn);
6197 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006198
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006199# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006200 _set_fmode(oldMode);
6201# endif
6202
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006203 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204 return f;
6205 /* Retry with non-wide function (for Windows 98). Can't use
6206 * GetLastError() here and it's unclear what errno gets set to if
6207 * the _wfopen() fails for missing wide functions. */
6208 }
6209
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006210 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6211 * and shorter than _MAX_PATH characters successfully, but sometimes it
6212 * causes unexpected error in another part. We make it an error explicitly
6213 * here. */
6214 if (strlen(name) >= _MAX_PATH)
6215 return NULL;
6216
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217 return fopen(name, mode);
6218}
6219#endif
6220
6221#ifdef FEAT_MBYTE
6222/*
6223 * SUB STREAM (aka info stream) handling:
6224 *
6225 * NTFS can have sub streams for each file. Normal contents of file is
6226 * stored in the main stream, and extra contents (author information and
6227 * title and so on) can be stored in sub stream. After Windows 2000, user
6228 * can access and store those informations in sub streams via explorer's
6229 * property menuitem in right click menu. Those informations in sub streams
6230 * were lost when copying only the main stream. So we have to copy sub
6231 * streams.
6232 *
6233 * Incomplete explanation:
6234 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6235 * More useful info and an example:
6236 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6237 */
6238
6239/*
6240 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6241 * and write to stream "substream" of file "to".
6242 * Errors are ignored.
6243 */
6244 static void
6245copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6246{
6247 HANDLE hTo;
6248 WCHAR *to_name;
6249
6250 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6251 wcscpy(to_name, to);
6252 wcscat(to_name, substream);
6253
6254 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6255 FILE_ATTRIBUTE_NORMAL, NULL);
6256 if (hTo != INVALID_HANDLE_VALUE)
6257 {
6258 long done;
6259 DWORD todo;
6260 DWORD readcnt, written;
6261 char buf[4096];
6262
6263 /* Copy block of bytes at a time. Abort when something goes wrong. */
6264 for (done = 0; done < len; done += written)
6265 {
6266 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006267 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6268 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6270 FALSE, FALSE, context)
6271 || readcnt != todo
6272 || !WriteFile(hTo, buf, todo, &written, NULL)
6273 || written != todo)
6274 break;
6275 }
6276 CloseHandle(hTo);
6277 }
6278
6279 free(to_name);
6280}
6281
6282/*
6283 * Copy info streams from file "from" to file "to".
6284 */
6285 static void
6286copy_infostreams(char_u *from, char_u *to)
6287{
6288 WCHAR *fromw;
6289 WCHAR *tow;
6290 HANDLE sh;
6291 WIN32_STREAM_ID sid;
6292 int headersize;
6293 WCHAR streamname[_MAX_PATH];
6294 DWORD readcount;
6295 void *context = NULL;
6296 DWORD lo, hi;
6297 int len;
6298
6299 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006300 fromw = enc_to_utf16(from, NULL);
6301 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 if (fromw != NULL && tow != NULL)
6303 {
6304 /* Open the file for reading. */
6305 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6306 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6307 if (sh != INVALID_HANDLE_VALUE)
6308 {
6309 /* Use BackupRead() to find the info streams. Repeat until we
6310 * have done them all.*/
6311 for (;;)
6312 {
6313 /* Get the header to find the length of the stream name. If
6314 * the "readcount" is zero we have done all info streams. */
6315 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006316 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6318 &readcount, FALSE, FALSE, &context)
6319 || readcount == 0)
6320 break;
6321
6322 /* We only deal with streams that have a name. The normal
6323 * file data appears to be without a name, even though docs
6324 * suggest it is called "::$DATA". */
6325 if (sid.dwStreamNameSize > 0)
6326 {
6327 /* Read the stream name. */
6328 if (!BackupRead(sh, (LPBYTE)streamname,
6329 sid.dwStreamNameSize,
6330 &readcount, FALSE, FALSE, &context))
6331 break;
6332
6333 /* Copy an info stream with a name ":anything:$DATA".
6334 * Skip "::$DATA", it has no stream name (examples suggest
6335 * it might be used for the normal file contents).
6336 * Note that BackupRead() counts bytes, but the name is in
6337 * wide characters. */
6338 len = readcount / sizeof(WCHAR);
6339 streamname[len] = 0;
6340 if (len > 7 && wcsicmp(streamname + len - 6,
6341 L":$DATA") == 0)
6342 {
6343 streamname[len - 6] = 0;
6344 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006345 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 }
6347 }
6348
6349 /* Advance to the next stream. We might try seeking too far,
6350 * but BackupSeek() doesn't skip over stream borders, thus
6351 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006352 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006353 &lo, &hi, &context);
6354 }
6355
6356 /* Clear the context. */
6357 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6358
6359 CloseHandle(sh);
6360 }
6361 }
6362 vim_free(fromw);
6363 vim_free(tow);
6364}
6365#endif
6366
6367/*
6368 * Copy file attributes from file "from" to file "to".
6369 * For Windows NT and later we copy info streams.
6370 * Always returns zero, errors are ignored.
6371 */
6372 int
6373mch_copy_file_attribute(char_u *from, char_u *to)
6374{
6375#ifdef FEAT_MBYTE
6376 /* File streams only work on Windows NT and later. */
6377 PlatformId();
6378 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6379 copy_infostreams(from, to);
6380#endif
6381 return 0;
6382}
6383
6384#if defined(MYRESETSTKOFLW) || defined(PROTO)
6385/*
6386 * Recreate a destroyed stack guard page in win32.
6387 * Written by Benjamin Peterson.
6388 */
6389
6390/* These magic numbers are from the MS header files */
6391#define MIN_STACK_WIN9X 17
6392#define MIN_STACK_WINNT 2
6393
6394/*
6395 * This function does the same thing as _resetstkoflw(), which is only
6396 * available in DevStudio .net and later.
6397 * Returns 0 for failure, 1 for success.
6398 */
6399 int
6400myresetstkoflw(void)
6401{
6402 BYTE *pStackPtr;
6403 BYTE *pGuardPage;
6404 BYTE *pStackBase;
6405 BYTE *pLowestPossiblePage;
6406 MEMORY_BASIC_INFORMATION mbi;
6407 SYSTEM_INFO si;
6408 DWORD nPageSize;
6409 DWORD dummy;
6410
6411 /* This code will not work on win32s. */
6412 PlatformId();
6413 if (g_PlatformId == VER_PLATFORM_WIN32s)
6414 return 0;
6415
6416 /* We need to know the system page size. */
6417 GetSystemInfo(&si);
6418 nPageSize = si.dwPageSize;
6419
6420 /* ...and the current stack pointer */
6421 pStackPtr = (BYTE*)_alloca(1);
6422
6423 /* ...and the base of the stack. */
6424 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6425 return 0;
6426 pStackBase = (BYTE*)mbi.AllocationBase;
6427
6428 /* ...and the page thats min_stack_req pages away from stack base; this is
6429 * the lowest page we could use. */
6430 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6431 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6432
6433 /* On Win95, we want the next page down from the end of the stack. */
6434 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6435 {
6436 /* Find the page that's only 1 page down from the page that the stack
6437 * ptr is in. */
6438 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6439 / (DWORD)nPageSize) - 1));
6440 if (pGuardPage < pLowestPossiblePage)
6441 return 0;
6442
6443 /* Apply the noaccess attribute to the page -- there's no guard
6444 * attribute in win95-type OSes. */
6445 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6446 return 0;
6447 }
6448 else
6449 {
6450 /* On NT, however, we want the first committed page in the stack Start
6451 * at the stack base and move forward through memory until we find a
6452 * committed block. */
6453 BYTE *pBlock = pStackBase;
6454
Bram Moolenaara466c992005-07-09 21:03:22 +00006455 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456 {
6457 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6458 return 0;
6459
6460 pBlock += mbi.RegionSize;
6461
6462 if (mbi.State & MEM_COMMIT)
6463 break;
6464 }
6465
6466 /* mbi now describes the first committed block in the stack. */
6467 if (mbi.Protect & PAGE_GUARD)
6468 return 1;
6469
6470 /* decide where the guard page should start */
6471 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6472 pGuardPage = pLowestPossiblePage;
6473 else
6474 pGuardPage = (BYTE*)mbi.BaseAddress;
6475
6476 /* allocate the guard page */
6477 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6478 return 0;
6479
6480 /* apply the guard attribute to the page */
6481 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6482 &dummy))
6483 return 0;
6484 }
6485
6486 return 1;
6487}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006488#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006490
6491#if defined(FEAT_MBYTE) || defined(PROTO)
6492/*
6493 * The command line arguments in UCS2
6494 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006495static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006496static LPWSTR *ArglistW = NULL;
6497static int global_argc = 0;
6498static char **global_argv;
6499
6500static int used_file_argc = 0; /* last argument in global_argv[] used
6501 for the argument list. */
6502static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6503 command line arguments added to
6504 the argument list */
6505static int used_file_count = 0; /* nr of entries in used_file_indexes */
6506static int used_file_literal = FALSE; /* take file names literally */
6507static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006508static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006509static int used_alist_count = 0;
6510
6511
6512/*
6513 * Get the command line arguments. Unicode version.
6514 * Returns argc. Zero when something fails.
6515 */
6516 int
6517get_cmd_argsW(char ***argvp)
6518{
6519 char **argv = NULL;
6520 int argc = 0;
6521 int i;
6522
Bram Moolenaar14993322014-09-09 12:25:33 +02006523 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006524 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6525 if (ArglistW != NULL)
6526 {
6527 argv = malloc((nArgsW + 1) * sizeof(char *));
6528 if (argv != NULL)
6529 {
6530 argc = nArgsW;
6531 argv[argc] = NULL;
6532 for (i = 0; i < argc; ++i)
6533 {
6534 int len;
6535
6536 /* Convert each Unicode argument to the current codepage. */
6537 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006538 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006539 (LPSTR *)&argv[i], &len, 0, 0);
6540 if (argv[i] == NULL)
6541 {
6542 /* Out of memory, clear everything. */
6543 while (i > 0)
6544 free(argv[--i]);
6545 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006546 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006547 argc = 0;
6548 }
6549 }
6550 }
6551 }
6552
6553 global_argc = argc;
6554 global_argv = argv;
6555 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006556 {
6557 if (used_file_indexes != NULL)
6558 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006559 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006560 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006561
6562 if (argvp != NULL)
6563 *argvp = argv;
6564 return argc;
6565}
6566
6567 void
6568free_cmd_argsW(void)
6569{
6570 if (ArglistW != NULL)
6571 {
6572 GlobalFree(ArglistW);
6573 ArglistW = NULL;
6574 }
6575}
6576
6577/*
6578 * Remember "name" is an argument that was added to the argument list.
6579 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6580 * is called.
6581 */
6582 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006583used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006584{
6585 int i;
6586
6587 if (used_file_indexes == NULL)
6588 return;
6589 for (i = used_file_argc + 1; i < global_argc; ++i)
6590 if (STRCMP(global_argv[i], name) == 0)
6591 {
6592 used_file_argc = i;
6593 used_file_indexes[used_file_count++] = i;
6594 break;
6595 }
6596 used_file_literal = literal;
6597 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006598 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006599}
6600
6601/*
6602 * Remember the length of the argument list as it was. If it changes then we
6603 * leave it alone when 'encoding' is set.
6604 */
6605 void
6606set_alist_count(void)
6607{
6608 used_alist_count = GARGCOUNT;
6609}
6610
6611/*
6612 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6613 * has been changed while starting up. Use the UCS-2 command line arguments
6614 * and convert them to 'encoding'.
6615 */
6616 void
6617fix_arg_enc(void)
6618{
6619 int i;
6620 int idx;
6621 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006622 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006623
6624 /* Safety checks:
6625 * - if argument count differs between the wide and non-wide argument
6626 * list, something must be wrong.
6627 * - the file name arguments must have been located.
6628 * - the length of the argument list wasn't changed by the user.
6629 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006630 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006631 || ArglistW == NULL
6632 || used_file_indexes == NULL
6633 || used_file_count == 0
6634 || used_alist_count != GARGCOUNT)
6635 return;
6636
Bram Moolenaar86b68352004-12-27 21:59:20 +00006637 /* Remember the buffer numbers for the arguments. */
6638 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6639 if (fnum_list == NULL)
6640 return; /* out of memory */
6641 for (i = 0; i < GARGCOUNT; ++i)
6642 fnum_list[i] = GARGLIST[i].ae_fnum;
6643
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006644 /* Clear the argument list. Make room for the new arguments. */
6645 alist_clear(&global_alist);
6646 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006647 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006648
6649 for (i = 0; i < used_file_count; ++i)
6650 {
6651 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006652 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006653 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006654 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006655#ifdef FEAT_DIFF
6656 /* When using diff mode may need to concatenate file name to
6657 * directory name. Just like it's done in main(). */
6658 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6659 && !mch_isdir(alist_name(&GARGLIST[0])))
6660 {
6661 char_u *r;
6662
6663 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6664 if (r != NULL)
6665 {
6666 vim_free(str);
6667 str = r;
6668 }
6669 }
6670#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006671 /* Re-use the old buffer by renaming it. When not using literal
6672 * names it's done by alist_expand() below. */
6673 if (used_file_literal)
6674 buf_set_name(fnum_list[i], str);
6675
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006676 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006677 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006678 }
6679
6680 if (!used_file_literal)
6681 {
6682 /* Now expand wildcards in the arguments. */
6683 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6684 * filename characters but are excluded from 'isfname' to make
6685 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6686 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006687 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006688 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6689 }
6690
6691 /* If wildcard expansion failed, we are editing the first file of the
6692 * arglist and there is no file name: Edit the first argument now. */
6693 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6694 {
6695 do_cmdline_cmd((char_u *)":rewind");
6696 if (GARGCOUNT == 1 && used_file_full_path)
6697 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6698 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006699
6700 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006701}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702#endif