blob: 25c63e0c07864960954b04ddada3d2d2eb89eafc [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);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200216static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
217static WCHAR tgetch(int *pmodifiers, WCHAR *pch2);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218static 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 Moolenaarbb86ebb2015-08-04 19:27:05 +0200262 if (nLength == -2)
263 return (s_dwMax > 0) ? TRUE : FALSE;
264
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100265 if (!win8_or_later)
266 {
267 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200268 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
269 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100270 }
271
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100272 if (s_dwMax == 0)
273 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100274 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200275 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
276 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100277 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100278 s_dwIndex = 0;
279 s_dwMax = dwEvents;
280 if (dwEvents == 0)
281 {
282 *lpEvents = 0;
283 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100284 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100285
286 if (s_dwMax > 1)
287 {
288 head = 0;
289 tail = s_dwMax - 1;
290 while (head != tail)
291 {
292 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
293 && s_irCache[head + 1].EventType
294 == WINDOW_BUFFER_SIZE_EVENT)
295 {
296 /* Remove duplicate event to avoid flicker. */
297 for (i = head; i < tail; ++i)
298 s_irCache[i] = s_irCache[i + 1];
299 --tail;
300 continue;
301 }
302 head++;
303 }
304 s_dwMax = tail + 1;
305 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100306 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100307
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100308 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200309 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100311 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100312 return TRUE;
313}
314
315/*
316 * Version of PeekConsoleInput() that works with IME.
317 */
318 static BOOL
319peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100320 HANDLE hInput,
321 INPUT_RECORD *lpBuffer,
322 DWORD nLength,
323 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100325 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326}
327
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200328 static DWORD
329msg_wait_for_multiple_objects(
330 DWORD nCount,
331 LPHANDLE pHandles,
332 BOOL fWaitAll,
333 DWORD dwMilliseconds,
334 DWORD dwWakeMask)
335{
336 if (read_console_input(NULL, NULL, -2, NULL))
337 return WAIT_OBJECT_0;
338 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
339 dwMilliseconds, dwWakeMask);
340}
341
342 static DWORD
343wait_for_single_object(
344 HANDLE hHandle,
345 DWORD dwMilliseconds)
346{
347 if (read_console_input(NULL, NULL, -2, NULL))
348 return WAIT_OBJECT_0;
349 return WaitForSingleObject(hHandle, dwMilliseconds);
350}
351
Bram Moolenaar071d4272004-06-13 20:20:40 +0000352 static void
353get_exe_name(void)
354{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100355 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
356 * as the maximum length that works (plus a NUL byte). */
357#define MAX_ENV_PATH_LEN 8192
358 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200359 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360
361 if (exe_name == NULL)
362 {
363 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100364 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365 if (*temp != NUL)
366 exe_name = FullName_save((char_u *)temp, FALSE);
367 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000368
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200369 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000370 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200371 exe_path = vim_strnsave(exe_name,
372 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200373 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000374 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200375 /* Append our starting directory to $PATH, so that when doing
376 * "!xxd" it's found in our starting directory. Needed because
377 * SearchPath() also looks there. */
378 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100379 if (p == NULL
380 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200381 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100382 if (p == NULL || *p == NUL)
383 temp[0] = NUL;
384 else
385 {
386 STRCPY(temp, p);
387 STRCAT(temp, ";");
388 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200389 STRCAT(temp, exe_path);
390 vim_setenv((char_u *)"PATH", temp);
391 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000392 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000393 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394}
395
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200396/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100397 * Unescape characters in "p" that appear in "escaped".
398 */
399 static void
400unescape_shellxquote(char_u *p, char_u *escaped)
401{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100402 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100403 int n;
404
405 while (*p != NUL)
406 {
407 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
408 mch_memmove(p, p + 1, l--);
409#ifdef FEAT_MBYTE
410 n = (*mb_ptr2len)(p);
411#else
412 n = 1;
413#endif
414 p += n;
415 l -= n;
416 }
417}
418
419/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200420 * Load library "name".
421 */
422 HINSTANCE
423vimLoadLib(char *name)
424{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200425 HINSTANCE dll = NULL;
426 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200428 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
429 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200430 if (exe_path == NULL)
431 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200432 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200433 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200434#ifdef FEAT_MBYTE
435 WCHAR old_dirw[MAXPATHL];
436
437 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
438 {
439 /* Change directory to where the executable is, both to make
440 * sure we find a .dll there and to avoid looking for a .dll
441 * in the current directory. */
442 SetCurrentDirectory(exe_path);
443 dll = LoadLibrary(name);
444 SetCurrentDirectoryW(old_dirw);
445 return dll;
446 }
447 /* Retry with non-wide function (for Windows 98). */
448 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
449#endif
450 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
451 {
452 /* Change directory to where the executable is, both to make
453 * sure we find a .dll there and to avoid looking for a .dll
454 * in the current directory. */
455 SetCurrentDirectory(exe_path);
456 dll = LoadLibrary(name);
457 SetCurrentDirectory(old_dir);
458 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200459 }
460 return dll;
461}
462
Bram Moolenaar071d4272004-06-13 20:20:40 +0000463#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
464# ifndef GETTEXT_DLL
465# define GETTEXT_DLL "libintl.dll"
466# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200467/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000468static char *null_libintl_gettext(const char *);
469static char *null_libintl_textdomain(const char *);
470static char *null_libintl_bindtextdomain(const char *, const char *);
471static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200473static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000474char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
475char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
476char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000478char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
479 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000480
481 int
482dyn_libintl_init(char *libname)
483{
484 int i;
485 static struct
486 {
487 char *name;
488 FARPROC *ptr;
489 } libintl_entry[] =
490 {
491 {"gettext", (FARPROC*)&dyn_libintl_gettext},
492 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
493 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
494 {NULL, NULL}
495 };
496
497 /* No need to initialize twice. */
498 if (hLibintlDLL)
499 return 1;
500 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200501 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502 if (!hLibintlDLL)
503 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200504 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200506 verbose_enter();
507 EMSG2(_(e_loadlib), GETTEXT_DLL);
508 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200510 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511 }
512 for (i = 0; libintl_entry[i].name != NULL
513 && libintl_entry[i].ptr != NULL; ++i)
514 {
515 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
516 libintl_entry[i].name)) == NULL)
517 {
518 dyn_libintl_end();
519 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000520 {
521 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000523 verbose_leave();
524 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525 return 0;
526 }
527 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000528
529 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000530 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000531 "bind_textdomain_codeset");
532 if (dyn_libintl_bind_textdomain_codeset == NULL)
533 dyn_libintl_bind_textdomain_codeset =
534 null_libintl_bind_textdomain_codeset;
535
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 return 1;
537}
538
539 void
540dyn_libintl_end()
541{
542 if (hLibintlDLL)
543 FreeLibrary(hLibintlDLL);
544 hLibintlDLL = NULL;
545 dyn_libintl_gettext = null_libintl_gettext;
546 dyn_libintl_textdomain = null_libintl_textdomain;
547 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000548 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549}
550
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000551/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000553null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000554{
555 return (char*)msgid;
556}
557
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000558/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000560null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561{
562 return NULL;
563}
564
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000565/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000566 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000567null_libintl_bind_textdomain_codeset(const char *domainname,
568 const char *codeset)
569{
570 return NULL;
571}
572
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000573/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000574 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000575null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576{
577 return NULL;
578}
579
580#endif /* DYNAMIC_GETTEXT */
581
582/* This symbol is not defined in older versions of the SDK or Visual C++ */
583
584#ifndef VER_PLATFORM_WIN32_WINDOWS
585# define VER_PLATFORM_WIN32_WINDOWS 1
586#endif
587
588DWORD g_PlatformId;
589
590#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100591# ifndef PROTO
592# include <aclapi.h>
593# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200594# ifndef PROTECTED_DACL_SECURITY_INFORMATION
595# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
596# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100597
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598/*
599 * These are needed to dynamically load the ADVAPI DLL, which is not
600 * implemented under Windows 95 (and causes VIM to crash)
601 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200602typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200604typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000605 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
606 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200607# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200608typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200609 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200610typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200611 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
612 PSECURITY_DESCRIPTOR *);
613# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614
615static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
616static PSNSECINFO pSetNamedSecurityInfo;
617static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200618# ifdef FEAT_MBYTE
619static PSNSECINFOW pSetNamedSecurityInfoW;
620static PGNSECINFOW pGetNamedSecurityInfoW;
621# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622#endif
623
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200624typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
625
626static BOOL allowPiping = FALSE;
627static PSETHANDLEINFORMATION pSetHandleInformation;
628
Bram Moolenaar27515922013-06-29 15:36:26 +0200629#ifdef HAVE_ACL
630/*
631 * Enables or disables the specified privilege.
632 */
633 static BOOL
634win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
635{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100636 BOOL bResult;
637 LUID luid;
638 HANDLE hToken;
639 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200640
641 if (!OpenProcessToken(GetCurrentProcess(),
642 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
643 return FALSE;
644
645 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
646 {
647 CloseHandle(hToken);
648 return FALSE;
649 }
650
Bram Moolenaar45500912014-07-09 20:51:07 +0200651 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200652 tokenPrivileges.Privileges[0].Luid = luid;
653 tokenPrivileges.Privileges[0].Attributes = bEnable ?
654 SE_PRIVILEGE_ENABLED : 0;
655
656 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
657 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
658
659 CloseHandle(hToken);
660
661 return bResult && GetLastError() == ERROR_SUCCESS;
662}
663#endif
664
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665/*
666 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
667 * VER_PLATFORM_WIN32_WINDOWS (Win95).
668 */
669 void
670PlatformId(void)
671{
672 static int done = FALSE;
673
674 if (!done)
675 {
676 OSVERSIONINFO ovi;
677
678 ovi.dwOSVersionInfoSize = sizeof(ovi);
679 GetVersionEx(&ovi);
680
681 g_PlatformId = ovi.dwPlatformId;
682
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100683 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
684 || ovi.dwMajorVersion > 6)
685 win8_or_later = TRUE;
686
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687#ifdef HAVE_ACL
688 /*
689 * Load the ADVAPI runtime if we are on anything
690 * other than Windows 95
691 */
692 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
693 {
694 /*
695 * do this load. Problems: Doesn't unload at end of run (this is
696 * theoretically okay, since Windows should unload it when VIM
697 * terminates). Should we be using the 'mch_libcall' routines?
698 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
699 * time we verify security...
700 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200701 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702 if (advapi_lib != NULL)
703 {
704 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
705 "SetNamedSecurityInfoA");
706 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
707 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200708# ifdef FEAT_MBYTE
709 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
710 "SetNamedSecurityInfoW");
711 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
712 "GetNamedSecurityInfoW");
713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200715 || pGetNamedSecurityInfo == NULL
716# ifdef FEAT_MBYTE
717 || pSetNamedSecurityInfoW == NULL
718 || pGetNamedSecurityInfoW == NULL
719# endif
720 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721 {
722 /* If we can't get the function addresses, set advapi_lib
723 * to NULL so that we don't use them. */
724 FreeLibrary(advapi_lib);
725 advapi_lib = NULL;
726 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200727 /* Enable privilege for getting or setting SACLs. */
728 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000729 }
730 }
731#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200732 /*
733 * If we are on windows NT, try to load the pipe functions, only
734 * available from Win2K.
735 */
736 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
737 {
738 HANDLE kernel32 = GetModuleHandle("kernel32");
739 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
740 kernel32, "SetHandleInformation");
741
742 allowPiping = pSetHandleInformation != NULL;
743 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744 done = TRUE;
745 }
746}
747
748/*
749 * Return TRUE when running on Windows 95 (or 98 or ME).
750 * Only to be used after mch_init().
751 */
752 int
753mch_windows95(void)
754{
755 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
756}
757
758#ifdef FEAT_GUI_W32
759/*
760 * Used to work around the "can't do synchronous spawn"
761 * problem on Win32s, without resorting to Universal Thunk.
762 */
763static int old_num_windows;
764static int num_windows;
765
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000766/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000767 static BOOL CALLBACK
768win32ssynch_cb(HWND hwnd, LPARAM lparam)
769{
770 num_windows++;
771 return TRUE;
772}
773#endif
774
775#ifndef FEAT_GUI_W32
776
777#define SHIFT (SHIFT_PRESSED)
778#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
779#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
780#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
781
782
783/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
784 * We map function keys to their ANSI terminal equivalents, as produced
785 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
786 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
787 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
788 * combinations of function/arrow/etc keys.
789 */
790
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000791static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792{
793 WORD wVirtKey;
794 BOOL fAnsiKey;
795 int chAlone;
796 int chShift;
797 int chCtrl;
798 int chAlt;
799} VirtKeyMap[] =
800{
801
802/* Key ANSI alone shift ctrl alt */
803 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
804
805 { VK_F1, TRUE, ';', 'T', '^', 'h', },
806 { VK_F2, TRUE, '<', 'U', '_', 'i', },
807 { VK_F3, TRUE, '=', 'V', '`', 'j', },
808 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
809 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
810 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
811 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
812 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
813 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
814 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
815 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
816 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
817
818 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
819 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
820 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
821 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
822 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
823 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
824 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
825 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
826 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
827 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
828
829 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
830
831#if 0
832 /* Most people don't have F13-F20, but what the hell... */
833 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
834 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
835 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
836 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
837 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
838 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
839 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
840 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
841#endif
842 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
843 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
844 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
845 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
846
847 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
848 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
849 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
850 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
851 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
852 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
853 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
854 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
855 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
856 /* Sorry, out of number space! <negri>*/
857 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
858
859};
860
861
862#ifdef _MSC_VER
863// The ToAscii bug destroys several registers. Need to turn off optimization
864// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000865# pragma warning(push)
866# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000867# pragma optimize("", off)
868#endif
869
870#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200871# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000872#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200873# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874#endif
875
876/* The return code indicates key code size. */
877 static int
878#ifdef __BORLANDC__
879 __stdcall
880#endif
881win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000882 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883{
884 UINT uMods = pker->dwControlKeyState;
885 static int s_iIsDead = 0;
886 static WORD awAnsiCode[2];
887 static BYTE abKeystate[256];
888
889
890 if (s_iIsDead == 2)
891 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200892 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893 s_iIsDead = 0;
894 return 1;
895 }
896
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200897 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898 return 1;
899
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200900 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901
902 // Should only be non-NULL on NT 4.0
903 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
904 {
905 CHAR szKLID[KL_NAMELENGTH];
906
907 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
908 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
909 }
910
911 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200912 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
914 if (uMods & SHIFT_PRESSED)
915 abKeystate[VK_SHIFT] = 0x80;
916 if (uMods & CAPSLOCK_ON)
917 abKeystate[VK_CAPITAL] = 1;
918
919 if ((uMods & ALT_GR) == ALT_GR)
920 {
921 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
922 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
923 }
924
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200925 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
926 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927
928 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200929 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930
931 return s_iIsDead;
932}
933
934#ifdef _MSC_VER
935/* MUST switch optimization on again here, otherwise a call to
936 * decode_key_event() may crash (e.g. when hitting caps-lock) */
937# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000938# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939
940# if (_MSC_VER < 1100)
941/* MUST turn off global optimisation for this next function, or
942 * pressing ctrl-minus in insert mode crashes Vim when built with
943 * VC4.1. -- negri. */
944# pragma optimize("g", off)
945# endif
946#endif
947
948static BOOL g_fJustGotFocus = FALSE;
949
950/*
951 * Decode a KEY_EVENT into one or two keystrokes
952 */
953 static BOOL
954decode_key_event(
955 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200956 WCHAR *pch,
957 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958 int *pmodifiers,
959 BOOL fDoPost)
960{
961 int i;
962 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
963
964 *pch = *pch2 = NUL;
965 g_fJustGotFocus = FALSE;
966
967 /* ignore key up events */
968 if (!pker->bKeyDown)
969 return FALSE;
970
971 /* ignore some keystrokes */
972 switch (pker->wVirtualKeyCode)
973 {
974 /* modifiers */
975 case VK_SHIFT:
976 case VK_CONTROL:
977 case VK_MENU: /* Alt key */
978 return FALSE;
979
980 default:
981 break;
982 }
983
984 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200985 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986 {
987 /* Ctrl-6 is Ctrl-^ */
988 if (pker->wVirtualKeyCode == '6')
989 {
990 *pch = Ctrl_HAT;
991 return TRUE;
992 }
993 /* Ctrl-2 is Ctrl-@ */
994 else if (pker->wVirtualKeyCode == '2')
995 {
996 *pch = NUL;
997 return TRUE;
998 }
999 /* Ctrl-- is Ctrl-_ */
1000 else if (pker->wVirtualKeyCode == 0xBD)
1001 {
1002 *pch = Ctrl__;
1003 return TRUE;
1004 }
1005 }
1006
1007 /* Shift-TAB */
1008 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1009 {
1010 *pch = K_NUL;
1011 *pch2 = '\017';
1012 return TRUE;
1013 }
1014
1015 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1016 {
1017 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1018 {
1019 if (nModifs == 0)
1020 *pch = VirtKeyMap[i].chAlone;
1021 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1022 *pch = VirtKeyMap[i].chShift;
1023 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1024 *pch = VirtKeyMap[i].chCtrl;
1025 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1026 *pch = VirtKeyMap[i].chAlt;
1027
1028 if (*pch != 0)
1029 {
1030 if (VirtKeyMap[i].fAnsiKey)
1031 {
1032 *pch2 = *pch;
1033 *pch = K_NUL;
1034 }
1035
1036 return TRUE;
1037 }
1038 }
1039 }
1040
1041 i = win32_kbd_patch_key(pker);
1042
1043 if (i < 0)
1044 *pch = NUL;
1045 else
1046 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001047 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048
1049 if (pmodifiers != NULL)
1050 {
1051 /* Pass on the ALT key as a modifier, but only when not combined
1052 * with CTRL (which is ALTGR). */
1053 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1054 *pmodifiers |= MOD_MASK_ALT;
1055
1056 /* Pass on SHIFT only for special keys, because we don't know when
1057 * it's already included with the character. */
1058 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1059 *pmodifiers |= MOD_MASK_SHIFT;
1060
1061 /* Pass on CTRL only for non-special keys, because we don't know
1062 * when it's already included with the character. And not when
1063 * combined with ALT (which is ALTGR). */
1064 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1065 && *pch >= 0x20 && *pch < 0x80)
1066 *pmodifiers |= MOD_MASK_CTRL;
1067 }
1068 }
1069
1070 return (*pch != NUL);
1071}
1072
1073#ifdef _MSC_VER
1074# pragma optimize("", on)
1075#endif
1076
1077#endif /* FEAT_GUI_W32 */
1078
1079
1080#ifdef FEAT_MOUSE
1081
1082/*
1083 * For the GUI the mouse handling is in gui_w32.c.
1084 */
1085# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001086/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001088mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001089{
1090}
1091# else
1092static int g_fMouseAvail = FALSE; /* mouse present */
1093static int g_fMouseActive = FALSE; /* mouse enabled */
1094static int g_nMouseClick = -1; /* mouse status */
1095static int g_xMouse; /* mouse x coordinate */
1096static int g_yMouse; /* mouse y coordinate */
1097
1098/*
1099 * Enable or disable mouse input
1100 */
1101 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001102mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103{
1104 DWORD cmodein;
1105
1106 if (!g_fMouseAvail)
1107 return;
1108
1109 g_fMouseActive = on;
1110 GetConsoleMode(g_hConIn, &cmodein);
1111
1112 if (g_fMouseActive)
1113 cmodein |= ENABLE_MOUSE_INPUT;
1114 else
1115 cmodein &= ~ENABLE_MOUSE_INPUT;
1116
1117 SetConsoleMode(g_hConIn, cmodein);
1118}
1119
1120
1121/*
1122 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1123 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1124 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1125 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1126 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1127 * and we return the mouse position in g_xMouse and g_yMouse.
1128 *
1129 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1130 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1131 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1132 *
1133 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1134 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1135 *
1136 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1137 * moves, even if it stays within the same character cell. We ignore
1138 * all MOUSE_MOVED messages if the position hasn't really changed, and
1139 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1140 * we're only interested in MOUSE_DRAG).
1141 *
1142 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1143 * 2-button mouses by pressing the left & right buttons simultaneously.
1144 * In practice, it's almost impossible to click both at the same time,
1145 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1146 * in such cases, if the user is clicking quickly.
1147 */
1148 static BOOL
1149decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001150 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151{
1152 static int s_nOldButton = -1;
1153 static int s_nOldMouseClick = -1;
1154 static int s_xOldMouse = -1;
1155 static int s_yOldMouse = -1;
1156 static linenr_T s_old_topline = 0;
1157#ifdef FEAT_DIFF
1158 static int s_old_topfill = 0;
1159#endif
1160 static int s_cClicks = 1;
1161 static BOOL s_fReleased = TRUE;
1162 static DWORD s_dwLastClickTime = 0;
1163 static BOOL s_fNextIsMiddle = FALSE;
1164
1165 static DWORD cButtons = 0; /* number of buttons supported */
1166
1167 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1168 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1169 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1170 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1171
1172 int nButton;
1173
1174 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1175 cButtons = 2;
1176
1177 if (!g_fMouseAvail || !g_fMouseActive)
1178 {
1179 g_nMouseClick = -1;
1180 return FALSE;
1181 }
1182
1183 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1184 if (g_fJustGotFocus)
1185 {
1186 g_fJustGotFocus = FALSE;
1187 return FALSE;
1188 }
1189
1190 /* unprocessed mouse click? */
1191 if (g_nMouseClick != -1)
1192 return TRUE;
1193
1194 nButton = -1;
1195 g_xMouse = pmer->dwMousePosition.X;
1196 g_yMouse = pmer->dwMousePosition.Y;
1197
1198 if (pmer->dwEventFlags == MOUSE_MOVED)
1199 {
1200 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1201 * events even when the mouse moves only within a char cell.) */
1202 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1203 return FALSE;
1204 }
1205
1206 /* If no buttons are pressed... */
1207 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1208 {
1209 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1210 if (s_fReleased)
1211 return FALSE;
1212
1213 nButton = MOUSE_RELEASE;
1214 s_fReleased = TRUE;
1215 }
1216 else /* one or more buttons pressed */
1217 {
1218 /* on a 2-button mouse, hold down left and right buttons
1219 * simultaneously to get MIDDLE. */
1220
1221 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1222 {
1223 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1224
1225 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001226 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001227 if (dwLR == LEFT || dwLR == RIGHT)
1228 {
1229 for (;;)
1230 {
1231 /* wait a short time for next input event */
1232 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1233 != WAIT_OBJECT_0)
1234 break;
1235 else
1236 {
1237 DWORD cRecords = 0;
1238 INPUT_RECORD ir;
1239 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1240
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001241 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001242
1243 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1244 || !(pmer2->dwButtonState & LEFT_RIGHT))
1245 break;
1246 else
1247 {
1248 if (pmer2->dwEventFlags != MOUSE_MOVED)
1249 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001250 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251
1252 return decode_mouse_event(pmer2);
1253 }
1254 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1255 s_yOldMouse == pmer2->dwMousePosition.Y)
1256 {
1257 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001258 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259
1260 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001261 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001262
1263 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1264 break;
1265 }
1266 else
1267 break;
1268 }
1269 }
1270 }
1271 }
1272 }
1273
1274 if (s_fNextIsMiddle)
1275 {
1276 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1277 ? MOUSE_DRAG : MOUSE_MIDDLE;
1278 s_fNextIsMiddle = FALSE;
1279 }
1280 else if (cButtons == 2 &&
1281 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1282 {
1283 nButton = MOUSE_MIDDLE;
1284
1285 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1286 {
1287 s_fNextIsMiddle = TRUE;
1288 nButton = MOUSE_RELEASE;
1289 }
1290 }
1291 else if ((pmer->dwButtonState & LEFT) == LEFT)
1292 nButton = MOUSE_LEFT;
1293 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1294 nButton = MOUSE_MIDDLE;
1295 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1296 nButton = MOUSE_RIGHT;
1297
1298 if (! s_fReleased && ! s_fNextIsMiddle
1299 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1300 return FALSE;
1301
1302 s_fReleased = s_fNextIsMiddle;
1303 }
1304
1305 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1306 {
1307 /* button pressed or released, without mouse moving */
1308 if (nButton != -1 && nButton != MOUSE_RELEASE)
1309 {
1310 DWORD dwCurrentTime = GetTickCount();
1311
1312 if (s_xOldMouse != g_xMouse
1313 || s_yOldMouse != g_yMouse
1314 || s_nOldButton != nButton
1315 || s_old_topline != curwin->w_topline
1316#ifdef FEAT_DIFF
1317 || s_old_topfill != curwin->w_topfill
1318#endif
1319 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1320 {
1321 s_cClicks = 1;
1322 }
1323 else if (++s_cClicks > 4)
1324 {
1325 s_cClicks = 1;
1326 }
1327
1328 s_dwLastClickTime = dwCurrentTime;
1329 }
1330 }
1331 else if (pmer->dwEventFlags == MOUSE_MOVED)
1332 {
1333 if (nButton != -1 && nButton != MOUSE_RELEASE)
1334 nButton = MOUSE_DRAG;
1335
1336 s_cClicks = 1;
1337 }
1338
1339 if (nButton == -1)
1340 return FALSE;
1341
1342 if (nButton != MOUSE_RELEASE)
1343 s_nOldButton = nButton;
1344
1345 g_nMouseClick = nButton;
1346
1347 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1348 g_nMouseClick |= MOUSE_SHIFT;
1349 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1350 g_nMouseClick |= MOUSE_CTRL;
1351 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1352 g_nMouseClick |= MOUSE_ALT;
1353
1354 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1355 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1356
1357 /* only pass on interesting (i.e., different) mouse events */
1358 if (s_xOldMouse == g_xMouse
1359 && s_yOldMouse == g_yMouse
1360 && s_nOldMouseClick == g_nMouseClick)
1361 {
1362 g_nMouseClick = -1;
1363 return FALSE;
1364 }
1365
1366 s_xOldMouse = g_xMouse;
1367 s_yOldMouse = g_yMouse;
1368 s_old_topline = curwin->w_topline;
1369#ifdef FEAT_DIFF
1370 s_old_topfill = curwin->w_topfill;
1371#endif
1372 s_nOldMouseClick = g_nMouseClick;
1373
1374 return TRUE;
1375}
1376
1377# endif /* FEAT_GUI_W32 */
1378#endif /* FEAT_MOUSE */
1379
1380
1381#ifdef MCH_CURSOR_SHAPE
1382/*
1383 * Set the shape of the cursor.
1384 * 'thickness' can be from 1 (thin) to 99 (block)
1385 */
1386 static void
1387mch_set_cursor_shape(int thickness)
1388{
1389 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1390 ConsoleCursorInfo.dwSize = thickness;
1391 ConsoleCursorInfo.bVisible = s_cursor_visible;
1392
1393 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1394 if (s_cursor_visible)
1395 SetConsoleCursorPosition(g_hConOut, g_coord);
1396}
1397
1398 void
1399mch_update_cursor(void)
1400{
1401 int idx;
1402 int thickness;
1403
1404 /*
1405 * How the cursor is drawn depends on the current mode.
1406 */
1407 idx = get_shape_idx(FALSE);
1408
1409 if (shape_table[idx].shape == SHAPE_BLOCK)
1410 thickness = 99; /* 100 doesn't work on W95 */
1411 else
1412 thickness = shape_table[idx].percentage;
1413 mch_set_cursor_shape(thickness);
1414}
1415#endif
1416
1417#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1418/*
1419 * Handle FOCUS_EVENT.
1420 */
1421 static void
1422handle_focus_event(INPUT_RECORD ir)
1423{
1424 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1425 ui_focus_change((int)g_fJustGotFocus);
1426}
1427
1428/*
1429 * Wait until console input from keyboard or mouse is available,
1430 * or the time is up.
1431 * Return TRUE if something is available FALSE if not.
1432 */
1433 static int
1434WaitForChar(long msec)
1435{
1436 DWORD dwNow = 0, dwEndTime = 0;
1437 INPUT_RECORD ir;
1438 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001439 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440
1441 if (msec > 0)
1442 /* Wait until the specified time has elapsed. */
1443 dwEndTime = GetTickCount() + msec;
1444 else if (msec < 0)
1445 /* Wait forever. */
1446 dwEndTime = INFINITE;
1447
1448 /* We need to loop until the end of the time period, because
1449 * we might get multiple unusable mouse events in that time.
1450 */
1451 for (;;)
1452 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001453#ifdef FEAT_MZSCHEME
1454 mzvim_check_threads();
1455#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456#ifdef FEAT_CLIENTSERVER
1457 serverProcessPendingMessages();
1458#endif
1459 if (0
1460#ifdef FEAT_MOUSE
1461 || g_nMouseClick != -1
1462#endif
1463#ifdef FEAT_CLIENTSERVER
1464 || input_available()
1465#endif
1466 )
1467 return TRUE;
1468
1469 if (msec > 0)
1470 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001471 /* If the specified wait time has passed, return. Beware that
1472 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001474 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475 break;
1476 }
1477 if (msec != 0)
1478 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001479 DWORD dwWaitTime = dwEndTime - dwNow;
1480
1481#ifdef FEAT_MZSCHEME
1482 if (mzthreads_allowed() && p_mzq > 0
1483 && (msec < 0 || (long)dwWaitTime > p_mzq))
1484 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1485#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486#ifdef FEAT_CLIENTSERVER
1487 /* Wait for either an event on the console input or a message in
1488 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001489 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001490 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001492 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493#endif
1494 continue;
1495 }
1496
1497 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001498 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499
1500#ifdef FEAT_MBYTE_IME
1501 if (State & CMDLINE && msg_row == Rows - 1)
1502 {
1503 CONSOLE_SCREEN_BUFFER_INFO csbi;
1504
1505 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1506 {
1507 if (csbi.dwCursorPosition.Y != msg_row)
1508 {
1509 /* The screen is now messed up, must redraw the
1510 * command line and later all the windows. */
1511 redraw_all_later(CLEAR);
1512 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1513 redrawcmd();
1514 }
1515 }
1516 }
1517#endif
1518
1519 if (cRecords > 0)
1520 {
1521 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1522 {
1523#ifdef FEAT_MBYTE_IME
1524 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1525 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001526 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001527 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1528 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001529 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530 continue;
1531 }
1532#endif
1533 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1534 NULL, FALSE))
1535 return TRUE;
1536 }
1537
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001538 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539
1540 if (ir.EventType == FOCUS_EVENT)
1541 handle_focus_event(ir);
1542 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1543 shell_resized();
1544#ifdef FEAT_MOUSE
1545 else if (ir.EventType == MOUSE_EVENT
1546 && decode_mouse_event(&ir.Event.MouseEvent))
1547 return TRUE;
1548#endif
1549 }
1550 else if (msec == 0)
1551 break;
1552 }
1553
1554#ifdef FEAT_CLIENTSERVER
1555 /* Something might have been received while we were waiting. */
1556 if (input_available())
1557 return TRUE;
1558#endif
1559 return FALSE;
1560}
1561
1562#ifndef FEAT_GUI_MSWIN
1563/*
1564 * return non-zero if a character is available
1565 */
1566 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001567mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568{
1569 return WaitForChar(0L);
1570}
1571#endif
1572
1573/*
1574 * Create the console input. Used when reading stdin doesn't work.
1575 */
1576 static void
1577create_conin(void)
1578{
1579 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1580 FILE_SHARE_READ|FILE_SHARE_WRITE,
1581 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001582 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583 did_create_conin = TRUE;
1584}
1585
1586/*
1587 * Get a keystroke or a mouse event
1588 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001589 static WCHAR
1590tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001592 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593
1594 for (;;)
1595 {
1596 INPUT_RECORD ir;
1597 DWORD cRecords = 0;
1598
1599#ifdef FEAT_CLIENTSERVER
1600 (void)WaitForChar(-1L);
1601 if (input_available())
1602 return 0;
1603# ifdef FEAT_MOUSE
1604 if (g_nMouseClick != -1)
1605 return 0;
1606# endif
1607#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001608 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609 {
1610 if (did_create_conin)
1611 read_error_exit();
1612 create_conin();
1613 continue;
1614 }
1615
1616 if (ir.EventType == KEY_EVENT)
1617 {
1618 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1619 pmodifiers, TRUE))
1620 return ch;
1621 }
1622 else if (ir.EventType == FOCUS_EVENT)
1623 handle_focus_event(ir);
1624 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1625 shell_resized();
1626#ifdef FEAT_MOUSE
1627 else if (ir.EventType == MOUSE_EVENT)
1628 {
1629 if (decode_mouse_event(&ir.Event.MouseEvent))
1630 return 0;
1631 }
1632#endif
1633 }
1634}
1635#endif /* !FEAT_GUI_W32 */
1636
1637
1638/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001639 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 * Get one or more characters from the keyboard or the mouse.
1641 * If time == 0, do not wait for characters.
1642 * If time == n, wait a short time for characters.
1643 * If time == -1, wait forever for characters.
1644 * Returns the number of characters read into buf.
1645 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001646/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647 int
1648mch_inchar(
1649 char_u *buf,
1650 int maxlen,
1651 long time,
1652 int tb_change_cnt)
1653{
1654#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1655
1656 int len;
1657 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658#define TYPEAHEADLEN 20
1659 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1660 static int typeaheadlen = 0;
1661
1662 /* First use any typeahead that was kept because "buf" was too small. */
1663 if (typeaheadlen > 0)
1664 goto theend;
1665
1666#ifdef FEAT_SNIFF
1667 if (want_sniff_request)
1668 {
1669 if (sniff_request_waiting)
1670 {
1671 /* return K_SNIFF */
1672 typeahead[typeaheadlen++] = CSI;
1673 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1674 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1675 sniff_request_waiting = 0;
1676 want_sniff_request = 0;
1677 goto theend;
1678 }
1679 else if (time < 0 || time > 250)
1680 {
1681 /* don't wait too long, a request might be pending */
1682 time = 250;
1683 }
1684 }
1685#endif
1686
1687 if (time >= 0)
1688 {
1689 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 }
1692 else /* time == -1, wait forever */
1693 {
1694 mch_set_winsize_now(); /* Allow winsize changes from now on */
1695
Bram Moolenaar3918c952005-03-15 22:34:55 +00001696 /*
1697 * If there is no character available within 2 seconds (default)
1698 * write the autoscript file to disk. Or cause the CursorHold event
1699 * to be triggered.
1700 */
1701 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702 {
1703#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001704 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001705 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001706 buf[0] = K_SPECIAL;
1707 buf[1] = KS_EXTRA;
1708 buf[2] = (int)KE_CURSORHOLD;
1709 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 }
1711#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001712 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 }
1714 }
1715
1716 /*
1717 * Try to read as many characters as there are, until the buffer is full.
1718 */
1719
1720 /* we will get at least one key. Get more if they are available. */
1721 g_fCBrkPressed = FALSE;
1722
1723#ifdef MCH_WRITE_DUMP
1724 if (fdDump)
1725 fputc('[', fdDump);
1726#endif
1727
1728 /* Keep looping until there is something in the typeahead buffer and more
1729 * to get and still room in the buffer (up to two bytes for a char and
1730 * three bytes for a modifier). */
1731 while ((typeaheadlen == 0 || WaitForChar(0L))
1732 && typeaheadlen + 5 <= TYPEAHEADLEN)
1733 {
1734 if (typebuf_changed(tb_change_cnt))
1735 {
1736 /* "buf" may be invalid now if a client put something in the
1737 * typeahead buffer and "buf" is in the typeahead buffer. */
1738 typeaheadlen = 0;
1739 break;
1740 }
1741#ifdef FEAT_MOUSE
1742 if (g_nMouseClick != -1)
1743 {
1744# ifdef MCH_WRITE_DUMP
1745 if (fdDump)
1746 fprintf(fdDump, "{%02x @ %d, %d}",
1747 g_nMouseClick, g_xMouse, g_yMouse);
1748# endif
1749 typeahead[typeaheadlen++] = ESC + 128;
1750 typeahead[typeaheadlen++] = 'M';
1751 typeahead[typeaheadlen++] = g_nMouseClick;
1752 typeahead[typeaheadlen++] = g_xMouse + '!';
1753 typeahead[typeaheadlen++] = g_yMouse + '!';
1754 g_nMouseClick = -1;
1755 }
1756 else
1757#endif
1758 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001759 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 int modifiers = 0;
1761
1762 c = tgetch(&modifiers, &ch2);
1763
1764 if (typebuf_changed(tb_change_cnt))
1765 {
1766 /* "buf" may be invalid now if a client put something in the
1767 * typeahead buffer and "buf" is in the typeahead buffer. */
1768 typeaheadlen = 0;
1769 break;
1770 }
1771
1772 if (c == Ctrl_C && ctrl_c_interrupts)
1773 {
1774#if defined(FEAT_CLIENTSERVER)
1775 trash_input_buf();
1776#endif
1777 got_int = TRUE;
1778 }
1779
1780#ifdef FEAT_MOUSE
1781 if (g_nMouseClick == -1)
1782#endif
1783 {
1784 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001785 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001787#ifdef FEAT_MBYTE
1788 if (ch2 == NUL)
1789 {
1790 int i;
1791 char_u *p;
1792 WCHAR ch[2];
1793
1794 ch[0] = c;
1795 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1796 {
1797 ch[1] = tgetch(&modifiers, &ch2);
1798 n++;
1799 }
1800 p = utf16_to_enc(ch, &n);
1801 if (p != NULL)
1802 {
1803 for (i = 0; i < n; i++)
1804 typeahead[typeaheadlen + i] = p[i];
1805 vim_free(p);
1806 }
1807 }
1808 else
1809#endif
1810 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 if (ch2 != NUL)
1812 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001813 typeahead[typeaheadlen + n] = 3;
1814 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001815 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817
Bram Moolenaar45500912014-07-09 20:51:07 +02001818 if (conv)
1819 {
1820 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001821
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001822 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001823 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001824 char_u *e = typeahead + TYPEAHEADLEN;
1825
1826 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001827 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001828 if (*p == K_NUL)
1829 {
1830 ++p;
1831 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1832 *p = 3;
1833 ++n;
1834 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001835 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001836 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001837 }
1838 }
1839
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 /* Use the ALT key to set the 8th bit of the character
1841 * when it's one byte, the 8th bit isn't set yet and not
1842 * using a double-byte encoding (would become a lead
1843 * byte). */
1844 if ((modifiers & MOD_MASK_ALT)
1845 && n == 1
1846 && (typeahead[typeaheadlen] & 0x80) == 0
1847#ifdef FEAT_MBYTE
1848 && !enc_dbcs
1849#endif
1850 )
1851 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001852#ifdef FEAT_MBYTE
1853 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1854 typeahead + typeaheadlen);
1855#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001856 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001857#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858 modifiers &= ~MOD_MASK_ALT;
1859 }
1860
1861 if (modifiers != 0)
1862 {
1863 /* Prepend modifiers to the character. */
1864 mch_memmove(typeahead + typeaheadlen + 3,
1865 typeahead + typeaheadlen, n);
1866 typeahead[typeaheadlen++] = K_SPECIAL;
1867 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1868 typeahead[typeaheadlen++] = modifiers;
1869 }
1870
1871 typeaheadlen += n;
1872
1873#ifdef MCH_WRITE_DUMP
1874 if (fdDump)
1875 fputc(c, fdDump);
1876#endif
1877 }
1878 }
1879 }
1880
1881#ifdef MCH_WRITE_DUMP
1882 if (fdDump)
1883 {
1884 fputs("]\n", fdDump);
1885 fflush(fdDump);
1886 }
1887#endif
1888
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889theend:
1890 /* Move typeahead to "buf", as much as fits. */
1891 len = 0;
1892 while (len < maxlen && typeaheadlen > 0)
1893 {
1894 buf[len++] = typeahead[0];
1895 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1896 }
1897 return len;
1898
1899#else /* FEAT_GUI_W32 */
1900 return 0;
1901#endif /* FEAT_GUI_W32 */
1902}
1903
Bram Moolenaar82881492012-11-20 16:53:39 +01001904#ifndef PROTO
1905# ifndef __MINGW32__
1906# include <shellapi.h> /* required for FindExecutable() */
1907# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908#endif
1909
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001910/*
1911 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001912 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001913 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001915executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001917 char *dum;
1918 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001919 char *curpath, *newpath;
1920 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001922#ifdef FEAT_MBYTE
1923 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001925 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001926 WCHAR fnamew[_MAX_PATH];
1927 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001928 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001929
1930 if (p != NULL)
1931 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001932 wcurpath = _wgetenv(L"PATH");
1933 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1934 * sizeof(WCHAR));
1935 if (wnewpath == NULL)
1936 return FALSE;
1937 wcscpy(wnewpath, L".;");
1938 wcscat(wnewpath, wcurpath);
1939 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1940 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001941 vim_free(p);
1942 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1943 {
1944 if (n == 0)
1945 return FALSE;
1946 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1947 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001948 if (path != NULL)
1949 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001950 return TRUE;
1951 }
1952 /* Retry with non-wide function (for Windows 98). */
1953 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001955#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001956
1957 curpath = getenv("PATH");
1958 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1959 if (newpath == NULL)
1960 return FALSE;
1961 STRCPY(newpath, ".;");
1962 STRCAT(newpath, curpath);
1963 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1964 vim_free(newpath);
1965 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001966 return FALSE;
1967 if (mch_isdir(fname))
1968 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001969 if (path != NULL)
1970 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001971 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972}
1973
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001974#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001975 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001976/*
1977 * Bad parameter handler.
1978 *
1979 * Certain MS CRT functions will intentionally crash when passed invalid
1980 * parameters to highlight possible security holes. Setting this function as
1981 * the bad parameter handler will prevent the crash.
1982 *
1983 * In debug builds the parameters contain CRT information that might help track
1984 * down the source of a problem, but in non-debug builds the arguments are all
1985 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1986 * worth allowing these to make debugging of issues easier.
1987 */
1988 static void
1989bad_param_handler(const wchar_t *expression,
1990 const wchar_t *function,
1991 const wchar_t *file,
1992 unsigned int line,
1993 uintptr_t pReserved)
1994{
1995}
1996
1997# define SET_INVALID_PARAM_HANDLER \
1998 ((void)_set_invalid_parameter_handler(bad_param_handler))
1999#else
2000# define SET_INVALID_PARAM_HANDLER
2001#endif
2002
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003#ifdef FEAT_GUI_W32
2004
2005/*
2006 * GUI version of mch_init().
2007 */
2008 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002009mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010{
2011#ifndef __MINGW32__
2012 extern int _fmode;
2013#endif
2014
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002015 /* Silently handle invalid parameters to CRT functions */
2016 SET_INVALID_PARAM_HANDLER;
2017
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018 /* Let critical errors result in a failure, not in a dialog box. Required
2019 * for the timestamp test to work on removed floppies. */
2020 SetErrorMode(SEM_FAILCRITICALERRORS);
2021
2022 _fmode = O_BINARY; /* we do our own CR-LF translation */
2023
2024 /* Specify window size. Is there a place to get the default from? */
2025 Rows = 25;
2026 Columns = 80;
2027
2028 /* Look for 'vimrun' */
2029 if (!gui_is_win32s())
2030 {
2031 char_u vimrun_location[_MAX_PATH + 4];
2032
2033 /* First try in same directory as gvim.exe */
2034 STRCPY(vimrun_location, exe_name);
2035 STRCPY(gettail(vimrun_location), "vimrun.exe");
2036 if (mch_getperm(vimrun_location) >= 0)
2037 {
2038 if (*skiptowhite(vimrun_location) != NUL)
2039 {
2040 /* Enclose path with white space in double quotes. */
2041 mch_memmove(vimrun_location + 1, vimrun_location,
2042 STRLEN(vimrun_location) + 1);
2043 *vimrun_location = '"';
2044 STRCPY(gettail(vimrun_location), "vimrun\" ");
2045 }
2046 else
2047 STRCPY(gettail(vimrun_location), "vimrun ");
2048
2049 vimrun_path = (char *)vim_strsave(vimrun_location);
2050 s_dont_use_vimrun = FALSE;
2051 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002052 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002053 s_dont_use_vimrun = FALSE;
2054
2055 /* Don't give the warning for a missing vimrun.exe right now, but only
2056 * when vimrun was supposed to be used. Don't bother people that do
2057 * not need vimrun.exe. */
2058 if (s_dont_use_vimrun)
2059 need_vimrun_warning = TRUE;
2060 }
2061
2062 /*
2063 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2064 * Otherwise the default "findstr /n" is used.
2065 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002066 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2068
2069#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002070 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071#endif
2072}
2073
2074
2075#else /* FEAT_GUI_W32 */
2076
2077#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2078#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2079
2080/*
2081 * ClearConsoleBuffer()
2082 * Description:
2083 * Clears the entire contents of the console screen buffer, using the
2084 * specified attribute.
2085 * Returns:
2086 * TRUE on success
2087 */
2088 static BOOL
2089ClearConsoleBuffer(WORD wAttribute)
2090{
2091 CONSOLE_SCREEN_BUFFER_INFO csbi;
2092 COORD coord;
2093 DWORD NumCells, dummy;
2094
2095 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2096 return FALSE;
2097
2098 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2099 coord.X = 0;
2100 coord.Y = 0;
2101 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2102 coord, &dummy))
2103 {
2104 return FALSE;
2105 }
2106 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2107 coord, &dummy))
2108 {
2109 return FALSE;
2110 }
2111
2112 return TRUE;
2113}
2114
2115/*
2116 * FitConsoleWindow()
2117 * Description:
2118 * Checks if the console window will fit within given buffer dimensions.
2119 * Also, if requested, will shrink the window to fit.
2120 * Returns:
2121 * TRUE on success
2122 */
2123 static BOOL
2124FitConsoleWindow(
2125 COORD dwBufferSize,
2126 BOOL WantAdjust)
2127{
2128 CONSOLE_SCREEN_BUFFER_INFO csbi;
2129 COORD dwWindowSize;
2130 BOOL NeedAdjust = FALSE;
2131
2132 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2133 {
2134 /*
2135 * A buffer resize will fail if the current console window does
2136 * not lie completely within that buffer. To avoid this, we might
2137 * have to move and possibly shrink the window.
2138 */
2139 if (csbi.srWindow.Right >= dwBufferSize.X)
2140 {
2141 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2142 if (dwWindowSize.X > dwBufferSize.X)
2143 dwWindowSize.X = dwBufferSize.X;
2144 csbi.srWindow.Right = dwBufferSize.X - 1;
2145 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2146 NeedAdjust = TRUE;
2147 }
2148 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2149 {
2150 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2151 if (dwWindowSize.Y > dwBufferSize.Y)
2152 dwWindowSize.Y = dwBufferSize.Y;
2153 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2154 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2155 NeedAdjust = TRUE;
2156 }
2157 if (NeedAdjust && WantAdjust)
2158 {
2159 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2160 return FALSE;
2161 }
2162 return TRUE;
2163 }
2164
2165 return FALSE;
2166}
2167
2168typedef struct ConsoleBufferStruct
2169{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002170 BOOL IsValid;
2171 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002172 PCHAR_INFO Buffer;
2173 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174} ConsoleBuffer;
2175
2176/*
2177 * SaveConsoleBuffer()
2178 * Description:
2179 * Saves important information about the console buffer, including the
2180 * actual buffer contents. The saved information is suitable for later
2181 * restoration by RestoreConsoleBuffer().
2182 * Returns:
2183 * TRUE if all information was saved; FALSE otherwise
2184 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2185 */
2186 static BOOL
2187SaveConsoleBuffer(
2188 ConsoleBuffer *cb)
2189{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002190 DWORD NumCells;
2191 COORD BufferCoord;
2192 SMALL_RECT ReadRegion;
2193 WORD Y, Y_incr;
2194
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195 if (cb == NULL)
2196 return FALSE;
2197
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002198 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 {
2200 cb->IsValid = FALSE;
2201 return FALSE;
2202 }
2203 cb->IsValid = TRUE;
2204
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002205 /*
2206 * Allocate a buffer large enough to hold the entire console screen
2207 * buffer. If this ConsoleBuffer structure has already been initialized
2208 * with a buffer of the correct size, then just use that one.
2209 */
2210 if (!cb->IsValid || cb->Buffer == NULL ||
2211 cb->BufferSize.X != cb->Info.dwSize.X ||
2212 cb->BufferSize.Y != cb->Info.dwSize.Y)
2213 {
2214 cb->BufferSize.X = cb->Info.dwSize.X;
2215 cb->BufferSize.Y = cb->Info.dwSize.Y;
2216 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2217 vim_free(cb->Buffer);
2218 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2219 if (cb->Buffer == NULL)
2220 return FALSE;
2221 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002222
2223 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002224 * We will now copy the console screen buffer into our buffer.
2225 * ReadConsoleOutput() seems to be limited as far as how much you
2226 * can read at a time. Empirically, this number seems to be about
2227 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2228 * in chunks until it is all copied. The chunks will all have the
2229 * same horizontal characteristics, so initialize them now. The
2230 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002232 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002233 ReadRegion.Left = 0;
2234 ReadRegion.Right = cb->Info.dwSize.X - 1;
2235 Y_incr = 12000 / cb->Info.dwSize.X;
2236 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002238 /*
2239 * Read into position (0, Y) in our buffer.
2240 */
2241 BufferCoord.Y = Y;
2242 /*
2243 * Read the region whose top left corner is (0, Y) and whose bottom
2244 * right corner is (width - 1, Y + Y_incr - 1). This should define
2245 * a region of size width by Y_incr. Don't worry if this region is
2246 * too large for the remaining buffer; it will be cropped.
2247 */
2248 ReadRegion.Top = Y;
2249 ReadRegion.Bottom = Y + Y_incr - 1;
2250 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2251 cb->Buffer, /* our buffer */
2252 cb->BufferSize, /* dimensions of our buffer */
2253 BufferCoord, /* offset in our buffer */
2254 &ReadRegion)) /* region to save */
2255 {
2256 vim_free(cb->Buffer);
2257 cb->Buffer = NULL;
2258 return FALSE;
2259 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260 }
2261
2262 return TRUE;
2263}
2264
2265/*
2266 * RestoreConsoleBuffer()
2267 * Description:
2268 * Restores important information about the console buffer, including the
2269 * actual buffer contents, if desired. The information to restore is in
2270 * the same format used by SaveConsoleBuffer().
2271 * Returns:
2272 * TRUE on success
2273 */
2274 static BOOL
2275RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002276 ConsoleBuffer *cb,
2277 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002279 COORD BufferCoord;
2280 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281
2282 if (cb == NULL || !cb->IsValid)
2283 return FALSE;
2284
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002285 /*
2286 * Before restoring the buffer contents, clear the current buffer, and
2287 * restore the cursor position and window information. Doing this now
2288 * prevents old buffer contents from "flashing" onto the screen.
2289 */
2290 if (RestoreScreen)
2291 ClearConsoleBuffer(cb->Info.wAttributes);
2292
2293 FitConsoleWindow(cb->Info.dwSize, TRUE);
2294 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2295 return FALSE;
2296 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2297 return FALSE;
2298
2299 if (!RestoreScreen)
2300 {
2301 /*
2302 * No need to restore the screen buffer contents, so we're done.
2303 */
2304 return TRUE;
2305 }
2306
2307 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2308 return FALSE;
2309 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2310 return FALSE;
2311
2312 /*
2313 * Restore the screen buffer contents.
2314 */
2315 if (cb->Buffer != NULL)
2316 {
2317 BufferCoord.X = 0;
2318 BufferCoord.Y = 0;
2319 WriteRegion.Left = 0;
2320 WriteRegion.Top = 0;
2321 WriteRegion.Right = cb->Info.dwSize.X - 1;
2322 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2323 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2324 cb->Buffer, /* our buffer */
2325 cb->BufferSize, /* dimensions of our buffer */
2326 BufferCoord, /* offset in our buffer */
2327 &WriteRegion)) /* region to restore */
2328 {
2329 return FALSE;
2330 }
2331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332
2333 return TRUE;
2334}
2335
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002336#define FEAT_RESTORE_ORIG_SCREEN
2337#ifdef FEAT_RESTORE_ORIG_SCREEN
2338static ConsoleBuffer g_cbOrig = { 0 };
2339#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340static ConsoleBuffer g_cbNonTermcap = { 0 };
2341static ConsoleBuffer g_cbTermcap = { 0 };
2342
2343#ifdef FEAT_TITLE
2344#ifdef __BORLANDC__
2345typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2346#else
2347typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2348#endif
2349char g_szOrigTitle[256] = { 0 };
2350HWND g_hWnd = NULL; /* also used in os_mswin.c */
2351static HICON g_hOrigIconSmall = NULL;
2352static HICON g_hOrigIcon = NULL;
2353static HICON g_hVimIcon = NULL;
2354static BOOL g_fCanChangeIcon = FALSE;
2355
2356/* ICON* are not defined in VC++ 4.0 */
2357#ifndef ICON_SMALL
2358#define ICON_SMALL 0
2359#endif
2360#ifndef ICON_BIG
2361#define ICON_BIG 1
2362#endif
2363/*
2364 * GetConsoleIcon()
2365 * Description:
2366 * Attempts to retrieve the small icon and/or the big icon currently in
2367 * use by a given window.
2368 * Returns:
2369 * TRUE on success
2370 */
2371 static BOOL
2372GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002373 HWND hWnd,
2374 HICON *phIconSmall,
2375 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376{
2377 if (hWnd == NULL)
2378 return FALSE;
2379
2380 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002381 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2382 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002384 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2385 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 return TRUE;
2387}
2388
2389/*
2390 * SetConsoleIcon()
2391 * Description:
2392 * Attempts to change the small icon and/or the big icon currently in
2393 * use by a given window.
2394 * Returns:
2395 * TRUE on success
2396 */
2397 static BOOL
2398SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002399 HWND hWnd,
2400 HICON hIconSmall,
2401 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002403 HICON hPrevIconSmall;
2404 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405
2406 if (hWnd == NULL)
2407 return FALSE;
2408
2409 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002410 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2411 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002413 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2414 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415 return TRUE;
2416}
2417
2418/*
2419 * SaveConsoleTitleAndIcon()
2420 * Description:
2421 * Saves the current console window title in g_szOrigTitle, for later
2422 * restoration. Also, attempts to obtain a handle to the console window,
2423 * and use it to save the small and big icons currently in use by the
2424 * console window. This is not always possible on some versions of Windows;
2425 * nor is it possible when running Vim remotely using Telnet (since the
2426 * console window the user sees is owned by a remote process).
2427 */
2428 static void
2429SaveConsoleTitleAndIcon(void)
2430{
2431 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2432
2433 /* Save the original title. */
2434 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2435 return;
2436
2437 /*
2438 * Obtain a handle to the console window using GetConsoleWindow() from
2439 * KERNEL32.DLL; we need to handle in order to change the window icon.
2440 * This function only exists on NT-based Windows, starting with Windows
2441 * 2000. On older operating systems, we can't change the window icon
2442 * anyway.
2443 */
2444 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2445 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2446 "GetConsoleWindow")) != NULL)
2447 {
2448 g_hWnd = (*GetConsoleWindowProc)();
2449 }
2450 if (g_hWnd == NULL)
2451 return;
2452
2453 /* Save the original console window icon. */
2454 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2455 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2456 return;
2457
2458 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002459 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2460 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461 if (g_hVimIcon != NULL)
2462 g_fCanChangeIcon = TRUE;
2463}
2464#endif
2465
2466static int g_fWindInitCalled = FALSE;
2467static int g_fTermcapMode = FALSE;
2468static CONSOLE_CURSOR_INFO g_cci;
2469static DWORD g_cmodein = 0;
2470static DWORD g_cmodeout = 0;
2471
2472/*
2473 * non-GUI version of mch_init().
2474 */
2475 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002476mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002478#ifndef FEAT_RESTORE_ORIG_SCREEN
2479 CONSOLE_SCREEN_BUFFER_INFO csbi;
2480#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481#ifndef __MINGW32__
2482 extern int _fmode;
2483#endif
2484
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002485 /* Silently handle invalid parameters to CRT functions */
2486 SET_INVALID_PARAM_HANDLER;
2487
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488 /* Let critical errors result in a failure, not in a dialog box. Required
2489 * for the timestamp test to work on removed floppies. */
2490 SetErrorMode(SEM_FAILCRITICALERRORS);
2491
2492 _fmode = O_BINARY; /* we do our own CR-LF translation */
2493 out_flush();
2494
2495 /* Obtain handles for the standard Console I/O devices */
2496 if (read_cmd_fd == 0)
2497 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2498 else
2499 create_conin();
2500 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2501
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002502#ifdef FEAT_RESTORE_ORIG_SCREEN
2503 /* Save the initial console buffer for later restoration */
2504 SaveConsoleBuffer(&g_cbOrig);
2505 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2506#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002508 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2509 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2510#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 if (cterm_normal_fg_color == 0)
2512 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2513 if (cterm_normal_bg_color == 0)
2514 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2515
2516 /* set termcap codes to current text attributes */
2517 update_tcap(g_attrCurrent);
2518
2519 GetConsoleCursorInfo(g_hConOut, &g_cci);
2520 GetConsoleMode(g_hConIn, &g_cmodein);
2521 GetConsoleMode(g_hConOut, &g_cmodeout);
2522
2523#ifdef FEAT_TITLE
2524 SaveConsoleTitleAndIcon();
2525 /*
2526 * Set both the small and big icons of the console window to Vim's icon.
2527 * Note that Vim presently only has one size of icon (32x32), but it
2528 * automatically gets scaled down to 16x16 when setting the small icon.
2529 */
2530 if (g_fCanChangeIcon)
2531 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2532#endif
2533
2534 ui_get_shellsize();
2535
2536#ifdef MCH_WRITE_DUMP
2537 fdDump = fopen("dump", "wt");
2538
2539 if (fdDump)
2540 {
2541 time_t t;
2542
2543 time(&t);
2544 fputs(ctime(&t), fdDump);
2545 fflush(fdDump);
2546 }
2547#endif
2548
2549 g_fWindInitCalled = TRUE;
2550
2551#ifdef FEAT_MOUSE
2552 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2553#endif
2554
2555#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002556 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557#endif
2558
2559 /* This will be NULL on anything but NT 4.0 */
2560 s_pfnGetConsoleKeyboardLayoutName =
2561 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2562 "GetConsoleKeyboardLayoutNameA");
2563}
2564
2565/*
2566 * non-GUI version of mch_exit().
2567 * Shut down and exit with status `r'
2568 * Careful: mch_exit() may be called before mch_init()!
2569 */
2570 void
2571mch_exit(int r)
2572{
2573 stoptermcap();
2574
2575 if (g_fWindInitCalled)
2576 settmode(TMODE_COOK);
2577
2578 ml_close_all(TRUE); /* remove all memfiles */
2579
2580 if (g_fWindInitCalled)
2581 {
2582#ifdef FEAT_TITLE
2583 mch_restore_title(3);
2584 /*
2585 * Restore both the small and big icons of the console window to
2586 * what they were at startup. Don't do this when the window is
2587 * closed, Vim would hang here.
2588 */
2589 if (g_fCanChangeIcon && !g_fForceExit)
2590 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2591#endif
2592
2593#ifdef MCH_WRITE_DUMP
2594 if (fdDump)
2595 {
2596 time_t t;
2597
2598 time(&t);
2599 fputs(ctime(&t), fdDump);
2600 fclose(fdDump);
2601 }
2602 fdDump = NULL;
2603#endif
2604 }
2605
2606 SetConsoleCursorInfo(g_hConOut, &g_cci);
2607 SetConsoleMode(g_hConIn, g_cmodein);
2608 SetConsoleMode(g_hConOut, g_cmodeout);
2609
2610#ifdef DYNAMIC_GETTEXT
2611 dyn_libintl_end();
2612#endif
2613
2614 exit(r);
2615}
2616#endif /* !FEAT_GUI_W32 */
2617
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618/*
2619 * Do we have an interactive window?
2620 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002621/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 int
2623mch_check_win(
2624 int argc,
2625 char **argv)
2626{
2627 get_exe_name();
2628
2629#ifdef FEAT_GUI_W32
2630 return OK; /* GUI always has a tty */
2631#else
2632 if (isatty(1))
2633 return OK;
2634 return FAIL;
2635#endif
2636}
2637
2638
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002639#ifdef FEAT_MBYTE
2640/*
2641 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2642 * if it already exists. When "len" is > 0, also expand short to long
2643 * filenames.
2644 * Return FAIL if wide functions are not available, OK otherwise.
2645 * NOTE: much of this is identical to fname_case(), keep in sync!
2646 */
2647 static int
2648fname_casew(
2649 WCHAR *name,
2650 int len)
2651{
2652 WCHAR szTrueName[_MAX_PATH + 2];
2653 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2654 WCHAR *ptrue, *ptruePrev;
2655 WCHAR *porig, *porigPrev;
2656 int flen;
2657 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002658 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002659 int c;
2660 int slen;
2661
2662 flen = (int)wcslen(name);
2663 if (flen > _MAX_PATH)
2664 return OK;
2665
2666 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2667
2668 /* Build the new name in szTrueName[] one component at a time. */
2669 porig = name;
2670 ptrue = szTrueName;
2671
2672 if (iswalpha(porig[0]) && porig[1] == L':')
2673 {
2674 /* copy leading drive letter */
2675 *ptrue++ = *porig++;
2676 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002677 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002678 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002679
2680 while (*porig != NUL)
2681 {
2682 /* copy \ characters */
2683 while (*porig == psepc)
2684 *ptrue++ = *porig++;
2685
2686 ptruePrev = ptrue;
2687 porigPrev = porig;
2688 while (*porig != NUL && *porig != psepc)
2689 {
2690 *ptrue++ = *porig++;
2691 }
2692 *ptrue = NUL;
2693
2694 /* To avoid a slow failure append "\*" when searching a directory,
2695 * server or network share. */
2696 wcscpy(szTrueNameTemp, szTrueName);
2697 slen = (int)wcslen(szTrueNameTemp);
2698 if (*porig == psepc && slen + 2 < _MAX_PATH)
2699 wcscpy(szTrueNameTemp + slen, L"\\*");
2700
2701 /* Skip "", "." and "..". */
2702 if (ptrue > ptruePrev
2703 && (ptruePrev[0] != L'.'
2704 || (ptruePrev[1] != NUL
2705 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2706 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2707 != INVALID_HANDLE_VALUE)
2708 {
2709 c = *porig;
2710 *porig = NUL;
2711
2712 /* Only use the match when it's the same name (ignoring case) or
2713 * expansion is allowed and there is a match with the short name
2714 * and there is enough room. */
2715 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2716 || (len > 0
2717 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2718 && (int)(ptruePrev - szTrueName)
2719 + (int)wcslen(fb.cFileName) < len)))
2720 {
2721 wcscpy(ptruePrev, fb.cFileName);
2722
2723 /* Look for exact match and prefer it if found. Must be a
2724 * long name, otherwise there would be only one match. */
2725 while (FindNextFileW(hFind, &fb))
2726 {
2727 if (*fb.cAlternateFileName != NUL
2728 && (wcscoll(porigPrev, fb.cFileName) == 0
2729 || (len > 0
2730 && (_wcsicoll(porigPrev,
2731 fb.cAlternateFileName) == 0
2732 && (int)(ptruePrev - szTrueName)
2733 + (int)wcslen(fb.cFileName) < len))))
2734 {
2735 wcscpy(ptruePrev, fb.cFileName);
2736 break;
2737 }
2738 }
2739 }
2740 FindClose(hFind);
2741 *porig = c;
2742 ptrue = ptruePrev + wcslen(ptruePrev);
2743 }
2744 else if (hFind == INVALID_HANDLE_VALUE
2745 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2746 return FAIL;
2747 }
2748
2749 wcscpy(name, szTrueName);
2750 return OK;
2751}
2752#endif
2753
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754/*
2755 * fname_case(): Set the case of the file name, if it already exists.
2756 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002757 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002758 */
2759 void
2760fname_case(
2761 char_u *name,
2762 int len)
2763{
2764 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002765 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766 char *ptrue, *ptruePrev;
2767 char *porig, *porigPrev;
2768 int flen;
2769 WIN32_FIND_DATA fb;
2770 HANDLE hFind;
2771 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002772 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002773
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002774 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002775 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776 return;
2777
2778 slash_adjust(name);
2779
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002780#ifdef FEAT_MBYTE
2781 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2782 {
2783 WCHAR *p = enc_to_utf16(name, NULL);
2784
2785 if (p != NULL)
2786 {
2787 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002788 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002789
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002790 wcsncpy(buf, p, _MAX_PATH);
2791 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002792 vim_free(p);
2793
2794 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2795 {
2796 q = utf16_to_enc(buf, NULL);
2797 if (q != NULL)
2798 {
2799 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2800 vim_free(q);
2801 return;
2802 }
2803 }
2804 }
2805 /* Retry with non-wide function (for Windows 98). */
2806 }
2807#endif
2808
2809 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2810 * So we should check this after calling wide function. */
2811 if (flen > _MAX_PATH)
2812 return;
2813
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814 /* Build the new name in szTrueName[] one component at a time. */
2815 porig = name;
2816 ptrue = szTrueName;
2817
2818 if (isalpha(porig[0]) && porig[1] == ':')
2819 {
2820 /* copy leading drive letter */
2821 *ptrue++ = *porig++;
2822 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002823 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002824 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825
2826 while (*porig != NUL)
2827 {
2828 /* copy \ characters */
2829 while (*porig == psepc)
2830 *ptrue++ = *porig++;
2831
2832 ptruePrev = ptrue;
2833 porigPrev = porig;
2834 while (*porig != NUL && *porig != psepc)
2835 {
2836#ifdef FEAT_MBYTE
2837 int l;
2838
2839 if (enc_dbcs)
2840 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002841 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842 while (--l >= 0)
2843 *ptrue++ = *porig++;
2844 }
2845 else
2846#endif
2847 *ptrue++ = *porig++;
2848 }
2849 *ptrue = NUL;
2850
Bram Moolenaar464c9252010-10-13 20:37:41 +02002851 /* To avoid a slow failure append "\*" when searching a directory,
2852 * server or network share. */
2853 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002854 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002855 if (*porig == psepc && slen + 2 < _MAX_PATH)
2856 STRCPY(szTrueNameTemp + slen, "\\*");
2857
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858 /* Skip "", "." and "..". */
2859 if (ptrue > ptruePrev
2860 && (ptruePrev[0] != '.'
2861 || (ptruePrev[1] != NUL
2862 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002863 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864 != INVALID_HANDLE_VALUE)
2865 {
2866 c = *porig;
2867 *porig = NUL;
2868
2869 /* Only use the match when it's the same name (ignoring case) or
2870 * expansion is allowed and there is a match with the short name
2871 * and there is enough room. */
2872 if (_stricoll(porigPrev, fb.cFileName) == 0
2873 || (len > 0
2874 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2875 && (int)(ptruePrev - szTrueName)
2876 + (int)strlen(fb.cFileName) < len)))
2877 {
2878 STRCPY(ptruePrev, fb.cFileName);
2879
2880 /* Look for exact match and prefer it if found. Must be a
2881 * long name, otherwise there would be only one match. */
2882 while (FindNextFile(hFind, &fb))
2883 {
2884 if (*fb.cAlternateFileName != NUL
2885 && (strcoll(porigPrev, fb.cFileName) == 0
2886 || (len > 0
2887 && (_stricoll(porigPrev,
2888 fb.cAlternateFileName) == 0
2889 && (int)(ptruePrev - szTrueName)
2890 + (int)strlen(fb.cFileName) < len))))
2891 {
2892 STRCPY(ptruePrev, fb.cFileName);
2893 break;
2894 }
2895 }
2896 }
2897 FindClose(hFind);
2898 *porig = c;
2899 ptrue = ptruePrev + strlen(ptruePrev);
2900 }
2901 }
2902
2903 STRCPY(name, szTrueName);
2904}
2905
2906
2907/*
2908 * Insert user name in s[len].
2909 */
2910 int
2911mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002912 char_u *s,
2913 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002915 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 DWORD cch = sizeof szUserName;
2917
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002918#ifdef FEAT_MBYTE
2919 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2920 {
2921 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2922 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2923
2924 if (GetUserNameW(wszUserName, &wcch))
2925 {
2926 char_u *p = utf16_to_enc(wszUserName, NULL);
2927
2928 if (p != NULL)
2929 {
2930 vim_strncpy(s, p, len - 1);
2931 vim_free(p);
2932 return OK;
2933 }
2934 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002935 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2936 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002937 /* Retry with non-wide function (for Windows 98). */
2938 }
2939#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940 if (GetUserName(szUserName, &cch))
2941 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002942 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 return OK;
2944 }
2945 s[0] = NUL;
2946 return FAIL;
2947}
2948
2949
2950/*
2951 * Insert host name in s[len].
2952 */
2953 void
2954mch_get_host_name(
2955 char_u *s,
2956 int len)
2957{
2958 DWORD cch = len;
2959
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002960#ifdef FEAT_MBYTE
2961 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2962 {
2963 WCHAR wszHostName[256 + 1];
2964 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2965
2966 if (GetComputerNameW(wszHostName, &wcch))
2967 {
2968 char_u *p = utf16_to_enc(wszHostName, NULL);
2969
2970 if (p != NULL)
2971 {
2972 vim_strncpy(s, p, len - 1);
2973 vim_free(p);
2974 return;
2975 }
2976 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002977 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2978 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002979 /* Retry with non-wide function (for Windows 98). */
2980 }
2981#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002983 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984}
2985
2986
2987/*
2988 * return process ID
2989 */
2990 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002991mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992{
2993 return (long)GetCurrentProcessId();
2994}
2995
2996
2997/*
2998 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2999 * Return OK for success, FAIL for failure.
3000 */
3001 int
3002mch_dirname(
3003 char_u *buf,
3004 int len)
3005{
3006 /*
3007 * Originally this was:
3008 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3009 * But the Win32s known bug list says that getcwd() doesn't work
3010 * so use the Win32 system call instead. <Negri>
3011 */
3012#ifdef FEAT_MBYTE
3013 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3014 {
3015 WCHAR wbuf[_MAX_PATH + 1];
3016
3017 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3018 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003019 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020
3021 if (p != NULL)
3022 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003023 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024 vim_free(p);
3025 return OK;
3026 }
3027 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003028 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3029 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 /* Retry with non-wide function (for Windows 98). */
3031 }
3032#endif
3033 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3034}
3035
3036/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003037 * Get file permissions for "name".
3038 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003039 */
3040 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003041mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003043 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003044 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003046 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003047 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048}
3049
3050
3051/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003052 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003053 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003054 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 */
3056 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003057mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003059 long n = -1;
3060
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061#ifdef FEAT_MBYTE
3062 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3063 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003064 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065
3066 if (p != NULL)
3067 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003068 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003070 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003071 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 /* Retry with non-wide function (for Windows 98). */
3073 }
3074 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003075 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003077 n = _chmod(name, perm);
3078 if (n == -1)
3079 return FAIL;
3080
3081 win32_set_archive(name);
3082
3083 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084}
3085
3086/*
3087 * Set hidden flag for "name".
3088 */
3089 void
3090mch_hide(char_u *name)
3091{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003092 int attrs = win32_getattrs(name);
3093 if (attrs == -1)
3094 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003096 attrs |= FILE_ATTRIBUTE_HIDDEN;
3097 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098}
3099
3100/*
3101 * return TRUE if "name" is a directory
3102 * return FALSE if "name" is not a directory or upon error
3103 */
3104 int
3105mch_isdir(char_u *name)
3106{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003107 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108
3109 if (f == -1)
3110 return FALSE; /* file does not exist at all */
3111
3112 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3113}
3114
3115/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003116 * Create directory "name".
3117 * Return 0 on success, -1 on error.
3118 */
3119 int
3120mch_mkdir(char_u *name)
3121{
3122#ifdef FEAT_MBYTE
3123 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3124 {
3125 WCHAR *p;
3126 int retval;
3127
3128 p = enc_to_utf16(name, NULL);
3129 if (p == NULL)
3130 return -1;
3131 retval = _wmkdir(p);
3132 vim_free(p);
3133 return retval;
3134 }
3135#endif
3136 return _mkdir(name);
3137}
3138
3139/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003140 * Return TRUE if file "fname" has more than one link.
3141 */
3142 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003143mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003144{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003145 BY_HANDLE_FILE_INFORMATION info;
3146
3147 return win32_fileinfo(fname, &info) == FILEINFO_OK
3148 && info.nNumberOfLinks > 1;
3149}
3150
3151/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003152 * Return TRUE if file "fname" is a symbolic link.
3153 */
3154 int
3155mch_is_symbolic_link(char_u *fname)
3156{
3157 HANDLE hFind;
3158 int res = FALSE;
3159 WIN32_FIND_DATAA findDataA;
3160 DWORD fileFlags = 0, reparseTag = 0;
3161#ifdef FEAT_MBYTE
3162 WCHAR *wn = NULL;
3163 WIN32_FIND_DATAW findDataW;
3164
3165 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3166 wn = enc_to_utf16(fname, NULL);
3167 if (wn != NULL)
3168 {
3169 hFind = FindFirstFileW(wn, &findDataW);
3170 vim_free(wn);
3171 if (hFind == INVALID_HANDLE_VALUE
3172 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3173 {
3174 /* Retry with non-wide function (for Windows 98). */
3175 hFind = FindFirstFile(fname, &findDataA);
3176 if (hFind != INVALID_HANDLE_VALUE)
3177 {
3178 fileFlags = findDataA.dwFileAttributes;
3179 reparseTag = findDataA.dwReserved0;
3180 }
3181 }
3182 else
3183 {
3184 fileFlags = findDataW.dwFileAttributes;
3185 reparseTag = findDataW.dwReserved0;
3186 }
3187 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003188 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003189#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003190 {
3191 hFind = FindFirstFile(fname, &findDataA);
3192 if (hFind != INVALID_HANDLE_VALUE)
3193 {
3194 fileFlags = findDataA.dwFileAttributes;
3195 reparseTag = findDataA.dwReserved0;
3196 }
3197 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003198
3199 if (hFind != INVALID_HANDLE_VALUE)
3200 FindClose(hFind);
3201
3202 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3203 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3204 res = TRUE;
3205
3206 return res;
3207}
3208
3209/*
3210 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3211 * link.
3212 */
3213 int
3214mch_is_linked(char_u *fname)
3215{
3216 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3217 return TRUE;
3218 return FALSE;
3219}
3220
3221/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003222 * Get the by-handle-file-information for "fname".
3223 * Returns FILEINFO_OK when OK.
3224 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3225 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3226 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3227 */
3228 int
3229win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3230{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003231 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003232 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003233#ifdef FEAT_MBYTE
3234 WCHAR *wn = NULL;
3235
3236 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003237 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003238 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003239 if (wn == NULL)
3240 res = FILEINFO_ENC_FAIL;
3241 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003242 if (wn != NULL)
3243 {
3244 hFile = CreateFileW(wn, /* file name */
3245 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003246 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003247 NULL, /* security descriptor */
3248 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003249 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003250 NULL); /* handle to template file */
3251 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003252 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003253 {
3254 /* Retry with non-wide function (for Windows 98). */
3255 vim_free(wn);
3256 wn = NULL;
3257 }
3258 }
3259 if (wn == NULL)
3260#endif
3261 hFile = CreateFile(fname, /* file name */
3262 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003263 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003264 NULL, /* security descriptor */
3265 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003266 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003267 NULL); /* handle to template file */
3268
3269 if (hFile != INVALID_HANDLE_VALUE)
3270 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003271 if (GetFileInformationByHandle(hFile, info) != 0)
3272 res = FILEINFO_OK;
3273 else
3274 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003275 CloseHandle(hFile);
3276 }
3277
3278#ifdef FEAT_MBYTE
3279 vim_free(wn);
3280#endif
3281 return res;
3282}
3283
3284/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003285 * get file attributes for `name'
3286 * -1 : error
3287 * else FILE_ATTRIBUTE_* defined in winnt.h
3288 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003289 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003290win32_getattrs(char_u *name)
3291{
3292 int attr;
3293#ifdef FEAT_MBYTE
3294 WCHAR *p = NULL;
3295
3296 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3297 p = enc_to_utf16(name, NULL);
3298
3299 if (p != NULL)
3300 {
3301 attr = GetFileAttributesW(p);
3302 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3303 {
3304 /* Retry with non-wide function (for Windows 98). */
3305 vim_free(p);
3306 p = NULL;
3307 }
3308 }
3309 if (p == NULL)
3310#endif
3311 attr = GetFileAttributes((char *)name);
3312#ifdef FEAT_MBYTE
3313 vim_free(p);
3314#endif
3315 return attr;
3316}
3317
3318/*
3319 * set file attributes for `name' to `attrs'
3320 *
3321 * return -1 for failure, 0 otherwise
3322 */
3323 static
3324 int
3325win32_setattrs(char_u *name, int attrs)
3326{
3327 int res;
3328#ifdef FEAT_MBYTE
3329 WCHAR *p = NULL;
3330
3331 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3332 p = enc_to_utf16(name, NULL);
3333
3334 if (p != NULL)
3335 {
3336 res = SetFileAttributesW(p, attrs);
3337 if (res == FALSE
3338 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3339 {
3340 /* Retry with non-wide function (for Windows 98). */
3341 vim_free(p);
3342 p = NULL;
3343 }
3344 }
3345 if (p == NULL)
3346#endif
3347 res = SetFileAttributes((char *)name, attrs);
3348#ifdef FEAT_MBYTE
3349 vim_free(p);
3350#endif
3351 return res ? 0 : -1;
3352}
3353
3354/*
3355 * Set archive flag for "name".
3356 */
3357 static
3358 int
3359win32_set_archive(char_u *name)
3360{
3361 int attrs = win32_getattrs(name);
3362 if (attrs == -1)
3363 return -1;
3364
3365 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3366 return win32_setattrs(name, attrs);
3367}
3368
3369/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003370 * Return TRUE if file or directory "name" is writable (not readonly).
3371 * Strange semantics of Win32: a readonly directory is writable, but you can't
3372 * delete a file. Let's say this means it is writable.
3373 */
3374 int
3375mch_writable(char_u *name)
3376{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003377 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003378
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003379 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3380 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003381}
3382
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383/*
3384 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003385 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386 * Return -1 if unknown.
3387 */
3388 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003389mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003390{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003391 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003392 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003393 char_u *p;
3394
3395 if (len >= _MAX_PATH) /* safety check */
3396 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003397 if (!use_path)
3398 {
3399 /* TODO: check if file is really executable. */
3400 return mch_getperm(name) != -1 && !mch_isdir(name);
3401 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003402
3403 /* If there already is an extension try using the name directly. Also do
3404 * this with a Unix-shell like 'shell'. */
3405 if (vim_strchr(gettail(name), '.') != NULL
3406 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003407 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003408 return TRUE;
3409
3410 /*
3411 * Loop over all extensions in $PATHEXT.
3412 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003413 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003414 p = mch_getenv("PATHEXT");
3415 if (p == NULL)
3416 p = (char_u *)".com;.exe;.bat;.cmd";
3417 while (*p)
3418 {
3419 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3420 {
3421 /* A single "." means no extension is added. */
3422 buf[len] = NUL;
3423 ++p;
3424 if (*p)
3425 ++p;
3426 }
3427 else
3428 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003429 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003430 return TRUE;
3431 }
3432 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434
3435/*
3436 * Check what "name" is:
3437 * NODE_NORMAL: file or directory (or doesn't exist)
3438 * NODE_WRITABLE: writable device, socket, fifo, etc.
3439 * NODE_OTHER: non-writable things
3440 */
3441 int
3442mch_nodetype(char_u *name)
3443{
3444 HANDLE hFile;
3445 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003446#ifdef FEAT_MBYTE
3447 WCHAR *wn = NULL;
3448#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449
Bram Moolenaar043545e2006-10-10 16:44:07 +00003450 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3451 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3452 * here. */
3453 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3454 return NODE_WRITABLE;
3455
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003456#ifdef FEAT_MBYTE
3457 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3458 {
3459 wn = enc_to_utf16(name, NULL);
3460 if (wn != NULL)
3461 {
3462 hFile = CreateFileW(wn, /* file name */
3463 GENERIC_WRITE, /* access mode */
3464 0, /* share mode */
3465 NULL, /* security descriptor */
3466 OPEN_EXISTING, /* creation disposition */
3467 0, /* file attributes */
3468 NULL); /* handle to template file */
3469 if (hFile == INVALID_HANDLE_VALUE
3470 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3471 {
3472 /* Retry with non-wide function (for Windows 98). */
3473 vim_free(wn);
3474 wn = NULL;
3475 }
3476 }
3477 }
3478 if (wn == NULL)
3479#endif
3480 hFile = CreateFile(name, /* file name */
3481 GENERIC_WRITE, /* access mode */
3482 0, /* share mode */
3483 NULL, /* security descriptor */
3484 OPEN_EXISTING, /* creation disposition */
3485 0, /* file attributes */
3486 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003488#ifdef FEAT_MBYTE
3489 vim_free(wn);
3490#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491 if (hFile == INVALID_HANDLE_VALUE)
3492 return NODE_NORMAL;
3493
3494 type = GetFileType(hFile);
3495 CloseHandle(hFile);
3496 if (type == FILE_TYPE_CHAR)
3497 return NODE_WRITABLE;
3498 if (type == FILE_TYPE_DISK)
3499 return NODE_NORMAL;
3500 return NODE_OTHER;
3501}
3502
3503#ifdef HAVE_ACL
3504struct my_acl
3505{
3506 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3507 PSID pSidOwner;
3508 PSID pSidGroup;
3509 PACL pDacl;
3510 PACL pSacl;
3511};
3512#endif
3513
3514/*
3515 * Return a pointer to the ACL of file "fname" in allocated memory.
3516 * Return NULL if the ACL is not available for whatever reason.
3517 */
3518 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003519mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003520{
3521#ifndef HAVE_ACL
3522 return (vim_acl_T)NULL;
3523#else
3524 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003525 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003526
3527 /* This only works on Windows NT and 2000. */
3528 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3529 {
3530 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3531 if (p != NULL)
3532 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003533# ifdef FEAT_MBYTE
3534 WCHAR *wn = NULL;
3535
3536 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3537 wn = enc_to_utf16(fname, NULL);
3538 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003539 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003540 /* Try to retrieve the entire security descriptor. */
3541 err = pGetNamedSecurityInfoW(
3542 wn, // Abstract filename
3543 SE_FILE_OBJECT, // File Object
3544 OWNER_SECURITY_INFORMATION |
3545 GROUP_SECURITY_INFORMATION |
3546 DACL_SECURITY_INFORMATION |
3547 SACL_SECURITY_INFORMATION,
3548 &p->pSidOwner, // Ownership information.
3549 &p->pSidGroup, // Group membership.
3550 &p->pDacl, // Discretionary information.
3551 &p->pSacl, // For auditing purposes.
3552 &p->pSecurityDescriptor);
3553 if (err == ERROR_ACCESS_DENIED ||
3554 err == ERROR_PRIVILEGE_NOT_HELD)
3555 {
3556 /* Retrieve only DACL. */
3557 (void)pGetNamedSecurityInfoW(
3558 wn,
3559 SE_FILE_OBJECT,
3560 DACL_SECURITY_INFORMATION,
3561 NULL,
3562 NULL,
3563 &p->pDacl,
3564 NULL,
3565 &p->pSecurityDescriptor);
3566 }
3567 if (p->pSecurityDescriptor == NULL)
3568 {
3569 mch_free_acl((vim_acl_T)p);
3570 p = NULL;
3571 }
3572 vim_free(wn);
3573 }
3574 else
3575# endif
3576 {
3577 /* Try to retrieve the entire security descriptor. */
3578 err = pGetNamedSecurityInfo(
3579 (LPSTR)fname, // Abstract filename
3580 SE_FILE_OBJECT, // File Object
3581 OWNER_SECURITY_INFORMATION |
3582 GROUP_SECURITY_INFORMATION |
3583 DACL_SECURITY_INFORMATION |
3584 SACL_SECURITY_INFORMATION,
3585 &p->pSidOwner, // Ownership information.
3586 &p->pSidGroup, // Group membership.
3587 &p->pDacl, // Discretionary information.
3588 &p->pSacl, // For auditing purposes.
3589 &p->pSecurityDescriptor);
3590 if (err == ERROR_ACCESS_DENIED ||
3591 err == ERROR_PRIVILEGE_NOT_HELD)
3592 {
3593 /* Retrieve only DACL. */
3594 (void)pGetNamedSecurityInfo(
3595 (LPSTR)fname,
3596 SE_FILE_OBJECT,
3597 DACL_SECURITY_INFORMATION,
3598 NULL,
3599 NULL,
3600 &p->pDacl,
3601 NULL,
3602 &p->pSecurityDescriptor);
3603 }
3604 if (p->pSecurityDescriptor == NULL)
3605 {
3606 mch_free_acl((vim_acl_T)p);
3607 p = NULL;
3608 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609 }
3610 }
3611 }
3612
3613 return (vim_acl_T)p;
3614#endif
3615}
3616
Bram Moolenaar27515922013-06-29 15:36:26 +02003617#ifdef HAVE_ACL
3618/*
3619 * Check if "acl" contains inherited ACE.
3620 */
3621 static BOOL
3622is_acl_inherited(PACL acl)
3623{
3624 DWORD i;
3625 ACL_SIZE_INFORMATION acl_info;
3626 PACCESS_ALLOWED_ACE ace;
3627
3628 acl_info.AceCount = 0;
3629 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3630 for (i = 0; i < acl_info.AceCount; i++)
3631 {
3632 GetAce(acl, i, (LPVOID *)&ace);
3633 if (ace->Header.AceFlags & INHERITED_ACE)
3634 return TRUE;
3635 }
3636 return FALSE;
3637}
3638#endif
3639
Bram Moolenaar071d4272004-06-13 20:20:40 +00003640/*
3641 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3642 * Errors are ignored.
3643 * This must only be called with "acl" equal to what mch_get_acl() returned.
3644 */
3645 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003646mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647{
3648#ifdef HAVE_ACL
3649 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003650 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003651
3652 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003653 {
3654# ifdef FEAT_MBYTE
3655 WCHAR *wn = NULL;
3656# endif
3657
3658 /* Set security flags */
3659 if (p->pSidOwner)
3660 sec_info |= OWNER_SECURITY_INFORMATION;
3661 if (p->pSidGroup)
3662 sec_info |= GROUP_SECURITY_INFORMATION;
3663 if (p->pDacl)
3664 {
3665 sec_info |= DACL_SECURITY_INFORMATION;
3666 /* Do not inherit its parent's DACL.
3667 * If the DACL is inherited, Cygwin permissions would be changed.
3668 */
3669 if (!is_acl_inherited(p->pDacl))
3670 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3671 }
3672 if (p->pSacl)
3673 sec_info |= SACL_SECURITY_INFORMATION;
3674
3675# ifdef FEAT_MBYTE
3676 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3677 wn = enc_to_utf16(fname, NULL);
3678 if (wn != NULL)
3679 {
3680 (void)pSetNamedSecurityInfoW(
3681 wn, // Abstract filename
3682 SE_FILE_OBJECT, // File Object
3683 sec_info,
3684 p->pSidOwner, // Ownership information.
3685 p->pSidGroup, // Group membership.
3686 p->pDacl, // Discretionary information.
3687 p->pSacl // For auditing purposes.
3688 );
3689 vim_free(wn);
3690 }
3691 else
3692# endif
3693 {
3694 (void)pSetNamedSecurityInfo(
3695 (LPSTR)fname, // Abstract filename
3696 SE_FILE_OBJECT, // File Object
3697 sec_info,
3698 p->pSidOwner, // Ownership information.
3699 p->pSidGroup, // Group membership.
3700 p->pDacl, // Discretionary information.
3701 p->pSacl // For auditing purposes.
3702 );
3703 }
3704 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705#endif
3706}
3707
3708 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003709mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003710{
3711#ifdef HAVE_ACL
3712 struct my_acl *p = (struct my_acl *)acl;
3713
3714 if (p != NULL)
3715 {
3716 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3717 vim_free(p);
3718 }
3719#endif
3720}
3721
3722#ifndef FEAT_GUI_W32
3723
3724/*
3725 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3726 */
3727 static BOOL WINAPI
3728handler_routine(
3729 DWORD dwCtrlType)
3730{
3731 switch (dwCtrlType)
3732 {
3733 case CTRL_C_EVENT:
3734 if (ctrl_c_interrupts)
3735 g_fCtrlCPressed = TRUE;
3736 return TRUE;
3737
3738 case CTRL_BREAK_EVENT:
3739 g_fCBrkPressed = TRUE;
3740 return TRUE;
3741
3742 /* fatal events: shut down gracefully */
3743 case CTRL_CLOSE_EVENT:
3744 case CTRL_LOGOFF_EVENT:
3745 case CTRL_SHUTDOWN_EVENT:
3746 windgoto((int)Rows - 1, 0);
3747 g_fForceExit = TRUE;
3748
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003749 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750 (dwCtrlType == CTRL_CLOSE_EVENT
3751 ? _("close")
3752 : dwCtrlType == CTRL_LOGOFF_EVENT
3753 ? _("logoff")
3754 : _("shutdown")));
3755#ifdef DEBUG
3756 OutputDebugString(IObuff);
3757#endif
3758
3759 preserve_exit(); /* output IObuff, preserve files and exit */
3760
3761 return TRUE; /* not reached */
3762
3763 default:
3764 return FALSE;
3765 }
3766}
3767
3768
3769/*
3770 * set the tty in (raw) ? "raw" : "cooked" mode
3771 */
3772 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003773mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774{
3775 DWORD cmodein;
3776 DWORD cmodeout;
3777 BOOL bEnableHandler;
3778
3779 GetConsoleMode(g_hConIn, &cmodein);
3780 GetConsoleMode(g_hConOut, &cmodeout);
3781 if (tmode == TMODE_RAW)
3782 {
3783 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3784 ENABLE_ECHO_INPUT);
3785#ifdef FEAT_MOUSE
3786 if (g_fMouseActive)
3787 cmodein |= ENABLE_MOUSE_INPUT;
3788#endif
3789 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3790 bEnableHandler = TRUE;
3791 }
3792 else /* cooked */
3793 {
3794 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3795 ENABLE_ECHO_INPUT);
3796 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3797 bEnableHandler = FALSE;
3798 }
3799 SetConsoleMode(g_hConIn, cmodein);
3800 SetConsoleMode(g_hConOut, cmodeout);
3801 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3802
3803#ifdef MCH_WRITE_DUMP
3804 if (fdDump)
3805 {
3806 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3807 tmode == TMODE_RAW ? "raw" :
3808 tmode == TMODE_COOK ? "cooked" : "normal",
3809 cmodein, cmodeout);
3810 fflush(fdDump);
3811 }
3812#endif
3813}
3814
3815
3816/*
3817 * Get the size of the current window in `Rows' and `Columns'
3818 * Return OK when size could be determined, FAIL otherwise.
3819 */
3820 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003821mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822{
3823 CONSOLE_SCREEN_BUFFER_INFO csbi;
3824
3825 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3826 {
3827 /*
3828 * For some reason, we are trying to get the screen dimensions
3829 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3830 * variables are really intended to mean the size of Vim screen
3831 * while in termcap mode.
3832 */
3833 Rows = g_cbTermcap.Info.dwSize.Y;
3834 Columns = g_cbTermcap.Info.dwSize.X;
3835 }
3836 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3837 {
3838 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3839 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3840 }
3841 else
3842 {
3843 Rows = 25;
3844 Columns = 80;
3845 }
3846 return OK;
3847}
3848
3849/*
3850 * Set a console window to `xSize' * `ySize'
3851 */
3852 static void
3853ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003854 HANDLE hConsole,
3855 int xSize,
3856 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857{
3858 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3859 SMALL_RECT srWindowRect; /* hold the new console size */
3860 COORD coordScreen;
3861
3862#ifdef MCH_WRITE_DUMP
3863 if (fdDump)
3864 {
3865 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3866 fflush(fdDump);
3867 }
3868#endif
3869
3870 /* get the largest size we can size the console window to */
3871 coordScreen = GetLargestConsoleWindowSize(hConsole);
3872
3873 /* define the new console window size and scroll position */
3874 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3875 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3876 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3877
3878 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3879 {
3880 int sx, sy;
3881
3882 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3883 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3884 if (sy < ySize || sx < xSize)
3885 {
3886 /*
3887 * Increasing number of lines/columns, do buffer first.
3888 * Use the maximal size in x and y direction.
3889 */
3890 if (sy < ySize)
3891 coordScreen.Y = ySize;
3892 else
3893 coordScreen.Y = sy;
3894 if (sx < xSize)
3895 coordScreen.X = xSize;
3896 else
3897 coordScreen.X = sx;
3898 SetConsoleScreenBufferSize(hConsole, coordScreen);
3899 }
3900 }
3901
3902 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3903 {
3904#ifdef MCH_WRITE_DUMP
3905 if (fdDump)
3906 {
3907 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3908 GetLastError());
3909 fflush(fdDump);
3910 }
3911#endif
3912 }
3913
3914 /* define the new console buffer size */
3915 coordScreen.X = xSize;
3916 coordScreen.Y = ySize;
3917
3918 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3919 {
3920#ifdef MCH_WRITE_DUMP
3921 if (fdDump)
3922 {
3923 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3924 GetLastError());
3925 fflush(fdDump);
3926 }
3927#endif
3928 }
3929}
3930
3931
3932/*
3933 * Set the console window to `Rows' * `Columns'
3934 */
3935 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003936mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937{
3938 COORD coordScreen;
3939
3940 /* Don't change window size while still starting up */
3941 if (suppress_winsize != 0)
3942 {
3943 suppress_winsize = 2;
3944 return;
3945 }
3946
3947 if (term_console)
3948 {
3949 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3950
3951 /* Clamp Rows and Columns to reasonable values */
3952 if (Rows > coordScreen.Y)
3953 Rows = coordScreen.Y;
3954 if (Columns > coordScreen.X)
3955 Columns = coordScreen.X;
3956
3957 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3958 }
3959}
3960
3961/*
3962 * Rows and/or Columns has changed.
3963 */
3964 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003965mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966{
3967 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3968}
3969
3970
3971/*
3972 * Called when started up, to set the winsize that was delayed.
3973 */
3974 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003975mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976{
3977 if (suppress_winsize == 2)
3978 {
3979 suppress_winsize = 0;
3980 mch_set_shellsize();
3981 shell_resized();
3982 }
3983 suppress_winsize = 0;
3984}
3985#endif /* FEAT_GUI_W32 */
3986
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003987 static BOOL
3988vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003989 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003990 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003991 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003992 STARTUPINFO *si,
3993 PROCESS_INFORMATION *pi)
3994{
3995# ifdef FEAT_MBYTE
3996 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3997 {
3998 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
3999
4000 if (wcmd != NULL)
4001 {
4002 BOOL ret;
4003 ret = CreateProcessW(
4004 NULL, /* Executable name */
4005 wcmd, /* Command to execute */
4006 NULL, /* Process security attributes */
4007 NULL, /* Thread security attributes */
4008 inherit_handles, /* Inherit handles */
4009 flags, /* Creation flags */
4010 NULL, /* Environment */
4011 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004012 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004013 pi); /* Process information */
4014 vim_free(wcmd);
4015 return ret;
4016 }
4017 }
4018#endif
4019 return CreateProcess(
4020 NULL, /* Executable name */
4021 cmd, /* Command to execute */
4022 NULL, /* Process security attributes */
4023 NULL, /* Thread security attributes */
4024 inherit_handles, /* Inherit handles */
4025 flags, /* Creation flags */
4026 NULL, /* Environment */
4027 NULL, /* Current directory */
4028 si, /* Startup information */
4029 pi); /* Process information */
4030}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031
4032
4033#if defined(FEAT_GUI_W32) || defined(PROTO)
4034
4035/*
4036 * Specialised version of system() for Win32 GUI mode.
4037 * This version proceeds as follows:
4038 * 1. Create a console window for use by the subprocess
4039 * 2. Run the subprocess (it gets the allocated console by default)
4040 * 3. Wait for the subprocess to terminate and get its exit code
4041 * 4. Prompt the user to press a key to close the console window
4042 */
4043 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004044mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004045{
4046 STARTUPINFO si;
4047 PROCESS_INFORMATION pi;
4048 DWORD ret = 0;
4049 HWND hwnd = GetFocus();
4050
4051 si.cb = sizeof(si);
4052 si.lpReserved = NULL;
4053 si.lpDesktop = NULL;
4054 si.lpTitle = NULL;
4055 si.dwFlags = STARTF_USESHOWWINDOW;
4056 /*
4057 * It's nicer to run a filter command in a minimized window, but in
4058 * Windows 95 this makes the command MUCH slower. We can't do it under
4059 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004060 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004061 */
4062 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004063 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004064 else
4065 si.wShowWindow = SW_SHOWNORMAL;
4066 si.cbReserved2 = 0;
4067 si.lpReserved2 = NULL;
4068
4069 /* There is a strange error on Windows 95 when using "c:\\command.com".
4070 * When the "c:\\" is left out it works OK...? */
4071 if (mch_windows95()
4072 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4073 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4074 cmd += 3;
4075
4076 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004077 vim_create_process(cmd, FALSE,
4078 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079
4080 /* Wait for the command to terminate before continuing */
4081 if (g_PlatformId != VER_PLATFORM_WIN32s)
4082 {
4083#ifdef FEAT_GUI
4084 int delay = 1;
4085
4086 /* Keep updating the window while waiting for the shell to finish. */
4087 for (;;)
4088 {
4089 MSG msg;
4090
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004091 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004092 {
4093 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004094 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004095 delay = 1;
4096 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097 }
4098 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4099 break;
4100
4101 /* We start waiting for a very short time and then increase it, so
4102 * that we respond quickly when the process is quick, and don't
4103 * consume too much overhead when it's slow. */
4104 if (delay < 50)
4105 delay += 10;
4106 }
4107#else
4108 WaitForSingleObject(pi.hProcess, INFINITE);
4109#endif
4110
4111 /* Get the command exit code */
4112 GetExitCodeProcess(pi.hProcess, &ret);
4113 }
4114 else
4115 {
4116 /*
4117 * This ugly code is the only quick way of performing
4118 * a synchronous spawn under Win32s. Yuk.
4119 */
4120 num_windows = 0;
4121 EnumWindows(win32ssynch_cb, 0);
4122 old_num_windows = num_windows;
4123 do
4124 {
4125 Sleep(1000);
4126 num_windows = 0;
4127 EnumWindows(win32ssynch_cb, 0);
4128 } while (num_windows == old_num_windows);
4129 ret = 0;
4130 }
4131
4132 /* Close the handles to the subprocess, so that it goes away */
4133 CloseHandle(pi.hThread);
4134 CloseHandle(pi.hProcess);
4135
4136 /* Try to get input focus back. Doesn't always work though. */
4137 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4138
4139 return ret;
4140}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004141
4142/*
4143 * Thread launched by the gui to send the current buffer data to the
4144 * process. This way avoid to hang up vim totally if the children
4145 * process take a long time to process the lines.
4146 */
4147 static DWORD WINAPI
4148sub_process_writer(LPVOID param)
4149{
4150 HANDLE g_hChildStd_IN_Wr = param;
4151 linenr_T lnum = curbuf->b_op_start.lnum;
4152 DWORD len = 0;
4153 DWORD l;
4154 char_u *lp = ml_get(lnum);
4155 char_u *s;
4156 int written = 0;
4157
4158 for (;;)
4159 {
4160 l = (DWORD)STRLEN(lp + written);
4161 if (l == 0)
4162 len = 0;
4163 else if (lp[written] == NL)
4164 {
4165 /* NL -> NUL translation */
4166 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4167 }
4168 else
4169 {
4170 s = vim_strchr(lp + written, NL);
4171 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4172 s == NULL ? l : (DWORD)(s - (lp + written)),
4173 &len, NULL);
4174 }
4175 if (len == (int)l)
4176 {
4177 /* Finished a line, add a NL, unless this line should not have
4178 * one. */
4179 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004180 || (!curbuf->b_p_bin
4181 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004182 || (lnum != curbuf->b_no_eol_lnum
4183 && (lnum != curbuf->b_ml.ml_line_count
4184 || curbuf->b_p_eol)))
4185 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004186 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004187 }
4188
4189 ++lnum;
4190 if (lnum > curbuf->b_op_end.lnum)
4191 break;
4192
4193 lp = ml_get(lnum);
4194 written = 0;
4195 }
4196 else if (len > 0)
4197 written += len;
4198 }
4199
4200 /* finished all the lines, close pipe */
4201 CloseHandle(g_hChildStd_IN_Wr);
4202 ExitThread(0);
4203}
4204
4205
4206# define BUFLEN 100 /* length for buffer, stolen from unix version */
4207
4208/*
4209 * This function read from the children's stdout and write the
4210 * data on screen or in the buffer accordingly.
4211 */
4212 static void
4213dump_pipe(int options,
4214 HANDLE g_hChildStd_OUT_Rd,
4215 garray_T *ga,
4216 char_u buffer[],
4217 DWORD *buffer_off)
4218{
4219 DWORD availableBytes = 0;
4220 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004221 int ret;
4222 DWORD len;
4223 DWORD toRead;
4224 int repeatCount;
4225
4226 /* we query the pipe to see if there is any data to read
4227 * to avoid to perform a blocking read */
4228 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4229 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004230 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004231 NULL, /* number of read bytes */
4232 &availableBytes, /* available bytes total */
4233 NULL); /* byteLeft */
4234
4235 repeatCount = 0;
4236 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004237 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004238 {
4239 repeatCount++;
4240 toRead =
4241# ifdef FEAT_MBYTE
4242 (DWORD)(BUFLEN - *buffer_off);
4243# else
4244 (DWORD)BUFLEN;
4245# endif
4246 toRead = availableBytes < toRead ? availableBytes : toRead;
4247 ReadFile(g_hChildStd_OUT_Rd, buffer
4248# ifdef FEAT_MBYTE
4249 + *buffer_off, toRead
4250# else
4251 , toRead
4252# endif
4253 , &len, NULL);
4254
4255 /* If we haven't read anything, there is a problem */
4256 if (len == 0)
4257 break;
4258
4259 availableBytes -= len;
4260
4261 if (options & SHELL_READ)
4262 {
4263 /* Do NUL -> NL translation, append NL separated
4264 * lines to the current buffer. */
4265 for (i = 0; i < len; ++i)
4266 {
4267 if (buffer[i] == NL)
4268 append_ga_line(ga);
4269 else if (buffer[i] == NUL)
4270 ga_append(ga, NL);
4271 else
4272 ga_append(ga, buffer[i]);
4273 }
4274 }
4275# ifdef FEAT_MBYTE
4276 else if (has_mbyte)
4277 {
4278 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004279 int c;
4280 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004281
4282 len += *buffer_off;
4283 buffer[len] = NUL;
4284
4285 /* Check if the last character in buffer[] is
4286 * incomplete, keep these bytes for the next
4287 * round. */
4288 for (p = buffer; p < buffer + len; p += l)
4289 {
4290 l = mb_cptr2len(p);
4291 if (l == 0)
4292 l = 1; /* NUL byte? */
4293 else if (MB_BYTE2LEN(*p) != l)
4294 break;
4295 }
4296 if (p == buffer) /* no complete character */
4297 {
4298 /* avoid getting stuck at an illegal byte */
4299 if (len >= 12)
4300 ++p;
4301 else
4302 {
4303 *buffer_off = len;
4304 return;
4305 }
4306 }
4307 c = *p;
4308 *p = NUL;
4309 msg_puts(buffer);
4310 if (p < buffer + len)
4311 {
4312 *p = c;
4313 *buffer_off = (DWORD)((buffer + len) - p);
4314 mch_memmove(buffer, p, *buffer_off);
4315 return;
4316 }
4317 *buffer_off = 0;
4318 }
4319# endif /* FEAT_MBYTE */
4320 else
4321 {
4322 buffer[len] = NUL;
4323 msg_puts(buffer);
4324 }
4325
4326 windgoto(msg_row, msg_col);
4327 cursor_on();
4328 out_flush();
4329 }
4330}
4331
4332/*
4333 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4334 * for communication and doesn't open any new window.
4335 */
4336 static int
4337mch_system_piped(char *cmd, int options)
4338{
4339 STARTUPINFO si;
4340 PROCESS_INFORMATION pi;
4341 DWORD ret = 0;
4342
4343 HANDLE g_hChildStd_IN_Rd = NULL;
4344 HANDLE g_hChildStd_IN_Wr = NULL;
4345 HANDLE g_hChildStd_OUT_Rd = NULL;
4346 HANDLE g_hChildStd_OUT_Wr = NULL;
4347
4348 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4349 DWORD len;
4350
4351 /* buffer used to receive keys */
4352 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4353 int ta_len = 0; /* valid bytes in ta_buf[] */
4354
4355 DWORD i;
4356 int c;
4357 int noread_cnt = 0;
4358 garray_T ga;
4359 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004360 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004361 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004362
4363 SECURITY_ATTRIBUTES saAttr;
4364
4365 /* Set the bInheritHandle flag so pipe handles are inherited. */
4366 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4367 saAttr.bInheritHandle = TRUE;
4368 saAttr.lpSecurityDescriptor = NULL;
4369
4370 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4371 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4372 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4373 /* Create a pipe for the child process's STDIN. */
4374 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4375 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4376 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4377 {
4378 CloseHandle(g_hChildStd_IN_Rd);
4379 CloseHandle(g_hChildStd_IN_Wr);
4380 CloseHandle(g_hChildStd_OUT_Rd);
4381 CloseHandle(g_hChildStd_OUT_Wr);
4382 MSG_PUTS(_("\nCannot create pipes\n"));
4383 }
4384
4385 si.cb = sizeof(si);
4386 si.lpReserved = NULL;
4387 si.lpDesktop = NULL;
4388 si.lpTitle = NULL;
4389 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4390
4391 /* set-up our file redirection */
4392 si.hStdError = g_hChildStd_OUT_Wr;
4393 si.hStdOutput = g_hChildStd_OUT_Wr;
4394 si.hStdInput = g_hChildStd_IN_Rd;
4395 si.wShowWindow = SW_HIDE;
4396 si.cbReserved2 = 0;
4397 si.lpReserved2 = NULL;
4398
4399 if (options & SHELL_READ)
4400 ga_init2(&ga, 1, BUFLEN);
4401
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004402 if (cmd != NULL)
4403 {
4404 p = (char *)vim_strsave((char_u *)cmd);
4405 if (p != NULL)
4406 unescape_shellxquote((char_u *)p, p_sxe);
4407 else
4408 p = cmd;
4409 }
4410
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004411 /* Now, run the command.
4412 * About "Inherit handles" being TRUE: this command can be litigious,
4413 * handle inheritance was deactivated for pending temp file, but, if we
4414 * deactivate it, the pipes don't work for some reason. */
4415 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004417 if (p != cmd)
4418 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004419
4420 /* Close our unused side of the pipes */
4421 CloseHandle(g_hChildStd_IN_Rd);
4422 CloseHandle(g_hChildStd_OUT_Wr);
4423
4424 if (options & SHELL_WRITE)
4425 {
4426 HANDLE thread =
4427 CreateThread(NULL, /* security attributes */
4428 0, /* default stack size */
4429 sub_process_writer, /* function to be executed */
4430 g_hChildStd_IN_Wr, /* parameter */
4431 0, /* creation flag, start immediately */
4432 NULL); /* we don't care about thread id */
4433 CloseHandle(thread);
4434 g_hChildStd_IN_Wr = NULL;
4435 }
4436
4437 /* Keep updating the window while waiting for the shell to finish. */
4438 for (;;)
4439 {
4440 MSG msg;
4441
Bram Moolenaar175d0702013-12-11 18:36:33 +01004442 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004443 {
4444 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004445 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004446 }
4447
4448 /* write pipe information in the window */
4449 if ((options & (SHELL_READ|SHELL_WRITE))
4450# ifdef FEAT_GUI
4451 || gui.in_use
4452# endif
4453 )
4454 {
4455 len = 0;
4456 if (!(options & SHELL_EXPAND)
4457 && ((options &
4458 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4459 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4460# ifdef FEAT_GUI
4461 || gui.in_use
4462# endif
4463 )
4464 && (ta_len > 0 || noread_cnt > 4))
4465 {
4466 if (ta_len == 0)
4467 {
4468 /* Get extra characters when we don't have any. Reset the
4469 * counter and timer. */
4470 noread_cnt = 0;
4471# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4472 gettimeofday(&start_tv, NULL);
4473# endif
4474 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4475 }
4476 if (ta_len > 0 || len > 0)
4477 {
4478 /*
4479 * For pipes: Check for CTRL-C: send interrupt signal to
4480 * child. Check for CTRL-D: EOF, close pipe to child.
4481 */
4482 if (len == 1 && cmd != NULL)
4483 {
4484 if (ta_buf[ta_len] == Ctrl_C)
4485 {
4486 /* Learn what exit code is expected, for
4487 * now put 9 as SIGKILL */
4488 TerminateProcess(pi.hProcess, 9);
4489 }
4490 if (ta_buf[ta_len] == Ctrl_D)
4491 {
4492 CloseHandle(g_hChildStd_IN_Wr);
4493 g_hChildStd_IN_Wr = NULL;
4494 }
4495 }
4496
4497 /* replace K_BS by <BS> and K_DEL by <DEL> */
4498 for (i = ta_len; i < ta_len + len; ++i)
4499 {
4500 if (ta_buf[i] == CSI && len - i > 2)
4501 {
4502 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4503 if (c == K_DEL || c == K_KDEL || c == K_BS)
4504 {
4505 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4506 (size_t)(len - i - 2));
4507 if (c == K_DEL || c == K_KDEL)
4508 ta_buf[i] = DEL;
4509 else
4510 ta_buf[i] = Ctrl_H;
4511 len -= 2;
4512 }
4513 }
4514 else if (ta_buf[i] == '\r')
4515 ta_buf[i] = '\n';
4516# ifdef FEAT_MBYTE
4517 if (has_mbyte)
4518 i += (*mb_ptr2len_len)(ta_buf + i,
4519 ta_len + len - i) - 1;
4520# endif
4521 }
4522
4523 /*
4524 * For pipes: echo the typed characters. For a pty this
4525 * does not seem to work.
4526 */
4527 for (i = ta_len; i < ta_len + len; ++i)
4528 {
4529 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4530 msg_putchar(ta_buf[i]);
4531# ifdef FEAT_MBYTE
4532 else if (has_mbyte)
4533 {
4534 int l = (*mb_ptr2len)(ta_buf + i);
4535
4536 msg_outtrans_len(ta_buf + i, l);
4537 i += l - 1;
4538 }
4539# endif
4540 else
4541 msg_outtrans_len(ta_buf + i, 1);
4542 }
4543 windgoto(msg_row, msg_col);
4544 out_flush();
4545
4546 ta_len += len;
4547
4548 /*
4549 * Write the characters to the child, unless EOF has been
4550 * typed for pipes. Write one character at a time, to
4551 * avoid losing too much typeahead. When writing buffer
4552 * lines, drop the typed characters (only check for
4553 * CTRL-C).
4554 */
4555 if (options & SHELL_WRITE)
4556 ta_len = 0;
4557 else if (g_hChildStd_IN_Wr != NULL)
4558 {
4559 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4560 1, &len, NULL);
4561 // if we are typing in, we want to keep things reactive
4562 delay = 1;
4563 if (len > 0)
4564 {
4565 ta_len -= len;
4566 mch_memmove(ta_buf, ta_buf + len, ta_len);
4567 }
4568 }
4569 }
4570 }
4571 }
4572
4573 if (ta_len)
4574 ui_inchar_undo(ta_buf, ta_len);
4575
4576 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4577 {
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 break;
4580 }
4581
4582 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004583 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004584
4585 /* We start waiting for a very short time and then increase it, so
4586 * that we respond quickly when the process is quick, and don't
4587 * consume too much overhead when it's slow. */
4588 if (delay < 50)
4589 delay += 10;
4590 }
4591
4592 /* Close the pipe */
4593 CloseHandle(g_hChildStd_OUT_Rd);
4594 if (g_hChildStd_IN_Wr != NULL)
4595 CloseHandle(g_hChildStd_IN_Wr);
4596
4597 WaitForSingleObject(pi.hProcess, INFINITE);
4598
4599 /* Get the command exit code */
4600 GetExitCodeProcess(pi.hProcess, &ret);
4601
4602 if (options & SHELL_READ)
4603 {
4604 if (ga.ga_len > 0)
4605 {
4606 append_ga_line(&ga);
4607 /* remember that the NL was missing */
4608 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4609 }
4610 else
4611 curbuf->b_no_eol_lnum = 0;
4612 ga_clear(&ga);
4613 }
4614
4615 /* Close the handles to the subprocess, so that it goes away */
4616 CloseHandle(pi.hThread);
4617 CloseHandle(pi.hProcess);
4618
4619 return ret;
4620}
4621
4622 static int
4623mch_system(char *cmd, int options)
4624{
4625 /* if we can pipe and the shelltemp option is off */
4626 if (allowPiping && !p_stmp)
4627 return mch_system_piped(cmd, options);
4628 else
4629 return mch_system_classic(cmd, options);
4630}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631#else
4632
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004633# ifdef FEAT_MBYTE
4634 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004635mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004636{
4637 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4638 {
4639 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4640 if (wcmd != NULL)
4641 {
4642 int ret = _wsystem(wcmd);
4643 vim_free(wcmd);
4644 return ret;
4645 }
4646 }
4647 return system(cmd);
4648}
4649# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004650# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004651# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004652
4653#endif
4654
4655/*
4656 * Either execute a command by calling the shell or start a new shell
4657 */
4658 int
4659mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004660 char_u *cmd,
4661 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004662{
4663 int x = 0;
4664 int tmode = cur_tmode;
4665#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004666 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004667# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004668 int did_set_title = FALSE;
4669
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004670 /* Change the title to reflect that we are in a subshell. */
4671 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4672 {
4673 WCHAR szShellTitle[512];
4674
4675 if (GetConsoleTitleW(szShellTitle,
4676 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4677 {
4678 if (cmd == NULL)
4679 wcscat(szShellTitle, L" :sh");
4680 else
4681 {
4682 WCHAR *wn = enc_to_utf16(cmd, NULL);
4683
4684 if (wn != NULL)
4685 {
4686 wcscat(szShellTitle, L" - !");
4687 if ((wcslen(szShellTitle) + wcslen(wn) <
4688 sizeof(szShellTitle)/sizeof(WCHAR)))
4689 wcscat(szShellTitle, wn);
4690 SetConsoleTitleW(szShellTitle);
4691 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004692 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004693 }
4694 }
4695 }
4696 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004697 if (!did_set_title)
4698# endif
4699 /* Change the title to reflect that we are in a subshell. */
4700 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004701 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004702 if (cmd == NULL)
4703 strcat(szShellTitle, " :sh");
4704 else
4705 {
4706 strcat(szShellTitle, " - !");
4707 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4708 strcat(szShellTitle, cmd);
4709 }
4710 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004711 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004712#endif
4713
4714 out_flush();
4715
4716#ifdef MCH_WRITE_DUMP
4717 if (fdDump)
4718 {
4719 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4720 fflush(fdDump);
4721 }
4722#endif
4723
4724 /*
4725 * Catch all deadly signals while running the external command, because a
4726 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4727 */
4728 signal(SIGINT, SIG_IGN);
4729#if defined(__GNUC__) && !defined(__MINGW32__)
4730 signal(SIGKILL, SIG_IGN);
4731#else
4732 signal(SIGBREAK, SIG_IGN);
4733#endif
4734 signal(SIGILL, SIG_IGN);
4735 signal(SIGFPE, SIG_IGN);
4736 signal(SIGSEGV, SIG_IGN);
4737 signal(SIGTERM, SIG_IGN);
4738 signal(SIGABRT, SIG_IGN);
4739
4740 if (options & SHELL_COOKED)
4741 settmode(TMODE_COOK); /* set to normal mode */
4742
4743 if (cmd == NULL)
4744 {
4745 x = mch_system(p_sh, options);
4746 }
4747 else
4748 {
4749 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004750 char_u *newcmd = NULL;
4751 char_u *cmdbase = cmd;
4752 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004753
4754 /* Skip a leading ", ( and "(. */
4755 if (*cmdbase == '"' )
4756 ++cmdbase;
4757 if (*cmdbase == '(')
4758 ++cmdbase;
4759
4760 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4761 {
4762 STARTUPINFO si;
4763 PROCESS_INFORMATION pi;
4764 DWORD flags = CREATE_NEW_CONSOLE;
4765 char_u *p;
4766
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004767 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004768 si.cb = sizeof(si);
4769 si.lpReserved = NULL;
4770 si.lpDesktop = NULL;
4771 si.lpTitle = NULL;
4772 si.dwFlags = 0;
4773 si.cbReserved2 = 0;
4774 si.lpReserved2 = NULL;
4775
4776 cmdbase = skipwhite(cmdbase + 5);
4777 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4778 && vim_iswhite(cmdbase[4]))
4779 {
4780 cmdbase = skipwhite(cmdbase + 4);
4781 si.dwFlags = STARTF_USESHOWWINDOW;
4782 si.wShowWindow = SW_SHOWMINNOACTIVE;
4783 }
4784 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4785 && vim_iswhite(cmdbase[2]))
4786 {
4787 cmdbase = skipwhite(cmdbase + 2);
4788 flags = CREATE_NO_WINDOW;
4789 si.dwFlags = STARTF_USESTDHANDLES;
4790 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004791 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004792 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004793 NULL, // Security att.
4794 OPEN_EXISTING, // Open flags
4795 FILE_ATTRIBUTE_NORMAL, // File att.
4796 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004797 si.hStdOutput = si.hStdInput;
4798 si.hStdError = si.hStdInput;
4799 }
4800
4801 /* Remove a trailing ", ) and )" if they have a match
4802 * at the start of the command. */
4803 if (cmdbase > cmd)
4804 {
4805 p = cmdbase + STRLEN(cmdbase);
4806 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4807 *--p = NUL;
4808 if (p > cmdbase && p[-1] == ')'
4809 && (*cmd =='(' || cmd[1] == '('))
4810 *--p = NUL;
4811 }
4812
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004813 newcmd = cmdbase;
4814 unescape_shellxquote(cmdbase, p_sxe);
4815
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004816 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004817 * If creating new console, arguments are passed to the
4818 * 'cmd.exe' as-is. If it's not, arguments are not treated
4819 * correctly for current 'cmd.exe'. So unescape characters in
4820 * shellxescape except '|' for avoiding to be treated as
4821 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004822 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004823 if (flags != CREATE_NEW_CONSOLE)
4824 {
4825 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004826 char_u *cmd_shell = mch_getenv("COMSPEC");
4827
4828 if (cmd_shell == NULL || *cmd_shell == NUL)
4829 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004830
4831 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4832 if (subcmd != NULL)
4833 {
4834 /* make "cmd.exe /c arguments" */
4835 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004836 newcmd = lalloc(cmdlen, TRUE);
4837 if (newcmd != NULL)
4838 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004839 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004840 else
4841 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004842 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004843 }
4844 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004845
4846 /*
4847 * Now, start the command as a process, so that it doesn't
4848 * inherit our handles which causes unpleasant dangling swap
4849 * files if we exit before the spawned process
4850 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004851 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004852 x = 0;
4853 else
4854 {
4855 x = -1;
4856#ifdef FEAT_GUI_W32
4857 EMSG(_("E371: Command not found"));
4858#endif
4859 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004860
4861 if (newcmd != cmdbase)
4862 vim_free(newcmd);
4863
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004864 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004865 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004866 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004867 CloseHandle(si.hStdInput);
4868 }
4869 /* Close the handles to the subprocess, so that it goes away */
4870 CloseHandle(pi.hThread);
4871 CloseHandle(pi.hProcess);
4872 }
4873 else
4874 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004875 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004876#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004877 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004878#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004879 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4880
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004881 newcmd = lalloc(cmdlen, TRUE);
4882 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004883 {
4884#if defined(FEAT_GUI_W32)
4885 if (need_vimrun_warning)
4886 {
4887 MessageBox(NULL,
4888 _("VIMRUN.EXE not found in your $PATH.\n"
4889 "External commands will not pause after completion.\n"
4890 "See :help win32-vimrun for more information."),
4891 _("Vim Warning"),
4892 MB_ICONWARNING);
4893 need_vimrun_warning = FALSE;
4894 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004895 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004896 /* Use vimrun to execute the command. It opens a console
4897 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004898 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004899 vimrun_path,
4900 (msg_silent != 0 || (options & SHELL_DOOUT))
4901 ? "-s " : "",
4902 p_sh, p_shcf, cmd);
4903 else
4904#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004905 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004906 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004908 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004909 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004910 }
4911 }
4912
4913 if (tmode == TMODE_RAW)
4914 settmode(TMODE_RAW); /* set to raw mode */
4915
4916 /* Print the return value, unless "vimrun" was used. */
4917 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4918#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004919 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4920 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921#endif
4922 )
4923 {
4924 smsg(_("shell returned %d"), x);
4925 msg_putchar('\n');
4926 }
4927#ifdef FEAT_TITLE
4928 resettitle();
4929#endif
4930
4931 signal(SIGINT, SIG_DFL);
4932#if defined(__GNUC__) && !defined(__MINGW32__)
4933 signal(SIGKILL, SIG_DFL);
4934#else
4935 signal(SIGBREAK, SIG_DFL);
4936#endif
4937 signal(SIGILL, SIG_DFL);
4938 signal(SIGFPE, SIG_DFL);
4939 signal(SIGSEGV, SIG_DFL);
4940 signal(SIGTERM, SIG_DFL);
4941 signal(SIGABRT, SIG_DFL);
4942
4943 return x;
4944}
4945
4946
4947#ifndef FEAT_GUI_W32
4948
4949/*
4950 * Start termcap mode
4951 */
4952 static void
4953termcap_mode_start(void)
4954{
4955 DWORD cmodein;
4956
4957 if (g_fTermcapMode)
4958 return;
4959
4960 SaveConsoleBuffer(&g_cbNonTermcap);
4961
4962 if (g_cbTermcap.IsValid)
4963 {
4964 /*
4965 * We've been in termcap mode before. Restore certain screen
4966 * characteristics, including the buffer size and the window
4967 * size. Since we will be redrawing the screen, we don't need
4968 * to restore the actual contents of the buffer.
4969 */
4970 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4971 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4972 Rows = g_cbTermcap.Info.dwSize.Y;
4973 Columns = g_cbTermcap.Info.dwSize.X;
4974 }
4975 else
4976 {
4977 /*
4978 * This is our first time entering termcap mode. Clear the console
4979 * screen buffer, and resize the buffer to match the current window
4980 * size. We will use this as the size of our editing environment.
4981 */
4982 ClearConsoleBuffer(g_attrCurrent);
4983 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4984 }
4985
4986#ifdef FEAT_TITLE
4987 resettitle();
4988#endif
4989
4990 GetConsoleMode(g_hConIn, &cmodein);
4991#ifdef FEAT_MOUSE
4992 if (g_fMouseActive)
4993 cmodein |= ENABLE_MOUSE_INPUT;
4994 else
4995 cmodein &= ~ENABLE_MOUSE_INPUT;
4996#endif
4997 cmodein |= ENABLE_WINDOW_INPUT;
4998 SetConsoleMode(g_hConIn, cmodein);
4999
5000 redraw_later_clear();
5001 g_fTermcapMode = TRUE;
5002}
5003
5004
5005/*
5006 * End termcap mode
5007 */
5008 static void
5009termcap_mode_end(void)
5010{
5011 DWORD cmodein;
5012 ConsoleBuffer *cb;
5013 COORD coord;
5014 DWORD dwDummy;
5015
5016 if (!g_fTermcapMode)
5017 return;
5018
5019 SaveConsoleBuffer(&g_cbTermcap);
5020
5021 GetConsoleMode(g_hConIn, &cmodein);
5022 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5023 SetConsoleMode(g_hConIn, cmodein);
5024
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005025#ifdef FEAT_RESTORE_ORIG_SCREEN
5026 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5027#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005029#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030 RestoreConsoleBuffer(cb, p_rs);
5031 SetConsoleCursorInfo(g_hConOut, &g_cci);
5032
5033 if (p_rs || exiting)
5034 {
5035 /*
5036 * Clear anything that happens to be on the current line.
5037 */
5038 coord.X = 0;
5039 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5040 FillConsoleOutputCharacter(g_hConOut, ' ',
5041 cb->Info.dwSize.X, coord, &dwDummy);
5042 /*
5043 * The following is just for aesthetics. If we are exiting without
5044 * restoring the screen, then we want to have a prompt string
5045 * appear at the bottom line. However, the command interpreter
5046 * seems to always advance the cursor one line before displaying
5047 * the prompt string, which causes the screen to scroll. To
5048 * counter this, move the cursor up one line before exiting.
5049 */
5050 if (exiting && !p_rs)
5051 coord.Y--;
5052 /*
5053 * Position the cursor at the leftmost column of the desired row.
5054 */
5055 SetConsoleCursorPosition(g_hConOut, coord);
5056 }
5057
5058 g_fTermcapMode = FALSE;
5059}
5060#endif /* FEAT_GUI_W32 */
5061
5062
5063#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005064/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065 void
5066mch_write(
5067 char_u *s,
5068 int len)
5069{
5070 /* never used */
5071}
5072
5073#else
5074
5075/*
5076 * clear `n' chars, starting from `coord'
5077 */
5078 static void
5079clear_chars(
5080 COORD coord,
5081 DWORD n)
5082{
5083 DWORD dwDummy;
5084
5085 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5086 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5087}
5088
5089
5090/*
5091 * Clear the screen
5092 */
5093 static void
5094clear_screen(void)
5095{
5096 g_coord.X = g_coord.Y = 0;
5097 clear_chars(g_coord, Rows * Columns);
5098}
5099
5100
5101/*
5102 * Clear to end of display
5103 */
5104 static void
5105clear_to_end_of_display(void)
5106{
5107 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5108 * Columns + (Columns - g_coord.X));
5109}
5110
5111
5112/*
5113 * Clear to end of line
5114 */
5115 static void
5116clear_to_end_of_line(void)
5117{
5118 clear_chars(g_coord, Columns - g_coord.X);
5119}
5120
5121
5122/*
5123 * Scroll the scroll region up by `cLines' lines
5124 */
5125 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005126scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005127{
5128 COORD oldcoord = g_coord;
5129
5130 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5131 delete_lines(cLines);
5132
5133 g_coord = oldcoord;
5134}
5135
5136
5137/*
5138 * Set the scroll region
5139 */
5140 static void
5141set_scroll_region(
5142 unsigned left,
5143 unsigned top,
5144 unsigned right,
5145 unsigned bottom)
5146{
5147 if (left >= right
5148 || top >= bottom
5149 || right > (unsigned) Columns - 1
5150 || bottom > (unsigned) Rows - 1)
5151 return;
5152
5153 g_srScrollRegion.Left = left;
5154 g_srScrollRegion.Top = top;
5155 g_srScrollRegion.Right = right;
5156 g_srScrollRegion.Bottom = bottom;
5157}
5158
5159
5160/*
5161 * Insert `cLines' lines at the current cursor position
5162 */
5163 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005164insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005165{
5166 SMALL_RECT source;
5167 COORD dest;
5168 CHAR_INFO fill;
5169
5170 dest.X = 0;
5171 dest.Y = g_coord.Y + cLines;
5172
5173 source.Left = 0;
5174 source.Top = g_coord.Y;
5175 source.Right = g_srScrollRegion.Right;
5176 source.Bottom = g_srScrollRegion.Bottom - cLines;
5177
5178 fill.Char.AsciiChar = ' ';
5179 fill.Attributes = g_attrCurrent;
5180
5181 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5182
5183 /* Here we have to deal with a win32 console flake: If the scroll
5184 * region looks like abc and we scroll c to a and fill with d we get
5185 * cbd... if we scroll block c one line at a time to a, we get cdd...
5186 * vim expects cdd consistently... So we have to deal with that
5187 * here... (this also occurs scrolling the same way in the other
5188 * direction). */
5189
5190 if (source.Bottom < dest.Y)
5191 {
5192 COORD coord;
5193
5194 coord.X = 0;
5195 coord.Y = source.Bottom;
5196 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5197 }
5198}
5199
5200
5201/*
5202 * Delete `cLines' lines at the current cursor position
5203 */
5204 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005205delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206{
5207 SMALL_RECT source;
5208 COORD dest;
5209 CHAR_INFO fill;
5210 int nb;
5211
5212 dest.X = 0;
5213 dest.Y = g_coord.Y;
5214
5215 source.Left = 0;
5216 source.Top = g_coord.Y + cLines;
5217 source.Right = g_srScrollRegion.Right;
5218 source.Bottom = g_srScrollRegion.Bottom;
5219
5220 fill.Char.AsciiChar = ' ';
5221 fill.Attributes = g_attrCurrent;
5222
5223 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5224
5225 /* Here we have to deal with a win32 console flake: If the scroll
5226 * region looks like abc and we scroll c to a and fill with d we get
5227 * cbd... if we scroll block c one line at a time to a, we get cdd...
5228 * vim expects cdd consistently... So we have to deal with that
5229 * here... (this also occurs scrolling the same way in the other
5230 * direction). */
5231
5232 nb = dest.Y + (source.Bottom - source.Top) + 1;
5233
5234 if (nb < source.Top)
5235 {
5236 COORD coord;
5237
5238 coord.X = 0;
5239 coord.Y = nb;
5240 clear_chars(coord, Columns * (source.Top - nb));
5241 }
5242}
5243
5244
5245/*
5246 * Set the cursor position
5247 */
5248 static void
5249gotoxy(
5250 unsigned x,
5251 unsigned y)
5252{
5253 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5254 return;
5255
5256 /* external cursor coords are 1-based; internal are 0-based */
5257 g_coord.X = x - 1;
5258 g_coord.Y = y - 1;
5259 SetConsoleCursorPosition(g_hConOut, g_coord);
5260}
5261
5262
5263/*
5264 * Set the current text attribute = (foreground | background)
5265 * See ../doc/os_win32.txt for the numbers.
5266 */
5267 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005268textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005269{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005270 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005271
5272 SetConsoleTextAttribute(g_hConOut, wAttr);
5273}
5274
5275
5276 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005277textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005278{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005279 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005280
5281 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5282}
5283
5284
5285 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005286textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005287{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005288 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005289
5290 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5291}
5292
5293
5294/*
5295 * restore the default text attribute (whatever we started with)
5296 */
5297 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005298normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005299{
5300 textattr(g_attrDefault);
5301}
5302
5303
5304static WORD g_attrPreStandout = 0;
5305
5306/*
5307 * Make the text standout, by brightening it
5308 */
5309 static void
5310standout(void)
5311{
5312 g_attrPreStandout = g_attrCurrent;
5313 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5314}
5315
5316
5317/*
5318 * Turn off standout mode
5319 */
5320 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005321standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322{
5323 if (g_attrPreStandout)
5324 {
5325 textattr(g_attrPreStandout);
5326 g_attrPreStandout = 0;
5327 }
5328}
5329
5330
5331/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005332 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005333 */
5334 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005335mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005336{
5337 char_u *p;
5338 int n;
5339
5340 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5341 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5342 if (T_ME[0] == ESC && T_ME[1] == '|')
5343 {
5344 p = T_ME + 2;
5345 n = getdigits(&p);
5346 if (*p == 'm' && n > 0)
5347 {
5348 cterm_normal_fg_color = (n & 0xf) + 1;
5349 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5350 }
5351 }
5352}
5353
5354
5355/*
5356 * visual bell: flash the screen
5357 */
5358 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005359visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005360{
5361 COORD coordOrigin = {0, 0};
5362 WORD attrFlash = ~g_attrCurrent & 0xff;
5363
5364 DWORD dwDummy;
5365 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5366
5367 if (oldattrs == NULL)
5368 return;
5369 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5370 coordOrigin, &dwDummy);
5371 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5372 coordOrigin, &dwDummy);
5373
5374 Sleep(15); /* wait for 15 msec */
5375 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5376 coordOrigin, &dwDummy);
5377 vim_free(oldattrs);
5378}
5379
5380
5381/*
5382 * Make the cursor visible or invisible
5383 */
5384 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005385cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386{
5387 s_cursor_visible = fVisible;
5388#ifdef MCH_CURSOR_SHAPE
5389 mch_update_cursor();
5390#endif
5391}
5392
5393
5394/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005395 * write `cbToWrite' bytes in `pchBuf' to the screen
5396 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005397 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005398 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005399write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005400 char_u *pchBuf,
5401 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402{
5403 COORD coord = g_coord;
5404 DWORD written;
5405
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005406#ifdef FEAT_MBYTE
5407 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5408 {
5409 static WCHAR *unicodebuf = NULL;
5410 static int unibuflen = 0;
5411 int length;
5412 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005414 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5415 if (unicodebuf == NULL || length > unibuflen)
5416 {
5417 vim_free(unicodebuf);
5418 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5419 unibuflen = length;
5420 }
5421 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5422 unicodebuf, unibuflen);
5423
5424 cells = mb_string2cells(pchBuf, cbToWrite);
5425 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5426 coord, &written);
5427 /* When writing fails or didn't write a single character, pretend one
5428 * character was written, otherwise we get stuck. */
5429 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5430 coord, &cchwritten) == 0
5431 || cchwritten == 0)
5432 cchwritten = 1;
5433
5434 if (cchwritten == length)
5435 {
5436 written = cbToWrite;
5437 g_coord.X += (SHORT)cells;
5438 }
5439 else
5440 {
5441 char_u *p = pchBuf;
5442 for (n = 0; n < cchwritten; n++)
5443 mb_cptr_adv(p);
5444 written = p - pchBuf;
5445 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5446 }
5447 }
5448 else
5449#endif
5450 {
5451 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5452 coord, &written);
5453 /* When writing fails or didn't write a single character, pretend one
5454 * character was written, otherwise we get stuck. */
5455 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5456 coord, &written) == 0
5457 || written == 0)
5458 written = 1;
5459
5460 g_coord.X += (SHORT) written;
5461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005462
5463 while (g_coord.X > g_srScrollRegion.Right)
5464 {
5465 g_coord.X -= (SHORT) Columns;
5466 if (g_coord.Y < g_srScrollRegion.Bottom)
5467 g_coord.Y++;
5468 }
5469
5470 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5471
5472 return written;
5473}
5474
5475
5476/*
5477 * mch_write(): write the output buffer to the screen, translating ESC
5478 * sequences into calls to console output routines.
5479 */
5480 void
5481mch_write(
5482 char_u *s,
5483 int len)
5484{
5485 s[len] = NUL;
5486
5487 if (!term_console)
5488 {
5489 write(1, s, (unsigned)len);
5490 return;
5491 }
5492
5493 /* translate ESC | sequences into faked bios calls */
5494 while (len--)
5495 {
5496 /* optimization: use one single write_chars for runs of text,
5497 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005498 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005499
5500 if (p_wd)
5501 {
5502 WaitForChar(p_wd);
5503 if (prefix != 0)
5504 prefix = 1;
5505 }
5506
5507 if (prefix != 0)
5508 {
5509 DWORD nWritten;
5510
5511 nWritten = write_chars(s, prefix);
5512#ifdef MCH_WRITE_DUMP
5513 if (fdDump)
5514 {
5515 fputc('>', fdDump);
5516 fwrite(s, sizeof(char_u), nWritten, fdDump);
5517 fputs("<\n", fdDump);
5518 }
5519#endif
5520 len -= (nWritten - 1);
5521 s += nWritten;
5522 }
5523 else if (s[0] == '\n')
5524 {
5525 /* \n, newline: go to the beginning of the next line or scroll */
5526 if (g_coord.Y == g_srScrollRegion.Bottom)
5527 {
5528 scroll(1);
5529 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5530 }
5531 else
5532 {
5533 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5534 }
5535#ifdef MCH_WRITE_DUMP
5536 if (fdDump)
5537 fputs("\\n\n", fdDump);
5538#endif
5539 s++;
5540 }
5541 else if (s[0] == '\r')
5542 {
5543 /* \r, carriage return: go to beginning of line */
5544 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5545#ifdef MCH_WRITE_DUMP
5546 if (fdDump)
5547 fputs("\\r\n", fdDump);
5548#endif
5549 s++;
5550 }
5551 else if (s[0] == '\b')
5552 {
5553 /* \b, backspace: move cursor one position left */
5554 if (g_coord.X > g_srScrollRegion.Left)
5555 g_coord.X--;
5556 else if (g_coord.Y > g_srScrollRegion.Top)
5557 {
5558 g_coord.X = g_srScrollRegion.Right;
5559 g_coord.Y--;
5560 }
5561 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5562#ifdef MCH_WRITE_DUMP
5563 if (fdDump)
5564 fputs("\\b\n", fdDump);
5565#endif
5566 s++;
5567 }
5568 else if (s[0] == '\a')
5569 {
5570 /* \a, bell */
5571 MessageBeep(0xFFFFFFFF);
5572#ifdef MCH_WRITE_DUMP
5573 if (fdDump)
5574 fputs("\\a\n", fdDump);
5575#endif
5576 s++;
5577 }
5578 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5579 {
5580#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005581 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005582#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005583 char_u *p;
5584 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005585
5586 switch (s[2])
5587 {
5588 /* one or two numeric arguments, separated by ';' */
5589
5590 case '0': case '1': case '2': case '3': case '4':
5591 case '5': case '6': case '7': case '8': case '9':
5592 p = s + 2;
5593 arg1 = getdigits(&p); /* no check for length! */
5594 if (p > s + len)
5595 break;
5596
5597 if (*p == ';')
5598 {
5599 ++p;
5600 arg2 = getdigits(&p); /* no check for length! */
5601 if (p > s + len)
5602 break;
5603
5604 if (*p == 'H')
5605 gotoxy(arg2, arg1);
5606 else if (*p == 'r')
5607 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5608 }
5609 else if (*p == 'A')
5610 {
5611 /* move cursor up arg1 lines in same column */
5612 gotoxy(g_coord.X + 1,
5613 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5614 }
5615 else if (*p == 'C')
5616 {
5617 /* move cursor right arg1 columns in same line */
5618 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5619 g_coord.Y + 1);
5620 }
5621 else if (*p == 'H')
5622 {
5623 gotoxy(1, arg1);
5624 }
5625 else if (*p == 'L')
5626 {
5627 insert_lines(arg1);
5628 }
5629 else if (*p == 'm')
5630 {
5631 if (arg1 == 0)
5632 normvideo();
5633 else
5634 textattr((WORD) arg1);
5635 }
5636 else if (*p == 'f')
5637 {
5638 textcolor((WORD) arg1);
5639 }
5640 else if (*p == 'b')
5641 {
5642 textbackground((WORD) arg1);
5643 }
5644 else if (*p == 'M')
5645 {
5646 delete_lines(arg1);
5647 }
5648
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005649 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 s = p + 1;
5651 break;
5652
5653
5654 /* Three-character escape sequences */
5655
5656 case 'A':
5657 /* move cursor up one line in same column */
5658 gotoxy(g_coord.X + 1,
5659 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5660 goto got3;
5661
5662 case 'B':
5663 visual_bell();
5664 goto got3;
5665
5666 case 'C':
5667 /* move cursor right one column in same line */
5668 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5669 g_coord.Y + 1);
5670 goto got3;
5671
5672 case 'E':
5673 termcap_mode_end();
5674 goto got3;
5675
5676 case 'F':
5677 standout();
5678 goto got3;
5679
5680 case 'f':
5681 standend();
5682 goto got3;
5683
5684 case 'H':
5685 gotoxy(1, 1);
5686 goto got3;
5687
5688 case 'j':
5689 clear_to_end_of_display();
5690 goto got3;
5691
5692 case 'J':
5693 clear_screen();
5694 goto got3;
5695
5696 case 'K':
5697 clear_to_end_of_line();
5698 goto got3;
5699
5700 case 'L':
5701 insert_lines(1);
5702 goto got3;
5703
5704 case 'M':
5705 delete_lines(1);
5706 goto got3;
5707
5708 case 'S':
5709 termcap_mode_start();
5710 goto got3;
5711
5712 case 'V':
5713 cursor_visible(TRUE);
5714 goto got3;
5715
5716 case 'v':
5717 cursor_visible(FALSE);
5718 goto got3;
5719
5720 got3:
5721 s += 3;
5722 len -= 2;
5723 }
5724
5725#ifdef MCH_WRITE_DUMP
5726 if (fdDump)
5727 {
5728 fputs("ESC | ", fdDump);
5729 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5730 fputc('\n', fdDump);
5731 }
5732#endif
5733 }
5734 else
5735 {
5736 /* Write a single character */
5737 DWORD nWritten;
5738
5739 nWritten = write_chars(s, 1);
5740#ifdef MCH_WRITE_DUMP
5741 if (fdDump)
5742 {
5743 fputc('>', fdDump);
5744 fwrite(s, sizeof(char_u), nWritten, fdDump);
5745 fputs("<\n", fdDump);
5746 }
5747#endif
5748
5749 len -= (nWritten - 1);
5750 s += nWritten;
5751 }
5752 }
5753
5754#ifdef MCH_WRITE_DUMP
5755 if (fdDump)
5756 fflush(fdDump);
5757#endif
5758}
5759
5760#endif /* FEAT_GUI_W32 */
5761
5762
5763/*
5764 * Delay for half a second.
5765 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005766/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767 void
5768mch_delay(
5769 long msec,
5770 int ignoreinput)
5771{
5772#ifdef FEAT_GUI_W32
5773 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005774#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005776# ifdef FEAT_MZSCHEME
5777 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5778 {
5779 int towait = p_mzq;
5780
5781 /* if msec is large enough, wait by portions in p_mzq */
5782 while (msec > 0)
5783 {
5784 mzvim_check_threads();
5785 if (msec < towait)
5786 towait = msec;
5787 Sleep(towait);
5788 msec -= towait;
5789 }
5790 }
5791 else
5792# endif
5793 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794 else
5795 WaitForChar(msec);
5796#endif
5797}
5798
5799
5800/*
5801 * this version of remove is not scared by a readonly (backup) file
5802 * Return 0 for success, -1 for failure.
5803 */
5804 int
5805mch_remove(char_u *name)
5806{
5807#ifdef FEAT_MBYTE
5808 WCHAR *wn = NULL;
5809 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005810#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005812 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5813
5814#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5816 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005817 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005818 if (wn != NULL)
5819 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820 n = DeleteFileW(wn) ? 0 : -1;
5821 vim_free(wn);
5822 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5823 return n;
5824 /* Retry with non-wide function (for Windows 98). */
5825 }
5826 }
5827#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828 return DeleteFile(name) ? 0 : -1;
5829}
5830
5831
5832/*
5833 * check for an "interrupt signal": CTRL-break or CTRL-C
5834 */
5835 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005836mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837{
5838#ifndef FEAT_GUI_W32 /* never used */
5839 if (g_fCtrlCPressed || g_fCBrkPressed)
5840 {
5841 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5842 got_int = TRUE;
5843 }
5844#endif
5845}
5846
5847
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848#ifdef FEAT_MBYTE
5849/*
5850 * Same code as below, but with wide functions and no comments.
5851 * Return 0 for success, non-zero for failure.
5852 */
5853 int
5854mch_wrename(WCHAR *wold, WCHAR *wnew)
5855{
5856 WCHAR *p;
5857 int i;
5858 WCHAR szTempFile[_MAX_PATH + 1];
5859 WCHAR szNewPath[_MAX_PATH + 1];
5860 HANDLE hf;
5861
5862 if (!mch_windows95())
5863 {
5864 p = wold;
5865 for (i = 0; wold[i] != NUL; ++i)
5866 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5867 && wold[i + 1] != 0)
5868 p = wold + i + 1;
5869 if ((int)(wold + i - p) < 8 || p[6] != '~')
5870 return (MoveFileW(wold, wnew) == 0);
5871 }
5872
5873 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5874 return -1;
5875 *p = NUL;
5876
5877 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5878 return -2;
5879
5880 if (!DeleteFileW(szTempFile))
5881 return -3;
5882
5883 if (!MoveFileW(wold, szTempFile))
5884 return -4;
5885
5886 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5887 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5888 return -5;
5889 if (!CloseHandle(hf))
5890 return -6;
5891
5892 if (!MoveFileW(szTempFile, wnew))
5893 {
5894 (void)MoveFileW(szTempFile, wold);
5895 return -7;
5896 }
5897
5898 DeleteFileW(szTempFile);
5899
5900 if (!DeleteFileW(wold))
5901 return -8;
5902
5903 return 0;
5904}
5905#endif
5906
5907
5908/*
5909 * mch_rename() works around a bug in rename (aka MoveFile) in
5910 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5911 * file whose short file name is "FOO.BAR" (its long file name will
5912 * be correct: "foo.bar~"). Because a file can be accessed by
5913 * either its SFN or its LFN, "foo.bar" has effectively been
5914 * renamed to "foo.bar", which is not at all what was wanted. This
5915 * seems to happen only when renaming files with three-character
5916 * extensions by appending a suffix that does not include ".".
5917 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5918 *
5919 * There is another problem, which isn't really a bug but isn't right either:
5920 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5921 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5922 * service pack 6. Doesn't seem to happen on Windows 98.
5923 *
5924 * Like rename(), returns 0 upon success, non-zero upon failure.
5925 * Should probably set errno appropriately when errors occur.
5926 */
5927 int
5928mch_rename(
5929 const char *pszOldFile,
5930 const char *pszNewFile)
5931{
5932 char szTempFile[_MAX_PATH+1];
5933 char szNewPath[_MAX_PATH+1];
5934 char *pszFilePart;
5935 HANDLE hf;
5936#ifdef FEAT_MBYTE
5937 WCHAR *wold = NULL;
5938 WCHAR *wnew = NULL;
5939 int retval = -1;
5940
5941 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5942 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005943 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5944 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945 if (wold != NULL && wnew != NULL)
5946 retval = mch_wrename(wold, wnew);
5947 vim_free(wold);
5948 vim_free(wnew);
5949 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5950 return retval;
5951 /* Retry with non-wide function (for Windows 98). */
5952 }
5953#endif
5954
5955 /*
5956 * No need to play tricks if not running Windows 95, unless the file name
5957 * contains a "~" as the seventh character.
5958 */
5959 if (!mch_windows95())
5960 {
5961 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5962 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5963 return rename(pszOldFile, pszNewFile);
5964 }
5965
5966 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5967 * a directory, no error is returned and pszFilePart will be NULL. */
5968 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5969 || pszFilePart == NULL)
5970 return -1;
5971 *pszFilePart = NUL;
5972
5973 /* Get (and create) a unique temporary file name in directory of new file */
5974 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5975 return -2;
5976
5977 /* blow the temp file away */
5978 if (!DeleteFile(szTempFile))
5979 return -3;
5980
5981 /* rename old file to the temp file */
5982 if (!MoveFile(pszOldFile, szTempFile))
5983 return -4;
5984
5985 /* now create an empty file called pszOldFile; this prevents the operating
5986 * system using pszOldFile as an alias (SFN) if we're renaming within the
5987 * same directory. For example, we're editing a file called
5988 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5989 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5990 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005991 * cause all sorts of problems later in buf_write(). So, we create an
5992 * empty file called filena~1.txt and the system will have to find some
5993 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005994 */
5995 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5996 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5997 return -5;
5998 if (!CloseHandle(hf))
5999 return -6;
6000
6001 /* rename the temp file to the new file */
6002 if (!MoveFile(szTempFile, pszNewFile))
6003 {
6004 /* Renaming failed. Rename the file back to its old name, so that it
6005 * looks like nothing happened. */
6006 (void)MoveFile(szTempFile, pszOldFile);
6007
6008 return -7;
6009 }
6010
6011 /* Seems to be left around on Novell filesystems */
6012 DeleteFile(szTempFile);
6013
6014 /* finally, remove the empty old file */
6015 if (!DeleteFile(pszOldFile))
6016 return -8;
6017
6018 return 0; /* success */
6019}
6020
6021/*
6022 * Get the default shell for the current hardware platform
6023 */
6024 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006025default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026{
6027 char* psz = NULL;
6028
6029 PlatformId();
6030
6031 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6032 psz = "cmd.exe";
6033 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6034 psz = "command.com";
6035
6036 return psz;
6037}
6038
6039/*
6040 * mch_access() extends access() to do more detailed check on network drives.
6041 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6042 */
6043 int
6044mch_access(char *n, int p)
6045{
6046 HANDLE hFile;
6047 DWORD am;
6048 int retval = -1; /* default: fail */
6049#ifdef FEAT_MBYTE
6050 WCHAR *wn = NULL;
6051
6052 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006053 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054#endif
6055
6056 if (mch_isdir(n))
6057 {
6058 char TempName[_MAX_PATH + 16] = "";
6059#ifdef FEAT_MBYTE
6060 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6061#endif
6062
6063 if (p & R_OK)
6064 {
6065 /* Read check is performed by seeing if we can do a find file on
6066 * the directory for any file. */
6067#ifdef FEAT_MBYTE
6068 if (wn != NULL)
6069 {
6070 int i;
6071 WIN32_FIND_DATAW d;
6072
6073 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6074 TempNameW[i] = wn[i];
6075 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6076 TempNameW[i++] = '\\';
6077 TempNameW[i++] = '*';
6078 TempNameW[i++] = 0;
6079
6080 hFile = FindFirstFileW(TempNameW, &d);
6081 if (hFile == INVALID_HANDLE_VALUE)
6082 {
6083 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6084 goto getout;
6085
6086 /* Retry with non-wide function (for Windows 98). */
6087 vim_free(wn);
6088 wn = NULL;
6089 }
6090 else
6091 (void)FindClose(hFile);
6092 }
6093 if (wn == NULL)
6094#endif
6095 {
6096 char *pch;
6097 WIN32_FIND_DATA d;
6098
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006099 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100 pch = TempName + STRLEN(TempName) - 1;
6101 if (*pch != '\\' && *pch != '/')
6102 *++pch = '\\';
6103 *++pch = '*';
6104 *++pch = NUL;
6105
6106 hFile = FindFirstFile(TempName, &d);
6107 if (hFile == INVALID_HANDLE_VALUE)
6108 goto getout;
6109 (void)FindClose(hFile);
6110 }
6111 }
6112
6113 if (p & W_OK)
6114 {
6115 /* Trying to create a temporary file in the directory should catch
6116 * directories on read-only network shares. However, in
6117 * directories whose ACL allows writes but denies deletes will end
6118 * up keeping the temporary file :-(. */
6119#ifdef FEAT_MBYTE
6120 if (wn != NULL)
6121 {
6122 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6123 {
6124 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6125 goto getout;
6126
6127 /* Retry with non-wide function (for Windows 98). */
6128 vim_free(wn);
6129 wn = NULL;
6130 }
6131 else
6132 DeleteFileW(TempNameW);
6133 }
6134 if (wn == NULL)
6135#endif
6136 {
6137 if (!GetTempFileName(n, "VIM", 0, TempName))
6138 goto getout;
6139 mch_remove((char_u *)TempName);
6140 }
6141 }
6142 }
6143 else
6144 {
6145 /* Trying to open the file for the required access does ACL, read-only
6146 * network share, and file attribute checks. */
6147 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6148 | ((p & R_OK) ? GENERIC_READ : 0);
6149#ifdef FEAT_MBYTE
6150 if (wn != NULL)
6151 {
6152 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6153 if (hFile == INVALID_HANDLE_VALUE
6154 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6155 {
6156 /* Retry with non-wide function (for Windows 98). */
6157 vim_free(wn);
6158 wn = NULL;
6159 }
6160 }
6161 if (wn == NULL)
6162#endif
6163 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6164 if (hFile == INVALID_HANDLE_VALUE)
6165 goto getout;
6166 CloseHandle(hFile);
6167 }
6168
6169 retval = 0; /* success */
6170getout:
6171#ifdef FEAT_MBYTE
6172 vim_free(wn);
6173#endif
6174 return retval;
6175}
6176
6177#if defined(FEAT_MBYTE) || defined(PROTO)
6178/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006179 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180 */
6181 int
6182mch_open(char *name, int flags, int mode)
6183{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006184 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6185# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186 WCHAR *wn;
6187 int f;
6188
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006189 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006190 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006191 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006192 if (wn != NULL)
6193 {
6194 f = _wopen(wn, flags, mode);
6195 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006196 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197 return f;
6198 /* Retry with non-wide function (for Windows 98). Can't use
6199 * GetLastError() here and it's unclear what errno gets set to if
6200 * the _wopen() fails for missing wide functions. */
6201 }
6202 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006203# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006205 /* open() can open a file which name is longer than _MAX_PATH bytes
6206 * and shorter than _MAX_PATH characters successfully, but sometimes it
6207 * causes unexpected error in another part. We make it an error explicitly
6208 * here. */
6209 if (strlen(name) >= _MAX_PATH)
6210 return -1;
6211
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212 return open(name, flags, mode);
6213}
6214
6215/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006216 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217 */
6218 FILE *
6219mch_fopen(char *name, char *mode)
6220{
6221 WCHAR *wn, *wm;
6222 FILE *f = NULL;
6223
6224 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6225# ifdef __BORLANDC__
6226 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6227 && g_PlatformId == VER_PLATFORM_WIN32_NT
6228# endif
6229 )
6230 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006231# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006232 /* Work around an annoying assertion in the Microsoft debug CRT
6233 * when mode's text/binary setting doesn't match _get_fmode(). */
6234 char newMode = mode[strlen(mode) - 1];
6235 int oldMode = 0;
6236
6237 _get_fmode(&oldMode);
6238 if (newMode == 't')
6239 _set_fmode(_O_TEXT);
6240 else if (newMode == 'b')
6241 _set_fmode(_O_BINARY);
6242# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006243 wn = enc_to_utf16(name, NULL);
6244 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245 if (wn != NULL && wm != NULL)
6246 f = _wfopen(wn, wm);
6247 vim_free(wn);
6248 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006249
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006250# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006251 _set_fmode(oldMode);
6252# endif
6253
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006254 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 return f;
6256 /* Retry with non-wide function (for Windows 98). Can't use
6257 * GetLastError() here and it's unclear what errno gets set to if
6258 * the _wfopen() fails for missing wide functions. */
6259 }
6260
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006261 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6262 * and shorter than _MAX_PATH characters successfully, but sometimes it
6263 * causes unexpected error in another part. We make it an error explicitly
6264 * here. */
6265 if (strlen(name) >= _MAX_PATH)
6266 return NULL;
6267
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268 return fopen(name, mode);
6269}
6270#endif
6271
6272#ifdef FEAT_MBYTE
6273/*
6274 * SUB STREAM (aka info stream) handling:
6275 *
6276 * NTFS can have sub streams for each file. Normal contents of file is
6277 * stored in the main stream, and extra contents (author information and
6278 * title and so on) can be stored in sub stream. After Windows 2000, user
6279 * can access and store those informations in sub streams via explorer's
6280 * property menuitem in right click menu. Those informations in sub streams
6281 * were lost when copying only the main stream. So we have to copy sub
6282 * streams.
6283 *
6284 * Incomplete explanation:
6285 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6286 * More useful info and an example:
6287 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6288 */
6289
6290/*
6291 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6292 * and write to stream "substream" of file "to".
6293 * Errors are ignored.
6294 */
6295 static void
6296copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6297{
6298 HANDLE hTo;
6299 WCHAR *to_name;
6300
6301 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6302 wcscpy(to_name, to);
6303 wcscat(to_name, substream);
6304
6305 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6306 FILE_ATTRIBUTE_NORMAL, NULL);
6307 if (hTo != INVALID_HANDLE_VALUE)
6308 {
6309 long done;
6310 DWORD todo;
6311 DWORD readcnt, written;
6312 char buf[4096];
6313
6314 /* Copy block of bytes at a time. Abort when something goes wrong. */
6315 for (done = 0; done < len; done += written)
6316 {
6317 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006318 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6319 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6321 FALSE, FALSE, context)
6322 || readcnt != todo
6323 || !WriteFile(hTo, buf, todo, &written, NULL)
6324 || written != todo)
6325 break;
6326 }
6327 CloseHandle(hTo);
6328 }
6329
6330 free(to_name);
6331}
6332
6333/*
6334 * Copy info streams from file "from" to file "to".
6335 */
6336 static void
6337copy_infostreams(char_u *from, char_u *to)
6338{
6339 WCHAR *fromw;
6340 WCHAR *tow;
6341 HANDLE sh;
6342 WIN32_STREAM_ID sid;
6343 int headersize;
6344 WCHAR streamname[_MAX_PATH];
6345 DWORD readcount;
6346 void *context = NULL;
6347 DWORD lo, hi;
6348 int len;
6349
6350 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006351 fromw = enc_to_utf16(from, NULL);
6352 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006353 if (fromw != NULL && tow != NULL)
6354 {
6355 /* Open the file for reading. */
6356 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6357 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6358 if (sh != INVALID_HANDLE_VALUE)
6359 {
6360 /* Use BackupRead() to find the info streams. Repeat until we
6361 * have done them all.*/
6362 for (;;)
6363 {
6364 /* Get the header to find the length of the stream name. If
6365 * the "readcount" is zero we have done all info streams. */
6366 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006367 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6369 &readcount, FALSE, FALSE, &context)
6370 || readcount == 0)
6371 break;
6372
6373 /* We only deal with streams that have a name. The normal
6374 * file data appears to be without a name, even though docs
6375 * suggest it is called "::$DATA". */
6376 if (sid.dwStreamNameSize > 0)
6377 {
6378 /* Read the stream name. */
6379 if (!BackupRead(sh, (LPBYTE)streamname,
6380 sid.dwStreamNameSize,
6381 &readcount, FALSE, FALSE, &context))
6382 break;
6383
6384 /* Copy an info stream with a name ":anything:$DATA".
6385 * Skip "::$DATA", it has no stream name (examples suggest
6386 * it might be used for the normal file contents).
6387 * Note that BackupRead() counts bytes, but the name is in
6388 * wide characters. */
6389 len = readcount / sizeof(WCHAR);
6390 streamname[len] = 0;
6391 if (len > 7 && wcsicmp(streamname + len - 6,
6392 L":$DATA") == 0)
6393 {
6394 streamname[len - 6] = 0;
6395 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006396 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397 }
6398 }
6399
6400 /* Advance to the next stream. We might try seeking too far,
6401 * but BackupSeek() doesn't skip over stream borders, thus
6402 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006403 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404 &lo, &hi, &context);
6405 }
6406
6407 /* Clear the context. */
6408 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6409
6410 CloseHandle(sh);
6411 }
6412 }
6413 vim_free(fromw);
6414 vim_free(tow);
6415}
6416#endif
6417
6418/*
6419 * Copy file attributes from file "from" to file "to".
6420 * For Windows NT and later we copy info streams.
6421 * Always returns zero, errors are ignored.
6422 */
6423 int
6424mch_copy_file_attribute(char_u *from, char_u *to)
6425{
6426#ifdef FEAT_MBYTE
6427 /* File streams only work on Windows NT and later. */
6428 PlatformId();
6429 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6430 copy_infostreams(from, to);
6431#endif
6432 return 0;
6433}
6434
6435#if defined(MYRESETSTKOFLW) || defined(PROTO)
6436/*
6437 * Recreate a destroyed stack guard page in win32.
6438 * Written by Benjamin Peterson.
6439 */
6440
6441/* These magic numbers are from the MS header files */
6442#define MIN_STACK_WIN9X 17
6443#define MIN_STACK_WINNT 2
6444
6445/*
6446 * This function does the same thing as _resetstkoflw(), which is only
6447 * available in DevStudio .net and later.
6448 * Returns 0 for failure, 1 for success.
6449 */
6450 int
6451myresetstkoflw(void)
6452{
6453 BYTE *pStackPtr;
6454 BYTE *pGuardPage;
6455 BYTE *pStackBase;
6456 BYTE *pLowestPossiblePage;
6457 MEMORY_BASIC_INFORMATION mbi;
6458 SYSTEM_INFO si;
6459 DWORD nPageSize;
6460 DWORD dummy;
6461
6462 /* This code will not work on win32s. */
6463 PlatformId();
6464 if (g_PlatformId == VER_PLATFORM_WIN32s)
6465 return 0;
6466
6467 /* We need to know the system page size. */
6468 GetSystemInfo(&si);
6469 nPageSize = si.dwPageSize;
6470
6471 /* ...and the current stack pointer */
6472 pStackPtr = (BYTE*)_alloca(1);
6473
6474 /* ...and the base of the stack. */
6475 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6476 return 0;
6477 pStackBase = (BYTE*)mbi.AllocationBase;
6478
6479 /* ...and the page thats min_stack_req pages away from stack base; this is
6480 * the lowest page we could use. */
6481 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6482 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6483
6484 /* On Win95, we want the next page down from the end of the stack. */
6485 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6486 {
6487 /* Find the page that's only 1 page down from the page that the stack
6488 * ptr is in. */
6489 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6490 / (DWORD)nPageSize) - 1));
6491 if (pGuardPage < pLowestPossiblePage)
6492 return 0;
6493
6494 /* Apply the noaccess attribute to the page -- there's no guard
6495 * attribute in win95-type OSes. */
6496 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6497 return 0;
6498 }
6499 else
6500 {
6501 /* On NT, however, we want the first committed page in the stack Start
6502 * at the stack base and move forward through memory until we find a
6503 * committed block. */
6504 BYTE *pBlock = pStackBase;
6505
Bram Moolenaara466c992005-07-09 21:03:22 +00006506 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 {
6508 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6509 return 0;
6510
6511 pBlock += mbi.RegionSize;
6512
6513 if (mbi.State & MEM_COMMIT)
6514 break;
6515 }
6516
6517 /* mbi now describes the first committed block in the stack. */
6518 if (mbi.Protect & PAGE_GUARD)
6519 return 1;
6520
6521 /* decide where the guard page should start */
6522 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6523 pGuardPage = pLowestPossiblePage;
6524 else
6525 pGuardPage = (BYTE*)mbi.BaseAddress;
6526
6527 /* allocate the guard page */
6528 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6529 return 0;
6530
6531 /* apply the guard attribute to the page */
6532 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6533 &dummy))
6534 return 0;
6535 }
6536
6537 return 1;
6538}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006539#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006541
6542#if defined(FEAT_MBYTE) || defined(PROTO)
6543/*
6544 * The command line arguments in UCS2
6545 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006546static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006547static LPWSTR *ArglistW = NULL;
6548static int global_argc = 0;
6549static char **global_argv;
6550
6551static int used_file_argc = 0; /* last argument in global_argv[] used
6552 for the argument list. */
6553static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6554 command line arguments added to
6555 the argument list */
6556static int used_file_count = 0; /* nr of entries in used_file_indexes */
6557static int used_file_literal = FALSE; /* take file names literally */
6558static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006559static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006560static int used_alist_count = 0;
6561
6562
6563/*
6564 * Get the command line arguments. Unicode version.
6565 * Returns argc. Zero when something fails.
6566 */
6567 int
6568get_cmd_argsW(char ***argvp)
6569{
6570 char **argv = NULL;
6571 int argc = 0;
6572 int i;
6573
Bram Moolenaar14993322014-09-09 12:25:33 +02006574 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006575 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6576 if (ArglistW != NULL)
6577 {
6578 argv = malloc((nArgsW + 1) * sizeof(char *));
6579 if (argv != NULL)
6580 {
6581 argc = nArgsW;
6582 argv[argc] = NULL;
6583 for (i = 0; i < argc; ++i)
6584 {
6585 int len;
6586
6587 /* Convert each Unicode argument to the current codepage. */
6588 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006589 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006590 (LPSTR *)&argv[i], &len, 0, 0);
6591 if (argv[i] == NULL)
6592 {
6593 /* Out of memory, clear everything. */
6594 while (i > 0)
6595 free(argv[--i]);
6596 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006597 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006598 argc = 0;
6599 }
6600 }
6601 }
6602 }
6603
6604 global_argc = argc;
6605 global_argv = argv;
6606 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006607 {
6608 if (used_file_indexes != NULL)
6609 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006610 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006611 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006612
6613 if (argvp != NULL)
6614 *argvp = argv;
6615 return argc;
6616}
6617
6618 void
6619free_cmd_argsW(void)
6620{
6621 if (ArglistW != NULL)
6622 {
6623 GlobalFree(ArglistW);
6624 ArglistW = NULL;
6625 }
6626}
6627
6628/*
6629 * Remember "name" is an argument that was added to the argument list.
6630 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6631 * is called.
6632 */
6633 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006634used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006635{
6636 int i;
6637
6638 if (used_file_indexes == NULL)
6639 return;
6640 for (i = used_file_argc + 1; i < global_argc; ++i)
6641 if (STRCMP(global_argv[i], name) == 0)
6642 {
6643 used_file_argc = i;
6644 used_file_indexes[used_file_count++] = i;
6645 break;
6646 }
6647 used_file_literal = literal;
6648 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006649 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006650}
6651
6652/*
6653 * Remember the length of the argument list as it was. If it changes then we
6654 * leave it alone when 'encoding' is set.
6655 */
6656 void
6657set_alist_count(void)
6658{
6659 used_alist_count = GARGCOUNT;
6660}
6661
6662/*
6663 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6664 * has been changed while starting up. Use the UCS-2 command line arguments
6665 * and convert them to 'encoding'.
6666 */
6667 void
6668fix_arg_enc(void)
6669{
6670 int i;
6671 int idx;
6672 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006673 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006674
6675 /* Safety checks:
6676 * - if argument count differs between the wide and non-wide argument
6677 * list, something must be wrong.
6678 * - the file name arguments must have been located.
6679 * - the length of the argument list wasn't changed by the user.
6680 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006681 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006682 || ArglistW == NULL
6683 || used_file_indexes == NULL
6684 || used_file_count == 0
6685 || used_alist_count != GARGCOUNT)
6686 return;
6687
Bram Moolenaar86b68352004-12-27 21:59:20 +00006688 /* Remember the buffer numbers for the arguments. */
6689 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6690 if (fnum_list == NULL)
6691 return; /* out of memory */
6692 for (i = 0; i < GARGCOUNT; ++i)
6693 fnum_list[i] = GARGLIST[i].ae_fnum;
6694
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006695 /* Clear the argument list. Make room for the new arguments. */
6696 alist_clear(&global_alist);
6697 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006698 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006699
6700 for (i = 0; i < used_file_count; ++i)
6701 {
6702 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006703 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006704 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006705 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006706#ifdef FEAT_DIFF
6707 /* When using diff mode may need to concatenate file name to
6708 * directory name. Just like it's done in main(). */
6709 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6710 && !mch_isdir(alist_name(&GARGLIST[0])))
6711 {
6712 char_u *r;
6713
6714 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6715 if (r != NULL)
6716 {
6717 vim_free(str);
6718 str = r;
6719 }
6720 }
6721#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006722 /* Re-use the old buffer by renaming it. When not using literal
6723 * names it's done by alist_expand() below. */
6724 if (used_file_literal)
6725 buf_set_name(fnum_list[i], str);
6726
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006727 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006728 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006729 }
6730
6731 if (!used_file_literal)
6732 {
6733 /* Now expand wildcards in the arguments. */
6734 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6735 * filename characters but are excluded from 'isfname' to make
6736 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6737 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006738 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006739 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6740 }
6741
6742 /* If wildcard expansion failed, we are editing the first file of the
6743 * arglist and there is no file name: Edit the first argument now. */
6744 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6745 {
6746 do_cmdline_cmd((char_u *)":rewind");
6747 if (GARGCOUNT == 1 && used_file_full_path)
6748 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6749 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006750
6751 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006752}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753#endif