blob: 6981d2f31c81e44abe446986cd9034e9f783ac48 [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;
4615
4616 /*
4617 * Restore non-termcap screen buffer before execute external program, and
4618 * revert it after. Because msys and msys2's programs will cause freeze
4619 * or crash conhost.exe (Windows's console window provider) and vim.exe,
4620 * if active screen buffer is vim's one on Windows7.
4621 */
4622 if (is_win7 && g_fTermcapMode)
4623 SetConsoleActiveScreenBuffer(g_cbNonTermcap.handle);
4624
4625 ret = mch_system1(cmd, options);
4626
4627 if (is_win7 && g_fTermcapMode)
4628 SetConsoleActiveScreenBuffer(g_cbTermcap.handle);
4629
4630 return ret;
4631}
4632
Bram Moolenaar071d4272004-06-13 20:20:40 +00004633#endif
4634
4635/*
4636 * Either execute a command by calling the shell or start a new shell
4637 */
4638 int
4639mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004640 char_u *cmd,
4641 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004642{
4643 int x = 0;
4644 int tmode = cur_tmode;
4645#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004646 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004647# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004648 int did_set_title = FALSE;
4649
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004650 /* Change the title to reflect that we are in a subshell. */
4651 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4652 {
4653 WCHAR szShellTitle[512];
4654
4655 if (GetConsoleTitleW(szShellTitle,
4656 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4657 {
4658 if (cmd == NULL)
4659 wcscat(szShellTitle, L" :sh");
4660 else
4661 {
4662 WCHAR *wn = enc_to_utf16(cmd, NULL);
4663
4664 if (wn != NULL)
4665 {
4666 wcscat(szShellTitle, L" - !");
4667 if ((wcslen(szShellTitle) + wcslen(wn) <
4668 sizeof(szShellTitle)/sizeof(WCHAR)))
4669 wcscat(szShellTitle, wn);
4670 SetConsoleTitleW(szShellTitle);
4671 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004672 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004673 }
4674 }
4675 }
4676 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004677 if (!did_set_title)
4678# endif
4679 /* Change the title to reflect that we are in a subshell. */
4680 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004681 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004682 if (cmd == NULL)
4683 strcat(szShellTitle, " :sh");
4684 else
4685 {
4686 strcat(szShellTitle, " - !");
4687 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4688 strcat(szShellTitle, cmd);
4689 }
4690 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004691 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692#endif
4693
4694 out_flush();
4695
4696#ifdef MCH_WRITE_DUMP
4697 if (fdDump)
4698 {
4699 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4700 fflush(fdDump);
4701 }
4702#endif
4703
4704 /*
4705 * Catch all deadly signals while running the external command, because a
4706 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4707 */
4708 signal(SIGINT, SIG_IGN);
4709#if defined(__GNUC__) && !defined(__MINGW32__)
4710 signal(SIGKILL, SIG_IGN);
4711#else
4712 signal(SIGBREAK, SIG_IGN);
4713#endif
4714 signal(SIGILL, SIG_IGN);
4715 signal(SIGFPE, SIG_IGN);
4716 signal(SIGSEGV, SIG_IGN);
4717 signal(SIGTERM, SIG_IGN);
4718 signal(SIGABRT, SIG_IGN);
4719
4720 if (options & SHELL_COOKED)
4721 settmode(TMODE_COOK); /* set to normal mode */
4722
4723 if (cmd == NULL)
4724 {
4725 x = mch_system(p_sh, options);
4726 }
4727 else
4728 {
4729 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004730 char_u *newcmd = NULL;
4731 char_u *cmdbase = cmd;
4732 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004733
4734 /* Skip a leading ", ( and "(. */
4735 if (*cmdbase == '"' )
4736 ++cmdbase;
4737 if (*cmdbase == '(')
4738 ++cmdbase;
4739
4740 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4741 {
4742 STARTUPINFO si;
4743 PROCESS_INFORMATION pi;
4744 DWORD flags = CREATE_NEW_CONSOLE;
4745 char_u *p;
4746
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004747 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004748 si.cb = sizeof(si);
4749 si.lpReserved = NULL;
4750 si.lpDesktop = NULL;
4751 si.lpTitle = NULL;
4752 si.dwFlags = 0;
4753 si.cbReserved2 = 0;
4754 si.lpReserved2 = NULL;
4755
4756 cmdbase = skipwhite(cmdbase + 5);
4757 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4758 && vim_iswhite(cmdbase[4]))
4759 {
4760 cmdbase = skipwhite(cmdbase + 4);
4761 si.dwFlags = STARTF_USESHOWWINDOW;
4762 si.wShowWindow = SW_SHOWMINNOACTIVE;
4763 }
4764 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4765 && vim_iswhite(cmdbase[2]))
4766 {
4767 cmdbase = skipwhite(cmdbase + 2);
4768 flags = CREATE_NO_WINDOW;
4769 si.dwFlags = STARTF_USESTDHANDLES;
4770 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004771 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004772 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004773 NULL, // Security att.
4774 OPEN_EXISTING, // Open flags
4775 FILE_ATTRIBUTE_NORMAL, // File att.
4776 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004777 si.hStdOutput = si.hStdInput;
4778 si.hStdError = si.hStdInput;
4779 }
4780
4781 /* Remove a trailing ", ) and )" if they have a match
4782 * at the start of the command. */
4783 if (cmdbase > cmd)
4784 {
4785 p = cmdbase + STRLEN(cmdbase);
4786 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4787 *--p = NUL;
4788 if (p > cmdbase && p[-1] == ')'
4789 && (*cmd =='(' || cmd[1] == '('))
4790 *--p = NUL;
4791 }
4792
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004793 newcmd = cmdbase;
4794 unescape_shellxquote(cmdbase, p_sxe);
4795
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004796 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004797 * If creating new console, arguments are passed to the
4798 * 'cmd.exe' as-is. If it's not, arguments are not treated
4799 * correctly for current 'cmd.exe'. So unescape characters in
4800 * shellxescape except '|' for avoiding to be treated as
4801 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004802 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004803 if (flags != CREATE_NEW_CONSOLE)
4804 {
4805 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004806 char_u *cmd_shell = mch_getenv("COMSPEC");
4807
4808 if (cmd_shell == NULL || *cmd_shell == NUL)
4809 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004810
4811 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4812 if (subcmd != NULL)
4813 {
4814 /* make "cmd.exe /c arguments" */
4815 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004816 newcmd = lalloc(cmdlen, TRUE);
4817 if (newcmd != NULL)
4818 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004819 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004820 else
4821 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004822 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004823 }
4824 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004825
4826 /*
4827 * Now, start the command as a process, so that it doesn't
4828 * inherit our handles which causes unpleasant dangling swap
4829 * files if we exit before the spawned process
4830 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004831 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004832 x = 0;
4833 else
4834 {
4835 x = -1;
4836#ifdef FEAT_GUI_W32
4837 EMSG(_("E371: Command not found"));
4838#endif
4839 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004840
4841 if (newcmd != cmdbase)
4842 vim_free(newcmd);
4843
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004844 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004845 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004846 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004847 CloseHandle(si.hStdInput);
4848 }
4849 /* Close the handles to the subprocess, so that it goes away */
4850 CloseHandle(pi.hThread);
4851 CloseHandle(pi.hProcess);
4852 }
4853 else
4854 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004855 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004856#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004857 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004859 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4860
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004861 newcmd = lalloc(cmdlen, TRUE);
4862 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004863 {
4864#if defined(FEAT_GUI_W32)
4865 if (need_vimrun_warning)
4866 {
4867 MessageBox(NULL,
4868 _("VIMRUN.EXE not found in your $PATH.\n"
4869 "External commands will not pause after completion.\n"
4870 "See :help win32-vimrun for more information."),
4871 _("Vim Warning"),
4872 MB_ICONWARNING);
4873 need_vimrun_warning = FALSE;
4874 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004875 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004876 /* Use vimrun to execute the command. It opens a console
4877 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004878 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879 vimrun_path,
4880 (msg_silent != 0 || (options & SHELL_DOOUT))
4881 ? "-s " : "",
4882 p_sh, p_shcf, cmd);
4883 else
4884#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004885 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004886 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004887 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004888 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890 }
4891 }
4892
4893 if (tmode == TMODE_RAW)
4894 settmode(TMODE_RAW); /* set to raw mode */
4895
4896 /* Print the return value, unless "vimrun" was used. */
4897 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4898#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004899 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4900 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901#endif
4902 )
4903 {
4904 smsg(_("shell returned %d"), x);
4905 msg_putchar('\n');
4906 }
4907#ifdef FEAT_TITLE
4908 resettitle();
4909#endif
4910
4911 signal(SIGINT, SIG_DFL);
4912#if defined(__GNUC__) && !defined(__MINGW32__)
4913 signal(SIGKILL, SIG_DFL);
4914#else
4915 signal(SIGBREAK, SIG_DFL);
4916#endif
4917 signal(SIGILL, SIG_DFL);
4918 signal(SIGFPE, SIG_DFL);
4919 signal(SIGSEGV, SIG_DFL);
4920 signal(SIGTERM, SIG_DFL);
4921 signal(SIGABRT, SIG_DFL);
4922
4923 return x;
4924}
4925
4926
4927#ifndef FEAT_GUI_W32
4928
4929/*
4930 * Start termcap mode
4931 */
4932 static void
4933termcap_mode_start(void)
4934{
4935 DWORD cmodein;
4936
4937 if (g_fTermcapMode)
4938 return;
4939
4940 SaveConsoleBuffer(&g_cbNonTermcap);
4941
4942 if (g_cbTermcap.IsValid)
4943 {
4944 /*
4945 * We've been in termcap mode before. Restore certain screen
4946 * characteristics, including the buffer size and the window
4947 * size. Since we will be redrawing the screen, we don't need
4948 * to restore the actual contents of the buffer.
4949 */
4950 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4951 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4952 Rows = g_cbTermcap.Info.dwSize.Y;
4953 Columns = g_cbTermcap.Info.dwSize.X;
4954 }
4955 else
4956 {
4957 /*
4958 * This is our first time entering termcap mode. Clear the console
4959 * screen buffer, and resize the buffer to match the current window
4960 * size. We will use this as the size of our editing environment.
4961 */
Bram Moolenaar61594242015-09-01 20:23:37 +02004962 g_hConOut = g_cbTermcap.handle;
4963 SetConsoleActiveScreenBuffer(g_hConOut);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964 ClearConsoleBuffer(g_attrCurrent);
4965 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4966 }
4967
4968#ifdef FEAT_TITLE
4969 resettitle();
4970#endif
4971
4972 GetConsoleMode(g_hConIn, &cmodein);
4973#ifdef FEAT_MOUSE
4974 if (g_fMouseActive)
4975 cmodein |= ENABLE_MOUSE_INPUT;
4976 else
4977 cmodein &= ~ENABLE_MOUSE_INPUT;
4978#endif
4979 cmodein |= ENABLE_WINDOW_INPUT;
4980 SetConsoleMode(g_hConIn, cmodein);
4981
4982 redraw_later_clear();
4983 g_fTermcapMode = TRUE;
4984}
4985
4986
4987/*
4988 * End termcap mode
4989 */
4990 static void
4991termcap_mode_end(void)
4992{
4993 DWORD cmodein;
4994 ConsoleBuffer *cb;
4995 COORD coord;
4996 DWORD dwDummy;
4997
4998 if (!g_fTermcapMode)
4999 return;
5000
5001 SaveConsoleBuffer(&g_cbTermcap);
5002
5003 GetConsoleMode(g_hConIn, &cmodein);
5004 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5005 SetConsoleMode(g_hConIn, cmodein);
5006
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007 cb = &g_cbNonTermcap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005008 RestoreConsoleBuffer(cb, p_rs);
5009 SetConsoleCursorInfo(g_hConOut, &g_cci);
5010
5011 if (p_rs || exiting)
5012 {
5013 /*
5014 * Clear anything that happens to be on the current line.
5015 */
5016 coord.X = 0;
5017 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5018 FillConsoleOutputCharacter(g_hConOut, ' ',
5019 cb->Info.dwSize.X, coord, &dwDummy);
5020 /*
5021 * The following is just for aesthetics. If we are exiting without
5022 * restoring the screen, then we want to have a prompt string
5023 * appear at the bottom line. However, the command interpreter
5024 * seems to always advance the cursor one line before displaying
5025 * the prompt string, which causes the screen to scroll. To
5026 * counter this, move the cursor up one line before exiting.
5027 */
5028 if (exiting && !p_rs)
5029 coord.Y--;
5030 /*
5031 * Position the cursor at the leftmost column of the desired row.
5032 */
5033 SetConsoleCursorPosition(g_hConOut, coord);
5034 }
5035
5036 g_fTermcapMode = FALSE;
5037}
5038#endif /* FEAT_GUI_W32 */
5039
5040
5041#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005042/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043 void
5044mch_write(
5045 char_u *s,
5046 int len)
5047{
5048 /* never used */
5049}
5050
5051#else
5052
5053/*
5054 * clear `n' chars, starting from `coord'
5055 */
5056 static void
5057clear_chars(
5058 COORD coord,
5059 DWORD n)
5060{
5061 DWORD dwDummy;
5062
5063 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5064 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5065}
5066
5067
5068/*
5069 * Clear the screen
5070 */
5071 static void
5072clear_screen(void)
5073{
5074 g_coord.X = g_coord.Y = 0;
5075 clear_chars(g_coord, Rows * Columns);
5076}
5077
5078
5079/*
5080 * Clear to end of display
5081 */
5082 static void
5083clear_to_end_of_display(void)
5084{
5085 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5086 * Columns + (Columns - g_coord.X));
5087}
5088
5089
5090/*
5091 * Clear to end of line
5092 */
5093 static void
5094clear_to_end_of_line(void)
5095{
5096 clear_chars(g_coord, Columns - g_coord.X);
5097}
5098
5099
5100/*
5101 * Scroll the scroll region up by `cLines' lines
5102 */
5103 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005104scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005105{
5106 COORD oldcoord = g_coord;
5107
5108 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5109 delete_lines(cLines);
5110
5111 g_coord = oldcoord;
5112}
5113
5114
5115/*
5116 * Set the scroll region
5117 */
5118 static void
5119set_scroll_region(
5120 unsigned left,
5121 unsigned top,
5122 unsigned right,
5123 unsigned bottom)
5124{
5125 if (left >= right
5126 || top >= bottom
5127 || right > (unsigned) Columns - 1
5128 || bottom > (unsigned) Rows - 1)
5129 return;
5130
5131 g_srScrollRegion.Left = left;
5132 g_srScrollRegion.Top = top;
5133 g_srScrollRegion.Right = right;
5134 g_srScrollRegion.Bottom = bottom;
5135}
5136
5137
5138/*
5139 * Insert `cLines' lines at the current cursor position
5140 */
5141 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005142insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005143{
5144 SMALL_RECT source;
5145 COORD dest;
5146 CHAR_INFO fill;
5147
5148 dest.X = 0;
5149 dest.Y = g_coord.Y + cLines;
5150
5151 source.Left = 0;
5152 source.Top = g_coord.Y;
5153 source.Right = g_srScrollRegion.Right;
5154 source.Bottom = g_srScrollRegion.Bottom - cLines;
5155
5156 fill.Char.AsciiChar = ' ';
5157 fill.Attributes = g_attrCurrent;
5158
5159 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5160
5161 /* Here we have to deal with a win32 console flake: If the scroll
5162 * region looks like abc and we scroll c to a and fill with d we get
5163 * cbd... if we scroll block c one line at a time to a, we get cdd...
5164 * vim expects cdd consistently... So we have to deal with that
5165 * here... (this also occurs scrolling the same way in the other
5166 * direction). */
5167
5168 if (source.Bottom < dest.Y)
5169 {
5170 COORD coord;
5171
5172 coord.X = 0;
5173 coord.Y = source.Bottom;
5174 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5175 }
5176}
5177
5178
5179/*
5180 * Delete `cLines' lines at the current cursor position
5181 */
5182 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005183delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184{
5185 SMALL_RECT source;
5186 COORD dest;
5187 CHAR_INFO fill;
5188 int nb;
5189
5190 dest.X = 0;
5191 dest.Y = g_coord.Y;
5192
5193 source.Left = 0;
5194 source.Top = g_coord.Y + cLines;
5195 source.Right = g_srScrollRegion.Right;
5196 source.Bottom = g_srScrollRegion.Bottom;
5197
5198 fill.Char.AsciiChar = ' ';
5199 fill.Attributes = g_attrCurrent;
5200
5201 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5202
5203 /* Here we have to deal with a win32 console flake: If the scroll
5204 * region looks like abc and we scroll c to a and fill with d we get
5205 * cbd... if we scroll block c one line at a time to a, we get cdd...
5206 * vim expects cdd consistently... So we have to deal with that
5207 * here... (this also occurs scrolling the same way in the other
5208 * direction). */
5209
5210 nb = dest.Y + (source.Bottom - source.Top) + 1;
5211
5212 if (nb < source.Top)
5213 {
5214 COORD coord;
5215
5216 coord.X = 0;
5217 coord.Y = nb;
5218 clear_chars(coord, Columns * (source.Top - nb));
5219 }
5220}
5221
5222
5223/*
5224 * Set the cursor position
5225 */
5226 static void
5227gotoxy(
5228 unsigned x,
5229 unsigned y)
5230{
5231 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5232 return;
5233
5234 /* external cursor coords are 1-based; internal are 0-based */
5235 g_coord.X = x - 1;
5236 g_coord.Y = y - 1;
5237 SetConsoleCursorPosition(g_hConOut, g_coord);
5238}
5239
5240
5241/*
5242 * Set the current text attribute = (foreground | background)
5243 * See ../doc/os_win32.txt for the numbers.
5244 */
5245 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005246textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005247{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005248 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005249
5250 SetConsoleTextAttribute(g_hConOut, wAttr);
5251}
5252
5253
5254 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005255textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005256{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005257 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005258
5259 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5260}
5261
5262
5263 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005264textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005265{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005266 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005267
5268 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5269}
5270
5271
5272/*
5273 * restore the default text attribute (whatever we started with)
5274 */
5275 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005276normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005277{
5278 textattr(g_attrDefault);
5279}
5280
5281
5282static WORD g_attrPreStandout = 0;
5283
5284/*
5285 * Make the text standout, by brightening it
5286 */
5287 static void
5288standout(void)
5289{
5290 g_attrPreStandout = g_attrCurrent;
5291 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5292}
5293
5294
5295/*
5296 * Turn off standout mode
5297 */
5298 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005299standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005300{
5301 if (g_attrPreStandout)
5302 {
5303 textattr(g_attrPreStandout);
5304 g_attrPreStandout = 0;
5305 }
5306}
5307
5308
5309/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005310 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005311 */
5312 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005313mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005314{
5315 char_u *p;
5316 int n;
5317
5318 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5319 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5320 if (T_ME[0] == ESC && T_ME[1] == '|')
5321 {
5322 p = T_ME + 2;
5323 n = getdigits(&p);
5324 if (*p == 'm' && n > 0)
5325 {
5326 cterm_normal_fg_color = (n & 0xf) + 1;
5327 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5328 }
5329 }
5330}
5331
5332
5333/*
5334 * visual bell: flash the screen
5335 */
5336 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005337visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005338{
5339 COORD coordOrigin = {0, 0};
5340 WORD attrFlash = ~g_attrCurrent & 0xff;
5341
5342 DWORD dwDummy;
5343 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5344
5345 if (oldattrs == NULL)
5346 return;
5347 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5348 coordOrigin, &dwDummy);
5349 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5350 coordOrigin, &dwDummy);
5351
5352 Sleep(15); /* wait for 15 msec */
5353 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5354 coordOrigin, &dwDummy);
5355 vim_free(oldattrs);
5356}
5357
5358
5359/*
5360 * Make the cursor visible or invisible
5361 */
5362 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005363cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364{
5365 s_cursor_visible = fVisible;
5366#ifdef MCH_CURSOR_SHAPE
5367 mch_update_cursor();
5368#endif
5369}
5370
5371
5372/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005373 * write `cbToWrite' bytes in `pchBuf' to the screen
5374 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005376 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005377write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005378 char_u *pchBuf,
5379 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005380{
5381 COORD coord = g_coord;
5382 DWORD written;
5383
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005384#ifdef FEAT_MBYTE
5385 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5386 {
5387 static WCHAR *unicodebuf = NULL;
5388 static int unibuflen = 0;
5389 int length;
5390 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005391
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005392 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5393 if (unicodebuf == NULL || length > unibuflen)
5394 {
5395 vim_free(unicodebuf);
5396 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5397 unibuflen = length;
5398 }
5399 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5400 unicodebuf, unibuflen);
5401
5402 cells = mb_string2cells(pchBuf, cbToWrite);
5403 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5404 coord, &written);
5405 /* When writing fails or didn't write a single character, pretend one
5406 * character was written, otherwise we get stuck. */
5407 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5408 coord, &cchwritten) == 0
5409 || cchwritten == 0)
5410 cchwritten = 1;
5411
5412 if (cchwritten == length)
5413 {
5414 written = cbToWrite;
5415 g_coord.X += (SHORT)cells;
5416 }
5417 else
5418 {
5419 char_u *p = pchBuf;
5420 for (n = 0; n < cchwritten; n++)
5421 mb_cptr_adv(p);
5422 written = p - pchBuf;
5423 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5424 }
5425 }
5426 else
5427#endif
5428 {
5429 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5430 coord, &written);
5431 /* When writing fails or didn't write a single character, pretend one
5432 * character was written, otherwise we get stuck. */
5433 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5434 coord, &written) == 0
5435 || written == 0)
5436 written = 1;
5437
5438 g_coord.X += (SHORT) written;
5439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440
5441 while (g_coord.X > g_srScrollRegion.Right)
5442 {
5443 g_coord.X -= (SHORT) Columns;
5444 if (g_coord.Y < g_srScrollRegion.Bottom)
5445 g_coord.Y++;
5446 }
5447
5448 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5449
5450 return written;
5451}
5452
5453
5454/*
5455 * mch_write(): write the output buffer to the screen, translating ESC
5456 * sequences into calls to console output routines.
5457 */
5458 void
5459mch_write(
5460 char_u *s,
5461 int len)
5462{
5463 s[len] = NUL;
5464
5465 if (!term_console)
5466 {
5467 write(1, s, (unsigned)len);
5468 return;
5469 }
5470
5471 /* translate ESC | sequences into faked bios calls */
5472 while (len--)
5473 {
5474 /* optimization: use one single write_chars for runs of text,
5475 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005476 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005477
5478 if (p_wd)
5479 {
5480 WaitForChar(p_wd);
5481 if (prefix != 0)
5482 prefix = 1;
5483 }
5484
5485 if (prefix != 0)
5486 {
5487 DWORD nWritten;
5488
5489 nWritten = write_chars(s, prefix);
5490#ifdef MCH_WRITE_DUMP
5491 if (fdDump)
5492 {
5493 fputc('>', fdDump);
5494 fwrite(s, sizeof(char_u), nWritten, fdDump);
5495 fputs("<\n", fdDump);
5496 }
5497#endif
5498 len -= (nWritten - 1);
5499 s += nWritten;
5500 }
5501 else if (s[0] == '\n')
5502 {
5503 /* \n, newline: go to the beginning of the next line or scroll */
5504 if (g_coord.Y == g_srScrollRegion.Bottom)
5505 {
5506 scroll(1);
5507 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5508 }
5509 else
5510 {
5511 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5512 }
5513#ifdef MCH_WRITE_DUMP
5514 if (fdDump)
5515 fputs("\\n\n", fdDump);
5516#endif
5517 s++;
5518 }
5519 else if (s[0] == '\r')
5520 {
5521 /* \r, carriage return: go to beginning of line */
5522 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5523#ifdef MCH_WRITE_DUMP
5524 if (fdDump)
5525 fputs("\\r\n", fdDump);
5526#endif
5527 s++;
5528 }
5529 else if (s[0] == '\b')
5530 {
5531 /* \b, backspace: move cursor one position left */
5532 if (g_coord.X > g_srScrollRegion.Left)
5533 g_coord.X--;
5534 else if (g_coord.Y > g_srScrollRegion.Top)
5535 {
5536 g_coord.X = g_srScrollRegion.Right;
5537 g_coord.Y--;
5538 }
5539 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5540#ifdef MCH_WRITE_DUMP
5541 if (fdDump)
5542 fputs("\\b\n", fdDump);
5543#endif
5544 s++;
5545 }
5546 else if (s[0] == '\a')
5547 {
5548 /* \a, bell */
5549 MessageBeep(0xFFFFFFFF);
5550#ifdef MCH_WRITE_DUMP
5551 if (fdDump)
5552 fputs("\\a\n", fdDump);
5553#endif
5554 s++;
5555 }
5556 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5557 {
5558#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005559 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005561 char_u *p;
5562 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563
5564 switch (s[2])
5565 {
5566 /* one or two numeric arguments, separated by ';' */
5567
5568 case '0': case '1': case '2': case '3': case '4':
5569 case '5': case '6': case '7': case '8': case '9':
5570 p = s + 2;
5571 arg1 = getdigits(&p); /* no check for length! */
5572 if (p > s + len)
5573 break;
5574
5575 if (*p == ';')
5576 {
5577 ++p;
5578 arg2 = getdigits(&p); /* no check for length! */
5579 if (p > s + len)
5580 break;
5581
5582 if (*p == 'H')
5583 gotoxy(arg2, arg1);
5584 else if (*p == 'r')
5585 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5586 }
5587 else if (*p == 'A')
5588 {
5589 /* move cursor up arg1 lines in same column */
5590 gotoxy(g_coord.X + 1,
5591 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5592 }
5593 else if (*p == 'C')
5594 {
5595 /* move cursor right arg1 columns in same line */
5596 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5597 g_coord.Y + 1);
5598 }
5599 else if (*p == 'H')
5600 {
5601 gotoxy(1, arg1);
5602 }
5603 else if (*p == 'L')
5604 {
5605 insert_lines(arg1);
5606 }
5607 else if (*p == 'm')
5608 {
5609 if (arg1 == 0)
5610 normvideo();
5611 else
5612 textattr((WORD) arg1);
5613 }
5614 else if (*p == 'f')
5615 {
5616 textcolor((WORD) arg1);
5617 }
5618 else if (*p == 'b')
5619 {
5620 textbackground((WORD) arg1);
5621 }
5622 else if (*p == 'M')
5623 {
5624 delete_lines(arg1);
5625 }
5626
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005627 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628 s = p + 1;
5629 break;
5630
5631
5632 /* Three-character escape sequences */
5633
5634 case 'A':
5635 /* move cursor up one line in same column */
5636 gotoxy(g_coord.X + 1,
5637 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5638 goto got3;
5639
5640 case 'B':
5641 visual_bell();
5642 goto got3;
5643
5644 case 'C':
5645 /* move cursor right one column in same line */
5646 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5647 g_coord.Y + 1);
5648 goto got3;
5649
5650 case 'E':
5651 termcap_mode_end();
5652 goto got3;
5653
5654 case 'F':
5655 standout();
5656 goto got3;
5657
5658 case 'f':
5659 standend();
5660 goto got3;
5661
5662 case 'H':
5663 gotoxy(1, 1);
5664 goto got3;
5665
5666 case 'j':
5667 clear_to_end_of_display();
5668 goto got3;
5669
5670 case 'J':
5671 clear_screen();
5672 goto got3;
5673
5674 case 'K':
5675 clear_to_end_of_line();
5676 goto got3;
5677
5678 case 'L':
5679 insert_lines(1);
5680 goto got3;
5681
5682 case 'M':
5683 delete_lines(1);
5684 goto got3;
5685
5686 case 'S':
5687 termcap_mode_start();
5688 goto got3;
5689
5690 case 'V':
5691 cursor_visible(TRUE);
5692 goto got3;
5693
5694 case 'v':
5695 cursor_visible(FALSE);
5696 goto got3;
5697
5698 got3:
5699 s += 3;
5700 len -= 2;
5701 }
5702
5703#ifdef MCH_WRITE_DUMP
5704 if (fdDump)
5705 {
5706 fputs("ESC | ", fdDump);
5707 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5708 fputc('\n', fdDump);
5709 }
5710#endif
5711 }
5712 else
5713 {
5714 /* Write a single character */
5715 DWORD nWritten;
5716
5717 nWritten = write_chars(s, 1);
5718#ifdef MCH_WRITE_DUMP
5719 if (fdDump)
5720 {
5721 fputc('>', fdDump);
5722 fwrite(s, sizeof(char_u), nWritten, fdDump);
5723 fputs("<\n", fdDump);
5724 }
5725#endif
5726
5727 len -= (nWritten - 1);
5728 s += nWritten;
5729 }
5730 }
5731
5732#ifdef MCH_WRITE_DUMP
5733 if (fdDump)
5734 fflush(fdDump);
5735#endif
5736}
5737
5738#endif /* FEAT_GUI_W32 */
5739
5740
5741/*
5742 * Delay for half a second.
5743 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005744/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745 void
5746mch_delay(
5747 long msec,
5748 int ignoreinput)
5749{
5750#ifdef FEAT_GUI_W32
5751 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005752#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005753 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005754# ifdef FEAT_MZSCHEME
5755 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5756 {
5757 int towait = p_mzq;
5758
5759 /* if msec is large enough, wait by portions in p_mzq */
5760 while (msec > 0)
5761 {
5762 mzvim_check_threads();
5763 if (msec < towait)
5764 towait = msec;
5765 Sleep(towait);
5766 msec -= towait;
5767 }
5768 }
5769 else
5770# endif
5771 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005772 else
5773 WaitForChar(msec);
5774#endif
5775}
5776
5777
5778/*
5779 * this version of remove is not scared by a readonly (backup) file
5780 * Return 0 for success, -1 for failure.
5781 */
5782 int
5783mch_remove(char_u *name)
5784{
5785#ifdef FEAT_MBYTE
5786 WCHAR *wn = NULL;
5787 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005788#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005790 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5791
5792#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5794 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005795 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005796 if (wn != NULL)
5797 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798 n = DeleteFileW(wn) ? 0 : -1;
5799 vim_free(wn);
5800 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5801 return n;
5802 /* Retry with non-wide function (for Windows 98). */
5803 }
5804 }
5805#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806 return DeleteFile(name) ? 0 : -1;
5807}
5808
5809
5810/*
5811 * check for an "interrupt signal": CTRL-break or CTRL-C
5812 */
5813 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005814mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815{
5816#ifndef FEAT_GUI_W32 /* never used */
5817 if (g_fCtrlCPressed || g_fCBrkPressed)
5818 {
5819 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5820 got_int = TRUE;
5821 }
5822#endif
5823}
5824
5825
Bram Moolenaar071d4272004-06-13 20:20:40 +00005826#ifdef FEAT_MBYTE
5827/*
5828 * Same code as below, but with wide functions and no comments.
5829 * Return 0 for success, non-zero for failure.
5830 */
5831 int
5832mch_wrename(WCHAR *wold, WCHAR *wnew)
5833{
5834 WCHAR *p;
5835 int i;
5836 WCHAR szTempFile[_MAX_PATH + 1];
5837 WCHAR szNewPath[_MAX_PATH + 1];
5838 HANDLE hf;
5839
5840 if (!mch_windows95())
5841 {
5842 p = wold;
5843 for (i = 0; wold[i] != NUL; ++i)
5844 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5845 && wold[i + 1] != 0)
5846 p = wold + i + 1;
5847 if ((int)(wold + i - p) < 8 || p[6] != '~')
5848 return (MoveFileW(wold, wnew) == 0);
5849 }
5850
5851 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5852 return -1;
5853 *p = NUL;
5854
5855 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5856 return -2;
5857
5858 if (!DeleteFileW(szTempFile))
5859 return -3;
5860
5861 if (!MoveFileW(wold, szTempFile))
5862 return -4;
5863
5864 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5865 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5866 return -5;
5867 if (!CloseHandle(hf))
5868 return -6;
5869
5870 if (!MoveFileW(szTempFile, wnew))
5871 {
5872 (void)MoveFileW(szTempFile, wold);
5873 return -7;
5874 }
5875
5876 DeleteFileW(szTempFile);
5877
5878 if (!DeleteFileW(wold))
5879 return -8;
5880
5881 return 0;
5882}
5883#endif
5884
5885
5886/*
5887 * mch_rename() works around a bug in rename (aka MoveFile) in
5888 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5889 * file whose short file name is "FOO.BAR" (its long file name will
5890 * be correct: "foo.bar~"). Because a file can be accessed by
5891 * either its SFN or its LFN, "foo.bar" has effectively been
5892 * renamed to "foo.bar", which is not at all what was wanted. This
5893 * seems to happen only when renaming files with three-character
5894 * extensions by appending a suffix that does not include ".".
5895 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5896 *
5897 * There is another problem, which isn't really a bug but isn't right either:
5898 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5899 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5900 * service pack 6. Doesn't seem to happen on Windows 98.
5901 *
5902 * Like rename(), returns 0 upon success, non-zero upon failure.
5903 * Should probably set errno appropriately when errors occur.
5904 */
5905 int
5906mch_rename(
5907 const char *pszOldFile,
5908 const char *pszNewFile)
5909{
5910 char szTempFile[_MAX_PATH+1];
5911 char szNewPath[_MAX_PATH+1];
5912 char *pszFilePart;
5913 HANDLE hf;
5914#ifdef FEAT_MBYTE
5915 WCHAR *wold = NULL;
5916 WCHAR *wnew = NULL;
5917 int retval = -1;
5918
5919 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5920 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005921 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5922 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923 if (wold != NULL && wnew != NULL)
5924 retval = mch_wrename(wold, wnew);
5925 vim_free(wold);
5926 vim_free(wnew);
5927 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5928 return retval;
5929 /* Retry with non-wide function (for Windows 98). */
5930 }
5931#endif
5932
5933 /*
5934 * No need to play tricks if not running Windows 95, unless the file name
5935 * contains a "~" as the seventh character.
5936 */
5937 if (!mch_windows95())
5938 {
5939 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5940 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5941 return rename(pszOldFile, pszNewFile);
5942 }
5943
5944 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5945 * a directory, no error is returned and pszFilePart will be NULL. */
5946 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5947 || pszFilePart == NULL)
5948 return -1;
5949 *pszFilePart = NUL;
5950
5951 /* Get (and create) a unique temporary file name in directory of new file */
5952 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5953 return -2;
5954
5955 /* blow the temp file away */
5956 if (!DeleteFile(szTempFile))
5957 return -3;
5958
5959 /* rename old file to the temp file */
5960 if (!MoveFile(pszOldFile, szTempFile))
5961 return -4;
5962
5963 /* now create an empty file called pszOldFile; this prevents the operating
5964 * system using pszOldFile as an alias (SFN) if we're renaming within the
5965 * same directory. For example, we're editing a file called
5966 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5967 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5968 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005969 * cause all sorts of problems later in buf_write(). So, we create an
5970 * empty file called filena~1.txt and the system will have to find some
5971 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972 */
5973 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5974 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5975 return -5;
5976 if (!CloseHandle(hf))
5977 return -6;
5978
5979 /* rename the temp file to the new file */
5980 if (!MoveFile(szTempFile, pszNewFile))
5981 {
5982 /* Renaming failed. Rename the file back to its old name, so that it
5983 * looks like nothing happened. */
5984 (void)MoveFile(szTempFile, pszOldFile);
5985
5986 return -7;
5987 }
5988
5989 /* Seems to be left around on Novell filesystems */
5990 DeleteFile(szTempFile);
5991
5992 /* finally, remove the empty old file */
5993 if (!DeleteFile(pszOldFile))
5994 return -8;
5995
5996 return 0; /* success */
5997}
5998
5999/*
6000 * Get the default shell for the current hardware platform
6001 */
6002 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006003default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004{
6005 char* psz = NULL;
6006
6007 PlatformId();
6008
6009 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6010 psz = "cmd.exe";
6011 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6012 psz = "command.com";
6013
6014 return psz;
6015}
6016
6017/*
6018 * mch_access() extends access() to do more detailed check on network drives.
6019 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6020 */
6021 int
6022mch_access(char *n, int p)
6023{
6024 HANDLE hFile;
6025 DWORD am;
6026 int retval = -1; /* default: fail */
6027#ifdef FEAT_MBYTE
6028 WCHAR *wn = NULL;
6029
6030 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006031 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032#endif
6033
6034 if (mch_isdir(n))
6035 {
6036 char TempName[_MAX_PATH + 16] = "";
6037#ifdef FEAT_MBYTE
6038 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6039#endif
6040
6041 if (p & R_OK)
6042 {
6043 /* Read check is performed by seeing if we can do a find file on
6044 * the directory for any file. */
6045#ifdef FEAT_MBYTE
6046 if (wn != NULL)
6047 {
6048 int i;
6049 WIN32_FIND_DATAW d;
6050
6051 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6052 TempNameW[i] = wn[i];
6053 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6054 TempNameW[i++] = '\\';
6055 TempNameW[i++] = '*';
6056 TempNameW[i++] = 0;
6057
6058 hFile = FindFirstFileW(TempNameW, &d);
6059 if (hFile == INVALID_HANDLE_VALUE)
6060 {
6061 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6062 goto getout;
6063
6064 /* Retry with non-wide function (for Windows 98). */
6065 vim_free(wn);
6066 wn = NULL;
6067 }
6068 else
6069 (void)FindClose(hFile);
6070 }
6071 if (wn == NULL)
6072#endif
6073 {
6074 char *pch;
6075 WIN32_FIND_DATA d;
6076
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006077 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006078 pch = TempName + STRLEN(TempName) - 1;
6079 if (*pch != '\\' && *pch != '/')
6080 *++pch = '\\';
6081 *++pch = '*';
6082 *++pch = NUL;
6083
6084 hFile = FindFirstFile(TempName, &d);
6085 if (hFile == INVALID_HANDLE_VALUE)
6086 goto getout;
6087 (void)FindClose(hFile);
6088 }
6089 }
6090
6091 if (p & W_OK)
6092 {
6093 /* Trying to create a temporary file in the directory should catch
6094 * directories on read-only network shares. However, in
6095 * directories whose ACL allows writes but denies deletes will end
6096 * up keeping the temporary file :-(. */
6097#ifdef FEAT_MBYTE
6098 if (wn != NULL)
6099 {
6100 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6101 {
6102 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6103 goto getout;
6104
6105 /* Retry with non-wide function (for Windows 98). */
6106 vim_free(wn);
6107 wn = NULL;
6108 }
6109 else
6110 DeleteFileW(TempNameW);
6111 }
6112 if (wn == NULL)
6113#endif
6114 {
6115 if (!GetTempFileName(n, "VIM", 0, TempName))
6116 goto getout;
6117 mch_remove((char_u *)TempName);
6118 }
6119 }
6120 }
6121 else
6122 {
6123 /* Trying to open the file for the required access does ACL, read-only
6124 * network share, and file attribute checks. */
6125 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6126 | ((p & R_OK) ? GENERIC_READ : 0);
6127#ifdef FEAT_MBYTE
6128 if (wn != NULL)
6129 {
6130 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6131 if (hFile == INVALID_HANDLE_VALUE
6132 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6133 {
6134 /* Retry with non-wide function (for Windows 98). */
6135 vim_free(wn);
6136 wn = NULL;
6137 }
6138 }
6139 if (wn == NULL)
6140#endif
6141 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6142 if (hFile == INVALID_HANDLE_VALUE)
6143 goto getout;
6144 CloseHandle(hFile);
6145 }
6146
6147 retval = 0; /* success */
6148getout:
6149#ifdef FEAT_MBYTE
6150 vim_free(wn);
6151#endif
6152 return retval;
6153}
6154
6155#if defined(FEAT_MBYTE) || defined(PROTO)
6156/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006157 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006158 */
6159 int
6160mch_open(char *name, int flags, int mode)
6161{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006162 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6163# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164 WCHAR *wn;
6165 int f;
6166
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006167 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006169 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 if (wn != NULL)
6171 {
6172 f = _wopen(wn, flags, mode);
6173 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006174 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 return f;
6176 /* Retry with non-wide function (for Windows 98). Can't use
6177 * GetLastError() here and it's unclear what errno gets set to if
6178 * the _wopen() fails for missing wide functions. */
6179 }
6180 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006181# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006183 /* open() can open a file which name is longer than _MAX_PATH bytes
6184 * and shorter than _MAX_PATH characters successfully, but sometimes it
6185 * causes unexpected error in another part. We make it an error explicitly
6186 * here. */
6187 if (strlen(name) >= _MAX_PATH)
6188 return -1;
6189
Bram Moolenaar071d4272004-06-13 20:20:40 +00006190 return open(name, flags, mode);
6191}
6192
6193/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006194 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006195 */
6196 FILE *
6197mch_fopen(char *name, char *mode)
6198{
6199 WCHAR *wn, *wm;
6200 FILE *f = NULL;
6201
6202 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6203# ifdef __BORLANDC__
6204 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6205 && g_PlatformId == VER_PLATFORM_WIN32_NT
6206# endif
6207 )
6208 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006209# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006210 /* Work around an annoying assertion in the Microsoft debug CRT
6211 * when mode's text/binary setting doesn't match _get_fmode(). */
6212 char newMode = mode[strlen(mode) - 1];
6213 int oldMode = 0;
6214
6215 _get_fmode(&oldMode);
6216 if (newMode == 't')
6217 _set_fmode(_O_TEXT);
6218 else if (newMode == 'b')
6219 _set_fmode(_O_BINARY);
6220# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006221 wn = enc_to_utf16(name, NULL);
6222 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223 if (wn != NULL && wm != NULL)
6224 f = _wfopen(wn, wm);
6225 vim_free(wn);
6226 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006227
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006228# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006229 _set_fmode(oldMode);
6230# endif
6231
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006232 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233 return f;
6234 /* Retry with non-wide function (for Windows 98). Can't use
6235 * GetLastError() here and it's unclear what errno gets set to if
6236 * the _wfopen() fails for missing wide functions. */
6237 }
6238
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006239 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6240 * and shorter than _MAX_PATH characters successfully, but sometimes it
6241 * causes unexpected error in another part. We make it an error explicitly
6242 * here. */
6243 if (strlen(name) >= _MAX_PATH)
6244 return NULL;
6245
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 return fopen(name, mode);
6247}
6248#endif
6249
6250#ifdef FEAT_MBYTE
6251/*
6252 * SUB STREAM (aka info stream) handling:
6253 *
6254 * NTFS can have sub streams for each file. Normal contents of file is
6255 * stored in the main stream, and extra contents (author information and
6256 * title and so on) can be stored in sub stream. After Windows 2000, user
6257 * can access and store those informations in sub streams via explorer's
6258 * property menuitem in right click menu. Those informations in sub streams
6259 * were lost when copying only the main stream. So we have to copy sub
6260 * streams.
6261 *
6262 * Incomplete explanation:
6263 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6264 * More useful info and an example:
6265 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6266 */
6267
6268/*
6269 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6270 * and write to stream "substream" of file "to".
6271 * Errors are ignored.
6272 */
6273 static void
6274copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6275{
6276 HANDLE hTo;
6277 WCHAR *to_name;
6278
6279 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6280 wcscpy(to_name, to);
6281 wcscat(to_name, substream);
6282
6283 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6284 FILE_ATTRIBUTE_NORMAL, NULL);
6285 if (hTo != INVALID_HANDLE_VALUE)
6286 {
6287 long done;
6288 DWORD todo;
6289 DWORD readcnt, written;
6290 char buf[4096];
6291
6292 /* Copy block of bytes at a time. Abort when something goes wrong. */
6293 for (done = 0; done < len; done += written)
6294 {
6295 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006296 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6297 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006298 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6299 FALSE, FALSE, context)
6300 || readcnt != todo
6301 || !WriteFile(hTo, buf, todo, &written, NULL)
6302 || written != todo)
6303 break;
6304 }
6305 CloseHandle(hTo);
6306 }
6307
6308 free(to_name);
6309}
6310
6311/*
6312 * Copy info streams from file "from" to file "to".
6313 */
6314 static void
6315copy_infostreams(char_u *from, char_u *to)
6316{
6317 WCHAR *fromw;
6318 WCHAR *tow;
6319 HANDLE sh;
6320 WIN32_STREAM_ID sid;
6321 int headersize;
6322 WCHAR streamname[_MAX_PATH];
6323 DWORD readcount;
6324 void *context = NULL;
6325 DWORD lo, hi;
6326 int len;
6327
6328 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006329 fromw = enc_to_utf16(from, NULL);
6330 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331 if (fromw != NULL && tow != NULL)
6332 {
6333 /* Open the file for reading. */
6334 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6335 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6336 if (sh != INVALID_HANDLE_VALUE)
6337 {
6338 /* Use BackupRead() to find the info streams. Repeat until we
6339 * have done them all.*/
6340 for (;;)
6341 {
6342 /* Get the header to find the length of the stream name. If
6343 * the "readcount" is zero we have done all info streams. */
6344 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006345 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6347 &readcount, FALSE, FALSE, &context)
6348 || readcount == 0)
6349 break;
6350
6351 /* We only deal with streams that have a name. The normal
6352 * file data appears to be without a name, even though docs
6353 * suggest it is called "::$DATA". */
6354 if (sid.dwStreamNameSize > 0)
6355 {
6356 /* Read the stream name. */
6357 if (!BackupRead(sh, (LPBYTE)streamname,
6358 sid.dwStreamNameSize,
6359 &readcount, FALSE, FALSE, &context))
6360 break;
6361
6362 /* Copy an info stream with a name ":anything:$DATA".
6363 * Skip "::$DATA", it has no stream name (examples suggest
6364 * it might be used for the normal file contents).
6365 * Note that BackupRead() counts bytes, but the name is in
6366 * wide characters. */
6367 len = readcount / sizeof(WCHAR);
6368 streamname[len] = 0;
6369 if (len > 7 && wcsicmp(streamname + len - 6,
6370 L":$DATA") == 0)
6371 {
6372 streamname[len - 6] = 0;
6373 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006374 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 }
6376 }
6377
6378 /* Advance to the next stream. We might try seeking too far,
6379 * but BackupSeek() doesn't skip over stream borders, thus
6380 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006381 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382 &lo, &hi, &context);
6383 }
6384
6385 /* Clear the context. */
6386 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6387
6388 CloseHandle(sh);
6389 }
6390 }
6391 vim_free(fromw);
6392 vim_free(tow);
6393}
6394#endif
6395
6396/*
6397 * Copy file attributes from file "from" to file "to".
6398 * For Windows NT and later we copy info streams.
6399 * Always returns zero, errors are ignored.
6400 */
6401 int
6402mch_copy_file_attribute(char_u *from, char_u *to)
6403{
6404#ifdef FEAT_MBYTE
6405 /* File streams only work on Windows NT and later. */
6406 PlatformId();
6407 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6408 copy_infostreams(from, to);
6409#endif
6410 return 0;
6411}
6412
6413#if defined(MYRESETSTKOFLW) || defined(PROTO)
6414/*
6415 * Recreate a destroyed stack guard page in win32.
6416 * Written by Benjamin Peterson.
6417 */
6418
6419/* These magic numbers are from the MS header files */
6420#define MIN_STACK_WIN9X 17
6421#define MIN_STACK_WINNT 2
6422
6423/*
6424 * This function does the same thing as _resetstkoflw(), which is only
6425 * available in DevStudio .net and later.
6426 * Returns 0 for failure, 1 for success.
6427 */
6428 int
6429myresetstkoflw(void)
6430{
6431 BYTE *pStackPtr;
6432 BYTE *pGuardPage;
6433 BYTE *pStackBase;
6434 BYTE *pLowestPossiblePage;
6435 MEMORY_BASIC_INFORMATION mbi;
6436 SYSTEM_INFO si;
6437 DWORD nPageSize;
6438 DWORD dummy;
6439
6440 /* This code will not work on win32s. */
6441 PlatformId();
6442 if (g_PlatformId == VER_PLATFORM_WIN32s)
6443 return 0;
6444
6445 /* We need to know the system page size. */
6446 GetSystemInfo(&si);
6447 nPageSize = si.dwPageSize;
6448
6449 /* ...and the current stack pointer */
6450 pStackPtr = (BYTE*)_alloca(1);
6451
6452 /* ...and the base of the stack. */
6453 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6454 return 0;
6455 pStackBase = (BYTE*)mbi.AllocationBase;
6456
6457 /* ...and the page thats min_stack_req pages away from stack base; this is
6458 * the lowest page we could use. */
6459 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6460 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6461
6462 /* On Win95, we want the next page down from the end of the stack. */
6463 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6464 {
6465 /* Find the page that's only 1 page down from the page that the stack
6466 * ptr is in. */
6467 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6468 / (DWORD)nPageSize) - 1));
6469 if (pGuardPage < pLowestPossiblePage)
6470 return 0;
6471
6472 /* Apply the noaccess attribute to the page -- there's no guard
6473 * attribute in win95-type OSes. */
6474 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6475 return 0;
6476 }
6477 else
6478 {
6479 /* On NT, however, we want the first committed page in the stack Start
6480 * at the stack base and move forward through memory until we find a
6481 * committed block. */
6482 BYTE *pBlock = pStackBase;
6483
Bram Moolenaara466c992005-07-09 21:03:22 +00006484 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 {
6486 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6487 return 0;
6488
6489 pBlock += mbi.RegionSize;
6490
6491 if (mbi.State & MEM_COMMIT)
6492 break;
6493 }
6494
6495 /* mbi now describes the first committed block in the stack. */
6496 if (mbi.Protect & PAGE_GUARD)
6497 return 1;
6498
6499 /* decide where the guard page should start */
6500 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6501 pGuardPage = pLowestPossiblePage;
6502 else
6503 pGuardPage = (BYTE*)mbi.BaseAddress;
6504
6505 /* allocate the guard page */
6506 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6507 return 0;
6508
6509 /* apply the guard attribute to the page */
6510 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6511 &dummy))
6512 return 0;
6513 }
6514
6515 return 1;
6516}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006517#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006519
6520#if defined(FEAT_MBYTE) || defined(PROTO)
6521/*
6522 * The command line arguments in UCS2
6523 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006524static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006525static LPWSTR *ArglistW = NULL;
6526static int global_argc = 0;
6527static char **global_argv;
6528
6529static int used_file_argc = 0; /* last argument in global_argv[] used
6530 for the argument list. */
6531static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6532 command line arguments added to
6533 the argument list */
6534static int used_file_count = 0; /* nr of entries in used_file_indexes */
6535static int used_file_literal = FALSE; /* take file names literally */
6536static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006537static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006538static int used_alist_count = 0;
6539
6540
6541/*
6542 * Get the command line arguments. Unicode version.
6543 * Returns argc. Zero when something fails.
6544 */
6545 int
6546get_cmd_argsW(char ***argvp)
6547{
6548 char **argv = NULL;
6549 int argc = 0;
6550 int i;
6551
Bram Moolenaar14993322014-09-09 12:25:33 +02006552 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006553 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6554 if (ArglistW != NULL)
6555 {
6556 argv = malloc((nArgsW + 1) * sizeof(char *));
6557 if (argv != NULL)
6558 {
6559 argc = nArgsW;
6560 argv[argc] = NULL;
6561 for (i = 0; i < argc; ++i)
6562 {
6563 int len;
6564
6565 /* Convert each Unicode argument to the current codepage. */
6566 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006567 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006568 (LPSTR *)&argv[i], &len, 0, 0);
6569 if (argv[i] == NULL)
6570 {
6571 /* Out of memory, clear everything. */
6572 while (i > 0)
6573 free(argv[--i]);
6574 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006575 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006576 argc = 0;
6577 }
6578 }
6579 }
6580 }
6581
6582 global_argc = argc;
6583 global_argv = argv;
6584 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006585 {
6586 if (used_file_indexes != NULL)
6587 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006588 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006589 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006590
6591 if (argvp != NULL)
6592 *argvp = argv;
6593 return argc;
6594}
6595
6596 void
6597free_cmd_argsW(void)
6598{
6599 if (ArglistW != NULL)
6600 {
6601 GlobalFree(ArglistW);
6602 ArglistW = NULL;
6603 }
6604}
6605
6606/*
6607 * Remember "name" is an argument that was added to the argument list.
6608 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6609 * is called.
6610 */
6611 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006612used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006613{
6614 int i;
6615
6616 if (used_file_indexes == NULL)
6617 return;
6618 for (i = used_file_argc + 1; i < global_argc; ++i)
6619 if (STRCMP(global_argv[i], name) == 0)
6620 {
6621 used_file_argc = i;
6622 used_file_indexes[used_file_count++] = i;
6623 break;
6624 }
6625 used_file_literal = literal;
6626 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006627 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006628}
6629
6630/*
6631 * Remember the length of the argument list as it was. If it changes then we
6632 * leave it alone when 'encoding' is set.
6633 */
6634 void
6635set_alist_count(void)
6636{
6637 used_alist_count = GARGCOUNT;
6638}
6639
6640/*
6641 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6642 * has been changed while starting up. Use the UCS-2 command line arguments
6643 * and convert them to 'encoding'.
6644 */
6645 void
6646fix_arg_enc(void)
6647{
6648 int i;
6649 int idx;
6650 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006651 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006652
6653 /* Safety checks:
6654 * - if argument count differs between the wide and non-wide argument
6655 * list, something must be wrong.
6656 * - the file name arguments must have been located.
6657 * - the length of the argument list wasn't changed by the user.
6658 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006659 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006660 || ArglistW == NULL
6661 || used_file_indexes == NULL
6662 || used_file_count == 0
6663 || used_alist_count != GARGCOUNT)
6664 return;
6665
Bram Moolenaar86b68352004-12-27 21:59:20 +00006666 /* Remember the buffer numbers for the arguments. */
6667 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6668 if (fnum_list == NULL)
6669 return; /* out of memory */
6670 for (i = 0; i < GARGCOUNT; ++i)
6671 fnum_list[i] = GARGLIST[i].ae_fnum;
6672
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006673 /* Clear the argument list. Make room for the new arguments. */
6674 alist_clear(&global_alist);
6675 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006676 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006677
6678 for (i = 0; i < used_file_count; ++i)
6679 {
6680 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006681 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006682 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006683 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006684#ifdef FEAT_DIFF
6685 /* When using diff mode may need to concatenate file name to
6686 * directory name. Just like it's done in main(). */
6687 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6688 && !mch_isdir(alist_name(&GARGLIST[0])))
6689 {
6690 char_u *r;
6691
6692 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6693 if (r != NULL)
6694 {
6695 vim_free(str);
6696 str = r;
6697 }
6698 }
6699#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006700 /* Re-use the old buffer by renaming it. When not using literal
6701 * names it's done by alist_expand() below. */
6702 if (used_file_literal)
6703 buf_set_name(fnum_list[i], str);
6704
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006705 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006706 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006707 }
6708
6709 if (!used_file_literal)
6710 {
6711 /* Now expand wildcards in the arguments. */
6712 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6713 * filename characters but are excluded from 'isfname' to make
6714 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6715 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006716 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006717 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6718 }
6719
6720 /* If wildcard expansion failed, we are editing the first file of the
6721 * arglist and there is no file name: Edit the first argument now. */
6722 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6723 {
6724 do_cmdline_cmd((char_u *)":rewind");
6725 if (GARGCOUNT == 1 && used_file_full_path)
6726 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6727 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006728
6729 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006730}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731#endif