blob: 5114863faecefea7c160ad98ddcf81a17faddd08 [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 Moolenaarb0262f22015-09-25 15:28:38 +0200237static BOOL is_win7 = FALSE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100238static BOOL win8_or_later = FALSE;
239
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100240/*
241 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100242 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100243 */
244 static BOOL
245read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100246 HANDLE hInput,
247 INPUT_RECORD *lpBuffer,
248 DWORD nLength,
249 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100250{
251 enum
252 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100253 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100254 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100255 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100256 static DWORD s_dwIndex = 0;
257 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100258 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100259 int head;
260 int tail;
261 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100262
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200263 if (nLength == -2)
264 return (s_dwMax > 0) ? TRUE : FALSE;
265
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100266 if (!win8_or_later)
267 {
268 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200269 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
270 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100271 }
272
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100273 if (s_dwMax == 0)
274 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100275 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200276 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
277 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100278 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100279 s_dwIndex = 0;
280 s_dwMax = dwEvents;
281 if (dwEvents == 0)
282 {
283 *lpEvents = 0;
284 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100286
287 if (s_dwMax > 1)
288 {
289 head = 0;
290 tail = s_dwMax - 1;
291 while (head != tail)
292 {
293 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
294 && s_irCache[head + 1].EventType
295 == WINDOW_BUFFER_SIZE_EVENT)
296 {
297 /* Remove duplicate event to avoid flicker. */
298 for (i = head; i < tail; ++i)
299 s_irCache[i] = s_irCache[i + 1];
300 --tail;
301 continue;
302 }
303 head++;
304 }
305 s_dwMax = tail + 1;
306 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100307 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100308
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100309 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200310 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100311 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100312 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100313 return TRUE;
314}
315
316/*
317 * Version of PeekConsoleInput() that works with IME.
318 */
319 static BOOL
320peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100321 HANDLE hInput,
322 INPUT_RECORD *lpBuffer,
323 DWORD nLength,
324 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100326 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100327}
328
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200329 static DWORD
330msg_wait_for_multiple_objects(
331 DWORD nCount,
332 LPHANDLE pHandles,
333 BOOL fWaitAll,
334 DWORD dwMilliseconds,
335 DWORD dwWakeMask)
336{
337 if (read_console_input(NULL, NULL, -2, NULL))
338 return WAIT_OBJECT_0;
339 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
340 dwMilliseconds, dwWakeMask);
341}
342
343 static DWORD
344wait_for_single_object(
345 HANDLE hHandle,
346 DWORD dwMilliseconds)
347{
348 if (read_console_input(NULL, NULL, -2, NULL))
349 return WAIT_OBJECT_0;
350 return WaitForSingleObject(hHandle, dwMilliseconds);
351}
352
Bram Moolenaar071d4272004-06-13 20:20:40 +0000353 static void
354get_exe_name(void)
355{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100356 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
357 * as the maximum length that works (plus a NUL byte). */
358#define MAX_ENV_PATH_LEN 8192
359 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200360 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000361
362 if (exe_name == NULL)
363 {
364 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100365 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366 if (*temp != NUL)
367 exe_name = FullName_save((char_u *)temp, FALSE);
368 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000369
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200370 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000371 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200372 exe_path = vim_strnsave(exe_name,
373 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200374 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000375 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200376 /* Append our starting directory to $PATH, so that when doing
377 * "!xxd" it's found in our starting directory. Needed because
378 * SearchPath() also looks there. */
379 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100380 if (p == NULL
381 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200382 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100383 if (p == NULL || *p == NUL)
384 temp[0] = NUL;
385 else
386 {
387 STRCPY(temp, p);
388 STRCAT(temp, ";");
389 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200390 STRCAT(temp, exe_path);
391 vim_setenv((char_u *)"PATH", temp);
392 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000393 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000394 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000395}
396
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200397/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100398 * Unescape characters in "p" that appear in "escaped".
399 */
400 static void
401unescape_shellxquote(char_u *p, char_u *escaped)
402{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100403 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100404 int n;
405
406 while (*p != NUL)
407 {
408 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
409 mch_memmove(p, p + 1, l--);
410#ifdef FEAT_MBYTE
411 n = (*mb_ptr2len)(p);
412#else
413 n = 1;
414#endif
415 p += n;
416 l -= n;
417 }
418}
419
420/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200421 * Load library "name".
422 */
423 HINSTANCE
424vimLoadLib(char *name)
425{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200426 HINSTANCE dll = NULL;
427 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200428
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200429 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
430 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200431 if (exe_path == NULL)
432 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200433 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200434 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200435#ifdef FEAT_MBYTE
436 WCHAR old_dirw[MAXPATHL];
437
438 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
439 {
440 /* Change directory to where the executable is, both to make
441 * sure we find a .dll there and to avoid looking for a .dll
442 * in the current directory. */
443 SetCurrentDirectory(exe_path);
444 dll = LoadLibrary(name);
445 SetCurrentDirectoryW(old_dirw);
446 return dll;
447 }
448 /* Retry with non-wide function (for Windows 98). */
449 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
450#endif
451 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
452 {
453 /* Change directory to where the executable is, both to make
454 * sure we find a .dll there and to avoid looking for a .dll
455 * in the current directory. */
456 SetCurrentDirectory(exe_path);
457 dll = LoadLibrary(name);
458 SetCurrentDirectory(old_dir);
459 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200460 }
461 return dll;
462}
463
Bram Moolenaar071d4272004-06-13 20:20:40 +0000464#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
465# ifndef GETTEXT_DLL
466# define GETTEXT_DLL "libintl.dll"
467# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200468/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000469static char *null_libintl_gettext(const char *);
470static char *null_libintl_textdomain(const char *);
471static char *null_libintl_bindtextdomain(const char *, const char *);
472static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000475char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
476char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
477char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000479char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
480 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481
482 int
483dyn_libintl_init(char *libname)
484{
485 int i;
486 static struct
487 {
488 char *name;
489 FARPROC *ptr;
490 } libintl_entry[] =
491 {
492 {"gettext", (FARPROC*)&dyn_libintl_gettext},
493 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
494 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
495 {NULL, NULL}
496 };
497
498 /* No need to initialize twice. */
499 if (hLibintlDLL)
500 return 1;
501 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200502 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503 if (!hLibintlDLL)
504 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200505 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200507 verbose_enter();
508 EMSG2(_(e_loadlib), GETTEXT_DLL);
509 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200511 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512 }
513 for (i = 0; libintl_entry[i].name != NULL
514 && libintl_entry[i].ptr != NULL; ++i)
515 {
516 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
517 libintl_entry[i].name)) == NULL)
518 {
519 dyn_libintl_end();
520 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000521 {
522 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000524 verbose_leave();
525 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526 return 0;
527 }
528 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000529
530 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000531 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000532 "bind_textdomain_codeset");
533 if (dyn_libintl_bind_textdomain_codeset == NULL)
534 dyn_libintl_bind_textdomain_codeset =
535 null_libintl_bind_textdomain_codeset;
536
Bram Moolenaar071d4272004-06-13 20:20:40 +0000537 return 1;
538}
539
540 void
541dyn_libintl_end()
542{
543 if (hLibintlDLL)
544 FreeLibrary(hLibintlDLL);
545 hLibintlDLL = NULL;
546 dyn_libintl_gettext = null_libintl_gettext;
547 dyn_libintl_textdomain = null_libintl_textdomain;
548 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000549 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000550}
551
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000552/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000553 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000554null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555{
556 return (char*)msgid;
557}
558
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000559/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000561null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000562{
563 return NULL;
564}
565
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000566/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000567 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000568null_libintl_bind_textdomain_codeset(const char *domainname,
569 const char *codeset)
570{
571 return NULL;
572}
573
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000574/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000575 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000576null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577{
578 return NULL;
579}
580
581#endif /* DYNAMIC_GETTEXT */
582
583/* This symbol is not defined in older versions of the SDK or Visual C++ */
584
585#ifndef VER_PLATFORM_WIN32_WINDOWS
586# define VER_PLATFORM_WIN32_WINDOWS 1
587#endif
588
589DWORD g_PlatformId;
590
591#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100592# ifndef PROTO
593# include <aclapi.h>
594# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200595# ifndef PROTECTED_DACL_SECURITY_INFORMATION
596# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
597# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100598
Bram Moolenaar071d4272004-06-13 20:20:40 +0000599/*
600 * These are needed to dynamically load the ADVAPI DLL, which is not
601 * implemented under Windows 95 (and causes VIM to crash)
602 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200603typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000604 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200605typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
607 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200608# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200609typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200610 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200611typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200612 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
613 PSECURITY_DESCRIPTOR *);
614# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615
616static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
617static PSNSECINFO pSetNamedSecurityInfo;
618static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200619# ifdef FEAT_MBYTE
620static PSNSECINFOW pSetNamedSecurityInfoW;
621static PGNSECINFOW pGetNamedSecurityInfoW;
622# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623#endif
624
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200625typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
626
627static BOOL allowPiping = FALSE;
628static PSETHANDLEINFORMATION pSetHandleInformation;
629
Bram Moolenaar27515922013-06-29 15:36:26 +0200630#ifdef HAVE_ACL
631/*
632 * Enables or disables the specified privilege.
633 */
634 static BOOL
635win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
636{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100637 BOOL bResult;
638 LUID luid;
639 HANDLE hToken;
640 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200641
642 if (!OpenProcessToken(GetCurrentProcess(),
643 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
644 return FALSE;
645
646 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
647 {
648 CloseHandle(hToken);
649 return FALSE;
650 }
651
Bram Moolenaar45500912014-07-09 20:51:07 +0200652 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200653 tokenPrivileges.Privileges[0].Luid = luid;
654 tokenPrivileges.Privileges[0].Attributes = bEnable ?
655 SE_PRIVILEGE_ENABLED : 0;
656
657 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
658 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
659
660 CloseHandle(hToken);
661
662 return bResult && GetLastError() == ERROR_SUCCESS;
663}
664#endif
665
Bram Moolenaar071d4272004-06-13 20:20:40 +0000666/*
667 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
668 * VER_PLATFORM_WIN32_WINDOWS (Win95).
669 */
670 void
671PlatformId(void)
672{
673 static int done = FALSE;
674
675 if (!done)
676 {
677 OSVERSIONINFO ovi;
678
679 ovi.dwOSVersionInfoSize = sizeof(ovi);
680 GetVersionEx(&ovi);
681
682 g_PlatformId = ovi.dwPlatformId;
683
Bram Moolenaarb0262f22015-09-25 15:28:38 +0200684 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion == 1))
685 is_win7 = TRUE;
686
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100687 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
688 || ovi.dwMajorVersion > 6)
689 win8_or_later = TRUE;
690
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691#ifdef HAVE_ACL
692 /*
693 * Load the ADVAPI runtime if we are on anything
694 * other than Windows 95
695 */
696 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
697 {
698 /*
699 * do this load. Problems: Doesn't unload at end of run (this is
700 * theoretically okay, since Windows should unload it when VIM
701 * terminates). Should we be using the 'mch_libcall' routines?
702 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
703 * time we verify security...
704 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200705 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000706 if (advapi_lib != NULL)
707 {
708 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
709 "SetNamedSecurityInfoA");
710 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
711 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200712# ifdef FEAT_MBYTE
713 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
714 "SetNamedSecurityInfoW");
715 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
716 "GetNamedSecurityInfoW");
717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200719 || pGetNamedSecurityInfo == NULL
720# ifdef FEAT_MBYTE
721 || pSetNamedSecurityInfoW == NULL
722 || pGetNamedSecurityInfoW == NULL
723# endif
724 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 {
726 /* If we can't get the function addresses, set advapi_lib
727 * to NULL so that we don't use them. */
728 FreeLibrary(advapi_lib);
729 advapi_lib = NULL;
730 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200731 /* Enable privilege for getting or setting SACLs. */
732 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000733 }
734 }
735#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200736 /*
737 * If we are on windows NT, try to load the pipe functions, only
738 * available from Win2K.
739 */
740 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
741 {
742 HANDLE kernel32 = GetModuleHandle("kernel32");
743 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
744 kernel32, "SetHandleInformation");
745
746 allowPiping = pSetHandleInformation != NULL;
747 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 done = TRUE;
749 }
750}
751
752/*
753 * Return TRUE when running on Windows 95 (or 98 or ME).
754 * Only to be used after mch_init().
755 */
756 int
757mch_windows95(void)
758{
759 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
760}
761
762#ifdef FEAT_GUI_W32
763/*
764 * Used to work around the "can't do synchronous spawn"
765 * problem on Win32s, without resorting to Universal Thunk.
766 */
767static int old_num_windows;
768static int num_windows;
769
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000770/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771 static BOOL CALLBACK
772win32ssynch_cb(HWND hwnd, LPARAM lparam)
773{
774 num_windows++;
775 return TRUE;
776}
777#endif
778
779#ifndef FEAT_GUI_W32
780
781#define SHIFT (SHIFT_PRESSED)
782#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
783#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
784#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
785
786
787/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
788 * We map function keys to their ANSI terminal equivalents, as produced
789 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
790 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
791 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
792 * combinations of function/arrow/etc keys.
793 */
794
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000795static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796{
797 WORD wVirtKey;
798 BOOL fAnsiKey;
799 int chAlone;
800 int chShift;
801 int chCtrl;
802 int chAlt;
803} VirtKeyMap[] =
804{
805
806/* Key ANSI alone shift ctrl alt */
807 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
808
809 { VK_F1, TRUE, ';', 'T', '^', 'h', },
810 { VK_F2, TRUE, '<', 'U', '_', 'i', },
811 { VK_F3, TRUE, '=', 'V', '`', 'j', },
812 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
813 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
814 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
815 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
816 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
817 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
818 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
819 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
820 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
821
822 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
823 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
824 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
825 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
826 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
827 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
828 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
829 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
830 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
831 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
832
833 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
834
835#if 0
836 /* Most people don't have F13-F20, but what the hell... */
837 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
838 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
839 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
840 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
841 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
842 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
843 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
844 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
845#endif
846 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
847 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
848 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
849 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
850
851 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
852 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
853 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
854 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
855 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
856 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
857 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
858 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
859 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
860 /* Sorry, out of number space! <negri>*/
861 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
862
863};
864
865
866#ifdef _MSC_VER
867// The ToAscii bug destroys several registers. Need to turn off optimization
868// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000869# pragma warning(push)
870# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871# pragma optimize("", off)
872#endif
873
874#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200875# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200877# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878#endif
879
880/* The return code indicates key code size. */
881 static int
882#ifdef __BORLANDC__
883 __stdcall
884#endif
885win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000886 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887{
888 UINT uMods = pker->dwControlKeyState;
889 static int s_iIsDead = 0;
890 static WORD awAnsiCode[2];
891 static BYTE abKeystate[256];
892
893
894 if (s_iIsDead == 2)
895 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200896 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897 s_iIsDead = 0;
898 return 1;
899 }
900
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200901 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902 return 1;
903
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200904 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905
906 // Should only be non-NULL on NT 4.0
907 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
908 {
909 CHAR szKLID[KL_NAMELENGTH];
910
911 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
912 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
913 }
914
915 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200916 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917
918 if (uMods & SHIFT_PRESSED)
919 abKeystate[VK_SHIFT] = 0x80;
920 if (uMods & CAPSLOCK_ON)
921 abKeystate[VK_CAPITAL] = 1;
922
923 if ((uMods & ALT_GR) == ALT_GR)
924 {
925 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
926 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
927 }
928
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200929 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
930 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931
932 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200933 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934
935 return s_iIsDead;
936}
937
938#ifdef _MSC_VER
939/* MUST switch optimization on again here, otherwise a call to
940 * decode_key_event() may crash (e.g. when hitting caps-lock) */
941# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000942# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000943
944# if (_MSC_VER < 1100)
945/* MUST turn off global optimisation for this next function, or
946 * pressing ctrl-minus in insert mode crashes Vim when built with
947 * VC4.1. -- negri. */
948# pragma optimize("g", off)
949# endif
950#endif
951
952static BOOL g_fJustGotFocus = FALSE;
953
954/*
955 * Decode a KEY_EVENT into one or two keystrokes
956 */
957 static BOOL
958decode_key_event(
959 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200960 WCHAR *pch,
961 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962 int *pmodifiers,
963 BOOL fDoPost)
964{
965 int i;
966 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
967
968 *pch = *pch2 = NUL;
969 g_fJustGotFocus = FALSE;
970
971 /* ignore key up events */
972 if (!pker->bKeyDown)
973 return FALSE;
974
975 /* ignore some keystrokes */
976 switch (pker->wVirtualKeyCode)
977 {
978 /* modifiers */
979 case VK_SHIFT:
980 case VK_CONTROL:
981 case VK_MENU: /* Alt key */
982 return FALSE;
983
984 default:
985 break;
986 }
987
988 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200989 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990 {
991 /* Ctrl-6 is Ctrl-^ */
992 if (pker->wVirtualKeyCode == '6')
993 {
994 *pch = Ctrl_HAT;
995 return TRUE;
996 }
997 /* Ctrl-2 is Ctrl-@ */
998 else if (pker->wVirtualKeyCode == '2')
999 {
1000 *pch = NUL;
1001 return TRUE;
1002 }
1003 /* Ctrl-- is Ctrl-_ */
1004 else if (pker->wVirtualKeyCode == 0xBD)
1005 {
1006 *pch = Ctrl__;
1007 return TRUE;
1008 }
1009 }
1010
1011 /* Shift-TAB */
1012 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1013 {
1014 *pch = K_NUL;
1015 *pch2 = '\017';
1016 return TRUE;
1017 }
1018
1019 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1020 {
1021 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1022 {
1023 if (nModifs == 0)
1024 *pch = VirtKeyMap[i].chAlone;
1025 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1026 *pch = VirtKeyMap[i].chShift;
1027 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1028 *pch = VirtKeyMap[i].chCtrl;
1029 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1030 *pch = VirtKeyMap[i].chAlt;
1031
1032 if (*pch != 0)
1033 {
1034 if (VirtKeyMap[i].fAnsiKey)
1035 {
1036 *pch2 = *pch;
1037 *pch = K_NUL;
1038 }
1039
1040 return TRUE;
1041 }
1042 }
1043 }
1044
1045 i = win32_kbd_patch_key(pker);
1046
1047 if (i < 0)
1048 *pch = NUL;
1049 else
1050 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001051 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001052
1053 if (pmodifiers != NULL)
1054 {
1055 /* Pass on the ALT key as a modifier, but only when not combined
1056 * with CTRL (which is ALTGR). */
1057 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1058 *pmodifiers |= MOD_MASK_ALT;
1059
1060 /* Pass on SHIFT only for special keys, because we don't know when
1061 * it's already included with the character. */
1062 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1063 *pmodifiers |= MOD_MASK_SHIFT;
1064
1065 /* Pass on CTRL only for non-special keys, because we don't know
1066 * when it's already included with the character. And not when
1067 * combined with ALT (which is ALTGR). */
1068 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1069 && *pch >= 0x20 && *pch < 0x80)
1070 *pmodifiers |= MOD_MASK_CTRL;
1071 }
1072 }
1073
1074 return (*pch != NUL);
1075}
1076
1077#ifdef _MSC_VER
1078# pragma optimize("", on)
1079#endif
1080
1081#endif /* FEAT_GUI_W32 */
1082
1083
1084#ifdef FEAT_MOUSE
1085
1086/*
1087 * For the GUI the mouse handling is in gui_w32.c.
1088 */
1089# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001090/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001092mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093{
1094}
1095# else
1096static int g_fMouseAvail = FALSE; /* mouse present */
1097static int g_fMouseActive = FALSE; /* mouse enabled */
1098static int g_nMouseClick = -1; /* mouse status */
1099static int g_xMouse; /* mouse x coordinate */
1100static int g_yMouse; /* mouse y coordinate */
1101
1102/*
1103 * Enable or disable mouse input
1104 */
1105 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001106mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107{
1108 DWORD cmodein;
1109
1110 if (!g_fMouseAvail)
1111 return;
1112
1113 g_fMouseActive = on;
1114 GetConsoleMode(g_hConIn, &cmodein);
1115
1116 if (g_fMouseActive)
1117 cmodein |= ENABLE_MOUSE_INPUT;
1118 else
1119 cmodein &= ~ENABLE_MOUSE_INPUT;
1120
1121 SetConsoleMode(g_hConIn, cmodein);
1122}
1123
1124
1125/*
1126 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1127 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1128 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1129 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1130 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1131 * and we return the mouse position in g_xMouse and g_yMouse.
1132 *
1133 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1134 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1135 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1136 *
1137 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1138 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1139 *
1140 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1141 * moves, even if it stays within the same character cell. We ignore
1142 * all MOUSE_MOVED messages if the position hasn't really changed, and
1143 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1144 * we're only interested in MOUSE_DRAG).
1145 *
1146 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1147 * 2-button mouses by pressing the left & right buttons simultaneously.
1148 * In practice, it's almost impossible to click both at the same time,
1149 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1150 * in such cases, if the user is clicking quickly.
1151 */
1152 static BOOL
1153decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001154 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155{
1156 static int s_nOldButton = -1;
1157 static int s_nOldMouseClick = -1;
1158 static int s_xOldMouse = -1;
1159 static int s_yOldMouse = -1;
1160 static linenr_T s_old_topline = 0;
1161#ifdef FEAT_DIFF
1162 static int s_old_topfill = 0;
1163#endif
1164 static int s_cClicks = 1;
1165 static BOOL s_fReleased = TRUE;
1166 static DWORD s_dwLastClickTime = 0;
1167 static BOOL s_fNextIsMiddle = FALSE;
1168
1169 static DWORD cButtons = 0; /* number of buttons supported */
1170
1171 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1172 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1173 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1174 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1175
1176 int nButton;
1177
1178 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1179 cButtons = 2;
1180
1181 if (!g_fMouseAvail || !g_fMouseActive)
1182 {
1183 g_nMouseClick = -1;
1184 return FALSE;
1185 }
1186
1187 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1188 if (g_fJustGotFocus)
1189 {
1190 g_fJustGotFocus = FALSE;
1191 return FALSE;
1192 }
1193
1194 /* unprocessed mouse click? */
1195 if (g_nMouseClick != -1)
1196 return TRUE;
1197
1198 nButton = -1;
1199 g_xMouse = pmer->dwMousePosition.X;
1200 g_yMouse = pmer->dwMousePosition.Y;
1201
1202 if (pmer->dwEventFlags == MOUSE_MOVED)
1203 {
1204 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1205 * events even when the mouse moves only within a char cell.) */
1206 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1207 return FALSE;
1208 }
1209
1210 /* If no buttons are pressed... */
1211 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1212 {
1213 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1214 if (s_fReleased)
1215 return FALSE;
1216
1217 nButton = MOUSE_RELEASE;
1218 s_fReleased = TRUE;
1219 }
1220 else /* one or more buttons pressed */
1221 {
1222 /* on a 2-button mouse, hold down left and right buttons
1223 * simultaneously to get MIDDLE. */
1224
1225 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1226 {
1227 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1228
1229 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001230 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231 if (dwLR == LEFT || dwLR == RIGHT)
1232 {
1233 for (;;)
1234 {
1235 /* wait a short time for next input event */
1236 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1237 != WAIT_OBJECT_0)
1238 break;
1239 else
1240 {
1241 DWORD cRecords = 0;
1242 INPUT_RECORD ir;
1243 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1244
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001245 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246
1247 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1248 || !(pmer2->dwButtonState & LEFT_RIGHT))
1249 break;
1250 else
1251 {
1252 if (pmer2->dwEventFlags != MOUSE_MOVED)
1253 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001254 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255
1256 return decode_mouse_event(pmer2);
1257 }
1258 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1259 s_yOldMouse == pmer2->dwMousePosition.Y)
1260 {
1261 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001262 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001263
1264 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001265 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266
1267 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1268 break;
1269 }
1270 else
1271 break;
1272 }
1273 }
1274 }
1275 }
1276 }
1277
1278 if (s_fNextIsMiddle)
1279 {
1280 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1281 ? MOUSE_DRAG : MOUSE_MIDDLE;
1282 s_fNextIsMiddle = FALSE;
1283 }
1284 else if (cButtons == 2 &&
1285 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1286 {
1287 nButton = MOUSE_MIDDLE;
1288
1289 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1290 {
1291 s_fNextIsMiddle = TRUE;
1292 nButton = MOUSE_RELEASE;
1293 }
1294 }
1295 else if ((pmer->dwButtonState & LEFT) == LEFT)
1296 nButton = MOUSE_LEFT;
1297 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1298 nButton = MOUSE_MIDDLE;
1299 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1300 nButton = MOUSE_RIGHT;
1301
1302 if (! s_fReleased && ! s_fNextIsMiddle
1303 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1304 return FALSE;
1305
1306 s_fReleased = s_fNextIsMiddle;
1307 }
1308
1309 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1310 {
1311 /* button pressed or released, without mouse moving */
1312 if (nButton != -1 && nButton != MOUSE_RELEASE)
1313 {
1314 DWORD dwCurrentTime = GetTickCount();
1315
1316 if (s_xOldMouse != g_xMouse
1317 || s_yOldMouse != g_yMouse
1318 || s_nOldButton != nButton
1319 || s_old_topline != curwin->w_topline
1320#ifdef FEAT_DIFF
1321 || s_old_topfill != curwin->w_topfill
1322#endif
1323 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1324 {
1325 s_cClicks = 1;
1326 }
1327 else if (++s_cClicks > 4)
1328 {
1329 s_cClicks = 1;
1330 }
1331
1332 s_dwLastClickTime = dwCurrentTime;
1333 }
1334 }
1335 else if (pmer->dwEventFlags == MOUSE_MOVED)
1336 {
1337 if (nButton != -1 && nButton != MOUSE_RELEASE)
1338 nButton = MOUSE_DRAG;
1339
1340 s_cClicks = 1;
1341 }
1342
1343 if (nButton == -1)
1344 return FALSE;
1345
1346 if (nButton != MOUSE_RELEASE)
1347 s_nOldButton = nButton;
1348
1349 g_nMouseClick = nButton;
1350
1351 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1352 g_nMouseClick |= MOUSE_SHIFT;
1353 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1354 g_nMouseClick |= MOUSE_CTRL;
1355 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1356 g_nMouseClick |= MOUSE_ALT;
1357
1358 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1359 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1360
1361 /* only pass on interesting (i.e., different) mouse events */
1362 if (s_xOldMouse == g_xMouse
1363 && s_yOldMouse == g_yMouse
1364 && s_nOldMouseClick == g_nMouseClick)
1365 {
1366 g_nMouseClick = -1;
1367 return FALSE;
1368 }
1369
1370 s_xOldMouse = g_xMouse;
1371 s_yOldMouse = g_yMouse;
1372 s_old_topline = curwin->w_topline;
1373#ifdef FEAT_DIFF
1374 s_old_topfill = curwin->w_topfill;
1375#endif
1376 s_nOldMouseClick = g_nMouseClick;
1377
1378 return TRUE;
1379}
1380
1381# endif /* FEAT_GUI_W32 */
1382#endif /* FEAT_MOUSE */
1383
1384
1385#ifdef MCH_CURSOR_SHAPE
1386/*
1387 * Set the shape of the cursor.
1388 * 'thickness' can be from 1 (thin) to 99 (block)
1389 */
1390 static void
1391mch_set_cursor_shape(int thickness)
1392{
1393 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1394 ConsoleCursorInfo.dwSize = thickness;
1395 ConsoleCursorInfo.bVisible = s_cursor_visible;
1396
1397 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1398 if (s_cursor_visible)
1399 SetConsoleCursorPosition(g_hConOut, g_coord);
1400}
1401
1402 void
1403mch_update_cursor(void)
1404{
1405 int idx;
1406 int thickness;
1407
1408 /*
1409 * How the cursor is drawn depends on the current mode.
1410 */
1411 idx = get_shape_idx(FALSE);
1412
1413 if (shape_table[idx].shape == SHAPE_BLOCK)
1414 thickness = 99; /* 100 doesn't work on W95 */
1415 else
1416 thickness = shape_table[idx].percentage;
1417 mch_set_cursor_shape(thickness);
1418}
1419#endif
1420
1421#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1422/*
1423 * Handle FOCUS_EVENT.
1424 */
1425 static void
1426handle_focus_event(INPUT_RECORD ir)
1427{
1428 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1429 ui_focus_change((int)g_fJustGotFocus);
1430}
1431
1432/*
1433 * Wait until console input from keyboard or mouse is available,
1434 * or the time is up.
1435 * Return TRUE if something is available FALSE if not.
1436 */
1437 static int
1438WaitForChar(long msec)
1439{
1440 DWORD dwNow = 0, dwEndTime = 0;
1441 INPUT_RECORD ir;
1442 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001443 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001444
1445 if (msec > 0)
1446 /* Wait until the specified time has elapsed. */
1447 dwEndTime = GetTickCount() + msec;
1448 else if (msec < 0)
1449 /* Wait forever. */
1450 dwEndTime = INFINITE;
1451
1452 /* We need to loop until the end of the time period, because
1453 * we might get multiple unusable mouse events in that time.
1454 */
1455 for (;;)
1456 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001457#ifdef FEAT_MZSCHEME
1458 mzvim_check_threads();
1459#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460#ifdef FEAT_CLIENTSERVER
1461 serverProcessPendingMessages();
1462#endif
1463 if (0
1464#ifdef FEAT_MOUSE
1465 || g_nMouseClick != -1
1466#endif
1467#ifdef FEAT_CLIENTSERVER
1468 || input_available()
1469#endif
1470 )
1471 return TRUE;
1472
1473 if (msec > 0)
1474 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001475 /* If the specified wait time has passed, return. Beware that
1476 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001477 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001478 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479 break;
1480 }
1481 if (msec != 0)
1482 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001483 DWORD dwWaitTime = dwEndTime - dwNow;
1484
1485#ifdef FEAT_MZSCHEME
1486 if (mzthreads_allowed() && p_mzq > 0
1487 && (msec < 0 || (long)dwWaitTime > p_mzq))
1488 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1489#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490#ifdef FEAT_CLIENTSERVER
1491 /* Wait for either an event on the console input or a message in
1492 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001493 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001494 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001496 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497#endif
1498 continue;
1499 }
1500
1501 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001502 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503
1504#ifdef FEAT_MBYTE_IME
1505 if (State & CMDLINE && msg_row == Rows - 1)
1506 {
1507 CONSOLE_SCREEN_BUFFER_INFO csbi;
1508
1509 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1510 {
1511 if (csbi.dwCursorPosition.Y != msg_row)
1512 {
1513 /* The screen is now messed up, must redraw the
1514 * command line and later all the windows. */
1515 redraw_all_later(CLEAR);
1516 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1517 redrawcmd();
1518 }
1519 }
1520 }
1521#endif
1522
1523 if (cRecords > 0)
1524 {
1525 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1526 {
1527#ifdef FEAT_MBYTE_IME
1528 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1529 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001530 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1532 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001533 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 continue;
1535 }
1536#endif
1537 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1538 NULL, FALSE))
1539 return TRUE;
1540 }
1541
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001542 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543
1544 if (ir.EventType == FOCUS_EVENT)
1545 handle_focus_event(ir);
1546 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1547 shell_resized();
1548#ifdef FEAT_MOUSE
1549 else if (ir.EventType == MOUSE_EVENT
1550 && decode_mouse_event(&ir.Event.MouseEvent))
1551 return TRUE;
1552#endif
1553 }
1554 else if (msec == 0)
1555 break;
1556 }
1557
1558#ifdef FEAT_CLIENTSERVER
1559 /* Something might have been received while we were waiting. */
1560 if (input_available())
1561 return TRUE;
1562#endif
1563 return FALSE;
1564}
1565
1566#ifndef FEAT_GUI_MSWIN
1567/*
1568 * return non-zero if a character is available
1569 */
1570 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001571mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572{
1573 return WaitForChar(0L);
1574}
1575#endif
1576
1577/*
1578 * Create the console input. Used when reading stdin doesn't work.
1579 */
1580 static void
1581create_conin(void)
1582{
1583 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1584 FILE_SHARE_READ|FILE_SHARE_WRITE,
1585 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001586 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587 did_create_conin = TRUE;
1588}
1589
1590/*
1591 * Get a keystroke or a mouse event
1592 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001593 static WCHAR
1594tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001596 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597
1598 for (;;)
1599 {
1600 INPUT_RECORD ir;
1601 DWORD cRecords = 0;
1602
1603#ifdef FEAT_CLIENTSERVER
1604 (void)WaitForChar(-1L);
1605 if (input_available())
1606 return 0;
1607# ifdef FEAT_MOUSE
1608 if (g_nMouseClick != -1)
1609 return 0;
1610# endif
1611#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001612 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 {
1614 if (did_create_conin)
1615 read_error_exit();
1616 create_conin();
1617 continue;
1618 }
1619
1620 if (ir.EventType == KEY_EVENT)
1621 {
1622 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1623 pmodifiers, TRUE))
1624 return ch;
1625 }
1626 else if (ir.EventType == FOCUS_EVENT)
1627 handle_focus_event(ir);
1628 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1629 shell_resized();
1630#ifdef FEAT_MOUSE
1631 else if (ir.EventType == MOUSE_EVENT)
1632 {
1633 if (decode_mouse_event(&ir.Event.MouseEvent))
1634 return 0;
1635 }
1636#endif
1637 }
1638}
1639#endif /* !FEAT_GUI_W32 */
1640
1641
1642/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001643 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644 * Get one or more characters from the keyboard or the mouse.
1645 * If time == 0, do not wait for characters.
1646 * If time == n, wait a short time for characters.
1647 * If time == -1, wait forever for characters.
1648 * Returns the number of characters read into buf.
1649 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001650/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651 int
1652mch_inchar(
1653 char_u *buf,
1654 int maxlen,
1655 long time,
1656 int tb_change_cnt)
1657{
1658#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1659
1660 int len;
1661 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662#define TYPEAHEADLEN 20
1663 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1664 static int typeaheadlen = 0;
1665
1666 /* First use any typeahead that was kept because "buf" was too small. */
1667 if (typeaheadlen > 0)
1668 goto theend;
1669
1670#ifdef FEAT_SNIFF
1671 if (want_sniff_request)
1672 {
1673 if (sniff_request_waiting)
1674 {
1675 /* return K_SNIFF */
1676 typeahead[typeaheadlen++] = CSI;
1677 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1678 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1679 sniff_request_waiting = 0;
1680 want_sniff_request = 0;
1681 goto theend;
1682 }
1683 else if (time < 0 || time > 250)
1684 {
1685 /* don't wait too long, a request might be pending */
1686 time = 250;
1687 }
1688 }
1689#endif
1690
1691 if (time >= 0)
1692 {
1693 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695 }
1696 else /* time == -1, wait forever */
1697 {
1698 mch_set_winsize_now(); /* Allow winsize changes from now on */
1699
Bram Moolenaar3918c952005-03-15 22:34:55 +00001700 /*
1701 * If there is no character available within 2 seconds (default)
1702 * write the autoscript file to disk. Or cause the CursorHold event
1703 * to be triggered.
1704 */
1705 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 {
1707#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001708 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001710 buf[0] = K_SPECIAL;
1711 buf[1] = KS_EXTRA;
1712 buf[2] = (int)KE_CURSORHOLD;
1713 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 }
1715#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001716 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 }
1718 }
1719
1720 /*
1721 * Try to read as many characters as there are, until the buffer is full.
1722 */
1723
1724 /* we will get at least one key. Get more if they are available. */
1725 g_fCBrkPressed = FALSE;
1726
1727#ifdef MCH_WRITE_DUMP
1728 if (fdDump)
1729 fputc('[', fdDump);
1730#endif
1731
1732 /* Keep looping until there is something in the typeahead buffer and more
1733 * to get and still room in the buffer (up to two bytes for a char and
1734 * three bytes for a modifier). */
1735 while ((typeaheadlen == 0 || WaitForChar(0L))
1736 && typeaheadlen + 5 <= TYPEAHEADLEN)
1737 {
1738 if (typebuf_changed(tb_change_cnt))
1739 {
1740 /* "buf" may be invalid now if a client put something in the
1741 * typeahead buffer and "buf" is in the typeahead buffer. */
1742 typeaheadlen = 0;
1743 break;
1744 }
1745#ifdef FEAT_MOUSE
1746 if (g_nMouseClick != -1)
1747 {
1748# ifdef MCH_WRITE_DUMP
1749 if (fdDump)
1750 fprintf(fdDump, "{%02x @ %d, %d}",
1751 g_nMouseClick, g_xMouse, g_yMouse);
1752# endif
1753 typeahead[typeaheadlen++] = ESC + 128;
1754 typeahead[typeaheadlen++] = 'M';
1755 typeahead[typeaheadlen++] = g_nMouseClick;
1756 typeahead[typeaheadlen++] = g_xMouse + '!';
1757 typeahead[typeaheadlen++] = g_yMouse + '!';
1758 g_nMouseClick = -1;
1759 }
1760 else
1761#endif
1762 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001763 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764 int modifiers = 0;
1765
1766 c = tgetch(&modifiers, &ch2);
1767
1768 if (typebuf_changed(tb_change_cnt))
1769 {
1770 /* "buf" may be invalid now if a client put something in the
1771 * typeahead buffer and "buf" is in the typeahead buffer. */
1772 typeaheadlen = 0;
1773 break;
1774 }
1775
1776 if (c == Ctrl_C && ctrl_c_interrupts)
1777 {
1778#if defined(FEAT_CLIENTSERVER)
1779 trash_input_buf();
1780#endif
1781 got_int = TRUE;
1782 }
1783
1784#ifdef FEAT_MOUSE
1785 if (g_nMouseClick == -1)
1786#endif
1787 {
1788 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001789 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001790
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001791#ifdef FEAT_MBYTE
1792 if (ch2 == NUL)
1793 {
1794 int i;
1795 char_u *p;
1796 WCHAR ch[2];
1797
1798 ch[0] = c;
1799 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1800 {
1801 ch[1] = tgetch(&modifiers, &ch2);
1802 n++;
1803 }
1804 p = utf16_to_enc(ch, &n);
1805 if (p != NULL)
1806 {
1807 for (i = 0; i < n; i++)
1808 typeahead[typeaheadlen + i] = p[i];
1809 vim_free(p);
1810 }
1811 }
1812 else
1813#endif
1814 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 if (ch2 != NUL)
1816 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001817 typeahead[typeaheadlen + n] = 3;
1818 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001819 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821
Bram Moolenaar45500912014-07-09 20:51:07 +02001822 if (conv)
1823 {
1824 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001825
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001826 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001827 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001828 char_u *e = typeahead + TYPEAHEADLEN;
1829
1830 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001831 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001832 if (*p == K_NUL)
1833 {
1834 ++p;
1835 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1836 *p = 3;
1837 ++n;
1838 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001839 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001840 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001841 }
1842 }
1843
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 /* Use the ALT key to set the 8th bit of the character
1845 * when it's one byte, the 8th bit isn't set yet and not
1846 * using a double-byte encoding (would become a lead
1847 * byte). */
1848 if ((modifiers & MOD_MASK_ALT)
1849 && n == 1
1850 && (typeahead[typeaheadlen] & 0x80) == 0
1851#ifdef FEAT_MBYTE
1852 && !enc_dbcs
1853#endif
1854 )
1855 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001856#ifdef FEAT_MBYTE
1857 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1858 typeahead + typeaheadlen);
1859#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001860 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001861#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862 modifiers &= ~MOD_MASK_ALT;
1863 }
1864
1865 if (modifiers != 0)
1866 {
1867 /* Prepend modifiers to the character. */
1868 mch_memmove(typeahead + typeaheadlen + 3,
1869 typeahead + typeaheadlen, n);
1870 typeahead[typeaheadlen++] = K_SPECIAL;
1871 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1872 typeahead[typeaheadlen++] = modifiers;
1873 }
1874
1875 typeaheadlen += n;
1876
1877#ifdef MCH_WRITE_DUMP
1878 if (fdDump)
1879 fputc(c, fdDump);
1880#endif
1881 }
1882 }
1883 }
1884
1885#ifdef MCH_WRITE_DUMP
1886 if (fdDump)
1887 {
1888 fputs("]\n", fdDump);
1889 fflush(fdDump);
1890 }
1891#endif
1892
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893theend:
1894 /* Move typeahead to "buf", as much as fits. */
1895 len = 0;
1896 while (len < maxlen && typeaheadlen > 0)
1897 {
1898 buf[len++] = typeahead[0];
1899 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1900 }
1901 return len;
1902
1903#else /* FEAT_GUI_W32 */
1904 return 0;
1905#endif /* FEAT_GUI_W32 */
1906}
1907
Bram Moolenaar82881492012-11-20 16:53:39 +01001908#ifndef PROTO
1909# ifndef __MINGW32__
1910# include <shellapi.h> /* required for FindExecutable() */
1911# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912#endif
1913
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001914/*
1915 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001916 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001917 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001919executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001921 char *dum;
1922 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001923 char *curpath, *newpath;
1924 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001926#ifdef FEAT_MBYTE
1927 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001929 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001930 WCHAR fnamew[_MAX_PATH];
1931 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001932 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001933
1934 if (p != NULL)
1935 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001936 wcurpath = _wgetenv(L"PATH");
1937 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1938 * sizeof(WCHAR));
1939 if (wnewpath == NULL)
1940 return FALSE;
1941 wcscpy(wnewpath, L".;");
1942 wcscat(wnewpath, wcurpath);
1943 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1944 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001945 vim_free(p);
1946 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1947 {
1948 if (n == 0)
1949 return FALSE;
1950 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1951 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001952 if (path != NULL)
1953 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001954 return TRUE;
1955 }
1956 /* Retry with non-wide function (for Windows 98). */
1957 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001958 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001959#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001960
1961 curpath = getenv("PATH");
1962 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1963 if (newpath == NULL)
1964 return FALSE;
1965 STRCPY(newpath, ".;");
1966 STRCAT(newpath, curpath);
1967 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1968 vim_free(newpath);
1969 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001970 return FALSE;
1971 if (mch_isdir(fname))
1972 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001973 if (path != NULL)
1974 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001975 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976}
1977
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001978#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001979 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001980/*
1981 * Bad parameter handler.
1982 *
1983 * Certain MS CRT functions will intentionally crash when passed invalid
1984 * parameters to highlight possible security holes. Setting this function as
1985 * the bad parameter handler will prevent the crash.
1986 *
1987 * In debug builds the parameters contain CRT information that might help track
1988 * down the source of a problem, but in non-debug builds the arguments are all
1989 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1990 * worth allowing these to make debugging of issues easier.
1991 */
1992 static void
1993bad_param_handler(const wchar_t *expression,
1994 const wchar_t *function,
1995 const wchar_t *file,
1996 unsigned int line,
1997 uintptr_t pReserved)
1998{
1999}
2000
2001# define SET_INVALID_PARAM_HANDLER \
2002 ((void)_set_invalid_parameter_handler(bad_param_handler))
2003#else
2004# define SET_INVALID_PARAM_HANDLER
2005#endif
2006
Bram Moolenaar071d4272004-06-13 20:20:40 +00002007#ifdef FEAT_GUI_W32
2008
2009/*
2010 * GUI version of mch_init().
2011 */
2012 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002013mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014{
2015#ifndef __MINGW32__
2016 extern int _fmode;
2017#endif
2018
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002019 /* Silently handle invalid parameters to CRT functions */
2020 SET_INVALID_PARAM_HANDLER;
2021
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022 /* Let critical errors result in a failure, not in a dialog box. Required
2023 * for the timestamp test to work on removed floppies. */
2024 SetErrorMode(SEM_FAILCRITICALERRORS);
2025
2026 _fmode = O_BINARY; /* we do our own CR-LF translation */
2027
2028 /* Specify window size. Is there a place to get the default from? */
2029 Rows = 25;
2030 Columns = 80;
2031
2032 /* Look for 'vimrun' */
2033 if (!gui_is_win32s())
2034 {
2035 char_u vimrun_location[_MAX_PATH + 4];
2036
2037 /* First try in same directory as gvim.exe */
2038 STRCPY(vimrun_location, exe_name);
2039 STRCPY(gettail(vimrun_location), "vimrun.exe");
2040 if (mch_getperm(vimrun_location) >= 0)
2041 {
2042 if (*skiptowhite(vimrun_location) != NUL)
2043 {
2044 /* Enclose path with white space in double quotes. */
2045 mch_memmove(vimrun_location + 1, vimrun_location,
2046 STRLEN(vimrun_location) + 1);
2047 *vimrun_location = '"';
2048 STRCPY(gettail(vimrun_location), "vimrun\" ");
2049 }
2050 else
2051 STRCPY(gettail(vimrun_location), "vimrun ");
2052
2053 vimrun_path = (char *)vim_strsave(vimrun_location);
2054 s_dont_use_vimrun = FALSE;
2055 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002056 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 s_dont_use_vimrun = FALSE;
2058
2059 /* Don't give the warning for a missing vimrun.exe right now, but only
2060 * when vimrun was supposed to be used. Don't bother people that do
2061 * not need vimrun.exe. */
2062 if (s_dont_use_vimrun)
2063 need_vimrun_warning = TRUE;
2064 }
2065
2066 /*
2067 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2068 * Otherwise the default "findstr /n" is used.
2069 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002070 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2072
2073#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002074 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075#endif
2076}
2077
2078
2079#else /* FEAT_GUI_W32 */
2080
2081#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2082#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2083
2084/*
2085 * ClearConsoleBuffer()
2086 * Description:
2087 * Clears the entire contents of the console screen buffer, using the
2088 * specified attribute.
2089 * Returns:
2090 * TRUE on success
2091 */
2092 static BOOL
2093ClearConsoleBuffer(WORD wAttribute)
2094{
2095 CONSOLE_SCREEN_BUFFER_INFO csbi;
2096 COORD coord;
2097 DWORD NumCells, dummy;
2098
2099 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2100 return FALSE;
2101
2102 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2103 coord.X = 0;
2104 coord.Y = 0;
2105 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2106 coord, &dummy))
2107 {
2108 return FALSE;
2109 }
2110 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2111 coord, &dummy))
2112 {
2113 return FALSE;
2114 }
2115
2116 return TRUE;
2117}
2118
2119/*
2120 * FitConsoleWindow()
2121 * Description:
2122 * Checks if the console window will fit within given buffer dimensions.
2123 * Also, if requested, will shrink the window to fit.
2124 * Returns:
2125 * TRUE on success
2126 */
2127 static BOOL
2128FitConsoleWindow(
2129 COORD dwBufferSize,
2130 BOOL WantAdjust)
2131{
2132 CONSOLE_SCREEN_BUFFER_INFO csbi;
2133 COORD dwWindowSize;
2134 BOOL NeedAdjust = FALSE;
2135
2136 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2137 {
2138 /*
2139 * A buffer resize will fail if the current console window does
2140 * not lie completely within that buffer. To avoid this, we might
2141 * have to move and possibly shrink the window.
2142 */
2143 if (csbi.srWindow.Right >= dwBufferSize.X)
2144 {
2145 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2146 if (dwWindowSize.X > dwBufferSize.X)
2147 dwWindowSize.X = dwBufferSize.X;
2148 csbi.srWindow.Right = dwBufferSize.X - 1;
2149 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2150 NeedAdjust = TRUE;
2151 }
2152 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2153 {
2154 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2155 if (dwWindowSize.Y > dwBufferSize.Y)
2156 dwWindowSize.Y = dwBufferSize.Y;
2157 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2158 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2159 NeedAdjust = TRUE;
2160 }
2161 if (NeedAdjust && WantAdjust)
2162 {
2163 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2164 return FALSE;
2165 }
2166 return TRUE;
2167 }
2168
2169 return FALSE;
2170}
2171
2172typedef struct ConsoleBufferStruct
2173{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002174 BOOL IsValid;
2175 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar61594242015-09-01 20:23:37 +02002176 HANDLE handle;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177} ConsoleBuffer;
2178
2179/*
2180 * SaveConsoleBuffer()
2181 * Description:
2182 * Saves important information about the console buffer, including the
2183 * actual buffer contents. The saved information is suitable for later
2184 * restoration by RestoreConsoleBuffer().
2185 * Returns:
2186 * TRUE if all information was saved; FALSE otherwise
2187 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2188 */
2189 static BOOL
2190SaveConsoleBuffer(
2191 ConsoleBuffer *cb)
2192{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193 if (cb == NULL)
2194 return FALSE;
2195
Bram Moolenaar61594242015-09-01 20:23:37 +02002196 if (!GetConsoleScreenBufferInfo(cb->handle, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197 {
2198 cb->IsValid = FALSE;
2199 return FALSE;
2200 }
2201 cb->IsValid = TRUE;
2202
Bram Moolenaar61594242015-09-01 20:23:37 +02002203 return TRUE;
2204}
2205
2206/*
2207 * CopyOldConsoleBuffer()
2208 * Description:
2209 * Copies the old console buffer contents to the current console buffer.
2210 * This is used when 'restorescreen' is off.
2211 * Returns:
2212 * TRUE on success
2213 */
2214 static BOOL
2215CopyOldConsoleBuffer(
2216 ConsoleBuffer *cb,
2217 HANDLE hConOld)
2218{
2219 COORD BufferCoord;
2220 COORD BufferSize;
2221 PCHAR_INFO Buffer;
2222 DWORD NumCells;
2223 SMALL_RECT ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224
2225 /*
Bram Moolenaar61594242015-09-01 20:23:37 +02002226 * Before copying the buffer contents, clear the current buffer, and
2227 * restore the window information. Doing this now prevents old buffer
2228 * contents from "flashing" onto the screen.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002230 ClearConsoleBuffer(cb->Info.wAttributes);
2231
2232 /* We only need to copy the window area, not whole buffer. */
2233 BufferSize.X = cb->Info.srWindow.Right - cb->Info.srWindow.Left + 1;
2234 BufferSize.Y = cb->Info.srWindow.Bottom - cb->Info.srWindow.Top + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 ReadRegion.Left = 0;
Bram Moolenaar61594242015-09-01 20:23:37 +02002236 ReadRegion.Right = BufferSize.X - 1;
2237 ReadRegion.Top = 0;
2238 ReadRegion.Bottom = BufferSize.Y - 1;
2239
2240 NumCells = BufferSize.X * BufferSize.Y;
2241 Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2242 if (Buffer == NULL)
2243 return FALSE;
2244
2245 BufferCoord.X = 0;
2246 BufferCoord.Y = 0;
2247
2248 if (!ReadConsoleOutputW(hConOld, /* output handle */
2249 Buffer, /* our buffer */
2250 BufferSize, /* dimensions of our buffer */
2251 BufferCoord, /* offset in our buffer */
2252 &ReadRegion)) /* region to save */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002253 {
Bram Moolenaar61594242015-09-01 20:23:37 +02002254 vim_free(Buffer);
2255 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256 }
Bram Moolenaar61594242015-09-01 20:23:37 +02002257 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2258 Buffer, /* our buffer */
2259 BufferSize, /* dimensions of our buffer */
2260 BufferCoord, /* offset in our buffer */
2261 &ReadRegion)) /* region to restore */
2262 {
2263 vim_free(Buffer);
2264 return FALSE;
2265 }
2266 vim_free(Buffer);
2267 SetConsoleWindowInfo(g_hConOut, TRUE, &ReadRegion);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268
2269 return TRUE;
2270}
2271
2272/*
2273 * RestoreConsoleBuffer()
2274 * Description:
2275 * Restores important information about the console buffer, including the
2276 * actual buffer contents, if desired. The information to restore is in
2277 * the same format used by SaveConsoleBuffer().
2278 * Returns:
2279 * TRUE on success
2280 */
2281 static BOOL
2282RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002283 ConsoleBuffer *cb,
2284 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285{
Bram Moolenaar61594242015-09-01 20:23:37 +02002286 HANDLE hConOld;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287
2288 if (cb == NULL || !cb->IsValid)
2289 return FALSE;
2290
Bram Moolenaar61594242015-09-01 20:23:37 +02002291 hConOld = g_hConOut;
2292 g_hConOut = cb->handle;
2293 if (!RestoreScreen && exiting)
2294 CopyOldConsoleBuffer(cb, hConOld);
2295 SetConsoleActiveScreenBuffer(g_hConOut);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296
2297 return TRUE;
2298}
2299
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300static ConsoleBuffer g_cbNonTermcap = { 0 };
2301static ConsoleBuffer g_cbTermcap = { 0 };
2302
2303#ifdef FEAT_TITLE
2304#ifdef __BORLANDC__
2305typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2306#else
2307typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2308#endif
2309char g_szOrigTitle[256] = { 0 };
2310HWND g_hWnd = NULL; /* also used in os_mswin.c */
2311static HICON g_hOrigIconSmall = NULL;
2312static HICON g_hOrigIcon = NULL;
2313static HICON g_hVimIcon = NULL;
2314static BOOL g_fCanChangeIcon = FALSE;
2315
2316/* ICON* are not defined in VC++ 4.0 */
2317#ifndef ICON_SMALL
2318#define ICON_SMALL 0
2319#endif
2320#ifndef ICON_BIG
2321#define ICON_BIG 1
2322#endif
2323/*
2324 * GetConsoleIcon()
2325 * Description:
2326 * Attempts to retrieve the small icon and/or the big icon currently in
2327 * use by a given window.
2328 * Returns:
2329 * TRUE on success
2330 */
2331 static BOOL
2332GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002333 HWND hWnd,
2334 HICON *phIconSmall,
2335 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336{
2337 if (hWnd == NULL)
2338 return FALSE;
2339
2340 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002341 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2342 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002343 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002344 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2345 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346 return TRUE;
2347}
2348
2349/*
2350 * SetConsoleIcon()
2351 * Description:
2352 * Attempts to change the small icon and/or the big icon currently in
2353 * use by a given window.
2354 * Returns:
2355 * TRUE on success
2356 */
2357 static BOOL
2358SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002359 HWND hWnd,
2360 HICON hIconSmall,
2361 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002363 HICON hPrevIconSmall;
2364 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365
2366 if (hWnd == NULL)
2367 return FALSE;
2368
2369 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002370 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2371 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002373 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2374 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375 return TRUE;
2376}
2377
2378/*
2379 * SaveConsoleTitleAndIcon()
2380 * Description:
2381 * Saves the current console window title in g_szOrigTitle, for later
2382 * restoration. Also, attempts to obtain a handle to the console window,
2383 * and use it to save the small and big icons currently in use by the
2384 * console window. This is not always possible on some versions of Windows;
2385 * nor is it possible when running Vim remotely using Telnet (since the
2386 * console window the user sees is owned by a remote process).
2387 */
2388 static void
2389SaveConsoleTitleAndIcon(void)
2390{
2391 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2392
2393 /* Save the original title. */
2394 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2395 return;
2396
2397 /*
2398 * Obtain a handle to the console window using GetConsoleWindow() from
2399 * KERNEL32.DLL; we need to handle in order to change the window icon.
2400 * This function only exists on NT-based Windows, starting with Windows
2401 * 2000. On older operating systems, we can't change the window icon
2402 * anyway.
2403 */
2404 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2405 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2406 "GetConsoleWindow")) != NULL)
2407 {
2408 g_hWnd = (*GetConsoleWindowProc)();
2409 }
2410 if (g_hWnd == NULL)
2411 return;
2412
2413 /* Save the original console window icon. */
2414 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2415 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2416 return;
2417
2418 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002419 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2420 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421 if (g_hVimIcon != NULL)
2422 g_fCanChangeIcon = TRUE;
2423}
2424#endif
2425
2426static int g_fWindInitCalled = FALSE;
2427static int g_fTermcapMode = FALSE;
2428static CONSOLE_CURSOR_INFO g_cci;
2429static DWORD g_cmodein = 0;
2430static DWORD g_cmodeout = 0;
2431
2432/*
2433 * non-GUI version of mch_init().
2434 */
2435 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002436mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438#ifndef __MINGW32__
2439 extern int _fmode;
2440#endif
2441
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002442 /* Silently handle invalid parameters to CRT functions */
2443 SET_INVALID_PARAM_HANDLER;
2444
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445 /* Let critical errors result in a failure, not in a dialog box. Required
2446 * for the timestamp test to work on removed floppies. */
2447 SetErrorMode(SEM_FAILCRITICALERRORS);
2448
2449 _fmode = O_BINARY; /* we do our own CR-LF translation */
2450 out_flush();
2451
2452 /* Obtain handles for the standard Console I/O devices */
2453 if (read_cmd_fd == 0)
2454 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2455 else
2456 create_conin();
2457 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaar61594242015-09-01 20:23:37 +02002458 g_cbNonTermcap.handle = g_hConOut;
2459 g_cbTermcap.handle = CreateConsoleScreenBuffer(
2460 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
2461 NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462
Bram Moolenaar071d4272004-06-13 20:20:40 +00002463 /* Get current text attributes */
Bram Moolenaar61594242015-09-01 20:23:37 +02002464 SaveConsoleBuffer(&g_cbNonTermcap);
2465 g_attrCurrent = g_attrDefault = g_cbNonTermcap.Info.wAttributes;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466 if (cterm_normal_fg_color == 0)
2467 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2468 if (cterm_normal_bg_color == 0)
2469 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2470
2471 /* set termcap codes to current text attributes */
2472 update_tcap(g_attrCurrent);
2473
2474 GetConsoleCursorInfo(g_hConOut, &g_cci);
2475 GetConsoleMode(g_hConIn, &g_cmodein);
2476 GetConsoleMode(g_hConOut, &g_cmodeout);
2477
2478#ifdef FEAT_TITLE
2479 SaveConsoleTitleAndIcon();
2480 /*
2481 * Set both the small and big icons of the console window to Vim's icon.
2482 * Note that Vim presently only has one size of icon (32x32), but it
2483 * automatically gets scaled down to 16x16 when setting the small icon.
2484 */
2485 if (g_fCanChangeIcon)
2486 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2487#endif
2488
2489 ui_get_shellsize();
2490
2491#ifdef MCH_WRITE_DUMP
2492 fdDump = fopen("dump", "wt");
2493
2494 if (fdDump)
2495 {
2496 time_t t;
2497
2498 time(&t);
2499 fputs(ctime(&t), fdDump);
2500 fflush(fdDump);
2501 }
2502#endif
2503
2504 g_fWindInitCalled = TRUE;
2505
2506#ifdef FEAT_MOUSE
2507 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2508#endif
2509
2510#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002511 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512#endif
2513
2514 /* This will be NULL on anything but NT 4.0 */
2515 s_pfnGetConsoleKeyboardLayoutName =
2516 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2517 "GetConsoleKeyboardLayoutNameA");
2518}
2519
2520/*
2521 * non-GUI version of mch_exit().
2522 * Shut down and exit with status `r'
2523 * Careful: mch_exit() may be called before mch_init()!
2524 */
2525 void
2526mch_exit(int r)
2527{
2528 stoptermcap();
2529
2530 if (g_fWindInitCalled)
2531 settmode(TMODE_COOK);
2532
2533 ml_close_all(TRUE); /* remove all memfiles */
2534
2535 if (g_fWindInitCalled)
2536 {
2537#ifdef FEAT_TITLE
2538 mch_restore_title(3);
2539 /*
2540 * Restore both the small and big icons of the console window to
2541 * what they were at startup. Don't do this when the window is
2542 * closed, Vim would hang here.
2543 */
2544 if (g_fCanChangeIcon && !g_fForceExit)
2545 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2546#endif
2547
2548#ifdef MCH_WRITE_DUMP
2549 if (fdDump)
2550 {
2551 time_t t;
2552
2553 time(&t);
2554 fputs(ctime(&t), fdDump);
2555 fclose(fdDump);
2556 }
2557 fdDump = NULL;
2558#endif
2559 }
2560
2561 SetConsoleCursorInfo(g_hConOut, &g_cci);
2562 SetConsoleMode(g_hConIn, g_cmodein);
2563 SetConsoleMode(g_hConOut, g_cmodeout);
2564
Bram Moolenaar61594242015-09-01 20:23:37 +02002565 CloseHandle(g_cbTermcap.handle);
2566
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567#ifdef DYNAMIC_GETTEXT
2568 dyn_libintl_end();
2569#endif
2570
2571 exit(r);
2572}
2573#endif /* !FEAT_GUI_W32 */
2574
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575/*
2576 * Do we have an interactive window?
2577 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002578/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002579 int
2580mch_check_win(
2581 int argc,
2582 char **argv)
2583{
2584 get_exe_name();
2585
2586#ifdef FEAT_GUI_W32
2587 return OK; /* GUI always has a tty */
2588#else
2589 if (isatty(1))
2590 return OK;
2591 return FAIL;
2592#endif
2593}
2594
2595
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002596#ifdef FEAT_MBYTE
2597/*
2598 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2599 * if it already exists. When "len" is > 0, also expand short to long
2600 * filenames.
2601 * Return FAIL if wide functions are not available, OK otherwise.
2602 * NOTE: much of this is identical to fname_case(), keep in sync!
2603 */
2604 static int
2605fname_casew(
2606 WCHAR *name,
2607 int len)
2608{
2609 WCHAR szTrueName[_MAX_PATH + 2];
2610 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2611 WCHAR *ptrue, *ptruePrev;
2612 WCHAR *porig, *porigPrev;
2613 int flen;
2614 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002615 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002616 int c;
2617 int slen;
2618
2619 flen = (int)wcslen(name);
2620 if (flen > _MAX_PATH)
2621 return OK;
2622
2623 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2624
2625 /* Build the new name in szTrueName[] one component at a time. */
2626 porig = name;
2627 ptrue = szTrueName;
2628
2629 if (iswalpha(porig[0]) && porig[1] == L':')
2630 {
2631 /* copy leading drive letter */
2632 *ptrue++ = *porig++;
2633 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002634 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002635 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002636
2637 while (*porig != NUL)
2638 {
2639 /* copy \ characters */
2640 while (*porig == psepc)
2641 *ptrue++ = *porig++;
2642
2643 ptruePrev = ptrue;
2644 porigPrev = porig;
2645 while (*porig != NUL && *porig != psepc)
2646 {
2647 *ptrue++ = *porig++;
2648 }
2649 *ptrue = NUL;
2650
2651 /* To avoid a slow failure append "\*" when searching a directory,
2652 * server or network share. */
2653 wcscpy(szTrueNameTemp, szTrueName);
2654 slen = (int)wcslen(szTrueNameTemp);
2655 if (*porig == psepc && slen + 2 < _MAX_PATH)
2656 wcscpy(szTrueNameTemp + slen, L"\\*");
2657
2658 /* Skip "", "." and "..". */
2659 if (ptrue > ptruePrev
2660 && (ptruePrev[0] != L'.'
2661 || (ptruePrev[1] != NUL
2662 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2663 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2664 != INVALID_HANDLE_VALUE)
2665 {
2666 c = *porig;
2667 *porig = NUL;
2668
2669 /* Only use the match when it's the same name (ignoring case) or
2670 * expansion is allowed and there is a match with the short name
2671 * and there is enough room. */
2672 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2673 || (len > 0
2674 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2675 && (int)(ptruePrev - szTrueName)
2676 + (int)wcslen(fb.cFileName) < len)))
2677 {
2678 wcscpy(ptruePrev, fb.cFileName);
2679
2680 /* Look for exact match and prefer it if found. Must be a
2681 * long name, otherwise there would be only one match. */
2682 while (FindNextFileW(hFind, &fb))
2683 {
2684 if (*fb.cAlternateFileName != NUL
2685 && (wcscoll(porigPrev, fb.cFileName) == 0
2686 || (len > 0
2687 && (_wcsicoll(porigPrev,
2688 fb.cAlternateFileName) == 0
2689 && (int)(ptruePrev - szTrueName)
2690 + (int)wcslen(fb.cFileName) < len))))
2691 {
2692 wcscpy(ptruePrev, fb.cFileName);
2693 break;
2694 }
2695 }
2696 }
2697 FindClose(hFind);
2698 *porig = c;
2699 ptrue = ptruePrev + wcslen(ptruePrev);
2700 }
2701 else if (hFind == INVALID_HANDLE_VALUE
2702 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2703 return FAIL;
2704 }
2705
2706 wcscpy(name, szTrueName);
2707 return OK;
2708}
2709#endif
2710
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711/*
2712 * fname_case(): Set the case of the file name, if it already exists.
2713 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002714 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715 */
2716 void
2717fname_case(
2718 char_u *name,
2719 int len)
2720{
2721 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002722 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723 char *ptrue, *ptruePrev;
2724 char *porig, *porigPrev;
2725 int flen;
2726 WIN32_FIND_DATA fb;
2727 HANDLE hFind;
2728 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002729 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002731 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002732 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733 return;
2734
2735 slash_adjust(name);
2736
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002737#ifdef FEAT_MBYTE
2738 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2739 {
2740 WCHAR *p = enc_to_utf16(name, NULL);
2741
2742 if (p != NULL)
2743 {
2744 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002745 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002746
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002747 wcsncpy(buf, p, _MAX_PATH);
2748 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002749 vim_free(p);
2750
2751 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2752 {
2753 q = utf16_to_enc(buf, NULL);
2754 if (q != NULL)
2755 {
2756 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2757 vim_free(q);
2758 return;
2759 }
2760 }
2761 }
2762 /* Retry with non-wide function (for Windows 98). */
2763 }
2764#endif
2765
2766 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2767 * So we should check this after calling wide function. */
2768 if (flen > _MAX_PATH)
2769 return;
2770
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771 /* Build the new name in szTrueName[] one component at a time. */
2772 porig = name;
2773 ptrue = szTrueName;
2774
2775 if (isalpha(porig[0]) && porig[1] == ':')
2776 {
2777 /* copy leading drive letter */
2778 *ptrue++ = *porig++;
2779 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002781 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782
2783 while (*porig != NUL)
2784 {
2785 /* copy \ characters */
2786 while (*porig == psepc)
2787 *ptrue++ = *porig++;
2788
2789 ptruePrev = ptrue;
2790 porigPrev = porig;
2791 while (*porig != NUL && *porig != psepc)
2792 {
2793#ifdef FEAT_MBYTE
2794 int l;
2795
2796 if (enc_dbcs)
2797 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002798 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002799 while (--l >= 0)
2800 *ptrue++ = *porig++;
2801 }
2802 else
2803#endif
2804 *ptrue++ = *porig++;
2805 }
2806 *ptrue = NUL;
2807
Bram Moolenaar464c9252010-10-13 20:37:41 +02002808 /* To avoid a slow failure append "\*" when searching a directory,
2809 * server or network share. */
2810 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002811 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002812 if (*porig == psepc && slen + 2 < _MAX_PATH)
2813 STRCPY(szTrueNameTemp + slen, "\\*");
2814
Bram Moolenaar071d4272004-06-13 20:20:40 +00002815 /* Skip "", "." and "..". */
2816 if (ptrue > ptruePrev
2817 && (ptruePrev[0] != '.'
2818 || (ptruePrev[1] != NUL
2819 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002820 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002821 != INVALID_HANDLE_VALUE)
2822 {
2823 c = *porig;
2824 *porig = NUL;
2825
2826 /* Only use the match when it's the same name (ignoring case) or
2827 * expansion is allowed and there is a match with the short name
2828 * and there is enough room. */
2829 if (_stricoll(porigPrev, fb.cFileName) == 0
2830 || (len > 0
2831 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2832 && (int)(ptruePrev - szTrueName)
2833 + (int)strlen(fb.cFileName) < len)))
2834 {
2835 STRCPY(ptruePrev, fb.cFileName);
2836
2837 /* Look for exact match and prefer it if found. Must be a
2838 * long name, otherwise there would be only one match. */
2839 while (FindNextFile(hFind, &fb))
2840 {
2841 if (*fb.cAlternateFileName != NUL
2842 && (strcoll(porigPrev, fb.cFileName) == 0
2843 || (len > 0
2844 && (_stricoll(porigPrev,
2845 fb.cAlternateFileName) == 0
2846 && (int)(ptruePrev - szTrueName)
2847 + (int)strlen(fb.cFileName) < len))))
2848 {
2849 STRCPY(ptruePrev, fb.cFileName);
2850 break;
2851 }
2852 }
2853 }
2854 FindClose(hFind);
2855 *porig = c;
2856 ptrue = ptruePrev + strlen(ptruePrev);
2857 }
2858 }
2859
2860 STRCPY(name, szTrueName);
2861}
2862
2863
2864/*
2865 * Insert user name in s[len].
2866 */
2867 int
2868mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002869 char_u *s,
2870 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002872 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 DWORD cch = sizeof szUserName;
2874
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002875#ifdef FEAT_MBYTE
2876 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2877 {
2878 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2879 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2880
2881 if (GetUserNameW(wszUserName, &wcch))
2882 {
2883 char_u *p = utf16_to_enc(wszUserName, NULL);
2884
2885 if (p != NULL)
2886 {
2887 vim_strncpy(s, p, len - 1);
2888 vim_free(p);
2889 return OK;
2890 }
2891 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002892 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2893 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002894 /* Retry with non-wide function (for Windows 98). */
2895 }
2896#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 if (GetUserName(szUserName, &cch))
2898 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002899 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900 return OK;
2901 }
2902 s[0] = NUL;
2903 return FAIL;
2904}
2905
2906
2907/*
2908 * Insert host name in s[len].
2909 */
2910 void
2911mch_get_host_name(
2912 char_u *s,
2913 int len)
2914{
2915 DWORD cch = len;
2916
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002917#ifdef FEAT_MBYTE
2918 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2919 {
2920 WCHAR wszHostName[256 + 1];
2921 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2922
2923 if (GetComputerNameW(wszHostName, &wcch))
2924 {
2925 char_u *p = utf16_to_enc(wszHostName, NULL);
2926
2927 if (p != NULL)
2928 {
2929 vim_strncpy(s, p, len - 1);
2930 vim_free(p);
2931 return;
2932 }
2933 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002934 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2935 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002936 /* Retry with non-wide function (for Windows 98). */
2937 }
2938#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002940 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941}
2942
2943
2944/*
2945 * return process ID
2946 */
2947 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002948mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949{
2950 return (long)GetCurrentProcessId();
2951}
2952
2953
2954/*
2955 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2956 * Return OK for success, FAIL for failure.
2957 */
2958 int
2959mch_dirname(
2960 char_u *buf,
2961 int len)
2962{
2963 /*
2964 * Originally this was:
2965 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2966 * But the Win32s known bug list says that getcwd() doesn't work
2967 * so use the Win32 system call instead. <Negri>
2968 */
2969#ifdef FEAT_MBYTE
2970 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2971 {
2972 WCHAR wbuf[_MAX_PATH + 1];
2973
2974 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2975 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002976 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977
2978 if (p != NULL)
2979 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002980 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981 vim_free(p);
2982 return OK;
2983 }
2984 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002985 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2986 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 /* Retry with non-wide function (for Windows 98). */
2988 }
2989#endif
2990 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2991}
2992
2993/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002994 * Get file permissions for "name".
2995 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996 */
2997 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002998mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003000 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003001 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003003 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003004 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005}
3006
3007
3008/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003009 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003010 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003011 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 */
3013 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003014mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003016 long n = -1;
3017
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018#ifdef FEAT_MBYTE
3019 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3020 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003021 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022
3023 if (p != NULL)
3024 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003025 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003027 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003028 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029 /* Retry with non-wide function (for Windows 98). */
3030 }
3031 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003032 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003034 n = _chmod(name, perm);
3035 if (n == -1)
3036 return FAIL;
3037
3038 win32_set_archive(name);
3039
3040 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041}
3042
3043/*
3044 * Set hidden flag for "name".
3045 */
3046 void
3047mch_hide(char_u *name)
3048{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003049 int attrs = win32_getattrs(name);
3050 if (attrs == -1)
3051 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003053 attrs |= FILE_ATTRIBUTE_HIDDEN;
3054 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055}
3056
3057/*
3058 * return TRUE if "name" is a directory
3059 * return FALSE if "name" is not a directory or upon error
3060 */
3061 int
3062mch_isdir(char_u *name)
3063{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003064 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065
3066 if (f == -1)
3067 return FALSE; /* file does not exist at all */
3068
3069 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3070}
3071
3072/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003073 * Create directory "name".
3074 * Return 0 on success, -1 on error.
3075 */
3076 int
3077mch_mkdir(char_u *name)
3078{
3079#ifdef FEAT_MBYTE
3080 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3081 {
3082 WCHAR *p;
3083 int retval;
3084
3085 p = enc_to_utf16(name, NULL);
3086 if (p == NULL)
3087 return -1;
3088 retval = _wmkdir(p);
3089 vim_free(p);
3090 return retval;
3091 }
3092#endif
3093 return _mkdir(name);
3094}
3095
3096/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003097 * Return TRUE if file "fname" has more than one link.
3098 */
3099 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003100mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003101{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003102 BY_HANDLE_FILE_INFORMATION info;
3103
3104 return win32_fileinfo(fname, &info) == FILEINFO_OK
3105 && info.nNumberOfLinks > 1;
3106}
3107
3108/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003109 * Return TRUE if file "fname" is a symbolic link.
3110 */
3111 int
3112mch_is_symbolic_link(char_u *fname)
3113{
3114 HANDLE hFind;
3115 int res = FALSE;
3116 WIN32_FIND_DATAA findDataA;
3117 DWORD fileFlags = 0, reparseTag = 0;
3118#ifdef FEAT_MBYTE
3119 WCHAR *wn = NULL;
3120 WIN32_FIND_DATAW findDataW;
3121
3122 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3123 wn = enc_to_utf16(fname, NULL);
3124 if (wn != NULL)
3125 {
3126 hFind = FindFirstFileW(wn, &findDataW);
3127 vim_free(wn);
3128 if (hFind == INVALID_HANDLE_VALUE
3129 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3130 {
3131 /* Retry with non-wide function (for Windows 98). */
3132 hFind = FindFirstFile(fname, &findDataA);
3133 if (hFind != INVALID_HANDLE_VALUE)
3134 {
3135 fileFlags = findDataA.dwFileAttributes;
3136 reparseTag = findDataA.dwReserved0;
3137 }
3138 }
3139 else
3140 {
3141 fileFlags = findDataW.dwFileAttributes;
3142 reparseTag = findDataW.dwReserved0;
3143 }
3144 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003145 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003146#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003147 {
3148 hFind = FindFirstFile(fname, &findDataA);
3149 if (hFind != INVALID_HANDLE_VALUE)
3150 {
3151 fileFlags = findDataA.dwFileAttributes;
3152 reparseTag = findDataA.dwReserved0;
3153 }
3154 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003155
3156 if (hFind != INVALID_HANDLE_VALUE)
3157 FindClose(hFind);
3158
3159 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3160 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3161 res = TRUE;
3162
3163 return res;
3164}
3165
3166/*
3167 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3168 * link.
3169 */
3170 int
3171mch_is_linked(char_u *fname)
3172{
3173 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3174 return TRUE;
3175 return FALSE;
3176}
3177
3178/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003179 * Get the by-handle-file-information for "fname".
3180 * Returns FILEINFO_OK when OK.
3181 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3182 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3183 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3184 */
3185 int
3186win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3187{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003188 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003189 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003190#ifdef FEAT_MBYTE
3191 WCHAR *wn = NULL;
3192
3193 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003194 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003195 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003196 if (wn == NULL)
3197 res = FILEINFO_ENC_FAIL;
3198 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003199 if (wn != NULL)
3200 {
3201 hFile = CreateFileW(wn, /* file name */
3202 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003203 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003204 NULL, /* security descriptor */
3205 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003206 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003207 NULL); /* handle to template file */
3208 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003209 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003210 {
3211 /* Retry with non-wide function (for Windows 98). */
3212 vim_free(wn);
3213 wn = NULL;
3214 }
3215 }
3216 if (wn == NULL)
3217#endif
3218 hFile = CreateFile(fname, /* file name */
3219 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003220 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003221 NULL, /* security descriptor */
3222 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003223 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003224 NULL); /* handle to template file */
3225
3226 if (hFile != INVALID_HANDLE_VALUE)
3227 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003228 if (GetFileInformationByHandle(hFile, info) != 0)
3229 res = FILEINFO_OK;
3230 else
3231 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003232 CloseHandle(hFile);
3233 }
3234
3235#ifdef FEAT_MBYTE
3236 vim_free(wn);
3237#endif
3238 return res;
3239}
3240
3241/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003242 * get file attributes for `name'
3243 * -1 : error
3244 * else FILE_ATTRIBUTE_* defined in winnt.h
3245 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003246 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003247win32_getattrs(char_u *name)
3248{
3249 int attr;
3250#ifdef FEAT_MBYTE
3251 WCHAR *p = NULL;
3252
3253 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3254 p = enc_to_utf16(name, NULL);
3255
3256 if (p != NULL)
3257 {
3258 attr = GetFileAttributesW(p);
3259 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3260 {
3261 /* Retry with non-wide function (for Windows 98). */
3262 vim_free(p);
3263 p = NULL;
3264 }
3265 }
3266 if (p == NULL)
3267#endif
3268 attr = GetFileAttributes((char *)name);
3269#ifdef FEAT_MBYTE
3270 vim_free(p);
3271#endif
3272 return attr;
3273}
3274
3275/*
3276 * set file attributes for `name' to `attrs'
3277 *
3278 * return -1 for failure, 0 otherwise
3279 */
3280 static
3281 int
3282win32_setattrs(char_u *name, int attrs)
3283{
3284 int res;
3285#ifdef FEAT_MBYTE
3286 WCHAR *p = NULL;
3287
3288 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3289 p = enc_to_utf16(name, NULL);
3290
3291 if (p != NULL)
3292 {
3293 res = SetFileAttributesW(p, attrs);
3294 if (res == FALSE
3295 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3296 {
3297 /* Retry with non-wide function (for Windows 98). */
3298 vim_free(p);
3299 p = NULL;
3300 }
3301 }
3302 if (p == NULL)
3303#endif
3304 res = SetFileAttributes((char *)name, attrs);
3305#ifdef FEAT_MBYTE
3306 vim_free(p);
3307#endif
3308 return res ? 0 : -1;
3309}
3310
3311/*
3312 * Set archive flag for "name".
3313 */
3314 static
3315 int
3316win32_set_archive(char_u *name)
3317{
3318 int attrs = win32_getattrs(name);
3319 if (attrs == -1)
3320 return -1;
3321
3322 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3323 return win32_setattrs(name, attrs);
3324}
3325
3326/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327 * Return TRUE if file or directory "name" is writable (not readonly).
3328 * Strange semantics of Win32: a readonly directory is writable, but you can't
3329 * delete a file. Let's say this means it is writable.
3330 */
3331 int
3332mch_writable(char_u *name)
3333{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003334 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003335
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003336 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3337 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338}
3339
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340/*
3341 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003342 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343 * Return -1 if unknown.
3344 */
3345 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003346mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003347{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003348 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003349 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003350 char_u *p;
3351
3352 if (len >= _MAX_PATH) /* safety check */
3353 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003354 if (!use_path)
3355 {
3356 /* TODO: check if file is really executable. */
3357 return mch_getperm(name) != -1 && !mch_isdir(name);
3358 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003359
3360 /* If there already is an extension try using the name directly. Also do
3361 * this with a Unix-shell like 'shell'. */
3362 if (vim_strchr(gettail(name), '.') != NULL
3363 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003364 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003365 return TRUE;
3366
3367 /*
3368 * Loop over all extensions in $PATHEXT.
3369 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003370 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003371 p = mch_getenv("PATHEXT");
3372 if (p == NULL)
3373 p = (char_u *)".com;.exe;.bat;.cmd";
3374 while (*p)
3375 {
3376 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3377 {
3378 /* A single "." means no extension is added. */
3379 buf[len] = NUL;
3380 ++p;
3381 if (*p)
3382 ++p;
3383 }
3384 else
3385 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003386 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003387 return TRUE;
3388 }
3389 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003390}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391
3392/*
3393 * Check what "name" is:
3394 * NODE_NORMAL: file or directory (or doesn't exist)
3395 * NODE_WRITABLE: writable device, socket, fifo, etc.
3396 * NODE_OTHER: non-writable things
3397 */
3398 int
3399mch_nodetype(char_u *name)
3400{
3401 HANDLE hFile;
3402 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003403#ifdef FEAT_MBYTE
3404 WCHAR *wn = NULL;
3405#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003406
Bram Moolenaar043545e2006-10-10 16:44:07 +00003407 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3408 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3409 * here. */
3410 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3411 return NODE_WRITABLE;
3412
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003413#ifdef FEAT_MBYTE
3414 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3415 {
3416 wn = enc_to_utf16(name, NULL);
3417 if (wn != NULL)
3418 {
3419 hFile = CreateFileW(wn, /* file name */
3420 GENERIC_WRITE, /* access mode */
3421 0, /* share mode */
3422 NULL, /* security descriptor */
3423 OPEN_EXISTING, /* creation disposition */
3424 0, /* file attributes */
3425 NULL); /* handle to template file */
3426 if (hFile == INVALID_HANDLE_VALUE
3427 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3428 {
3429 /* Retry with non-wide function (for Windows 98). */
3430 vim_free(wn);
3431 wn = NULL;
3432 }
3433 }
3434 }
3435 if (wn == NULL)
3436#endif
3437 hFile = CreateFile(name, /* file name */
3438 GENERIC_WRITE, /* access mode */
3439 0, /* share mode */
3440 NULL, /* security descriptor */
3441 OPEN_EXISTING, /* creation disposition */
3442 0, /* file attributes */
3443 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003445#ifdef FEAT_MBYTE
3446 vim_free(wn);
3447#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448 if (hFile == INVALID_HANDLE_VALUE)
3449 return NODE_NORMAL;
3450
3451 type = GetFileType(hFile);
3452 CloseHandle(hFile);
3453 if (type == FILE_TYPE_CHAR)
3454 return NODE_WRITABLE;
3455 if (type == FILE_TYPE_DISK)
3456 return NODE_NORMAL;
3457 return NODE_OTHER;
3458}
3459
3460#ifdef HAVE_ACL
3461struct my_acl
3462{
3463 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3464 PSID pSidOwner;
3465 PSID pSidGroup;
3466 PACL pDacl;
3467 PACL pSacl;
3468};
3469#endif
3470
3471/*
3472 * Return a pointer to the ACL of file "fname" in allocated memory.
3473 * Return NULL if the ACL is not available for whatever reason.
3474 */
3475 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003476mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477{
3478#ifndef HAVE_ACL
3479 return (vim_acl_T)NULL;
3480#else
3481 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003482 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483
3484 /* This only works on Windows NT and 2000. */
3485 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3486 {
3487 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3488 if (p != NULL)
3489 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003490# ifdef FEAT_MBYTE
3491 WCHAR *wn = NULL;
3492
3493 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3494 wn = enc_to_utf16(fname, NULL);
3495 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003497 /* Try to retrieve the entire security descriptor. */
3498 err = pGetNamedSecurityInfoW(
3499 wn, // Abstract filename
3500 SE_FILE_OBJECT, // File Object
3501 OWNER_SECURITY_INFORMATION |
3502 GROUP_SECURITY_INFORMATION |
3503 DACL_SECURITY_INFORMATION |
3504 SACL_SECURITY_INFORMATION,
3505 &p->pSidOwner, // Ownership information.
3506 &p->pSidGroup, // Group membership.
3507 &p->pDacl, // Discretionary information.
3508 &p->pSacl, // For auditing purposes.
3509 &p->pSecurityDescriptor);
3510 if (err == ERROR_ACCESS_DENIED ||
3511 err == ERROR_PRIVILEGE_NOT_HELD)
3512 {
3513 /* Retrieve only DACL. */
3514 (void)pGetNamedSecurityInfoW(
3515 wn,
3516 SE_FILE_OBJECT,
3517 DACL_SECURITY_INFORMATION,
3518 NULL,
3519 NULL,
3520 &p->pDacl,
3521 NULL,
3522 &p->pSecurityDescriptor);
3523 }
3524 if (p->pSecurityDescriptor == NULL)
3525 {
3526 mch_free_acl((vim_acl_T)p);
3527 p = NULL;
3528 }
3529 vim_free(wn);
3530 }
3531 else
3532# endif
3533 {
3534 /* Try to retrieve the entire security descriptor. */
3535 err = pGetNamedSecurityInfo(
3536 (LPSTR)fname, // Abstract filename
3537 SE_FILE_OBJECT, // File Object
3538 OWNER_SECURITY_INFORMATION |
3539 GROUP_SECURITY_INFORMATION |
3540 DACL_SECURITY_INFORMATION |
3541 SACL_SECURITY_INFORMATION,
3542 &p->pSidOwner, // Ownership information.
3543 &p->pSidGroup, // Group membership.
3544 &p->pDacl, // Discretionary information.
3545 &p->pSacl, // For auditing purposes.
3546 &p->pSecurityDescriptor);
3547 if (err == ERROR_ACCESS_DENIED ||
3548 err == ERROR_PRIVILEGE_NOT_HELD)
3549 {
3550 /* Retrieve only DACL. */
3551 (void)pGetNamedSecurityInfo(
3552 (LPSTR)fname,
3553 SE_FILE_OBJECT,
3554 DACL_SECURITY_INFORMATION,
3555 NULL,
3556 NULL,
3557 &p->pDacl,
3558 NULL,
3559 &p->pSecurityDescriptor);
3560 }
3561 if (p->pSecurityDescriptor == NULL)
3562 {
3563 mch_free_acl((vim_acl_T)p);
3564 p = NULL;
3565 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566 }
3567 }
3568 }
3569
3570 return (vim_acl_T)p;
3571#endif
3572}
3573
Bram Moolenaar27515922013-06-29 15:36:26 +02003574#ifdef HAVE_ACL
3575/*
3576 * Check if "acl" contains inherited ACE.
3577 */
3578 static BOOL
3579is_acl_inherited(PACL acl)
3580{
3581 DWORD i;
3582 ACL_SIZE_INFORMATION acl_info;
3583 PACCESS_ALLOWED_ACE ace;
3584
3585 acl_info.AceCount = 0;
3586 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3587 for (i = 0; i < acl_info.AceCount; i++)
3588 {
3589 GetAce(acl, i, (LPVOID *)&ace);
3590 if (ace->Header.AceFlags & INHERITED_ACE)
3591 return TRUE;
3592 }
3593 return FALSE;
3594}
3595#endif
3596
Bram Moolenaar071d4272004-06-13 20:20:40 +00003597/*
3598 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3599 * Errors are ignored.
3600 * This must only be called with "acl" equal to what mch_get_acl() returned.
3601 */
3602 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003603mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604{
3605#ifdef HAVE_ACL
3606 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003607 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608
3609 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003610 {
3611# ifdef FEAT_MBYTE
3612 WCHAR *wn = NULL;
3613# endif
3614
3615 /* Set security flags */
3616 if (p->pSidOwner)
3617 sec_info |= OWNER_SECURITY_INFORMATION;
3618 if (p->pSidGroup)
3619 sec_info |= GROUP_SECURITY_INFORMATION;
3620 if (p->pDacl)
3621 {
3622 sec_info |= DACL_SECURITY_INFORMATION;
3623 /* Do not inherit its parent's DACL.
3624 * If the DACL is inherited, Cygwin permissions would be changed.
3625 */
3626 if (!is_acl_inherited(p->pDacl))
3627 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3628 }
3629 if (p->pSacl)
3630 sec_info |= SACL_SECURITY_INFORMATION;
3631
3632# ifdef FEAT_MBYTE
3633 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3634 wn = enc_to_utf16(fname, NULL);
3635 if (wn != NULL)
3636 {
3637 (void)pSetNamedSecurityInfoW(
3638 wn, // Abstract filename
3639 SE_FILE_OBJECT, // File Object
3640 sec_info,
3641 p->pSidOwner, // Ownership information.
3642 p->pSidGroup, // Group membership.
3643 p->pDacl, // Discretionary information.
3644 p->pSacl // For auditing purposes.
3645 );
3646 vim_free(wn);
3647 }
3648 else
3649# endif
3650 {
3651 (void)pSetNamedSecurityInfo(
3652 (LPSTR)fname, // Abstract filename
3653 SE_FILE_OBJECT, // File Object
3654 sec_info,
3655 p->pSidOwner, // Ownership information.
3656 p->pSidGroup, // Group membership.
3657 p->pDacl, // Discretionary information.
3658 p->pSacl // For auditing purposes.
3659 );
3660 }
3661 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003662#endif
3663}
3664
3665 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003666mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003667{
3668#ifdef HAVE_ACL
3669 struct my_acl *p = (struct my_acl *)acl;
3670
3671 if (p != NULL)
3672 {
3673 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3674 vim_free(p);
3675 }
3676#endif
3677}
3678
3679#ifndef FEAT_GUI_W32
3680
3681/*
3682 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3683 */
3684 static BOOL WINAPI
3685handler_routine(
3686 DWORD dwCtrlType)
3687{
3688 switch (dwCtrlType)
3689 {
3690 case CTRL_C_EVENT:
3691 if (ctrl_c_interrupts)
3692 g_fCtrlCPressed = TRUE;
3693 return TRUE;
3694
3695 case CTRL_BREAK_EVENT:
3696 g_fCBrkPressed = TRUE;
3697 return TRUE;
3698
3699 /* fatal events: shut down gracefully */
3700 case CTRL_CLOSE_EVENT:
3701 case CTRL_LOGOFF_EVENT:
3702 case CTRL_SHUTDOWN_EVENT:
3703 windgoto((int)Rows - 1, 0);
3704 g_fForceExit = TRUE;
3705
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003706 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707 (dwCtrlType == CTRL_CLOSE_EVENT
3708 ? _("close")
3709 : dwCtrlType == CTRL_LOGOFF_EVENT
3710 ? _("logoff")
3711 : _("shutdown")));
3712#ifdef DEBUG
3713 OutputDebugString(IObuff);
3714#endif
3715
3716 preserve_exit(); /* output IObuff, preserve files and exit */
3717
3718 return TRUE; /* not reached */
3719
3720 default:
3721 return FALSE;
3722 }
3723}
3724
3725
3726/*
3727 * set the tty in (raw) ? "raw" : "cooked" mode
3728 */
3729 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003730mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731{
3732 DWORD cmodein;
3733 DWORD cmodeout;
3734 BOOL bEnableHandler;
3735
3736 GetConsoleMode(g_hConIn, &cmodein);
3737 GetConsoleMode(g_hConOut, &cmodeout);
3738 if (tmode == TMODE_RAW)
3739 {
3740 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3741 ENABLE_ECHO_INPUT);
3742#ifdef FEAT_MOUSE
3743 if (g_fMouseActive)
3744 cmodein |= ENABLE_MOUSE_INPUT;
3745#endif
3746 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3747 bEnableHandler = TRUE;
3748 }
3749 else /* cooked */
3750 {
3751 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3752 ENABLE_ECHO_INPUT);
3753 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3754 bEnableHandler = FALSE;
3755 }
3756 SetConsoleMode(g_hConIn, cmodein);
3757 SetConsoleMode(g_hConOut, cmodeout);
3758 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3759
3760#ifdef MCH_WRITE_DUMP
3761 if (fdDump)
3762 {
3763 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3764 tmode == TMODE_RAW ? "raw" :
3765 tmode == TMODE_COOK ? "cooked" : "normal",
3766 cmodein, cmodeout);
3767 fflush(fdDump);
3768 }
3769#endif
3770}
3771
3772
3773/*
3774 * Get the size of the current window in `Rows' and `Columns'
3775 * Return OK when size could be determined, FAIL otherwise.
3776 */
3777 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003778mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779{
3780 CONSOLE_SCREEN_BUFFER_INFO csbi;
3781
3782 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3783 {
3784 /*
3785 * For some reason, we are trying to get the screen dimensions
3786 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3787 * variables are really intended to mean the size of Vim screen
3788 * while in termcap mode.
3789 */
3790 Rows = g_cbTermcap.Info.dwSize.Y;
3791 Columns = g_cbTermcap.Info.dwSize.X;
3792 }
3793 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3794 {
3795 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3796 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3797 }
3798 else
3799 {
3800 Rows = 25;
3801 Columns = 80;
3802 }
3803 return OK;
3804}
3805
3806/*
3807 * Set a console window to `xSize' * `ySize'
3808 */
3809 static void
3810ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003811 HANDLE hConsole,
3812 int xSize,
3813 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814{
3815 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3816 SMALL_RECT srWindowRect; /* hold the new console size */
3817 COORD coordScreen;
3818
3819#ifdef MCH_WRITE_DUMP
3820 if (fdDump)
3821 {
3822 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3823 fflush(fdDump);
3824 }
3825#endif
3826
3827 /* get the largest size we can size the console window to */
3828 coordScreen = GetLargestConsoleWindowSize(hConsole);
3829
3830 /* define the new console window size and scroll position */
3831 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3832 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3833 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3834
3835 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3836 {
3837 int sx, sy;
3838
3839 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3840 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3841 if (sy < ySize || sx < xSize)
3842 {
3843 /*
3844 * Increasing number of lines/columns, do buffer first.
3845 * Use the maximal size in x and y direction.
3846 */
3847 if (sy < ySize)
3848 coordScreen.Y = ySize;
3849 else
3850 coordScreen.Y = sy;
3851 if (sx < xSize)
3852 coordScreen.X = xSize;
3853 else
3854 coordScreen.X = sx;
3855 SetConsoleScreenBufferSize(hConsole, coordScreen);
3856 }
3857 }
3858
3859 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3860 {
3861#ifdef MCH_WRITE_DUMP
3862 if (fdDump)
3863 {
3864 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3865 GetLastError());
3866 fflush(fdDump);
3867 }
3868#endif
3869 }
3870
3871 /* define the new console buffer size */
3872 coordScreen.X = xSize;
3873 coordScreen.Y = ySize;
3874
3875 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3876 {
3877#ifdef MCH_WRITE_DUMP
3878 if (fdDump)
3879 {
3880 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3881 GetLastError());
3882 fflush(fdDump);
3883 }
3884#endif
3885 }
3886}
3887
3888
3889/*
3890 * Set the console window to `Rows' * `Columns'
3891 */
3892 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003893mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003894{
3895 COORD coordScreen;
3896
3897 /* Don't change window size while still starting up */
3898 if (suppress_winsize != 0)
3899 {
3900 suppress_winsize = 2;
3901 return;
3902 }
3903
3904 if (term_console)
3905 {
3906 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3907
3908 /* Clamp Rows and Columns to reasonable values */
3909 if (Rows > coordScreen.Y)
3910 Rows = coordScreen.Y;
3911 if (Columns > coordScreen.X)
3912 Columns = coordScreen.X;
3913
3914 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3915 }
3916}
3917
3918/*
3919 * Rows and/or Columns has changed.
3920 */
3921 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003922mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923{
3924 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3925}
3926
3927
3928/*
3929 * Called when started up, to set the winsize that was delayed.
3930 */
3931 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003932mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933{
3934 if (suppress_winsize == 2)
3935 {
3936 suppress_winsize = 0;
3937 mch_set_shellsize();
3938 shell_resized();
3939 }
3940 suppress_winsize = 0;
3941}
3942#endif /* FEAT_GUI_W32 */
3943
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003944 static BOOL
3945vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003946 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003947 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003948 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003949 STARTUPINFO *si,
3950 PROCESS_INFORMATION *pi)
3951{
3952# ifdef FEAT_MBYTE
3953 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3954 {
3955 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
3956
3957 if (wcmd != NULL)
3958 {
3959 BOOL ret;
3960 ret = CreateProcessW(
3961 NULL, /* Executable name */
3962 wcmd, /* Command to execute */
3963 NULL, /* Process security attributes */
3964 NULL, /* Thread security attributes */
3965 inherit_handles, /* Inherit handles */
3966 flags, /* Creation flags */
3967 NULL, /* Environment */
3968 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003969 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003970 pi); /* Process information */
3971 vim_free(wcmd);
3972 return ret;
3973 }
3974 }
3975#endif
3976 return CreateProcess(
3977 NULL, /* Executable name */
3978 cmd, /* Command to execute */
3979 NULL, /* Process security attributes */
3980 NULL, /* Thread security attributes */
3981 inherit_handles, /* Inherit handles */
3982 flags, /* Creation flags */
3983 NULL, /* Environment */
3984 NULL, /* Current directory */
3985 si, /* Startup information */
3986 pi); /* Process information */
3987}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988
3989
3990#if defined(FEAT_GUI_W32) || defined(PROTO)
3991
3992/*
3993 * Specialised version of system() for Win32 GUI mode.
3994 * This version proceeds as follows:
3995 * 1. Create a console window for use by the subprocess
3996 * 2. Run the subprocess (it gets the allocated console by default)
3997 * 3. Wait for the subprocess to terminate and get its exit code
3998 * 4. Prompt the user to press a key to close the console window
3999 */
4000 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004001mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004002{
4003 STARTUPINFO si;
4004 PROCESS_INFORMATION pi;
4005 DWORD ret = 0;
4006 HWND hwnd = GetFocus();
4007
4008 si.cb = sizeof(si);
4009 si.lpReserved = NULL;
4010 si.lpDesktop = NULL;
4011 si.lpTitle = NULL;
4012 si.dwFlags = STARTF_USESHOWWINDOW;
4013 /*
4014 * It's nicer to run a filter command in a minimized window, but in
4015 * Windows 95 this makes the command MUCH slower. We can't do it under
4016 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004017 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004018 */
4019 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004020 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004021 else
4022 si.wShowWindow = SW_SHOWNORMAL;
4023 si.cbReserved2 = 0;
4024 si.lpReserved2 = NULL;
4025
4026 /* There is a strange error on Windows 95 when using "c:\\command.com".
4027 * When the "c:\\" is left out it works OK...? */
4028 if (mch_windows95()
4029 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4030 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4031 cmd += 3;
4032
4033 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004034 vim_create_process(cmd, FALSE,
4035 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004036
4037 /* Wait for the command to terminate before continuing */
4038 if (g_PlatformId != VER_PLATFORM_WIN32s)
4039 {
4040#ifdef FEAT_GUI
4041 int delay = 1;
4042
4043 /* Keep updating the window while waiting for the shell to finish. */
4044 for (;;)
4045 {
4046 MSG msg;
4047
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004048 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049 {
4050 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004051 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004052 delay = 1;
4053 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 }
4055 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4056 break;
4057
4058 /* We start waiting for a very short time and then increase it, so
4059 * that we respond quickly when the process is quick, and don't
4060 * consume too much overhead when it's slow. */
4061 if (delay < 50)
4062 delay += 10;
4063 }
4064#else
4065 WaitForSingleObject(pi.hProcess, INFINITE);
4066#endif
4067
4068 /* Get the command exit code */
4069 GetExitCodeProcess(pi.hProcess, &ret);
4070 }
4071 else
4072 {
4073 /*
4074 * This ugly code is the only quick way of performing
4075 * a synchronous spawn under Win32s. Yuk.
4076 */
4077 num_windows = 0;
4078 EnumWindows(win32ssynch_cb, 0);
4079 old_num_windows = num_windows;
4080 do
4081 {
4082 Sleep(1000);
4083 num_windows = 0;
4084 EnumWindows(win32ssynch_cb, 0);
4085 } while (num_windows == old_num_windows);
4086 ret = 0;
4087 }
4088
4089 /* Close the handles to the subprocess, so that it goes away */
4090 CloseHandle(pi.hThread);
4091 CloseHandle(pi.hProcess);
4092
4093 /* Try to get input focus back. Doesn't always work though. */
4094 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4095
4096 return ret;
4097}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004098
4099/*
4100 * Thread launched by the gui to send the current buffer data to the
4101 * process. This way avoid to hang up vim totally if the children
4102 * process take a long time to process the lines.
4103 */
4104 static DWORD WINAPI
4105sub_process_writer(LPVOID param)
4106{
4107 HANDLE g_hChildStd_IN_Wr = param;
4108 linenr_T lnum = curbuf->b_op_start.lnum;
4109 DWORD len = 0;
4110 DWORD l;
4111 char_u *lp = ml_get(lnum);
4112 char_u *s;
4113 int written = 0;
4114
4115 for (;;)
4116 {
4117 l = (DWORD)STRLEN(lp + written);
4118 if (l == 0)
4119 len = 0;
4120 else if (lp[written] == NL)
4121 {
4122 /* NL -> NUL translation */
4123 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4124 }
4125 else
4126 {
4127 s = vim_strchr(lp + written, NL);
4128 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4129 s == NULL ? l : (DWORD)(s - (lp + written)),
4130 &len, NULL);
4131 }
4132 if (len == (int)l)
4133 {
4134 /* Finished a line, add a NL, unless this line should not have
4135 * one. */
4136 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004137 || (!curbuf->b_p_bin
4138 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004139 || (lnum != curbuf->b_no_eol_lnum
4140 && (lnum != curbuf->b_ml.ml_line_count
4141 || curbuf->b_p_eol)))
4142 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004143 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004144 }
4145
4146 ++lnum;
4147 if (lnum > curbuf->b_op_end.lnum)
4148 break;
4149
4150 lp = ml_get(lnum);
4151 written = 0;
4152 }
4153 else if (len > 0)
4154 written += len;
4155 }
4156
4157 /* finished all the lines, close pipe */
4158 CloseHandle(g_hChildStd_IN_Wr);
4159 ExitThread(0);
4160}
4161
4162
4163# define BUFLEN 100 /* length for buffer, stolen from unix version */
4164
4165/*
4166 * This function read from the children's stdout and write the
4167 * data on screen or in the buffer accordingly.
4168 */
4169 static void
4170dump_pipe(int options,
4171 HANDLE g_hChildStd_OUT_Rd,
4172 garray_T *ga,
4173 char_u buffer[],
4174 DWORD *buffer_off)
4175{
4176 DWORD availableBytes = 0;
4177 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004178 int ret;
4179 DWORD len;
4180 DWORD toRead;
4181 int repeatCount;
4182
4183 /* we query the pipe to see if there is any data to read
4184 * to avoid to perform a blocking read */
4185 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4186 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004187 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004188 NULL, /* number of read bytes */
4189 &availableBytes, /* available bytes total */
4190 NULL); /* byteLeft */
4191
4192 repeatCount = 0;
4193 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004194 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004195 {
4196 repeatCount++;
4197 toRead =
4198# ifdef FEAT_MBYTE
4199 (DWORD)(BUFLEN - *buffer_off);
4200# else
4201 (DWORD)BUFLEN;
4202# endif
4203 toRead = availableBytes < toRead ? availableBytes : toRead;
4204 ReadFile(g_hChildStd_OUT_Rd, buffer
4205# ifdef FEAT_MBYTE
4206 + *buffer_off, toRead
4207# else
4208 , toRead
4209# endif
4210 , &len, NULL);
4211
4212 /* If we haven't read anything, there is a problem */
4213 if (len == 0)
4214 break;
4215
4216 availableBytes -= len;
4217
4218 if (options & SHELL_READ)
4219 {
4220 /* Do NUL -> NL translation, append NL separated
4221 * lines to the current buffer. */
4222 for (i = 0; i < len; ++i)
4223 {
4224 if (buffer[i] == NL)
4225 append_ga_line(ga);
4226 else if (buffer[i] == NUL)
4227 ga_append(ga, NL);
4228 else
4229 ga_append(ga, buffer[i]);
4230 }
4231 }
4232# ifdef FEAT_MBYTE
4233 else if (has_mbyte)
4234 {
4235 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004236 int c;
4237 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004238
4239 len += *buffer_off;
4240 buffer[len] = NUL;
4241
4242 /* Check if the last character in buffer[] is
4243 * incomplete, keep these bytes for the next
4244 * round. */
4245 for (p = buffer; p < buffer + len; p += l)
4246 {
4247 l = mb_cptr2len(p);
4248 if (l == 0)
4249 l = 1; /* NUL byte? */
4250 else if (MB_BYTE2LEN(*p) != l)
4251 break;
4252 }
4253 if (p == buffer) /* no complete character */
4254 {
4255 /* avoid getting stuck at an illegal byte */
4256 if (len >= 12)
4257 ++p;
4258 else
4259 {
4260 *buffer_off = len;
4261 return;
4262 }
4263 }
4264 c = *p;
4265 *p = NUL;
4266 msg_puts(buffer);
4267 if (p < buffer + len)
4268 {
4269 *p = c;
4270 *buffer_off = (DWORD)((buffer + len) - p);
4271 mch_memmove(buffer, p, *buffer_off);
4272 return;
4273 }
4274 *buffer_off = 0;
4275 }
4276# endif /* FEAT_MBYTE */
4277 else
4278 {
4279 buffer[len] = NUL;
4280 msg_puts(buffer);
4281 }
4282
4283 windgoto(msg_row, msg_col);
4284 cursor_on();
4285 out_flush();
4286 }
4287}
4288
4289/*
4290 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4291 * for communication and doesn't open any new window.
4292 */
4293 static int
4294mch_system_piped(char *cmd, int options)
4295{
4296 STARTUPINFO si;
4297 PROCESS_INFORMATION pi;
4298 DWORD ret = 0;
4299
4300 HANDLE g_hChildStd_IN_Rd = NULL;
4301 HANDLE g_hChildStd_IN_Wr = NULL;
4302 HANDLE g_hChildStd_OUT_Rd = NULL;
4303 HANDLE g_hChildStd_OUT_Wr = NULL;
4304
4305 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4306 DWORD len;
4307
4308 /* buffer used to receive keys */
4309 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4310 int ta_len = 0; /* valid bytes in ta_buf[] */
4311
4312 DWORD i;
4313 int c;
4314 int noread_cnt = 0;
4315 garray_T ga;
4316 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004317 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004318 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004319
4320 SECURITY_ATTRIBUTES saAttr;
4321
4322 /* Set the bInheritHandle flag so pipe handles are inherited. */
4323 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4324 saAttr.bInheritHandle = TRUE;
4325 saAttr.lpSecurityDescriptor = NULL;
4326
4327 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4328 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4329 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4330 /* Create a pipe for the child process's STDIN. */
4331 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4332 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4333 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4334 {
4335 CloseHandle(g_hChildStd_IN_Rd);
4336 CloseHandle(g_hChildStd_IN_Wr);
4337 CloseHandle(g_hChildStd_OUT_Rd);
4338 CloseHandle(g_hChildStd_OUT_Wr);
4339 MSG_PUTS(_("\nCannot create pipes\n"));
4340 }
4341
4342 si.cb = sizeof(si);
4343 si.lpReserved = NULL;
4344 si.lpDesktop = NULL;
4345 si.lpTitle = NULL;
4346 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4347
4348 /* set-up our file redirection */
4349 si.hStdError = g_hChildStd_OUT_Wr;
4350 si.hStdOutput = g_hChildStd_OUT_Wr;
4351 si.hStdInput = g_hChildStd_IN_Rd;
4352 si.wShowWindow = SW_HIDE;
4353 si.cbReserved2 = 0;
4354 si.lpReserved2 = NULL;
4355
4356 if (options & SHELL_READ)
4357 ga_init2(&ga, 1, BUFLEN);
4358
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004359 if (cmd != NULL)
4360 {
4361 p = (char *)vim_strsave((char_u *)cmd);
4362 if (p != NULL)
4363 unescape_shellxquote((char_u *)p, p_sxe);
4364 else
4365 p = cmd;
4366 }
4367
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004368 /* Now, run the command.
4369 * About "Inherit handles" being TRUE: this command can be litigious,
4370 * handle inheritance was deactivated for pending temp file, but, if we
4371 * deactivate it, the pipes don't work for some reason. */
4372 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004373
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004374 if (p != cmd)
4375 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004376
4377 /* Close our unused side of the pipes */
4378 CloseHandle(g_hChildStd_IN_Rd);
4379 CloseHandle(g_hChildStd_OUT_Wr);
4380
4381 if (options & SHELL_WRITE)
4382 {
4383 HANDLE thread =
4384 CreateThread(NULL, /* security attributes */
4385 0, /* default stack size */
4386 sub_process_writer, /* function to be executed */
4387 g_hChildStd_IN_Wr, /* parameter */
4388 0, /* creation flag, start immediately */
4389 NULL); /* we don't care about thread id */
4390 CloseHandle(thread);
4391 g_hChildStd_IN_Wr = NULL;
4392 }
4393
4394 /* Keep updating the window while waiting for the shell to finish. */
4395 for (;;)
4396 {
4397 MSG msg;
4398
Bram Moolenaar175d0702013-12-11 18:36:33 +01004399 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004400 {
4401 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004402 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004403 }
4404
4405 /* write pipe information in the window */
4406 if ((options & (SHELL_READ|SHELL_WRITE))
4407# ifdef FEAT_GUI
4408 || gui.in_use
4409# endif
4410 )
4411 {
4412 len = 0;
4413 if (!(options & SHELL_EXPAND)
4414 && ((options &
4415 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4416 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4417# ifdef FEAT_GUI
4418 || gui.in_use
4419# endif
4420 )
4421 && (ta_len > 0 || noread_cnt > 4))
4422 {
4423 if (ta_len == 0)
4424 {
4425 /* Get extra characters when we don't have any. Reset the
4426 * counter and timer. */
4427 noread_cnt = 0;
4428# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4429 gettimeofday(&start_tv, NULL);
4430# endif
4431 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4432 }
4433 if (ta_len > 0 || len > 0)
4434 {
4435 /*
4436 * For pipes: Check for CTRL-C: send interrupt signal to
4437 * child. Check for CTRL-D: EOF, close pipe to child.
4438 */
4439 if (len == 1 && cmd != NULL)
4440 {
4441 if (ta_buf[ta_len] == Ctrl_C)
4442 {
4443 /* Learn what exit code is expected, for
4444 * now put 9 as SIGKILL */
4445 TerminateProcess(pi.hProcess, 9);
4446 }
4447 if (ta_buf[ta_len] == Ctrl_D)
4448 {
4449 CloseHandle(g_hChildStd_IN_Wr);
4450 g_hChildStd_IN_Wr = NULL;
4451 }
4452 }
4453
4454 /* replace K_BS by <BS> and K_DEL by <DEL> */
4455 for (i = ta_len; i < ta_len + len; ++i)
4456 {
4457 if (ta_buf[i] == CSI && len - i > 2)
4458 {
4459 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4460 if (c == K_DEL || c == K_KDEL || c == K_BS)
4461 {
4462 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4463 (size_t)(len - i - 2));
4464 if (c == K_DEL || c == K_KDEL)
4465 ta_buf[i] = DEL;
4466 else
4467 ta_buf[i] = Ctrl_H;
4468 len -= 2;
4469 }
4470 }
4471 else if (ta_buf[i] == '\r')
4472 ta_buf[i] = '\n';
4473# ifdef FEAT_MBYTE
4474 if (has_mbyte)
4475 i += (*mb_ptr2len_len)(ta_buf + i,
4476 ta_len + len - i) - 1;
4477# endif
4478 }
4479
4480 /*
4481 * For pipes: echo the typed characters. For a pty this
4482 * does not seem to work.
4483 */
4484 for (i = ta_len; i < ta_len + len; ++i)
4485 {
4486 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4487 msg_putchar(ta_buf[i]);
4488# ifdef FEAT_MBYTE
4489 else if (has_mbyte)
4490 {
4491 int l = (*mb_ptr2len)(ta_buf + i);
4492
4493 msg_outtrans_len(ta_buf + i, l);
4494 i += l - 1;
4495 }
4496# endif
4497 else
4498 msg_outtrans_len(ta_buf + i, 1);
4499 }
4500 windgoto(msg_row, msg_col);
4501 out_flush();
4502
4503 ta_len += len;
4504
4505 /*
4506 * Write the characters to the child, unless EOF has been
4507 * typed for pipes. Write one character at a time, to
4508 * avoid losing too much typeahead. When writing buffer
4509 * lines, drop the typed characters (only check for
4510 * CTRL-C).
4511 */
4512 if (options & SHELL_WRITE)
4513 ta_len = 0;
4514 else if (g_hChildStd_IN_Wr != NULL)
4515 {
4516 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4517 1, &len, NULL);
4518 // if we are typing in, we want to keep things reactive
4519 delay = 1;
4520 if (len > 0)
4521 {
4522 ta_len -= len;
4523 mch_memmove(ta_buf, ta_buf + len, ta_len);
4524 }
4525 }
4526 }
4527 }
4528 }
4529
4530 if (ta_len)
4531 ui_inchar_undo(ta_buf, ta_len);
4532
4533 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4534 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004535 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004536 break;
4537 }
4538
4539 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004540 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004541
4542 /* We start waiting for a very short time and then increase it, so
4543 * that we respond quickly when the process is quick, and don't
4544 * consume too much overhead when it's slow. */
4545 if (delay < 50)
4546 delay += 10;
4547 }
4548
4549 /* Close the pipe */
4550 CloseHandle(g_hChildStd_OUT_Rd);
4551 if (g_hChildStd_IN_Wr != NULL)
4552 CloseHandle(g_hChildStd_IN_Wr);
4553
4554 WaitForSingleObject(pi.hProcess, INFINITE);
4555
4556 /* Get the command exit code */
4557 GetExitCodeProcess(pi.hProcess, &ret);
4558
4559 if (options & SHELL_READ)
4560 {
4561 if (ga.ga_len > 0)
4562 {
4563 append_ga_line(&ga);
4564 /* remember that the NL was missing */
4565 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4566 }
4567 else
4568 curbuf->b_no_eol_lnum = 0;
4569 ga_clear(&ga);
4570 }
4571
4572 /* Close the handles to the subprocess, so that it goes away */
4573 CloseHandle(pi.hThread);
4574 CloseHandle(pi.hProcess);
4575
4576 return ret;
4577}
4578
4579 static int
4580mch_system(char *cmd, int options)
4581{
4582 /* if we can pipe and the shelltemp option is off */
4583 if (allowPiping && !p_stmp)
4584 return mch_system_piped(cmd, options);
4585 else
4586 return mch_system_classic(cmd, options);
4587}
Bram Moolenaarb0262f22015-09-25 15:28:38 +02004588
Bram Moolenaar071d4272004-06-13 20:20:40 +00004589#else
4590
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004591# ifdef FEAT_MBYTE
4592 static int
Bram Moolenaarb0262f22015-09-25 15:28:38 +02004593mch_system1(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004594{
4595 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4596 {
4597 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4598 if (wcmd != NULL)
4599 {
4600 int ret = _wsystem(wcmd);
4601 vim_free(wcmd);
4602 return ret;
4603 }
4604 }
4605 return system(cmd);
4606}
4607# else
Bram Moolenaarb0262f22015-09-25 15:28:38 +02004608# define mch_system1(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004609# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004610
Bram Moolenaarb0262f22015-09-25 15:28:38 +02004611 static int
4612mch_system(char *cmd, int options)
4613{
4614 int ret;
Bram Moolenaar1d478a62015-09-29 14:01:12 +02004615 HANDLE hTemp = INVALID_HANDLE_VALUE;
Bram Moolenaarb0262f22015-09-25 15:28:38 +02004616
4617 /*
Bram Moolenaar1d478a62015-09-29 14:01:12 +02004618 * Call DuplicateHandle before executing an external program, because msys
4619 * and msys2's programs will call CreateConsoleScreenBuffer and
4620 * CloseHandle. CreateConsoleScreenBuffer returns the same handle which
4621 * created by vim. This causes a crash. This workaround is required on
4622 * Windows7.
Bram Moolenaarb0262f22015-09-25 15:28:38 +02004623 */
Bram Moolenaar1d478a62015-09-29 14:01:12 +02004624 if (is_win7
4625 && g_fTermcapMode
4626 && DuplicateHandle(
4627 GetCurrentProcess(),
4628 g_hConOut,
4629 GetCurrentProcess(),
4630 &hTemp,
4631 0,
4632 TRUE,
4633 DUPLICATE_SAME_ACCESS))
4634 SetConsoleActiveScreenBuffer(hTemp);
Bram Moolenaarb0262f22015-09-25 15:28:38 +02004635
4636 ret = mch_system1(cmd, options);
4637
Bram Moolenaar1d478a62015-09-29 14:01:12 +02004638 if (hTemp != INVALID_HANDLE_VALUE)
4639 {
4640 SetConsoleActiveScreenBuffer(g_hConOut);
4641 CloseHandle(hTemp);
4642 }
Bram Moolenaarb0262f22015-09-25 15:28:38 +02004643
4644 return ret;
4645}
4646
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647#endif
4648
4649/*
4650 * Either execute a command by calling the shell or start a new shell
4651 */
4652 int
4653mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004654 char_u *cmd,
4655 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656{
4657 int x = 0;
4658 int tmode = cur_tmode;
4659#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004660 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004661# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004662 int did_set_title = FALSE;
4663
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004664 /* Change the title to reflect that we are in a subshell. */
4665 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4666 {
4667 WCHAR szShellTitle[512];
4668
4669 if (GetConsoleTitleW(szShellTitle,
4670 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4671 {
4672 if (cmd == NULL)
4673 wcscat(szShellTitle, L" :sh");
4674 else
4675 {
4676 WCHAR *wn = enc_to_utf16(cmd, NULL);
4677
4678 if (wn != NULL)
4679 {
4680 wcscat(szShellTitle, L" - !");
4681 if ((wcslen(szShellTitle) + wcslen(wn) <
4682 sizeof(szShellTitle)/sizeof(WCHAR)))
4683 wcscat(szShellTitle, wn);
4684 SetConsoleTitleW(szShellTitle);
4685 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004686 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004687 }
4688 }
4689 }
4690 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004691 if (!did_set_title)
4692# endif
4693 /* Change the title to reflect that we are in a subshell. */
4694 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004695 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004696 if (cmd == NULL)
4697 strcat(szShellTitle, " :sh");
4698 else
4699 {
4700 strcat(szShellTitle, " - !");
4701 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4702 strcat(szShellTitle, cmd);
4703 }
4704 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004705 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706#endif
4707
4708 out_flush();
4709
4710#ifdef MCH_WRITE_DUMP
4711 if (fdDump)
4712 {
4713 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4714 fflush(fdDump);
4715 }
4716#endif
4717
4718 /*
4719 * Catch all deadly signals while running the external command, because a
4720 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4721 */
4722 signal(SIGINT, SIG_IGN);
4723#if defined(__GNUC__) && !defined(__MINGW32__)
4724 signal(SIGKILL, SIG_IGN);
4725#else
4726 signal(SIGBREAK, SIG_IGN);
4727#endif
4728 signal(SIGILL, SIG_IGN);
4729 signal(SIGFPE, SIG_IGN);
4730 signal(SIGSEGV, SIG_IGN);
4731 signal(SIGTERM, SIG_IGN);
4732 signal(SIGABRT, SIG_IGN);
4733
4734 if (options & SHELL_COOKED)
4735 settmode(TMODE_COOK); /* set to normal mode */
4736
4737 if (cmd == NULL)
4738 {
4739 x = mch_system(p_sh, options);
4740 }
4741 else
4742 {
4743 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004744 char_u *newcmd = NULL;
4745 char_u *cmdbase = cmd;
4746 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004747
4748 /* Skip a leading ", ( and "(. */
4749 if (*cmdbase == '"' )
4750 ++cmdbase;
4751 if (*cmdbase == '(')
4752 ++cmdbase;
4753
4754 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4755 {
4756 STARTUPINFO si;
4757 PROCESS_INFORMATION pi;
4758 DWORD flags = CREATE_NEW_CONSOLE;
4759 char_u *p;
4760
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004761 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004762 si.cb = sizeof(si);
4763 si.lpReserved = NULL;
4764 si.lpDesktop = NULL;
4765 si.lpTitle = NULL;
4766 si.dwFlags = 0;
4767 si.cbReserved2 = 0;
4768 si.lpReserved2 = NULL;
4769
4770 cmdbase = skipwhite(cmdbase + 5);
4771 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4772 && vim_iswhite(cmdbase[4]))
4773 {
4774 cmdbase = skipwhite(cmdbase + 4);
4775 si.dwFlags = STARTF_USESHOWWINDOW;
4776 si.wShowWindow = SW_SHOWMINNOACTIVE;
4777 }
4778 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4779 && vim_iswhite(cmdbase[2]))
4780 {
4781 cmdbase = skipwhite(cmdbase + 2);
4782 flags = CREATE_NO_WINDOW;
4783 si.dwFlags = STARTF_USESTDHANDLES;
4784 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004785 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004786 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004787 NULL, // Security att.
4788 OPEN_EXISTING, // Open flags
4789 FILE_ATTRIBUTE_NORMAL, // File att.
4790 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004791 si.hStdOutput = si.hStdInput;
4792 si.hStdError = si.hStdInput;
4793 }
4794
4795 /* Remove a trailing ", ) and )" if they have a match
4796 * at the start of the command. */
4797 if (cmdbase > cmd)
4798 {
4799 p = cmdbase + STRLEN(cmdbase);
4800 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4801 *--p = NUL;
4802 if (p > cmdbase && p[-1] == ')'
4803 && (*cmd =='(' || cmd[1] == '('))
4804 *--p = NUL;
4805 }
4806
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004807 newcmd = cmdbase;
4808 unescape_shellxquote(cmdbase, p_sxe);
4809
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004810 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004811 * If creating new console, arguments are passed to the
4812 * 'cmd.exe' as-is. If it's not, arguments are not treated
4813 * correctly for current 'cmd.exe'. So unescape characters in
4814 * shellxescape except '|' for avoiding to be treated as
4815 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004816 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004817 if (flags != CREATE_NEW_CONSOLE)
4818 {
4819 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004820 char_u *cmd_shell = mch_getenv("COMSPEC");
4821
4822 if (cmd_shell == NULL || *cmd_shell == NUL)
4823 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004824
4825 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4826 if (subcmd != NULL)
4827 {
4828 /* make "cmd.exe /c arguments" */
4829 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004830 newcmd = lalloc(cmdlen, TRUE);
4831 if (newcmd != NULL)
4832 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004833 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004834 else
4835 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004836 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004837 }
4838 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004839
4840 /*
4841 * Now, start the command as a process, so that it doesn't
4842 * inherit our handles which causes unpleasant dangling swap
4843 * files if we exit before the spawned process
4844 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004845 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004846 x = 0;
4847 else
4848 {
4849 x = -1;
4850#ifdef FEAT_GUI_W32
4851 EMSG(_("E371: Command not found"));
4852#endif
4853 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004854
4855 if (newcmd != cmdbase)
4856 vim_free(newcmd);
4857
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004858 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004859 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004860 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004861 CloseHandle(si.hStdInput);
4862 }
4863 /* Close the handles to the subprocess, so that it goes away */
4864 CloseHandle(pi.hThread);
4865 CloseHandle(pi.hProcess);
4866 }
4867 else
4868 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004869 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004870#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004871 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004873 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4874
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004875 newcmd = lalloc(cmdlen, TRUE);
4876 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877 {
4878#if defined(FEAT_GUI_W32)
4879 if (need_vimrun_warning)
4880 {
4881 MessageBox(NULL,
4882 _("VIMRUN.EXE not found in your $PATH.\n"
4883 "External commands will not pause after completion.\n"
4884 "See :help win32-vimrun for more information."),
4885 _("Vim Warning"),
4886 MB_ICONWARNING);
4887 need_vimrun_warning = FALSE;
4888 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004889 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890 /* Use vimrun to execute the command. It opens a console
4891 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004892 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 vimrun_path,
4894 (msg_silent != 0 || (options & SHELL_DOOUT))
4895 ? "-s " : "",
4896 p_sh, p_shcf, cmd);
4897 else
4898#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004899 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004900 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004902 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904 }
4905 }
4906
4907 if (tmode == TMODE_RAW)
4908 settmode(TMODE_RAW); /* set to raw mode */
4909
4910 /* Print the return value, unless "vimrun" was used. */
4911 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4912#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004913 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4914 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915#endif
4916 )
4917 {
4918 smsg(_("shell returned %d"), x);
4919 msg_putchar('\n');
4920 }
4921#ifdef FEAT_TITLE
4922 resettitle();
4923#endif
4924
4925 signal(SIGINT, SIG_DFL);
4926#if defined(__GNUC__) && !defined(__MINGW32__)
4927 signal(SIGKILL, SIG_DFL);
4928#else
4929 signal(SIGBREAK, SIG_DFL);
4930#endif
4931 signal(SIGILL, SIG_DFL);
4932 signal(SIGFPE, SIG_DFL);
4933 signal(SIGSEGV, SIG_DFL);
4934 signal(SIGTERM, SIG_DFL);
4935 signal(SIGABRT, SIG_DFL);
4936
4937 return x;
4938}
4939
4940
4941#ifndef FEAT_GUI_W32
4942
4943/*
4944 * Start termcap mode
4945 */
4946 static void
4947termcap_mode_start(void)
4948{
4949 DWORD cmodein;
4950
4951 if (g_fTermcapMode)
4952 return;
4953
4954 SaveConsoleBuffer(&g_cbNonTermcap);
4955
4956 if (g_cbTermcap.IsValid)
4957 {
4958 /*
4959 * We've been in termcap mode before. Restore certain screen
4960 * characteristics, including the buffer size and the window
4961 * size. Since we will be redrawing the screen, we don't need
4962 * to restore the actual contents of the buffer.
4963 */
4964 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4965 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4966 Rows = g_cbTermcap.Info.dwSize.Y;
4967 Columns = g_cbTermcap.Info.dwSize.X;
4968 }
4969 else
4970 {
4971 /*
4972 * This is our first time entering termcap mode. Clear the console
4973 * screen buffer, and resize the buffer to match the current window
4974 * size. We will use this as the size of our editing environment.
4975 */
Bram Moolenaar61594242015-09-01 20:23:37 +02004976 g_hConOut = g_cbTermcap.handle;
4977 SetConsoleActiveScreenBuffer(g_hConOut);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978 ClearConsoleBuffer(g_attrCurrent);
4979 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4980 }
4981
4982#ifdef FEAT_TITLE
4983 resettitle();
4984#endif
4985
4986 GetConsoleMode(g_hConIn, &cmodein);
4987#ifdef FEAT_MOUSE
4988 if (g_fMouseActive)
4989 cmodein |= ENABLE_MOUSE_INPUT;
4990 else
4991 cmodein &= ~ENABLE_MOUSE_INPUT;
4992#endif
4993 cmodein |= ENABLE_WINDOW_INPUT;
4994 SetConsoleMode(g_hConIn, cmodein);
4995
4996 redraw_later_clear();
4997 g_fTermcapMode = TRUE;
4998}
4999
5000
5001/*
5002 * End termcap mode
5003 */
5004 static void
5005termcap_mode_end(void)
5006{
5007 DWORD cmodein;
5008 ConsoleBuffer *cb;
5009 COORD coord;
5010 DWORD dwDummy;
5011
5012 if (!g_fTermcapMode)
5013 return;
5014
5015 SaveConsoleBuffer(&g_cbTermcap);
5016
5017 GetConsoleMode(g_hConIn, &cmodein);
5018 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5019 SetConsoleMode(g_hConIn, cmodein);
5020
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021 cb = &g_cbNonTermcap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005022 RestoreConsoleBuffer(cb, p_rs);
5023 SetConsoleCursorInfo(g_hConOut, &g_cci);
5024
5025 if (p_rs || exiting)
5026 {
5027 /*
5028 * Clear anything that happens to be on the current line.
5029 */
5030 coord.X = 0;
5031 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5032 FillConsoleOutputCharacter(g_hConOut, ' ',
5033 cb->Info.dwSize.X, coord, &dwDummy);
5034 /*
5035 * The following is just for aesthetics. If we are exiting without
5036 * restoring the screen, then we want to have a prompt string
5037 * appear at the bottom line. However, the command interpreter
5038 * seems to always advance the cursor one line before displaying
5039 * the prompt string, which causes the screen to scroll. To
5040 * counter this, move the cursor up one line before exiting.
5041 */
5042 if (exiting && !p_rs)
5043 coord.Y--;
5044 /*
5045 * Position the cursor at the leftmost column of the desired row.
5046 */
5047 SetConsoleCursorPosition(g_hConOut, coord);
5048 }
5049
5050 g_fTermcapMode = FALSE;
5051}
5052#endif /* FEAT_GUI_W32 */
5053
5054
5055#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005056/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005057 void
5058mch_write(
5059 char_u *s,
5060 int len)
5061{
5062 /* never used */
5063}
5064
5065#else
5066
5067/*
5068 * clear `n' chars, starting from `coord'
5069 */
5070 static void
5071clear_chars(
5072 COORD coord,
5073 DWORD n)
5074{
5075 DWORD dwDummy;
5076
5077 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5078 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5079}
5080
5081
5082/*
5083 * Clear the screen
5084 */
5085 static void
5086clear_screen(void)
5087{
5088 g_coord.X = g_coord.Y = 0;
5089 clear_chars(g_coord, Rows * Columns);
5090}
5091
5092
5093/*
5094 * Clear to end of display
5095 */
5096 static void
5097clear_to_end_of_display(void)
5098{
5099 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5100 * Columns + (Columns - g_coord.X));
5101}
5102
5103
5104/*
5105 * Clear to end of line
5106 */
5107 static void
5108clear_to_end_of_line(void)
5109{
5110 clear_chars(g_coord, Columns - g_coord.X);
5111}
5112
5113
5114/*
5115 * Scroll the scroll region up by `cLines' lines
5116 */
5117 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005118scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005119{
5120 COORD oldcoord = g_coord;
5121
5122 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5123 delete_lines(cLines);
5124
5125 g_coord = oldcoord;
5126}
5127
5128
5129/*
5130 * Set the scroll region
5131 */
5132 static void
5133set_scroll_region(
5134 unsigned left,
5135 unsigned top,
5136 unsigned right,
5137 unsigned bottom)
5138{
5139 if (left >= right
5140 || top >= bottom
5141 || right > (unsigned) Columns - 1
5142 || bottom > (unsigned) Rows - 1)
5143 return;
5144
5145 g_srScrollRegion.Left = left;
5146 g_srScrollRegion.Top = top;
5147 g_srScrollRegion.Right = right;
5148 g_srScrollRegion.Bottom = bottom;
5149}
5150
5151
5152/*
5153 * Insert `cLines' lines at the current cursor position
5154 */
5155 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005156insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157{
5158 SMALL_RECT source;
5159 COORD dest;
5160 CHAR_INFO fill;
5161
5162 dest.X = 0;
5163 dest.Y = g_coord.Y + cLines;
5164
5165 source.Left = 0;
5166 source.Top = g_coord.Y;
5167 source.Right = g_srScrollRegion.Right;
5168 source.Bottom = g_srScrollRegion.Bottom - cLines;
5169
5170 fill.Char.AsciiChar = ' ';
5171 fill.Attributes = g_attrCurrent;
5172
5173 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5174
5175 /* Here we have to deal with a win32 console flake: If the scroll
5176 * region looks like abc and we scroll c to a and fill with d we get
5177 * cbd... if we scroll block c one line at a time to a, we get cdd...
5178 * vim expects cdd consistently... So we have to deal with that
5179 * here... (this also occurs scrolling the same way in the other
5180 * direction). */
5181
5182 if (source.Bottom < dest.Y)
5183 {
5184 COORD coord;
5185
5186 coord.X = 0;
5187 coord.Y = source.Bottom;
5188 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5189 }
5190}
5191
5192
5193/*
5194 * Delete `cLines' lines at the current cursor position
5195 */
5196 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005197delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198{
5199 SMALL_RECT source;
5200 COORD dest;
5201 CHAR_INFO fill;
5202 int nb;
5203
5204 dest.X = 0;
5205 dest.Y = g_coord.Y;
5206
5207 source.Left = 0;
5208 source.Top = g_coord.Y + cLines;
5209 source.Right = g_srScrollRegion.Right;
5210 source.Bottom = g_srScrollRegion.Bottom;
5211
5212 fill.Char.AsciiChar = ' ';
5213 fill.Attributes = g_attrCurrent;
5214
5215 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5216
5217 /* Here we have to deal with a win32 console flake: If the scroll
5218 * region looks like abc and we scroll c to a and fill with d we get
5219 * cbd... if we scroll block c one line at a time to a, we get cdd...
5220 * vim expects cdd consistently... So we have to deal with that
5221 * here... (this also occurs scrolling the same way in the other
5222 * direction). */
5223
5224 nb = dest.Y + (source.Bottom - source.Top) + 1;
5225
5226 if (nb < source.Top)
5227 {
5228 COORD coord;
5229
5230 coord.X = 0;
5231 coord.Y = nb;
5232 clear_chars(coord, Columns * (source.Top - nb));
5233 }
5234}
5235
5236
5237/*
5238 * Set the cursor position
5239 */
5240 static void
5241gotoxy(
5242 unsigned x,
5243 unsigned y)
5244{
5245 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5246 return;
5247
5248 /* external cursor coords are 1-based; internal are 0-based */
5249 g_coord.X = x - 1;
5250 g_coord.Y = y - 1;
5251 SetConsoleCursorPosition(g_hConOut, g_coord);
5252}
5253
5254
5255/*
5256 * Set the current text attribute = (foreground | background)
5257 * See ../doc/os_win32.txt for the numbers.
5258 */
5259 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005260textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005262 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005263
5264 SetConsoleTextAttribute(g_hConOut, wAttr);
5265}
5266
5267
5268 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005269textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005270{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005271 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005272
5273 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5274}
5275
5276
5277 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005278textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005279{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005280 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005281
5282 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5283}
5284
5285
5286/*
5287 * restore the default text attribute (whatever we started with)
5288 */
5289 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005290normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291{
5292 textattr(g_attrDefault);
5293}
5294
5295
5296static WORD g_attrPreStandout = 0;
5297
5298/*
5299 * Make the text standout, by brightening it
5300 */
5301 static void
5302standout(void)
5303{
5304 g_attrPreStandout = g_attrCurrent;
5305 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5306}
5307
5308
5309/*
5310 * Turn off standout mode
5311 */
5312 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005313standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005314{
5315 if (g_attrPreStandout)
5316 {
5317 textattr(g_attrPreStandout);
5318 g_attrPreStandout = 0;
5319 }
5320}
5321
5322
5323/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005324 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005325 */
5326 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005327mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328{
5329 char_u *p;
5330 int n;
5331
5332 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5333 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5334 if (T_ME[0] == ESC && T_ME[1] == '|')
5335 {
5336 p = T_ME + 2;
5337 n = getdigits(&p);
5338 if (*p == 'm' && n > 0)
5339 {
5340 cterm_normal_fg_color = (n & 0xf) + 1;
5341 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5342 }
5343 }
5344}
5345
5346
5347/*
5348 * visual bell: flash the screen
5349 */
5350 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005351visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005352{
5353 COORD coordOrigin = {0, 0};
5354 WORD attrFlash = ~g_attrCurrent & 0xff;
5355
5356 DWORD dwDummy;
5357 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5358
5359 if (oldattrs == NULL)
5360 return;
5361 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5362 coordOrigin, &dwDummy);
5363 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5364 coordOrigin, &dwDummy);
5365
5366 Sleep(15); /* wait for 15 msec */
5367 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5368 coordOrigin, &dwDummy);
5369 vim_free(oldattrs);
5370}
5371
5372
5373/*
5374 * Make the cursor visible or invisible
5375 */
5376 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005377cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005378{
5379 s_cursor_visible = fVisible;
5380#ifdef MCH_CURSOR_SHAPE
5381 mch_update_cursor();
5382#endif
5383}
5384
5385
5386/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005387 * write `cbToWrite' bytes in `pchBuf' to the screen
5388 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005389 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005390 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005391write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005392 char_u *pchBuf,
5393 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005394{
5395 COORD coord = g_coord;
5396 DWORD written;
5397
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005398#ifdef FEAT_MBYTE
5399 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5400 {
5401 static WCHAR *unicodebuf = NULL;
5402 static int unibuflen = 0;
5403 int length;
5404 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005405
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005406 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5407 if (unicodebuf == NULL || length > unibuflen)
5408 {
5409 vim_free(unicodebuf);
5410 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5411 unibuflen = length;
5412 }
5413 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5414 unicodebuf, unibuflen);
5415
5416 cells = mb_string2cells(pchBuf, cbToWrite);
5417 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5418 coord, &written);
5419 /* When writing fails or didn't write a single character, pretend one
5420 * character was written, otherwise we get stuck. */
5421 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5422 coord, &cchwritten) == 0
5423 || cchwritten == 0)
5424 cchwritten = 1;
5425
5426 if (cchwritten == length)
5427 {
5428 written = cbToWrite;
5429 g_coord.X += (SHORT)cells;
5430 }
5431 else
5432 {
5433 char_u *p = pchBuf;
5434 for (n = 0; n < cchwritten; n++)
5435 mb_cptr_adv(p);
5436 written = p - pchBuf;
5437 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5438 }
5439 }
5440 else
5441#endif
5442 {
5443 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5444 coord, &written);
5445 /* When writing fails or didn't write a single character, pretend one
5446 * character was written, otherwise we get stuck. */
5447 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5448 coord, &written) == 0
5449 || written == 0)
5450 written = 1;
5451
5452 g_coord.X += (SHORT) written;
5453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454
5455 while (g_coord.X > g_srScrollRegion.Right)
5456 {
5457 g_coord.X -= (SHORT) Columns;
5458 if (g_coord.Y < g_srScrollRegion.Bottom)
5459 g_coord.Y++;
5460 }
5461
5462 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5463
5464 return written;
5465}
5466
5467
5468/*
5469 * mch_write(): write the output buffer to the screen, translating ESC
5470 * sequences into calls to console output routines.
5471 */
5472 void
5473mch_write(
5474 char_u *s,
5475 int len)
5476{
5477 s[len] = NUL;
5478
5479 if (!term_console)
5480 {
5481 write(1, s, (unsigned)len);
5482 return;
5483 }
5484
5485 /* translate ESC | sequences into faked bios calls */
5486 while (len--)
5487 {
5488 /* optimization: use one single write_chars for runs of text,
5489 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005490 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005491
5492 if (p_wd)
5493 {
5494 WaitForChar(p_wd);
5495 if (prefix != 0)
5496 prefix = 1;
5497 }
5498
5499 if (prefix != 0)
5500 {
5501 DWORD nWritten;
5502
5503 nWritten = write_chars(s, prefix);
5504#ifdef MCH_WRITE_DUMP
5505 if (fdDump)
5506 {
5507 fputc('>', fdDump);
5508 fwrite(s, sizeof(char_u), nWritten, fdDump);
5509 fputs("<\n", fdDump);
5510 }
5511#endif
5512 len -= (nWritten - 1);
5513 s += nWritten;
5514 }
5515 else if (s[0] == '\n')
5516 {
5517 /* \n, newline: go to the beginning of the next line or scroll */
5518 if (g_coord.Y == g_srScrollRegion.Bottom)
5519 {
5520 scroll(1);
5521 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5522 }
5523 else
5524 {
5525 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5526 }
5527#ifdef MCH_WRITE_DUMP
5528 if (fdDump)
5529 fputs("\\n\n", fdDump);
5530#endif
5531 s++;
5532 }
5533 else if (s[0] == '\r')
5534 {
5535 /* \r, carriage return: go to beginning of line */
5536 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5537#ifdef MCH_WRITE_DUMP
5538 if (fdDump)
5539 fputs("\\r\n", fdDump);
5540#endif
5541 s++;
5542 }
5543 else if (s[0] == '\b')
5544 {
5545 /* \b, backspace: move cursor one position left */
5546 if (g_coord.X > g_srScrollRegion.Left)
5547 g_coord.X--;
5548 else if (g_coord.Y > g_srScrollRegion.Top)
5549 {
5550 g_coord.X = g_srScrollRegion.Right;
5551 g_coord.Y--;
5552 }
5553 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5554#ifdef MCH_WRITE_DUMP
5555 if (fdDump)
5556 fputs("\\b\n", fdDump);
5557#endif
5558 s++;
5559 }
5560 else if (s[0] == '\a')
5561 {
5562 /* \a, bell */
5563 MessageBeep(0xFFFFFFFF);
5564#ifdef MCH_WRITE_DUMP
5565 if (fdDump)
5566 fputs("\\a\n", fdDump);
5567#endif
5568 s++;
5569 }
5570 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5571 {
5572#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005573 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005575 char_u *p;
5576 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577
5578 switch (s[2])
5579 {
5580 /* one or two numeric arguments, separated by ';' */
5581
5582 case '0': case '1': case '2': case '3': case '4':
5583 case '5': case '6': case '7': case '8': case '9':
5584 p = s + 2;
5585 arg1 = getdigits(&p); /* no check for length! */
5586 if (p > s + len)
5587 break;
5588
5589 if (*p == ';')
5590 {
5591 ++p;
5592 arg2 = getdigits(&p); /* no check for length! */
5593 if (p > s + len)
5594 break;
5595
5596 if (*p == 'H')
5597 gotoxy(arg2, arg1);
5598 else if (*p == 'r')
5599 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5600 }
5601 else if (*p == 'A')
5602 {
5603 /* move cursor up arg1 lines in same column */
5604 gotoxy(g_coord.X + 1,
5605 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5606 }
5607 else if (*p == 'C')
5608 {
5609 /* move cursor right arg1 columns in same line */
5610 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5611 g_coord.Y + 1);
5612 }
5613 else if (*p == 'H')
5614 {
5615 gotoxy(1, arg1);
5616 }
5617 else if (*p == 'L')
5618 {
5619 insert_lines(arg1);
5620 }
5621 else if (*p == 'm')
5622 {
5623 if (arg1 == 0)
5624 normvideo();
5625 else
5626 textattr((WORD) arg1);
5627 }
5628 else if (*p == 'f')
5629 {
5630 textcolor((WORD) arg1);
5631 }
5632 else if (*p == 'b')
5633 {
5634 textbackground((WORD) arg1);
5635 }
5636 else if (*p == 'M')
5637 {
5638 delete_lines(arg1);
5639 }
5640
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005641 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 s = p + 1;
5643 break;
5644
5645
5646 /* Three-character escape sequences */
5647
5648 case 'A':
5649 /* move cursor up one line in same column */
5650 gotoxy(g_coord.X + 1,
5651 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5652 goto got3;
5653
5654 case 'B':
5655 visual_bell();
5656 goto got3;
5657
5658 case 'C':
5659 /* move cursor right one column in same line */
5660 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5661 g_coord.Y + 1);
5662 goto got3;
5663
5664 case 'E':
5665 termcap_mode_end();
5666 goto got3;
5667
5668 case 'F':
5669 standout();
5670 goto got3;
5671
5672 case 'f':
5673 standend();
5674 goto got3;
5675
5676 case 'H':
5677 gotoxy(1, 1);
5678 goto got3;
5679
5680 case 'j':
5681 clear_to_end_of_display();
5682 goto got3;
5683
5684 case 'J':
5685 clear_screen();
5686 goto got3;
5687
5688 case 'K':
5689 clear_to_end_of_line();
5690 goto got3;
5691
5692 case 'L':
5693 insert_lines(1);
5694 goto got3;
5695
5696 case 'M':
5697 delete_lines(1);
5698 goto got3;
5699
5700 case 'S':
5701 termcap_mode_start();
5702 goto got3;
5703
5704 case 'V':
5705 cursor_visible(TRUE);
5706 goto got3;
5707
5708 case 'v':
5709 cursor_visible(FALSE);
5710 goto got3;
5711
5712 got3:
5713 s += 3;
5714 len -= 2;
5715 }
5716
5717#ifdef MCH_WRITE_DUMP
5718 if (fdDump)
5719 {
5720 fputs("ESC | ", fdDump);
5721 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5722 fputc('\n', fdDump);
5723 }
5724#endif
5725 }
5726 else
5727 {
5728 /* Write a single character */
5729 DWORD nWritten;
5730
5731 nWritten = write_chars(s, 1);
5732#ifdef MCH_WRITE_DUMP
5733 if (fdDump)
5734 {
5735 fputc('>', fdDump);
5736 fwrite(s, sizeof(char_u), nWritten, fdDump);
5737 fputs("<\n", fdDump);
5738 }
5739#endif
5740
5741 len -= (nWritten - 1);
5742 s += nWritten;
5743 }
5744 }
5745
5746#ifdef MCH_WRITE_DUMP
5747 if (fdDump)
5748 fflush(fdDump);
5749#endif
5750}
5751
5752#endif /* FEAT_GUI_W32 */
5753
5754
5755/*
5756 * Delay for half a second.
5757 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005758/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005759 void
5760mch_delay(
5761 long msec,
5762 int ignoreinput)
5763{
5764#ifdef FEAT_GUI_W32
5765 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005766#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005768# ifdef FEAT_MZSCHEME
5769 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5770 {
5771 int towait = p_mzq;
5772
5773 /* if msec is large enough, wait by portions in p_mzq */
5774 while (msec > 0)
5775 {
5776 mzvim_check_threads();
5777 if (msec < towait)
5778 towait = msec;
5779 Sleep(towait);
5780 msec -= towait;
5781 }
5782 }
5783 else
5784# endif
5785 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786 else
5787 WaitForChar(msec);
5788#endif
5789}
5790
5791
5792/*
5793 * this version of remove is not scared by a readonly (backup) file
5794 * Return 0 for success, -1 for failure.
5795 */
5796 int
5797mch_remove(char_u *name)
5798{
5799#ifdef FEAT_MBYTE
5800 WCHAR *wn = NULL;
5801 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005802#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005804 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5805
5806#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005807 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5808 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005809 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005810 if (wn != NULL)
5811 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005812 n = DeleteFileW(wn) ? 0 : -1;
5813 vim_free(wn);
5814 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5815 return n;
5816 /* Retry with non-wide function (for Windows 98). */
5817 }
5818 }
5819#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820 return DeleteFile(name) ? 0 : -1;
5821}
5822
5823
5824/*
5825 * check for an "interrupt signal": CTRL-break or CTRL-C
5826 */
5827 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005828mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829{
5830#ifndef FEAT_GUI_W32 /* never used */
5831 if (g_fCtrlCPressed || g_fCBrkPressed)
5832 {
5833 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5834 got_int = TRUE;
5835 }
5836#endif
5837}
5838
5839
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840#ifdef FEAT_MBYTE
5841/*
5842 * Same code as below, but with wide functions and no comments.
5843 * Return 0 for success, non-zero for failure.
5844 */
5845 int
5846mch_wrename(WCHAR *wold, WCHAR *wnew)
5847{
5848 WCHAR *p;
5849 int i;
5850 WCHAR szTempFile[_MAX_PATH + 1];
5851 WCHAR szNewPath[_MAX_PATH + 1];
5852 HANDLE hf;
5853
5854 if (!mch_windows95())
5855 {
5856 p = wold;
5857 for (i = 0; wold[i] != NUL; ++i)
5858 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5859 && wold[i + 1] != 0)
5860 p = wold + i + 1;
5861 if ((int)(wold + i - p) < 8 || p[6] != '~')
5862 return (MoveFileW(wold, wnew) == 0);
5863 }
5864
5865 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5866 return -1;
5867 *p = NUL;
5868
5869 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5870 return -2;
5871
5872 if (!DeleteFileW(szTempFile))
5873 return -3;
5874
5875 if (!MoveFileW(wold, szTempFile))
5876 return -4;
5877
5878 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5879 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5880 return -5;
5881 if (!CloseHandle(hf))
5882 return -6;
5883
5884 if (!MoveFileW(szTempFile, wnew))
5885 {
5886 (void)MoveFileW(szTempFile, wold);
5887 return -7;
5888 }
5889
5890 DeleteFileW(szTempFile);
5891
5892 if (!DeleteFileW(wold))
5893 return -8;
5894
5895 return 0;
5896}
5897#endif
5898
5899
5900/*
5901 * mch_rename() works around a bug in rename (aka MoveFile) in
5902 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5903 * file whose short file name is "FOO.BAR" (its long file name will
5904 * be correct: "foo.bar~"). Because a file can be accessed by
5905 * either its SFN or its LFN, "foo.bar" has effectively been
5906 * renamed to "foo.bar", which is not at all what was wanted. This
5907 * seems to happen only when renaming files with three-character
5908 * extensions by appending a suffix that does not include ".".
5909 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5910 *
5911 * There is another problem, which isn't really a bug but isn't right either:
5912 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5913 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5914 * service pack 6. Doesn't seem to happen on Windows 98.
5915 *
5916 * Like rename(), returns 0 upon success, non-zero upon failure.
5917 * Should probably set errno appropriately when errors occur.
5918 */
5919 int
5920mch_rename(
5921 const char *pszOldFile,
5922 const char *pszNewFile)
5923{
5924 char szTempFile[_MAX_PATH+1];
5925 char szNewPath[_MAX_PATH+1];
5926 char *pszFilePart;
5927 HANDLE hf;
5928#ifdef FEAT_MBYTE
5929 WCHAR *wold = NULL;
5930 WCHAR *wnew = NULL;
5931 int retval = -1;
5932
5933 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5934 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005935 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5936 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937 if (wold != NULL && wnew != NULL)
5938 retval = mch_wrename(wold, wnew);
5939 vim_free(wold);
5940 vim_free(wnew);
5941 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5942 return retval;
5943 /* Retry with non-wide function (for Windows 98). */
5944 }
5945#endif
5946
5947 /*
5948 * No need to play tricks if not running Windows 95, unless the file name
5949 * contains a "~" as the seventh character.
5950 */
5951 if (!mch_windows95())
5952 {
5953 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5954 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5955 return rename(pszOldFile, pszNewFile);
5956 }
5957
5958 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5959 * a directory, no error is returned and pszFilePart will be NULL. */
5960 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5961 || pszFilePart == NULL)
5962 return -1;
5963 *pszFilePart = NUL;
5964
5965 /* Get (and create) a unique temporary file name in directory of new file */
5966 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5967 return -2;
5968
5969 /* blow the temp file away */
5970 if (!DeleteFile(szTempFile))
5971 return -3;
5972
5973 /* rename old file to the temp file */
5974 if (!MoveFile(pszOldFile, szTempFile))
5975 return -4;
5976
5977 /* now create an empty file called pszOldFile; this prevents the operating
5978 * system using pszOldFile as an alias (SFN) if we're renaming within the
5979 * same directory. For example, we're editing a file called
5980 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5981 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5982 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005983 * cause all sorts of problems later in buf_write(). So, we create an
5984 * empty file called filena~1.txt and the system will have to find some
5985 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005986 */
5987 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5988 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5989 return -5;
5990 if (!CloseHandle(hf))
5991 return -6;
5992
5993 /* rename the temp file to the new file */
5994 if (!MoveFile(szTempFile, pszNewFile))
5995 {
5996 /* Renaming failed. Rename the file back to its old name, so that it
5997 * looks like nothing happened. */
5998 (void)MoveFile(szTempFile, pszOldFile);
5999
6000 return -7;
6001 }
6002
6003 /* Seems to be left around on Novell filesystems */
6004 DeleteFile(szTempFile);
6005
6006 /* finally, remove the empty old file */
6007 if (!DeleteFile(pszOldFile))
6008 return -8;
6009
6010 return 0; /* success */
6011}
6012
6013/*
6014 * Get the default shell for the current hardware platform
6015 */
6016 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006017default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018{
6019 char* psz = NULL;
6020
6021 PlatformId();
6022
6023 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6024 psz = "cmd.exe";
6025 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6026 psz = "command.com";
6027
6028 return psz;
6029}
6030
6031/*
6032 * mch_access() extends access() to do more detailed check on network drives.
6033 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6034 */
6035 int
6036mch_access(char *n, int p)
6037{
6038 HANDLE hFile;
6039 DWORD am;
6040 int retval = -1; /* default: fail */
6041#ifdef FEAT_MBYTE
6042 WCHAR *wn = NULL;
6043
6044 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006045 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046#endif
6047
6048 if (mch_isdir(n))
6049 {
6050 char TempName[_MAX_PATH + 16] = "";
6051#ifdef FEAT_MBYTE
6052 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6053#endif
6054
6055 if (p & R_OK)
6056 {
6057 /* Read check is performed by seeing if we can do a find file on
6058 * the directory for any file. */
6059#ifdef FEAT_MBYTE
6060 if (wn != NULL)
6061 {
6062 int i;
6063 WIN32_FIND_DATAW d;
6064
6065 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6066 TempNameW[i] = wn[i];
6067 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6068 TempNameW[i++] = '\\';
6069 TempNameW[i++] = '*';
6070 TempNameW[i++] = 0;
6071
6072 hFile = FindFirstFileW(TempNameW, &d);
6073 if (hFile == INVALID_HANDLE_VALUE)
6074 {
6075 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6076 goto getout;
6077
6078 /* Retry with non-wide function (for Windows 98). */
6079 vim_free(wn);
6080 wn = NULL;
6081 }
6082 else
6083 (void)FindClose(hFile);
6084 }
6085 if (wn == NULL)
6086#endif
6087 {
6088 char *pch;
6089 WIN32_FIND_DATA d;
6090
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006091 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092 pch = TempName + STRLEN(TempName) - 1;
6093 if (*pch != '\\' && *pch != '/')
6094 *++pch = '\\';
6095 *++pch = '*';
6096 *++pch = NUL;
6097
6098 hFile = FindFirstFile(TempName, &d);
6099 if (hFile == INVALID_HANDLE_VALUE)
6100 goto getout;
6101 (void)FindClose(hFile);
6102 }
6103 }
6104
6105 if (p & W_OK)
6106 {
6107 /* Trying to create a temporary file in the directory should catch
6108 * directories on read-only network shares. However, in
6109 * directories whose ACL allows writes but denies deletes will end
6110 * up keeping the temporary file :-(. */
6111#ifdef FEAT_MBYTE
6112 if (wn != NULL)
6113 {
6114 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6115 {
6116 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6117 goto getout;
6118
6119 /* Retry with non-wide function (for Windows 98). */
6120 vim_free(wn);
6121 wn = NULL;
6122 }
6123 else
6124 DeleteFileW(TempNameW);
6125 }
6126 if (wn == NULL)
6127#endif
6128 {
6129 if (!GetTempFileName(n, "VIM", 0, TempName))
6130 goto getout;
6131 mch_remove((char_u *)TempName);
6132 }
6133 }
6134 }
6135 else
6136 {
6137 /* Trying to open the file for the required access does ACL, read-only
6138 * network share, and file attribute checks. */
6139 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6140 | ((p & R_OK) ? GENERIC_READ : 0);
6141#ifdef FEAT_MBYTE
6142 if (wn != NULL)
6143 {
6144 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6145 if (hFile == INVALID_HANDLE_VALUE
6146 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6147 {
6148 /* Retry with non-wide function (for Windows 98). */
6149 vim_free(wn);
6150 wn = NULL;
6151 }
6152 }
6153 if (wn == NULL)
6154#endif
6155 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6156 if (hFile == INVALID_HANDLE_VALUE)
6157 goto getout;
6158 CloseHandle(hFile);
6159 }
6160
6161 retval = 0; /* success */
6162getout:
6163#ifdef FEAT_MBYTE
6164 vim_free(wn);
6165#endif
6166 return retval;
6167}
6168
6169#if defined(FEAT_MBYTE) || defined(PROTO)
6170/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006171 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 */
6173 int
6174mch_open(char *name, int flags, int mode)
6175{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006176 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6177# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178 WCHAR *wn;
6179 int f;
6180
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006181 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006183 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184 if (wn != NULL)
6185 {
6186 f = _wopen(wn, flags, mode);
6187 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006188 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 return f;
6190 /* Retry with non-wide function (for Windows 98). Can't use
6191 * GetLastError() here and it's unclear what errno gets set to if
6192 * the _wopen() fails for missing wide functions. */
6193 }
6194 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006195# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006197 /* open() can open a file which name is longer than _MAX_PATH bytes
6198 * and shorter than _MAX_PATH characters successfully, but sometimes it
6199 * causes unexpected error in another part. We make it an error explicitly
6200 * here. */
6201 if (strlen(name) >= _MAX_PATH)
6202 return -1;
6203
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204 return open(name, flags, mode);
6205}
6206
6207/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006208 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209 */
6210 FILE *
6211mch_fopen(char *name, char *mode)
6212{
6213 WCHAR *wn, *wm;
6214 FILE *f = NULL;
6215
6216 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6217# ifdef __BORLANDC__
6218 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6219 && g_PlatformId == VER_PLATFORM_WIN32_NT
6220# endif
6221 )
6222 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006223# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006224 /* Work around an annoying assertion in the Microsoft debug CRT
6225 * when mode's text/binary setting doesn't match _get_fmode(). */
6226 char newMode = mode[strlen(mode) - 1];
6227 int oldMode = 0;
6228
6229 _get_fmode(&oldMode);
6230 if (newMode == 't')
6231 _set_fmode(_O_TEXT);
6232 else if (newMode == 'b')
6233 _set_fmode(_O_BINARY);
6234# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006235 wn = enc_to_utf16(name, NULL);
6236 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 if (wn != NULL && wm != NULL)
6238 f = _wfopen(wn, wm);
6239 vim_free(wn);
6240 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006241
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006242# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006243 _set_fmode(oldMode);
6244# endif
6245
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006246 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247 return f;
6248 /* Retry with non-wide function (for Windows 98). Can't use
6249 * GetLastError() here and it's unclear what errno gets set to if
6250 * the _wfopen() fails for missing wide functions. */
6251 }
6252
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006253 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6254 * and shorter than _MAX_PATH characters successfully, but sometimes it
6255 * causes unexpected error in another part. We make it an error explicitly
6256 * here. */
6257 if (strlen(name) >= _MAX_PATH)
6258 return NULL;
6259
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 return fopen(name, mode);
6261}
6262#endif
6263
6264#ifdef FEAT_MBYTE
6265/*
6266 * SUB STREAM (aka info stream) handling:
6267 *
6268 * NTFS can have sub streams for each file. Normal contents of file is
6269 * stored in the main stream, and extra contents (author information and
6270 * title and so on) can be stored in sub stream. After Windows 2000, user
6271 * can access and store those informations in sub streams via explorer's
6272 * property menuitem in right click menu. Those informations in sub streams
6273 * were lost when copying only the main stream. So we have to copy sub
6274 * streams.
6275 *
6276 * Incomplete explanation:
6277 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6278 * More useful info and an example:
6279 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6280 */
6281
6282/*
6283 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6284 * and write to stream "substream" of file "to".
6285 * Errors are ignored.
6286 */
6287 static void
6288copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6289{
6290 HANDLE hTo;
6291 WCHAR *to_name;
6292
6293 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6294 wcscpy(to_name, to);
6295 wcscat(to_name, substream);
6296
6297 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6298 FILE_ATTRIBUTE_NORMAL, NULL);
6299 if (hTo != INVALID_HANDLE_VALUE)
6300 {
6301 long done;
6302 DWORD todo;
6303 DWORD readcnt, written;
6304 char buf[4096];
6305
6306 /* Copy block of bytes at a time. Abort when something goes wrong. */
6307 for (done = 0; done < len; done += written)
6308 {
6309 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006310 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6311 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6313 FALSE, FALSE, context)
6314 || readcnt != todo
6315 || !WriteFile(hTo, buf, todo, &written, NULL)
6316 || written != todo)
6317 break;
6318 }
6319 CloseHandle(hTo);
6320 }
6321
6322 free(to_name);
6323}
6324
6325/*
6326 * Copy info streams from file "from" to file "to".
6327 */
6328 static void
6329copy_infostreams(char_u *from, char_u *to)
6330{
6331 WCHAR *fromw;
6332 WCHAR *tow;
6333 HANDLE sh;
6334 WIN32_STREAM_ID sid;
6335 int headersize;
6336 WCHAR streamname[_MAX_PATH];
6337 DWORD readcount;
6338 void *context = NULL;
6339 DWORD lo, hi;
6340 int len;
6341
6342 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006343 fromw = enc_to_utf16(from, NULL);
6344 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 if (fromw != NULL && tow != NULL)
6346 {
6347 /* Open the file for reading. */
6348 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6349 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6350 if (sh != INVALID_HANDLE_VALUE)
6351 {
6352 /* Use BackupRead() to find the info streams. Repeat until we
6353 * have done them all.*/
6354 for (;;)
6355 {
6356 /* Get the header to find the length of the stream name. If
6357 * the "readcount" is zero we have done all info streams. */
6358 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006359 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6361 &readcount, FALSE, FALSE, &context)
6362 || readcount == 0)
6363 break;
6364
6365 /* We only deal with streams that have a name. The normal
6366 * file data appears to be without a name, even though docs
6367 * suggest it is called "::$DATA". */
6368 if (sid.dwStreamNameSize > 0)
6369 {
6370 /* Read the stream name. */
6371 if (!BackupRead(sh, (LPBYTE)streamname,
6372 sid.dwStreamNameSize,
6373 &readcount, FALSE, FALSE, &context))
6374 break;
6375
6376 /* Copy an info stream with a name ":anything:$DATA".
6377 * Skip "::$DATA", it has no stream name (examples suggest
6378 * it might be used for the normal file contents).
6379 * Note that BackupRead() counts bytes, but the name is in
6380 * wide characters. */
6381 len = readcount / sizeof(WCHAR);
6382 streamname[len] = 0;
6383 if (len > 7 && wcsicmp(streamname + len - 6,
6384 L":$DATA") == 0)
6385 {
6386 streamname[len - 6] = 0;
6387 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006388 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389 }
6390 }
6391
6392 /* Advance to the next stream. We might try seeking too far,
6393 * but BackupSeek() doesn't skip over stream borders, thus
6394 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006395 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006396 &lo, &hi, &context);
6397 }
6398
6399 /* Clear the context. */
6400 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6401
6402 CloseHandle(sh);
6403 }
6404 }
6405 vim_free(fromw);
6406 vim_free(tow);
6407}
6408#endif
6409
6410/*
6411 * Copy file attributes from file "from" to file "to".
6412 * For Windows NT and later we copy info streams.
6413 * Always returns zero, errors are ignored.
6414 */
6415 int
6416mch_copy_file_attribute(char_u *from, char_u *to)
6417{
6418#ifdef FEAT_MBYTE
6419 /* File streams only work on Windows NT and later. */
6420 PlatformId();
6421 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6422 copy_infostreams(from, to);
6423#endif
6424 return 0;
6425}
6426
6427#if defined(MYRESETSTKOFLW) || defined(PROTO)
6428/*
6429 * Recreate a destroyed stack guard page in win32.
6430 * Written by Benjamin Peterson.
6431 */
6432
6433/* These magic numbers are from the MS header files */
6434#define MIN_STACK_WIN9X 17
6435#define MIN_STACK_WINNT 2
6436
6437/*
6438 * This function does the same thing as _resetstkoflw(), which is only
6439 * available in DevStudio .net and later.
6440 * Returns 0 for failure, 1 for success.
6441 */
6442 int
6443myresetstkoflw(void)
6444{
6445 BYTE *pStackPtr;
6446 BYTE *pGuardPage;
6447 BYTE *pStackBase;
6448 BYTE *pLowestPossiblePage;
6449 MEMORY_BASIC_INFORMATION mbi;
6450 SYSTEM_INFO si;
6451 DWORD nPageSize;
6452 DWORD dummy;
6453
6454 /* This code will not work on win32s. */
6455 PlatformId();
6456 if (g_PlatformId == VER_PLATFORM_WIN32s)
6457 return 0;
6458
6459 /* We need to know the system page size. */
6460 GetSystemInfo(&si);
6461 nPageSize = si.dwPageSize;
6462
6463 /* ...and the current stack pointer */
6464 pStackPtr = (BYTE*)_alloca(1);
6465
6466 /* ...and the base of the stack. */
6467 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6468 return 0;
6469 pStackBase = (BYTE*)mbi.AllocationBase;
6470
6471 /* ...and the page thats min_stack_req pages away from stack base; this is
6472 * the lowest page we could use. */
6473 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6474 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6475
6476 /* On Win95, we want the next page down from the end of the stack. */
6477 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6478 {
6479 /* Find the page that's only 1 page down from the page that the stack
6480 * ptr is in. */
6481 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6482 / (DWORD)nPageSize) - 1));
6483 if (pGuardPage < pLowestPossiblePage)
6484 return 0;
6485
6486 /* Apply the noaccess attribute to the page -- there's no guard
6487 * attribute in win95-type OSes. */
6488 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6489 return 0;
6490 }
6491 else
6492 {
6493 /* On NT, however, we want the first committed page in the stack Start
6494 * at the stack base and move forward through memory until we find a
6495 * committed block. */
6496 BYTE *pBlock = pStackBase;
6497
Bram Moolenaara466c992005-07-09 21:03:22 +00006498 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499 {
6500 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6501 return 0;
6502
6503 pBlock += mbi.RegionSize;
6504
6505 if (mbi.State & MEM_COMMIT)
6506 break;
6507 }
6508
6509 /* mbi now describes the first committed block in the stack. */
6510 if (mbi.Protect & PAGE_GUARD)
6511 return 1;
6512
6513 /* decide where the guard page should start */
6514 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6515 pGuardPage = pLowestPossiblePage;
6516 else
6517 pGuardPage = (BYTE*)mbi.BaseAddress;
6518
6519 /* allocate the guard page */
6520 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6521 return 0;
6522
6523 /* apply the guard attribute to the page */
6524 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6525 &dummy))
6526 return 0;
6527 }
6528
6529 return 1;
6530}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006531#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006533
6534#if defined(FEAT_MBYTE) || defined(PROTO)
6535/*
6536 * The command line arguments in UCS2
6537 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006538static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006539static LPWSTR *ArglistW = NULL;
6540static int global_argc = 0;
6541static char **global_argv;
6542
6543static int used_file_argc = 0; /* last argument in global_argv[] used
6544 for the argument list. */
6545static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6546 command line arguments added to
6547 the argument list */
6548static int used_file_count = 0; /* nr of entries in used_file_indexes */
6549static int used_file_literal = FALSE; /* take file names literally */
6550static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006551static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006552static int used_alist_count = 0;
6553
6554
6555/*
6556 * Get the command line arguments. Unicode version.
6557 * Returns argc. Zero when something fails.
6558 */
6559 int
6560get_cmd_argsW(char ***argvp)
6561{
6562 char **argv = NULL;
6563 int argc = 0;
6564 int i;
6565
Bram Moolenaar14993322014-09-09 12:25:33 +02006566 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006567 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6568 if (ArglistW != NULL)
6569 {
6570 argv = malloc((nArgsW + 1) * sizeof(char *));
6571 if (argv != NULL)
6572 {
6573 argc = nArgsW;
6574 argv[argc] = NULL;
6575 for (i = 0; i < argc; ++i)
6576 {
6577 int len;
6578
6579 /* Convert each Unicode argument to the current codepage. */
6580 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006581 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006582 (LPSTR *)&argv[i], &len, 0, 0);
6583 if (argv[i] == NULL)
6584 {
6585 /* Out of memory, clear everything. */
6586 while (i > 0)
6587 free(argv[--i]);
6588 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006589 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006590 argc = 0;
6591 }
6592 }
6593 }
6594 }
6595
6596 global_argc = argc;
6597 global_argv = argv;
6598 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006599 {
6600 if (used_file_indexes != NULL)
6601 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006602 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006603 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006604
6605 if (argvp != NULL)
6606 *argvp = argv;
6607 return argc;
6608}
6609
6610 void
6611free_cmd_argsW(void)
6612{
6613 if (ArglistW != NULL)
6614 {
6615 GlobalFree(ArglistW);
6616 ArglistW = NULL;
6617 }
6618}
6619
6620/*
6621 * Remember "name" is an argument that was added to the argument list.
6622 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6623 * is called.
6624 */
6625 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006626used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006627{
6628 int i;
6629
6630 if (used_file_indexes == NULL)
6631 return;
6632 for (i = used_file_argc + 1; i < global_argc; ++i)
6633 if (STRCMP(global_argv[i], name) == 0)
6634 {
6635 used_file_argc = i;
6636 used_file_indexes[used_file_count++] = i;
6637 break;
6638 }
6639 used_file_literal = literal;
6640 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006641 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006642}
6643
6644/*
6645 * Remember the length of the argument list as it was. If it changes then we
6646 * leave it alone when 'encoding' is set.
6647 */
6648 void
6649set_alist_count(void)
6650{
6651 used_alist_count = GARGCOUNT;
6652}
6653
6654/*
6655 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6656 * has been changed while starting up. Use the UCS-2 command line arguments
6657 * and convert them to 'encoding'.
6658 */
6659 void
6660fix_arg_enc(void)
6661{
6662 int i;
6663 int idx;
6664 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006665 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006666
6667 /* Safety checks:
6668 * - if argument count differs between the wide and non-wide argument
6669 * list, something must be wrong.
6670 * - the file name arguments must have been located.
6671 * - the length of the argument list wasn't changed by the user.
6672 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006673 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006674 || ArglistW == NULL
6675 || used_file_indexes == NULL
6676 || used_file_count == 0
6677 || used_alist_count != GARGCOUNT)
6678 return;
6679
Bram Moolenaar86b68352004-12-27 21:59:20 +00006680 /* Remember the buffer numbers for the arguments. */
6681 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6682 if (fnum_list == NULL)
6683 return; /* out of memory */
6684 for (i = 0; i < GARGCOUNT; ++i)
6685 fnum_list[i] = GARGLIST[i].ae_fnum;
6686
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006687 /* Clear the argument list. Make room for the new arguments. */
6688 alist_clear(&global_alist);
6689 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006690 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006691
6692 for (i = 0; i < used_file_count; ++i)
6693 {
6694 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006695 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006696 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006697 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006698#ifdef FEAT_DIFF
6699 /* When using diff mode may need to concatenate file name to
6700 * directory name. Just like it's done in main(). */
6701 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6702 && !mch_isdir(alist_name(&GARGLIST[0])))
6703 {
6704 char_u *r;
6705
6706 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6707 if (r != NULL)
6708 {
6709 vim_free(str);
6710 str = r;
6711 }
6712 }
6713#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006714 /* Re-use the old buffer by renaming it. When not using literal
6715 * names it's done by alist_expand() below. */
6716 if (used_file_literal)
6717 buf_set_name(fnum_list[i], str);
6718
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006719 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006720 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006721 }
6722
6723 if (!used_file_literal)
6724 {
6725 /* Now expand wildcards in the arguments. */
6726 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6727 * filename characters but are excluded from 'isfname' to make
6728 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6729 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006730 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006731 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6732 }
6733
6734 /* If wildcard expansion failed, we are editing the first file of the
6735 * arglist and there is no file name: Edit the first argument now. */
6736 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6737 {
6738 do_cmdline_cmd((char_u *)":rewind");
6739 if (GARGCOUNT == 1 && used_file_full_path)
6740 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6741 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006742
6743 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006744}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745#endif