blob: be7bd95b587773e6640031d7ada8a93fc64d5aea [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;
Bram Moolenaaref269542016-01-19 13:22:12 +0100104typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int HDC;
106typedef int HFONT;
107typedef int HICON;
108typedef int HINSTANCE;
109typedef int HWND;
110typedef int INPUT_RECORD;
111typedef int KEY_EVENT_RECORD;
112typedef int LOGFONT;
113typedef int LPBOOL;
114typedef int LPCTSTR;
115typedef int LPDWORD;
116typedef int LPSTR;
117typedef int LPTSTR;
118typedef int LPVOID;
119typedef int MOUSE_EVENT_RECORD;
120typedef int PACL;
121typedef int PDWORD;
122typedef int PHANDLE;
123typedef int PRINTDLG;
124typedef int PSECURITY_DESCRIPTOR;
125typedef int PSID;
126typedef int SECURITY_INFORMATION;
127typedef int SHORT;
128typedef int SMALL_RECT;
129typedef int TEXTMETRIC;
130typedef int TOKEN_INFORMATION_CLASS;
131typedef int TRUSTEE;
132typedef int WORD;
133typedef int WCHAR;
134typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100135typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200136typedef int SE_OBJECT_TYPE;
137typedef int PSNSECINFO;
138typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100139typedef int STARTUPINFO;
140typedef int PROCESS_INFORMATION;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000141#endif
142
143#ifndef FEAT_GUI_W32
144/* Undocumented API in kernel32.dll needed to work around dead key bug in
145 * console-mode applications in NT 4.0. If you switch keyboard layouts
146 * in a console app to a layout that includes dead keys and then hit a
147 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
148 * and Michael Dietrich for helping me figure out this workaround.
149 */
150
151/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
152#ifndef WINBASEAPI
153# define WINBASEAPI __stdcall
154#endif
155#if defined(__BORLANDC__)
156typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
157#else
158typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
159#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000160static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161#endif
162
163#if defined(__BORLANDC__)
164/* Strangely Borland uses a non-standard name. */
165# define wcsicmp(a, b) wcscmpi((a), (b))
166#endif
167
Bram Moolenaar82881492012-11-20 16:53:39 +0100168#ifndef PROTO
169
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200170/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200171#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100172LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200173BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
174BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
175BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
176#endif
177
Bram Moolenaar82881492012-11-20 16:53:39 +0100178#endif /* PROTO */
179
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180#ifndef FEAT_GUI_W32
181/* Win32 Console handles for input and output */
182static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
183static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
184
185/* Win32 Screen buffer,coordinate,console I/O information */
186static SMALL_RECT g_srScrollRegion;
187static COORD g_coord; /* 0-based, but external coords are 1-based */
188
189/* The attribute of the screen when the editor was started */
190static WORD g_attrDefault = 7; /* lightgray text on black background */
191static WORD g_attrCurrent;
192
193static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
194static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
195static int g_fForceExit = FALSE; /* set when forcefully exiting */
196
197static void termcap_mode_start(void);
198static void termcap_mode_end(void);
199static void clear_chars(COORD coord, DWORD n);
200static void clear_screen(void);
201static void clear_to_end_of_display(void);
202static void clear_to_end_of_line(void);
203static void scroll(unsigned cLines);
204static void set_scroll_region(unsigned left, unsigned top,
205 unsigned right, unsigned bottom);
206static void insert_lines(unsigned cLines);
207static void delete_lines(unsigned cLines);
208static void gotoxy(unsigned x, unsigned y);
209static void normvideo(void);
210static void textattr(WORD wAttr);
211static void textcolor(WORD wAttr);
212static void textbackground(WORD wAttr);
213static void standout(void);
214static void standend(void);
215static void visual_bell(void);
216static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200217static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
218static WCHAR tgetch(int *pmodifiers, WCHAR *pch2);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000219static void create_conin(void);
220static int s_cursor_visible = TRUE;
221static int did_create_conin = FALSE;
222#else
223static int s_dont_use_vimrun = TRUE;
224static int need_vimrun_warning = FALSE;
225static char *vimrun_path = "vimrun ";
226#endif
227
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200228static int win32_getattrs(char_u *name);
229static int win32_setattrs(char_u *name, int attrs);
230static int win32_set_archive(char_u *name);
231
Bram Moolenaar071d4272004-06-13 20:20:40 +0000232#ifndef FEAT_GUI_W32
233static int suppress_winsize = 1; /* don't fiddle with console */
234#endif
235
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200236static char_u *exe_path = NULL;
237
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"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100467# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200469/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000470static char *null_libintl_gettext(const char *);
471static char *null_libintl_textdomain(const char *);
472static char *null_libintl_bindtextdomain(const char *, const char *);
473static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000476char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
477char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
478char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000480char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
481 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482
483 int
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100484dyn_libintl_init()
Bram Moolenaar071d4272004-06-13 20:20:40 +0000485{
486 int i;
487 static struct
488 {
489 char *name;
490 FARPROC *ptr;
491 } libintl_entry[] =
492 {
493 {"gettext", (FARPROC*)&dyn_libintl_gettext},
494 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
495 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
496 {NULL, NULL}
497 };
498
499 /* No need to initialize twice. */
500 if (hLibintlDLL)
501 return 1;
502 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100503 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100504#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100505 if (!hLibintlDLL)
506 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100507#endif
508 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200510 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200512 verbose_enter();
513 EMSG2(_(e_loadlib), GETTEXT_DLL);
514 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200516 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000517 }
518 for (i = 0; libintl_entry[i].name != NULL
519 && libintl_entry[i].ptr != NULL; ++i)
520 {
521 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
522 libintl_entry[i].name)) == NULL)
523 {
524 dyn_libintl_end();
525 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000526 {
527 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000528 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000529 verbose_leave();
530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000531 return 0;
532 }
533 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000534
535 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000536 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000537 "bind_textdomain_codeset");
538 if (dyn_libintl_bind_textdomain_codeset == NULL)
539 dyn_libintl_bind_textdomain_codeset =
540 null_libintl_bind_textdomain_codeset;
541
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542 return 1;
543}
544
545 void
546dyn_libintl_end()
547{
548 if (hLibintlDLL)
549 FreeLibrary(hLibintlDLL);
550 hLibintlDLL = NULL;
551 dyn_libintl_gettext = null_libintl_gettext;
552 dyn_libintl_textdomain = null_libintl_textdomain;
553 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000554 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555}
556
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000557/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000559null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560{
561 return (char*)msgid;
562}
563
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000564/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000566null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000567{
568 return NULL;
569}
570
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000571/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000573null_libintl_bind_textdomain_codeset(const char *domainname,
574 const char *codeset)
575{
576 return NULL;
577}
578
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000579/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000580 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000581null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582{
583 return NULL;
584}
585
586#endif /* DYNAMIC_GETTEXT */
587
588/* This symbol is not defined in older versions of the SDK or Visual C++ */
589
590#ifndef VER_PLATFORM_WIN32_WINDOWS
591# define VER_PLATFORM_WIN32_WINDOWS 1
592#endif
593
594DWORD g_PlatformId;
595
596#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100597# ifndef PROTO
598# include <aclapi.h>
599# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200600# ifndef PROTECTED_DACL_SECURITY_INFORMATION
601# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
602# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100603
Bram Moolenaar071d4272004-06-13 20:20:40 +0000604/*
605 * These are needed to dynamically load the ADVAPI DLL, which is not
606 * implemented under Windows 95 (and causes VIM to crash)
607 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200608typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200610typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
612 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200613# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200614typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200615 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200616typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200617 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
618 PSECURITY_DESCRIPTOR *);
619# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620
621static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
622static PSNSECINFO pSetNamedSecurityInfo;
623static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200624# ifdef FEAT_MBYTE
625static PSNSECINFOW pSetNamedSecurityInfoW;
626static PGNSECINFOW pGetNamedSecurityInfoW;
627# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000628#endif
629
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200630typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
631
632static BOOL allowPiping = FALSE;
633static PSETHANDLEINFORMATION pSetHandleInformation;
634
Bram Moolenaar27515922013-06-29 15:36:26 +0200635#ifdef HAVE_ACL
636/*
637 * Enables or disables the specified privilege.
638 */
639 static BOOL
640win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
641{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100642 BOOL bResult;
643 LUID luid;
644 HANDLE hToken;
645 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200646
647 if (!OpenProcessToken(GetCurrentProcess(),
648 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
649 return FALSE;
650
651 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
652 {
653 CloseHandle(hToken);
654 return FALSE;
655 }
656
Bram Moolenaar45500912014-07-09 20:51:07 +0200657 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200658 tokenPrivileges.Privileges[0].Luid = luid;
659 tokenPrivileges.Privileges[0].Attributes = bEnable ?
660 SE_PRIVILEGE_ENABLED : 0;
661
662 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
663 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
664
665 CloseHandle(hToken);
666
667 return bResult && GetLastError() == ERROR_SUCCESS;
668}
669#endif
670
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671/*
672 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
673 * VER_PLATFORM_WIN32_WINDOWS (Win95).
674 */
675 void
676PlatformId(void)
677{
678 static int done = FALSE;
679
680 if (!done)
681 {
682 OSVERSIONINFO ovi;
683
684 ovi.dwOSVersionInfoSize = sizeof(ovi);
685 GetVersionEx(&ovi);
686
687 g_PlatformId = ovi.dwPlatformId;
688
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100689 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
690 || ovi.dwMajorVersion > 6)
691 win8_or_later = TRUE;
692
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693#ifdef HAVE_ACL
694 /*
695 * Load the ADVAPI runtime if we are on anything
696 * other than Windows 95
697 */
698 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
699 {
700 /*
701 * do this load. Problems: Doesn't unload at end of run (this is
702 * theoretically okay, since Windows should unload it when VIM
703 * terminates). Should we be using the 'mch_libcall' routines?
704 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
705 * time we verify security...
706 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200707 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708 if (advapi_lib != NULL)
709 {
710 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
711 "SetNamedSecurityInfoA");
712 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
713 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200714# ifdef FEAT_MBYTE
715 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
716 "SetNamedSecurityInfoW");
717 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
718 "GetNamedSecurityInfoW");
719# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200721 || pGetNamedSecurityInfo == NULL
722# ifdef FEAT_MBYTE
723 || pSetNamedSecurityInfoW == NULL
724 || pGetNamedSecurityInfoW == NULL
725# endif
726 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727 {
728 /* If we can't get the function addresses, set advapi_lib
729 * to NULL so that we don't use them. */
730 FreeLibrary(advapi_lib);
731 advapi_lib = NULL;
732 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200733 /* Enable privilege for getting or setting SACLs. */
734 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 }
736 }
737#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200738 /*
739 * If we are on windows NT, try to load the pipe functions, only
740 * available from Win2K.
741 */
742 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
743 {
744 HANDLE kernel32 = GetModuleHandle("kernel32");
745 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
746 kernel32, "SetHandleInformation");
747
748 allowPiping = pSetHandleInformation != NULL;
749 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 done = TRUE;
751 }
752}
753
754/*
755 * Return TRUE when running on Windows 95 (or 98 or ME).
756 * Only to be used after mch_init().
757 */
758 int
759mch_windows95(void)
760{
761 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
762}
763
764#ifdef FEAT_GUI_W32
765/*
766 * Used to work around the "can't do synchronous spawn"
767 * problem on Win32s, without resorting to Universal Thunk.
768 */
769static int old_num_windows;
770static int num_windows;
771
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000772/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773 static BOOL CALLBACK
774win32ssynch_cb(HWND hwnd, LPARAM lparam)
775{
776 num_windows++;
777 return TRUE;
778}
779#endif
780
781#ifndef FEAT_GUI_W32
782
783#define SHIFT (SHIFT_PRESSED)
784#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
785#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
786#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
787
788
789/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
790 * We map function keys to their ANSI terminal equivalents, as produced
791 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
792 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
793 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
794 * combinations of function/arrow/etc keys.
795 */
796
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000797static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798{
799 WORD wVirtKey;
800 BOOL fAnsiKey;
801 int chAlone;
802 int chShift;
803 int chCtrl;
804 int chAlt;
805} VirtKeyMap[] =
806{
807
808/* Key ANSI alone shift ctrl alt */
809 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
810
811 { VK_F1, TRUE, ';', 'T', '^', 'h', },
812 { VK_F2, TRUE, '<', 'U', '_', 'i', },
813 { VK_F3, TRUE, '=', 'V', '`', 'j', },
814 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
815 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
816 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
817 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
818 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
819 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
820 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
821 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
822 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
823
824 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
825 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
826 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
827 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
828 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
829 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
830 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
831 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
832 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
833 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
834
835 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
836
837#if 0
838 /* Most people don't have F13-F20, but what the hell... */
839 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
840 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
841 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
842 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
843 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
844 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
845 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
846 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
847#endif
848 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
849 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
850 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
851 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
852
853 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
854 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
855 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
856 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
857 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
858 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
859 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
860 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
861 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
862 /* Sorry, out of number space! <negri>*/
863 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
864
865};
866
867
868#ifdef _MSC_VER
869// The ToAscii bug destroys several registers. Need to turn off optimization
870// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000871# pragma warning(push)
872# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873# pragma optimize("", off)
874#endif
875
876#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200877# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200879# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000880#endif
881
882/* The return code indicates key code size. */
883 static int
884#ifdef __BORLANDC__
885 __stdcall
886#endif
887win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000888 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889{
890 UINT uMods = pker->dwControlKeyState;
891 static int s_iIsDead = 0;
892 static WORD awAnsiCode[2];
893 static BYTE abKeystate[256];
894
895
896 if (s_iIsDead == 2)
897 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200898 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899 s_iIsDead = 0;
900 return 1;
901 }
902
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200903 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904 return 1;
905
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200906 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907
908 // Should only be non-NULL on NT 4.0
909 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
910 {
911 CHAR szKLID[KL_NAMELENGTH];
912
913 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
914 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
915 }
916
917 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200918 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919
920 if (uMods & SHIFT_PRESSED)
921 abKeystate[VK_SHIFT] = 0x80;
922 if (uMods & CAPSLOCK_ON)
923 abKeystate[VK_CAPITAL] = 1;
924
925 if ((uMods & ALT_GR) == ALT_GR)
926 {
927 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
928 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
929 }
930
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200931 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
932 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933
934 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200935 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936
937 return s_iIsDead;
938}
939
940#ifdef _MSC_VER
941/* MUST switch optimization on again here, otherwise a call to
942 * decode_key_event() may crash (e.g. when hitting caps-lock) */
943# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000944# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945
946# if (_MSC_VER < 1100)
947/* MUST turn off global optimisation for this next function, or
948 * pressing ctrl-minus in insert mode crashes Vim when built with
949 * VC4.1. -- negri. */
950# pragma optimize("g", off)
951# endif
952#endif
953
954static BOOL g_fJustGotFocus = FALSE;
955
956/*
957 * Decode a KEY_EVENT into one or two keystrokes
958 */
959 static BOOL
960decode_key_event(
961 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200962 WCHAR *pch,
963 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964 int *pmodifiers,
965 BOOL fDoPost)
966{
967 int i;
968 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
969
970 *pch = *pch2 = NUL;
971 g_fJustGotFocus = FALSE;
972
973 /* ignore key up events */
974 if (!pker->bKeyDown)
975 return FALSE;
976
977 /* ignore some keystrokes */
978 switch (pker->wVirtualKeyCode)
979 {
980 /* modifiers */
981 case VK_SHIFT:
982 case VK_CONTROL:
983 case VK_MENU: /* Alt key */
984 return FALSE;
985
986 default:
987 break;
988 }
989
990 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200991 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992 {
993 /* Ctrl-6 is Ctrl-^ */
994 if (pker->wVirtualKeyCode == '6')
995 {
996 *pch = Ctrl_HAT;
997 return TRUE;
998 }
999 /* Ctrl-2 is Ctrl-@ */
1000 else if (pker->wVirtualKeyCode == '2')
1001 {
1002 *pch = NUL;
1003 return TRUE;
1004 }
1005 /* Ctrl-- is Ctrl-_ */
1006 else if (pker->wVirtualKeyCode == 0xBD)
1007 {
1008 *pch = Ctrl__;
1009 return TRUE;
1010 }
1011 }
1012
1013 /* Shift-TAB */
1014 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1015 {
1016 *pch = K_NUL;
1017 *pch2 = '\017';
1018 return TRUE;
1019 }
1020
1021 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1022 {
1023 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1024 {
1025 if (nModifs == 0)
1026 *pch = VirtKeyMap[i].chAlone;
1027 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1028 *pch = VirtKeyMap[i].chShift;
1029 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1030 *pch = VirtKeyMap[i].chCtrl;
1031 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1032 *pch = VirtKeyMap[i].chAlt;
1033
1034 if (*pch != 0)
1035 {
1036 if (VirtKeyMap[i].fAnsiKey)
1037 {
1038 *pch2 = *pch;
1039 *pch = K_NUL;
1040 }
1041
1042 return TRUE;
1043 }
1044 }
1045 }
1046
1047 i = win32_kbd_patch_key(pker);
1048
1049 if (i < 0)
1050 *pch = NUL;
1051 else
1052 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001053 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054
1055 if (pmodifiers != NULL)
1056 {
1057 /* Pass on the ALT key as a modifier, but only when not combined
1058 * with CTRL (which is ALTGR). */
1059 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1060 *pmodifiers |= MOD_MASK_ALT;
1061
1062 /* Pass on SHIFT only for special keys, because we don't know when
1063 * it's already included with the character. */
1064 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1065 *pmodifiers |= MOD_MASK_SHIFT;
1066
1067 /* Pass on CTRL only for non-special keys, because we don't know
1068 * when it's already included with the character. And not when
1069 * combined with ALT (which is ALTGR). */
1070 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1071 && *pch >= 0x20 && *pch < 0x80)
1072 *pmodifiers |= MOD_MASK_CTRL;
1073 }
1074 }
1075
1076 return (*pch != NUL);
1077}
1078
1079#ifdef _MSC_VER
1080# pragma optimize("", on)
1081#endif
1082
1083#endif /* FEAT_GUI_W32 */
1084
1085
1086#ifdef FEAT_MOUSE
1087
1088/*
1089 * For the GUI the mouse handling is in gui_w32.c.
1090 */
1091# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001092/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001094mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095{
1096}
1097# else
1098static int g_fMouseAvail = FALSE; /* mouse present */
1099static int g_fMouseActive = FALSE; /* mouse enabled */
1100static int g_nMouseClick = -1; /* mouse status */
1101static int g_xMouse; /* mouse x coordinate */
1102static int g_yMouse; /* mouse y coordinate */
1103
1104/*
1105 * Enable or disable mouse input
1106 */
1107 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001108mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109{
1110 DWORD cmodein;
1111
1112 if (!g_fMouseAvail)
1113 return;
1114
1115 g_fMouseActive = on;
1116 GetConsoleMode(g_hConIn, &cmodein);
1117
1118 if (g_fMouseActive)
1119 cmodein |= ENABLE_MOUSE_INPUT;
1120 else
1121 cmodein &= ~ENABLE_MOUSE_INPUT;
1122
1123 SetConsoleMode(g_hConIn, cmodein);
1124}
1125
1126
1127/*
1128 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1129 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1130 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1131 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1132 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1133 * and we return the mouse position in g_xMouse and g_yMouse.
1134 *
1135 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1136 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1137 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1138 *
1139 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1140 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1141 *
1142 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1143 * moves, even if it stays within the same character cell. We ignore
1144 * all MOUSE_MOVED messages if the position hasn't really changed, and
1145 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1146 * we're only interested in MOUSE_DRAG).
1147 *
1148 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1149 * 2-button mouses by pressing the left & right buttons simultaneously.
1150 * In practice, it's almost impossible to click both at the same time,
1151 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1152 * in such cases, if the user is clicking quickly.
1153 */
1154 static BOOL
1155decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001156 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157{
1158 static int s_nOldButton = -1;
1159 static int s_nOldMouseClick = -1;
1160 static int s_xOldMouse = -1;
1161 static int s_yOldMouse = -1;
1162 static linenr_T s_old_topline = 0;
1163#ifdef FEAT_DIFF
1164 static int s_old_topfill = 0;
1165#endif
1166 static int s_cClicks = 1;
1167 static BOOL s_fReleased = TRUE;
1168 static DWORD s_dwLastClickTime = 0;
1169 static BOOL s_fNextIsMiddle = FALSE;
1170
1171 static DWORD cButtons = 0; /* number of buttons supported */
1172
1173 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1174 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1175 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1176 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1177
1178 int nButton;
1179
1180 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1181 cButtons = 2;
1182
1183 if (!g_fMouseAvail || !g_fMouseActive)
1184 {
1185 g_nMouseClick = -1;
1186 return FALSE;
1187 }
1188
1189 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1190 if (g_fJustGotFocus)
1191 {
1192 g_fJustGotFocus = FALSE;
1193 return FALSE;
1194 }
1195
1196 /* unprocessed mouse click? */
1197 if (g_nMouseClick != -1)
1198 return TRUE;
1199
1200 nButton = -1;
1201 g_xMouse = pmer->dwMousePosition.X;
1202 g_yMouse = pmer->dwMousePosition.Y;
1203
1204 if (pmer->dwEventFlags == MOUSE_MOVED)
1205 {
1206 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1207 * events even when the mouse moves only within a char cell.) */
1208 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1209 return FALSE;
1210 }
1211
1212 /* If no buttons are pressed... */
1213 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1214 {
1215 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1216 if (s_fReleased)
1217 return FALSE;
1218
1219 nButton = MOUSE_RELEASE;
1220 s_fReleased = TRUE;
1221 }
1222 else /* one or more buttons pressed */
1223 {
1224 /* on a 2-button mouse, hold down left and right buttons
1225 * simultaneously to get MIDDLE. */
1226
1227 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1228 {
1229 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1230
1231 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001232 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233 if (dwLR == LEFT || dwLR == RIGHT)
1234 {
1235 for (;;)
1236 {
1237 /* wait a short time for next input event */
1238 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1239 != WAIT_OBJECT_0)
1240 break;
1241 else
1242 {
1243 DWORD cRecords = 0;
1244 INPUT_RECORD ir;
1245 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1246
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001247 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001248
1249 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1250 || !(pmer2->dwButtonState & LEFT_RIGHT))
1251 break;
1252 else
1253 {
1254 if (pmer2->dwEventFlags != MOUSE_MOVED)
1255 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001256 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001257
1258 return decode_mouse_event(pmer2);
1259 }
1260 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1261 s_yOldMouse == pmer2->dwMousePosition.Y)
1262 {
1263 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001264 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265
1266 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001267 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001268
1269 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1270 break;
1271 }
1272 else
1273 break;
1274 }
1275 }
1276 }
1277 }
1278 }
1279
1280 if (s_fNextIsMiddle)
1281 {
1282 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1283 ? MOUSE_DRAG : MOUSE_MIDDLE;
1284 s_fNextIsMiddle = FALSE;
1285 }
1286 else if (cButtons == 2 &&
1287 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1288 {
1289 nButton = MOUSE_MIDDLE;
1290
1291 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1292 {
1293 s_fNextIsMiddle = TRUE;
1294 nButton = MOUSE_RELEASE;
1295 }
1296 }
1297 else if ((pmer->dwButtonState & LEFT) == LEFT)
1298 nButton = MOUSE_LEFT;
1299 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1300 nButton = MOUSE_MIDDLE;
1301 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1302 nButton = MOUSE_RIGHT;
1303
1304 if (! s_fReleased && ! s_fNextIsMiddle
1305 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1306 return FALSE;
1307
1308 s_fReleased = s_fNextIsMiddle;
1309 }
1310
1311 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1312 {
1313 /* button pressed or released, without mouse moving */
1314 if (nButton != -1 && nButton != MOUSE_RELEASE)
1315 {
1316 DWORD dwCurrentTime = GetTickCount();
1317
1318 if (s_xOldMouse != g_xMouse
1319 || s_yOldMouse != g_yMouse
1320 || s_nOldButton != nButton
1321 || s_old_topline != curwin->w_topline
1322#ifdef FEAT_DIFF
1323 || s_old_topfill != curwin->w_topfill
1324#endif
1325 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1326 {
1327 s_cClicks = 1;
1328 }
1329 else if (++s_cClicks > 4)
1330 {
1331 s_cClicks = 1;
1332 }
1333
1334 s_dwLastClickTime = dwCurrentTime;
1335 }
1336 }
1337 else if (pmer->dwEventFlags == MOUSE_MOVED)
1338 {
1339 if (nButton != -1 && nButton != MOUSE_RELEASE)
1340 nButton = MOUSE_DRAG;
1341
1342 s_cClicks = 1;
1343 }
1344
1345 if (nButton == -1)
1346 return FALSE;
1347
1348 if (nButton != MOUSE_RELEASE)
1349 s_nOldButton = nButton;
1350
1351 g_nMouseClick = nButton;
1352
1353 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1354 g_nMouseClick |= MOUSE_SHIFT;
1355 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1356 g_nMouseClick |= MOUSE_CTRL;
1357 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1358 g_nMouseClick |= MOUSE_ALT;
1359
1360 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1361 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1362
1363 /* only pass on interesting (i.e., different) mouse events */
1364 if (s_xOldMouse == g_xMouse
1365 && s_yOldMouse == g_yMouse
1366 && s_nOldMouseClick == g_nMouseClick)
1367 {
1368 g_nMouseClick = -1;
1369 return FALSE;
1370 }
1371
1372 s_xOldMouse = g_xMouse;
1373 s_yOldMouse = g_yMouse;
1374 s_old_topline = curwin->w_topline;
1375#ifdef FEAT_DIFF
1376 s_old_topfill = curwin->w_topfill;
1377#endif
1378 s_nOldMouseClick = g_nMouseClick;
1379
1380 return TRUE;
1381}
1382
1383# endif /* FEAT_GUI_W32 */
1384#endif /* FEAT_MOUSE */
1385
1386
1387#ifdef MCH_CURSOR_SHAPE
1388/*
1389 * Set the shape of the cursor.
1390 * 'thickness' can be from 1 (thin) to 99 (block)
1391 */
1392 static void
1393mch_set_cursor_shape(int thickness)
1394{
1395 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1396 ConsoleCursorInfo.dwSize = thickness;
1397 ConsoleCursorInfo.bVisible = s_cursor_visible;
1398
1399 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1400 if (s_cursor_visible)
1401 SetConsoleCursorPosition(g_hConOut, g_coord);
1402}
1403
1404 void
1405mch_update_cursor(void)
1406{
1407 int idx;
1408 int thickness;
1409
1410 /*
1411 * How the cursor is drawn depends on the current mode.
1412 */
1413 idx = get_shape_idx(FALSE);
1414
1415 if (shape_table[idx].shape == SHAPE_BLOCK)
1416 thickness = 99; /* 100 doesn't work on W95 */
1417 else
1418 thickness = shape_table[idx].percentage;
1419 mch_set_cursor_shape(thickness);
1420}
1421#endif
1422
1423#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1424/*
1425 * Handle FOCUS_EVENT.
1426 */
1427 static void
1428handle_focus_event(INPUT_RECORD ir)
1429{
1430 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1431 ui_focus_change((int)g_fJustGotFocus);
1432}
1433
1434/*
1435 * Wait until console input from keyboard or mouse is available,
1436 * or the time is up.
1437 * Return TRUE if something is available FALSE if not.
1438 */
1439 static int
1440WaitForChar(long msec)
1441{
1442 DWORD dwNow = 0, dwEndTime = 0;
1443 INPUT_RECORD ir;
1444 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001445 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001446
1447 if (msec > 0)
1448 /* Wait until the specified time has elapsed. */
1449 dwEndTime = GetTickCount() + msec;
1450 else if (msec < 0)
1451 /* Wait forever. */
1452 dwEndTime = INFINITE;
1453
1454 /* We need to loop until the end of the time period, because
1455 * we might get multiple unusable mouse events in that time.
1456 */
1457 for (;;)
1458 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001459#ifdef FEAT_MZSCHEME
1460 mzvim_check_threads();
1461#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462#ifdef FEAT_CLIENTSERVER
1463 serverProcessPendingMessages();
1464#endif
1465 if (0
1466#ifdef FEAT_MOUSE
1467 || g_nMouseClick != -1
1468#endif
1469#ifdef FEAT_CLIENTSERVER
1470 || input_available()
1471#endif
1472 )
1473 return TRUE;
1474
1475 if (msec > 0)
1476 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001477 /* If the specified wait time has passed, return. Beware that
1478 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001480 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001481 break;
1482 }
1483 if (msec != 0)
1484 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001485 DWORD dwWaitTime = dwEndTime - dwNow;
1486
1487#ifdef FEAT_MZSCHEME
1488 if (mzthreads_allowed() && p_mzq > 0
1489 && (msec < 0 || (long)dwWaitTime > p_mzq))
1490 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1491#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492#ifdef FEAT_CLIENTSERVER
1493 /* Wait for either an event on the console input or a message in
1494 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001495 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001496 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001498 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499#endif
1500 continue;
1501 }
1502
1503 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001504 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505
1506#ifdef FEAT_MBYTE_IME
1507 if (State & CMDLINE && msg_row == Rows - 1)
1508 {
1509 CONSOLE_SCREEN_BUFFER_INFO csbi;
1510
1511 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1512 {
1513 if (csbi.dwCursorPosition.Y != msg_row)
1514 {
1515 /* The screen is now messed up, must redraw the
1516 * command line and later all the windows. */
1517 redraw_all_later(CLEAR);
1518 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1519 redrawcmd();
1520 }
1521 }
1522 }
1523#endif
1524
1525 if (cRecords > 0)
1526 {
1527 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1528 {
1529#ifdef FEAT_MBYTE_IME
1530 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1531 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001532 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1534 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001535 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536 continue;
1537 }
1538#endif
1539 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1540 NULL, FALSE))
1541 return TRUE;
1542 }
1543
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001544 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545
1546 if (ir.EventType == FOCUS_EVENT)
1547 handle_focus_event(ir);
1548 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1549 shell_resized();
1550#ifdef FEAT_MOUSE
1551 else if (ir.EventType == MOUSE_EVENT
1552 && decode_mouse_event(&ir.Event.MouseEvent))
1553 return TRUE;
1554#endif
1555 }
1556 else if (msec == 0)
1557 break;
1558 }
1559
1560#ifdef FEAT_CLIENTSERVER
1561 /* Something might have been received while we were waiting. */
1562 if (input_available())
1563 return TRUE;
1564#endif
1565 return FALSE;
1566}
1567
1568#ifndef FEAT_GUI_MSWIN
1569/*
1570 * return non-zero if a character is available
1571 */
1572 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001573mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574{
1575 return WaitForChar(0L);
1576}
1577#endif
1578
1579/*
1580 * Create the console input. Used when reading stdin doesn't work.
1581 */
1582 static void
1583create_conin(void)
1584{
1585 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1586 FILE_SHARE_READ|FILE_SHARE_WRITE,
1587 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001588 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589 did_create_conin = TRUE;
1590}
1591
1592/*
1593 * Get a keystroke or a mouse event
1594 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001595 static WCHAR
1596tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001598 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599
1600 for (;;)
1601 {
1602 INPUT_RECORD ir;
1603 DWORD cRecords = 0;
1604
1605#ifdef FEAT_CLIENTSERVER
1606 (void)WaitForChar(-1L);
1607 if (input_available())
1608 return 0;
1609# ifdef FEAT_MOUSE
1610 if (g_nMouseClick != -1)
1611 return 0;
1612# endif
1613#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001614 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615 {
1616 if (did_create_conin)
1617 read_error_exit();
1618 create_conin();
1619 continue;
1620 }
1621
1622 if (ir.EventType == KEY_EVENT)
1623 {
1624 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1625 pmodifiers, TRUE))
1626 return ch;
1627 }
1628 else if (ir.EventType == FOCUS_EVENT)
1629 handle_focus_event(ir);
1630 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1631 shell_resized();
1632#ifdef FEAT_MOUSE
1633 else if (ir.EventType == MOUSE_EVENT)
1634 {
1635 if (decode_mouse_event(&ir.Event.MouseEvent))
1636 return 0;
1637 }
1638#endif
1639 }
1640}
1641#endif /* !FEAT_GUI_W32 */
1642
1643
1644/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001645 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001646 * Get one or more characters from the keyboard or the mouse.
1647 * If time == 0, do not wait for characters.
1648 * If time == n, wait a short time for characters.
1649 * If time == -1, wait forever for characters.
1650 * Returns the number of characters read into buf.
1651 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001652/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 int
1654mch_inchar(
1655 char_u *buf,
1656 int maxlen,
1657 long time,
1658 int tb_change_cnt)
1659{
1660#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1661
1662 int len;
1663 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001664#define TYPEAHEADLEN 20
1665 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1666 static int typeaheadlen = 0;
1667
1668 /* First use any typeahead that was kept because "buf" was too small. */
1669 if (typeaheadlen > 0)
1670 goto theend;
1671
1672#ifdef FEAT_SNIFF
1673 if (want_sniff_request)
1674 {
1675 if (sniff_request_waiting)
1676 {
1677 /* return K_SNIFF */
1678 typeahead[typeaheadlen++] = CSI;
1679 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1680 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1681 sniff_request_waiting = 0;
1682 want_sniff_request = 0;
1683 goto theend;
1684 }
1685 else if (time < 0 || time > 250)
1686 {
1687 /* don't wait too long, a request might be pending */
1688 time = 250;
1689 }
1690 }
1691#endif
1692
1693 if (time >= 0)
1694 {
1695 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697 }
1698 else /* time == -1, wait forever */
1699 {
1700 mch_set_winsize_now(); /* Allow winsize changes from now on */
1701
Bram Moolenaar3918c952005-03-15 22:34:55 +00001702 /*
1703 * If there is no character available within 2 seconds (default)
1704 * write the autoscript file to disk. Or cause the CursorHold event
1705 * to be triggered.
1706 */
1707 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 {
1709#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001710 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001712 buf[0] = K_SPECIAL;
1713 buf[1] = KS_EXTRA;
1714 buf[2] = (int)KE_CURSORHOLD;
1715 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716 }
1717#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001718 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719 }
1720 }
1721
1722 /*
1723 * Try to read as many characters as there are, until the buffer is full.
1724 */
1725
1726 /* we will get at least one key. Get more if they are available. */
1727 g_fCBrkPressed = FALSE;
1728
1729#ifdef MCH_WRITE_DUMP
1730 if (fdDump)
1731 fputc('[', fdDump);
1732#endif
1733
1734 /* Keep looping until there is something in the typeahead buffer and more
1735 * to get and still room in the buffer (up to two bytes for a char and
1736 * three bytes for a modifier). */
1737 while ((typeaheadlen == 0 || WaitForChar(0L))
1738 && typeaheadlen + 5 <= TYPEAHEADLEN)
1739 {
1740 if (typebuf_changed(tb_change_cnt))
1741 {
1742 /* "buf" may be invalid now if a client put something in the
1743 * typeahead buffer and "buf" is in the typeahead buffer. */
1744 typeaheadlen = 0;
1745 break;
1746 }
1747#ifdef FEAT_MOUSE
1748 if (g_nMouseClick != -1)
1749 {
1750# ifdef MCH_WRITE_DUMP
1751 if (fdDump)
1752 fprintf(fdDump, "{%02x @ %d, %d}",
1753 g_nMouseClick, g_xMouse, g_yMouse);
1754# endif
1755 typeahead[typeaheadlen++] = ESC + 128;
1756 typeahead[typeaheadlen++] = 'M';
1757 typeahead[typeaheadlen++] = g_nMouseClick;
1758 typeahead[typeaheadlen++] = g_xMouse + '!';
1759 typeahead[typeaheadlen++] = g_yMouse + '!';
1760 g_nMouseClick = -1;
1761 }
1762 else
1763#endif
1764 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001765 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001766 int modifiers = 0;
1767
1768 c = tgetch(&modifiers, &ch2);
1769
1770 if (typebuf_changed(tb_change_cnt))
1771 {
1772 /* "buf" may be invalid now if a client put something in the
1773 * typeahead buffer and "buf" is in the typeahead buffer. */
1774 typeaheadlen = 0;
1775 break;
1776 }
1777
1778 if (c == Ctrl_C && ctrl_c_interrupts)
1779 {
1780#if defined(FEAT_CLIENTSERVER)
1781 trash_input_buf();
1782#endif
1783 got_int = TRUE;
1784 }
1785
1786#ifdef FEAT_MOUSE
1787 if (g_nMouseClick == -1)
1788#endif
1789 {
1790 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001791 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001793#ifdef FEAT_MBYTE
1794 if (ch2 == NUL)
1795 {
1796 int i;
1797 char_u *p;
1798 WCHAR ch[2];
1799
1800 ch[0] = c;
1801 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1802 {
1803 ch[1] = tgetch(&modifiers, &ch2);
1804 n++;
1805 }
1806 p = utf16_to_enc(ch, &n);
1807 if (p != NULL)
1808 {
1809 for (i = 0; i < n; i++)
1810 typeahead[typeaheadlen + i] = p[i];
1811 vim_free(p);
1812 }
1813 }
1814 else
1815#endif
1816 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 if (ch2 != NUL)
1818 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001819 typeahead[typeaheadlen + n] = 3;
1820 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001821 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823
Bram Moolenaar45500912014-07-09 20:51:07 +02001824 if (conv)
1825 {
1826 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001827
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001828 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001829 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001830 char_u *e = typeahead + TYPEAHEADLEN;
1831
1832 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001833 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001834 if (*p == K_NUL)
1835 {
1836 ++p;
1837 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1838 *p = 3;
1839 ++n;
1840 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001841 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001842 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001843 }
1844 }
1845
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 /* Use the ALT key to set the 8th bit of the character
1847 * when it's one byte, the 8th bit isn't set yet and not
1848 * using a double-byte encoding (would become a lead
1849 * byte). */
1850 if ((modifiers & MOD_MASK_ALT)
1851 && n == 1
1852 && (typeahead[typeaheadlen] & 0x80) == 0
1853#ifdef FEAT_MBYTE
1854 && !enc_dbcs
1855#endif
1856 )
1857 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001858#ifdef FEAT_MBYTE
1859 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1860 typeahead + typeaheadlen);
1861#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001863#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864 modifiers &= ~MOD_MASK_ALT;
1865 }
1866
1867 if (modifiers != 0)
1868 {
1869 /* Prepend modifiers to the character. */
1870 mch_memmove(typeahead + typeaheadlen + 3,
1871 typeahead + typeaheadlen, n);
1872 typeahead[typeaheadlen++] = K_SPECIAL;
1873 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1874 typeahead[typeaheadlen++] = modifiers;
1875 }
1876
1877 typeaheadlen += n;
1878
1879#ifdef MCH_WRITE_DUMP
1880 if (fdDump)
1881 fputc(c, fdDump);
1882#endif
1883 }
1884 }
1885 }
1886
1887#ifdef MCH_WRITE_DUMP
1888 if (fdDump)
1889 {
1890 fputs("]\n", fdDump);
1891 fflush(fdDump);
1892 }
1893#endif
1894
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895theend:
1896 /* Move typeahead to "buf", as much as fits. */
1897 len = 0;
1898 while (len < maxlen && typeaheadlen > 0)
1899 {
1900 buf[len++] = typeahead[0];
1901 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1902 }
1903 return len;
1904
1905#else /* FEAT_GUI_W32 */
1906 return 0;
1907#endif /* FEAT_GUI_W32 */
1908}
1909
Bram Moolenaar82881492012-11-20 16:53:39 +01001910#ifndef PROTO
1911# ifndef __MINGW32__
1912# include <shellapi.h> /* required for FindExecutable() */
1913# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914#endif
1915
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001916/*
1917 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001918 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001919 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001921executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001923 char *dum;
1924 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001925 char *curpath, *newpath;
1926 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001928#ifdef FEAT_MBYTE
1929 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001930 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001931 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001932 WCHAR fnamew[_MAX_PATH];
1933 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001934 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001935
1936 if (p != NULL)
1937 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001938 wcurpath = _wgetenv(L"PATH");
1939 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1940 * sizeof(WCHAR));
1941 if (wnewpath == NULL)
1942 return FALSE;
1943 wcscpy(wnewpath, L".;");
1944 wcscat(wnewpath, wcurpath);
1945 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1946 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001947 vim_free(p);
1948 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1949 {
1950 if (n == 0)
1951 return FALSE;
1952 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1953 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001954 if (path != NULL)
1955 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001956 return TRUE;
1957 }
1958 /* Retry with non-wide function (for Windows 98). */
1959 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001961#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001962
1963 curpath = getenv("PATH");
1964 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1965 if (newpath == NULL)
1966 return FALSE;
1967 STRCPY(newpath, ".;");
1968 STRCAT(newpath, curpath);
1969 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1970 vim_free(newpath);
1971 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001972 return FALSE;
1973 if (mch_isdir(fname))
1974 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001975 if (path != NULL)
1976 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001977 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978}
1979
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001980#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001981 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001982/*
1983 * Bad parameter handler.
1984 *
1985 * Certain MS CRT functions will intentionally crash when passed invalid
1986 * parameters to highlight possible security holes. Setting this function as
1987 * the bad parameter handler will prevent the crash.
1988 *
1989 * In debug builds the parameters contain CRT information that might help track
1990 * down the source of a problem, but in non-debug builds the arguments are all
1991 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1992 * worth allowing these to make debugging of issues easier.
1993 */
1994 static void
1995bad_param_handler(const wchar_t *expression,
1996 const wchar_t *function,
1997 const wchar_t *file,
1998 unsigned int line,
1999 uintptr_t pReserved)
2000{
2001}
2002
2003# define SET_INVALID_PARAM_HANDLER \
2004 ((void)_set_invalid_parameter_handler(bad_param_handler))
2005#else
2006# define SET_INVALID_PARAM_HANDLER
2007#endif
2008
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009#ifdef FEAT_GUI_W32
2010
2011/*
2012 * GUI version of mch_init().
2013 */
2014 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002015mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016{
2017#ifndef __MINGW32__
2018 extern int _fmode;
2019#endif
2020
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002021 /* Silently handle invalid parameters to CRT functions */
2022 SET_INVALID_PARAM_HANDLER;
2023
Bram Moolenaar071d4272004-06-13 20:20:40 +00002024 /* Let critical errors result in a failure, not in a dialog box. Required
2025 * for the timestamp test to work on removed floppies. */
2026 SetErrorMode(SEM_FAILCRITICALERRORS);
2027
2028 _fmode = O_BINARY; /* we do our own CR-LF translation */
2029
2030 /* Specify window size. Is there a place to get the default from? */
2031 Rows = 25;
2032 Columns = 80;
2033
2034 /* Look for 'vimrun' */
2035 if (!gui_is_win32s())
2036 {
2037 char_u vimrun_location[_MAX_PATH + 4];
2038
2039 /* First try in same directory as gvim.exe */
2040 STRCPY(vimrun_location, exe_name);
2041 STRCPY(gettail(vimrun_location), "vimrun.exe");
2042 if (mch_getperm(vimrun_location) >= 0)
2043 {
2044 if (*skiptowhite(vimrun_location) != NUL)
2045 {
2046 /* Enclose path with white space in double quotes. */
2047 mch_memmove(vimrun_location + 1, vimrun_location,
2048 STRLEN(vimrun_location) + 1);
2049 *vimrun_location = '"';
2050 STRCPY(gettail(vimrun_location), "vimrun\" ");
2051 }
2052 else
2053 STRCPY(gettail(vimrun_location), "vimrun ");
2054
2055 vimrun_path = (char *)vim_strsave(vimrun_location);
2056 s_dont_use_vimrun = FALSE;
2057 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002058 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 s_dont_use_vimrun = FALSE;
2060
2061 /* Don't give the warning for a missing vimrun.exe right now, but only
2062 * when vimrun was supposed to be used. Don't bother people that do
2063 * not need vimrun.exe. */
2064 if (s_dont_use_vimrun)
2065 need_vimrun_warning = TRUE;
2066 }
2067
2068 /*
2069 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2070 * Otherwise the default "findstr /n" is used.
2071 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002072 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2074
2075#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002076 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077#endif
2078}
2079
2080
2081#else /* FEAT_GUI_W32 */
2082
2083#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2084#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2085
2086/*
2087 * ClearConsoleBuffer()
2088 * Description:
2089 * Clears the entire contents of the console screen buffer, using the
2090 * specified attribute.
2091 * Returns:
2092 * TRUE on success
2093 */
2094 static BOOL
2095ClearConsoleBuffer(WORD wAttribute)
2096{
2097 CONSOLE_SCREEN_BUFFER_INFO csbi;
2098 COORD coord;
2099 DWORD NumCells, dummy;
2100
2101 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2102 return FALSE;
2103
2104 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2105 coord.X = 0;
2106 coord.Y = 0;
2107 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2108 coord, &dummy))
2109 {
2110 return FALSE;
2111 }
2112 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2113 coord, &dummy))
2114 {
2115 return FALSE;
2116 }
2117
2118 return TRUE;
2119}
2120
2121/*
2122 * FitConsoleWindow()
2123 * Description:
2124 * Checks if the console window will fit within given buffer dimensions.
2125 * Also, if requested, will shrink the window to fit.
2126 * Returns:
2127 * TRUE on success
2128 */
2129 static BOOL
2130FitConsoleWindow(
2131 COORD dwBufferSize,
2132 BOOL WantAdjust)
2133{
2134 CONSOLE_SCREEN_BUFFER_INFO csbi;
2135 COORD dwWindowSize;
2136 BOOL NeedAdjust = FALSE;
2137
2138 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2139 {
2140 /*
2141 * A buffer resize will fail if the current console window does
2142 * not lie completely within that buffer. To avoid this, we might
2143 * have to move and possibly shrink the window.
2144 */
2145 if (csbi.srWindow.Right >= dwBufferSize.X)
2146 {
2147 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2148 if (dwWindowSize.X > dwBufferSize.X)
2149 dwWindowSize.X = dwBufferSize.X;
2150 csbi.srWindow.Right = dwBufferSize.X - 1;
2151 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2152 NeedAdjust = TRUE;
2153 }
2154 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2155 {
2156 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2157 if (dwWindowSize.Y > dwBufferSize.Y)
2158 dwWindowSize.Y = dwBufferSize.Y;
2159 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2160 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2161 NeedAdjust = TRUE;
2162 }
2163 if (NeedAdjust && WantAdjust)
2164 {
2165 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2166 return FALSE;
2167 }
2168 return TRUE;
2169 }
2170
2171 return FALSE;
2172}
2173
2174typedef struct ConsoleBufferStruct
2175{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002176 BOOL IsValid;
2177 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002178 PCHAR_INFO Buffer;
2179 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002180} ConsoleBuffer;
2181
2182/*
2183 * SaveConsoleBuffer()
2184 * Description:
2185 * Saves important information about the console buffer, including the
2186 * actual buffer contents. The saved information is suitable for later
2187 * restoration by RestoreConsoleBuffer().
2188 * Returns:
2189 * TRUE if all information was saved; FALSE otherwise
2190 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2191 */
2192 static BOOL
2193SaveConsoleBuffer(
2194 ConsoleBuffer *cb)
2195{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002196 DWORD NumCells;
2197 COORD BufferCoord;
2198 SMALL_RECT ReadRegion;
2199 WORD Y, Y_incr;
2200
Bram Moolenaar071d4272004-06-13 20:20:40 +00002201 if (cb == NULL)
2202 return FALSE;
2203
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002204 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205 {
2206 cb->IsValid = FALSE;
2207 return FALSE;
2208 }
2209 cb->IsValid = TRUE;
2210
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002211 /*
2212 * Allocate a buffer large enough to hold the entire console screen
2213 * buffer. If this ConsoleBuffer structure has already been initialized
2214 * with a buffer of the correct size, then just use that one.
2215 */
2216 if (!cb->IsValid || cb->Buffer == NULL ||
2217 cb->BufferSize.X != cb->Info.dwSize.X ||
2218 cb->BufferSize.Y != cb->Info.dwSize.Y)
2219 {
2220 cb->BufferSize.X = cb->Info.dwSize.X;
2221 cb->BufferSize.Y = cb->Info.dwSize.Y;
2222 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2223 vim_free(cb->Buffer);
2224 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2225 if (cb->Buffer == NULL)
2226 return FALSE;
2227 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228
2229 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002230 * We will now copy the console screen buffer into our buffer.
2231 * ReadConsoleOutput() seems to be limited as far as how much you
2232 * can read at a time. Empirically, this number seems to be about
2233 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2234 * in chunks until it is all copied. The chunks will all have the
2235 * same horizontal characteristics, so initialize them now. The
2236 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002238 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002239 ReadRegion.Left = 0;
2240 ReadRegion.Right = cb->Info.dwSize.X - 1;
2241 Y_incr = 12000 / cb->Info.dwSize.X;
2242 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002244 /*
2245 * Read into position (0, Y) in our buffer.
2246 */
2247 BufferCoord.Y = Y;
2248 /*
2249 * Read the region whose top left corner is (0, Y) and whose bottom
2250 * right corner is (width - 1, Y + Y_incr - 1). This should define
2251 * a region of size width by Y_incr. Don't worry if this region is
2252 * too large for the remaining buffer; it will be cropped.
2253 */
2254 ReadRegion.Top = Y;
2255 ReadRegion.Bottom = Y + Y_incr - 1;
2256 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2257 cb->Buffer, /* our buffer */
2258 cb->BufferSize, /* dimensions of our buffer */
2259 BufferCoord, /* offset in our buffer */
2260 &ReadRegion)) /* region to save */
2261 {
2262 vim_free(cb->Buffer);
2263 cb->Buffer = NULL;
2264 return FALSE;
2265 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 }
2267
2268 return TRUE;
2269}
2270
2271/*
2272 * RestoreConsoleBuffer()
2273 * Description:
2274 * Restores important information about the console buffer, including the
2275 * actual buffer contents, if desired. The information to restore is in
2276 * the same format used by SaveConsoleBuffer().
2277 * Returns:
2278 * TRUE on success
2279 */
2280 static BOOL
2281RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002282 ConsoleBuffer *cb,
2283 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002285 COORD BufferCoord;
2286 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287
2288 if (cb == NULL || !cb->IsValid)
2289 return FALSE;
2290
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002291 /*
2292 * Before restoring the buffer contents, clear the current buffer, and
2293 * restore the cursor position and window information. Doing this now
2294 * prevents old buffer contents from "flashing" onto the screen.
2295 */
2296 if (RestoreScreen)
2297 ClearConsoleBuffer(cb->Info.wAttributes);
2298
2299 FitConsoleWindow(cb->Info.dwSize, TRUE);
2300 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2301 return FALSE;
2302 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2303 return FALSE;
2304
2305 if (!RestoreScreen)
2306 {
2307 /*
2308 * No need to restore the screen buffer contents, so we're done.
2309 */
2310 return TRUE;
2311 }
2312
2313 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2314 return FALSE;
2315 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2316 return FALSE;
2317
2318 /*
2319 * Restore the screen buffer contents.
2320 */
2321 if (cb->Buffer != NULL)
2322 {
2323 BufferCoord.X = 0;
2324 BufferCoord.Y = 0;
2325 WriteRegion.Left = 0;
2326 WriteRegion.Top = 0;
2327 WriteRegion.Right = cb->Info.dwSize.X - 1;
2328 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2329 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2330 cb->Buffer, /* our buffer */
2331 cb->BufferSize, /* dimensions of our buffer */
2332 BufferCoord, /* offset in our buffer */
2333 &WriteRegion)) /* region to restore */
2334 {
2335 return FALSE;
2336 }
2337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338
2339 return TRUE;
2340}
2341
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002342#define FEAT_RESTORE_ORIG_SCREEN
2343#ifdef FEAT_RESTORE_ORIG_SCREEN
2344static ConsoleBuffer g_cbOrig = { 0 };
2345#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346static ConsoleBuffer g_cbNonTermcap = { 0 };
2347static ConsoleBuffer g_cbTermcap = { 0 };
2348
2349#ifdef FEAT_TITLE
2350#ifdef __BORLANDC__
2351typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2352#else
2353typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2354#endif
2355char g_szOrigTitle[256] = { 0 };
2356HWND g_hWnd = NULL; /* also used in os_mswin.c */
2357static HICON g_hOrigIconSmall = NULL;
2358static HICON g_hOrigIcon = NULL;
2359static HICON g_hVimIcon = NULL;
2360static BOOL g_fCanChangeIcon = FALSE;
2361
2362/* ICON* are not defined in VC++ 4.0 */
2363#ifndef ICON_SMALL
2364#define ICON_SMALL 0
2365#endif
2366#ifndef ICON_BIG
2367#define ICON_BIG 1
2368#endif
2369/*
2370 * GetConsoleIcon()
2371 * Description:
2372 * Attempts to retrieve the small icon and/or the big icon currently in
2373 * use by a given window.
2374 * Returns:
2375 * TRUE on success
2376 */
2377 static BOOL
2378GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002379 HWND hWnd,
2380 HICON *phIconSmall,
2381 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382{
2383 if (hWnd == NULL)
2384 return FALSE;
2385
2386 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002387 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2388 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002390 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2391 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392 return TRUE;
2393}
2394
2395/*
2396 * SetConsoleIcon()
2397 * Description:
2398 * Attempts to change the small icon and/or the big icon currently in
2399 * use by a given window.
2400 * Returns:
2401 * TRUE on success
2402 */
2403 static BOOL
2404SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002405 HWND hWnd,
2406 HICON hIconSmall,
2407 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002409 HICON hPrevIconSmall;
2410 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411
2412 if (hWnd == NULL)
2413 return FALSE;
2414
2415 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002416 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2417 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002419 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2420 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421 return TRUE;
2422}
2423
2424/*
2425 * SaveConsoleTitleAndIcon()
2426 * Description:
2427 * Saves the current console window title in g_szOrigTitle, for later
2428 * restoration. Also, attempts to obtain a handle to the console window,
2429 * and use it to save the small and big icons currently in use by the
2430 * console window. This is not always possible on some versions of Windows;
2431 * nor is it possible when running Vim remotely using Telnet (since the
2432 * console window the user sees is owned by a remote process).
2433 */
2434 static void
2435SaveConsoleTitleAndIcon(void)
2436{
2437 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2438
2439 /* Save the original title. */
2440 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2441 return;
2442
2443 /*
2444 * Obtain a handle to the console window using GetConsoleWindow() from
2445 * KERNEL32.DLL; we need to handle in order to change the window icon.
2446 * This function only exists on NT-based Windows, starting with Windows
2447 * 2000. On older operating systems, we can't change the window icon
2448 * anyway.
2449 */
2450 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2451 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2452 "GetConsoleWindow")) != NULL)
2453 {
2454 g_hWnd = (*GetConsoleWindowProc)();
2455 }
2456 if (g_hWnd == NULL)
2457 return;
2458
2459 /* Save the original console window icon. */
2460 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2461 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2462 return;
2463
2464 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002465 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2466 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 if (g_hVimIcon != NULL)
2468 g_fCanChangeIcon = TRUE;
2469}
2470#endif
2471
2472static int g_fWindInitCalled = FALSE;
2473static int g_fTermcapMode = FALSE;
2474static CONSOLE_CURSOR_INFO g_cci;
2475static DWORD g_cmodein = 0;
2476static DWORD g_cmodeout = 0;
2477
2478/*
2479 * non-GUI version of mch_init().
2480 */
2481 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002482mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002483{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002484#ifndef FEAT_RESTORE_ORIG_SCREEN
2485 CONSOLE_SCREEN_BUFFER_INFO csbi;
2486#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487#ifndef __MINGW32__
2488 extern int _fmode;
2489#endif
2490
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002491 /* Silently handle invalid parameters to CRT functions */
2492 SET_INVALID_PARAM_HANDLER;
2493
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 /* Let critical errors result in a failure, not in a dialog box. Required
2495 * for the timestamp test to work on removed floppies. */
2496 SetErrorMode(SEM_FAILCRITICALERRORS);
2497
2498 _fmode = O_BINARY; /* we do our own CR-LF translation */
2499 out_flush();
2500
2501 /* Obtain handles for the standard Console I/O devices */
2502 if (read_cmd_fd == 0)
2503 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2504 else
2505 create_conin();
2506 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2507
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002508#ifdef FEAT_RESTORE_ORIG_SCREEN
2509 /* Save the initial console buffer for later restoration */
2510 SaveConsoleBuffer(&g_cbOrig);
2511 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2512#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002514 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2515 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2516#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 if (cterm_normal_fg_color == 0)
2518 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2519 if (cterm_normal_bg_color == 0)
2520 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2521
2522 /* set termcap codes to current text attributes */
2523 update_tcap(g_attrCurrent);
2524
2525 GetConsoleCursorInfo(g_hConOut, &g_cci);
2526 GetConsoleMode(g_hConIn, &g_cmodein);
2527 GetConsoleMode(g_hConOut, &g_cmodeout);
2528
2529#ifdef FEAT_TITLE
2530 SaveConsoleTitleAndIcon();
2531 /*
2532 * Set both the small and big icons of the console window to Vim's icon.
2533 * Note that Vim presently only has one size of icon (32x32), but it
2534 * automatically gets scaled down to 16x16 when setting the small icon.
2535 */
2536 if (g_fCanChangeIcon)
2537 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2538#endif
2539
2540 ui_get_shellsize();
2541
2542#ifdef MCH_WRITE_DUMP
2543 fdDump = fopen("dump", "wt");
2544
2545 if (fdDump)
2546 {
2547 time_t t;
2548
2549 time(&t);
2550 fputs(ctime(&t), fdDump);
2551 fflush(fdDump);
2552 }
2553#endif
2554
2555 g_fWindInitCalled = TRUE;
2556
2557#ifdef FEAT_MOUSE
2558 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2559#endif
2560
2561#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002562 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563#endif
2564
2565 /* This will be NULL on anything but NT 4.0 */
2566 s_pfnGetConsoleKeyboardLayoutName =
2567 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2568 "GetConsoleKeyboardLayoutNameA");
2569}
2570
2571/*
2572 * non-GUI version of mch_exit().
2573 * Shut down and exit with status `r'
2574 * Careful: mch_exit() may be called before mch_init()!
2575 */
2576 void
2577mch_exit(int r)
2578{
2579 stoptermcap();
2580
2581 if (g_fWindInitCalled)
2582 settmode(TMODE_COOK);
2583
2584 ml_close_all(TRUE); /* remove all memfiles */
2585
2586 if (g_fWindInitCalled)
2587 {
2588#ifdef FEAT_TITLE
2589 mch_restore_title(3);
2590 /*
2591 * Restore both the small and big icons of the console window to
2592 * what they were at startup. Don't do this when the window is
2593 * closed, Vim would hang here.
2594 */
2595 if (g_fCanChangeIcon && !g_fForceExit)
2596 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2597#endif
2598
2599#ifdef MCH_WRITE_DUMP
2600 if (fdDump)
2601 {
2602 time_t t;
2603
2604 time(&t);
2605 fputs(ctime(&t), fdDump);
2606 fclose(fdDump);
2607 }
2608 fdDump = NULL;
2609#endif
2610 }
2611
2612 SetConsoleCursorInfo(g_hConOut, &g_cci);
2613 SetConsoleMode(g_hConIn, g_cmodein);
2614 SetConsoleMode(g_hConOut, g_cmodeout);
2615
2616#ifdef DYNAMIC_GETTEXT
2617 dyn_libintl_end();
2618#endif
2619
2620 exit(r);
2621}
2622#endif /* !FEAT_GUI_W32 */
2623
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624/*
2625 * Do we have an interactive window?
2626 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002627/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002628 int
2629mch_check_win(
2630 int argc,
2631 char **argv)
2632{
2633 get_exe_name();
2634
2635#ifdef FEAT_GUI_W32
2636 return OK; /* GUI always has a tty */
2637#else
2638 if (isatty(1))
2639 return OK;
2640 return FAIL;
2641#endif
2642}
2643
2644
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002645#ifdef FEAT_MBYTE
2646/*
2647 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2648 * if it already exists. When "len" is > 0, also expand short to long
2649 * filenames.
2650 * Return FAIL if wide functions are not available, OK otherwise.
2651 * NOTE: much of this is identical to fname_case(), keep in sync!
2652 */
2653 static int
2654fname_casew(
2655 WCHAR *name,
2656 int len)
2657{
2658 WCHAR szTrueName[_MAX_PATH + 2];
2659 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2660 WCHAR *ptrue, *ptruePrev;
2661 WCHAR *porig, *porigPrev;
2662 int flen;
2663 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002664 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002665 int c;
2666 int slen;
2667
2668 flen = (int)wcslen(name);
2669 if (flen > _MAX_PATH)
2670 return OK;
2671
2672 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2673
2674 /* Build the new name in szTrueName[] one component at a time. */
2675 porig = name;
2676 ptrue = szTrueName;
2677
2678 if (iswalpha(porig[0]) && porig[1] == L':')
2679 {
2680 /* copy leading drive letter */
2681 *ptrue++ = *porig++;
2682 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002683 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002684 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002685
2686 while (*porig != NUL)
2687 {
2688 /* copy \ characters */
2689 while (*porig == psepc)
2690 *ptrue++ = *porig++;
2691
2692 ptruePrev = ptrue;
2693 porigPrev = porig;
2694 while (*porig != NUL && *porig != psepc)
2695 {
2696 *ptrue++ = *porig++;
2697 }
2698 *ptrue = NUL;
2699
2700 /* To avoid a slow failure append "\*" when searching a directory,
2701 * server or network share. */
2702 wcscpy(szTrueNameTemp, szTrueName);
2703 slen = (int)wcslen(szTrueNameTemp);
2704 if (*porig == psepc && slen + 2 < _MAX_PATH)
2705 wcscpy(szTrueNameTemp + slen, L"\\*");
2706
2707 /* Skip "", "." and "..". */
2708 if (ptrue > ptruePrev
2709 && (ptruePrev[0] != L'.'
2710 || (ptruePrev[1] != NUL
2711 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2712 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2713 != INVALID_HANDLE_VALUE)
2714 {
2715 c = *porig;
2716 *porig = NUL;
2717
2718 /* Only use the match when it's the same name (ignoring case) or
2719 * expansion is allowed and there is a match with the short name
2720 * and there is enough room. */
2721 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2722 || (len > 0
2723 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2724 && (int)(ptruePrev - szTrueName)
2725 + (int)wcslen(fb.cFileName) < len)))
2726 {
2727 wcscpy(ptruePrev, fb.cFileName);
2728
2729 /* Look for exact match and prefer it if found. Must be a
2730 * long name, otherwise there would be only one match. */
2731 while (FindNextFileW(hFind, &fb))
2732 {
2733 if (*fb.cAlternateFileName != NUL
2734 && (wcscoll(porigPrev, fb.cFileName) == 0
2735 || (len > 0
2736 && (_wcsicoll(porigPrev,
2737 fb.cAlternateFileName) == 0
2738 && (int)(ptruePrev - szTrueName)
2739 + (int)wcslen(fb.cFileName) < len))))
2740 {
2741 wcscpy(ptruePrev, fb.cFileName);
2742 break;
2743 }
2744 }
2745 }
2746 FindClose(hFind);
2747 *porig = c;
2748 ptrue = ptruePrev + wcslen(ptruePrev);
2749 }
2750 else if (hFind == INVALID_HANDLE_VALUE
2751 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2752 return FAIL;
2753 }
2754
2755 wcscpy(name, szTrueName);
2756 return OK;
2757}
2758#endif
2759
Bram Moolenaar071d4272004-06-13 20:20:40 +00002760/*
2761 * fname_case(): Set the case of the file name, if it already exists.
2762 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002763 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764 */
2765 void
2766fname_case(
2767 char_u *name,
2768 int len)
2769{
2770 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002771 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772 char *ptrue, *ptruePrev;
2773 char *porig, *porigPrev;
2774 int flen;
2775 WIN32_FIND_DATA fb;
2776 HANDLE hFind;
2777 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002778 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002780 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002781 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782 return;
2783
2784 slash_adjust(name);
2785
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002786#ifdef FEAT_MBYTE
2787 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2788 {
2789 WCHAR *p = enc_to_utf16(name, NULL);
2790
2791 if (p != NULL)
2792 {
2793 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002794 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002795
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002796 wcsncpy(buf, p, _MAX_PATH);
2797 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002798 vim_free(p);
2799
2800 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2801 {
2802 q = utf16_to_enc(buf, NULL);
2803 if (q != NULL)
2804 {
2805 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2806 vim_free(q);
2807 return;
2808 }
2809 }
2810 }
2811 /* Retry with non-wide function (for Windows 98). */
2812 }
2813#endif
2814
2815 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2816 * So we should check this after calling wide function. */
2817 if (flen > _MAX_PATH)
2818 return;
2819
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820 /* Build the new name in szTrueName[] one component at a time. */
2821 porig = name;
2822 ptrue = szTrueName;
2823
2824 if (isalpha(porig[0]) && porig[1] == ':')
2825 {
2826 /* copy leading drive letter */
2827 *ptrue++ = *porig++;
2828 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002830 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831
2832 while (*porig != NUL)
2833 {
2834 /* copy \ characters */
2835 while (*porig == psepc)
2836 *ptrue++ = *porig++;
2837
2838 ptruePrev = ptrue;
2839 porigPrev = porig;
2840 while (*porig != NUL && *porig != psepc)
2841 {
2842#ifdef FEAT_MBYTE
2843 int l;
2844
2845 if (enc_dbcs)
2846 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002847 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848 while (--l >= 0)
2849 *ptrue++ = *porig++;
2850 }
2851 else
2852#endif
2853 *ptrue++ = *porig++;
2854 }
2855 *ptrue = NUL;
2856
Bram Moolenaar464c9252010-10-13 20:37:41 +02002857 /* To avoid a slow failure append "\*" when searching a directory,
2858 * server or network share. */
2859 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002860 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002861 if (*porig == psepc && slen + 2 < _MAX_PATH)
2862 STRCPY(szTrueNameTemp + slen, "\\*");
2863
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864 /* Skip "", "." and "..". */
2865 if (ptrue > ptruePrev
2866 && (ptruePrev[0] != '.'
2867 || (ptruePrev[1] != NUL
2868 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002869 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870 != INVALID_HANDLE_VALUE)
2871 {
2872 c = *porig;
2873 *porig = NUL;
2874
2875 /* Only use the match when it's the same name (ignoring case) or
2876 * expansion is allowed and there is a match with the short name
2877 * and there is enough room. */
2878 if (_stricoll(porigPrev, fb.cFileName) == 0
2879 || (len > 0
2880 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2881 && (int)(ptruePrev - szTrueName)
2882 + (int)strlen(fb.cFileName) < len)))
2883 {
2884 STRCPY(ptruePrev, fb.cFileName);
2885
2886 /* Look for exact match and prefer it if found. Must be a
2887 * long name, otherwise there would be only one match. */
2888 while (FindNextFile(hFind, &fb))
2889 {
2890 if (*fb.cAlternateFileName != NUL
2891 && (strcoll(porigPrev, fb.cFileName) == 0
2892 || (len > 0
2893 && (_stricoll(porigPrev,
2894 fb.cAlternateFileName) == 0
2895 && (int)(ptruePrev - szTrueName)
2896 + (int)strlen(fb.cFileName) < len))))
2897 {
2898 STRCPY(ptruePrev, fb.cFileName);
2899 break;
2900 }
2901 }
2902 }
2903 FindClose(hFind);
2904 *porig = c;
2905 ptrue = ptruePrev + strlen(ptruePrev);
2906 }
2907 }
2908
2909 STRCPY(name, szTrueName);
2910}
2911
2912
2913/*
2914 * Insert user name in s[len].
2915 */
2916 int
2917mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002918 char_u *s,
2919 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002921 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922 DWORD cch = sizeof szUserName;
2923
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002924#ifdef FEAT_MBYTE
2925 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2926 {
2927 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2928 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2929
2930 if (GetUserNameW(wszUserName, &wcch))
2931 {
2932 char_u *p = utf16_to_enc(wszUserName, NULL);
2933
2934 if (p != NULL)
2935 {
2936 vim_strncpy(s, p, len - 1);
2937 vim_free(p);
2938 return OK;
2939 }
2940 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002941 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2942 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002943 /* Retry with non-wide function (for Windows 98). */
2944 }
2945#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 if (GetUserName(szUserName, &cch))
2947 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002948 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949 return OK;
2950 }
2951 s[0] = NUL;
2952 return FAIL;
2953}
2954
2955
2956/*
2957 * Insert host name in s[len].
2958 */
2959 void
2960mch_get_host_name(
2961 char_u *s,
2962 int len)
2963{
2964 DWORD cch = len;
2965
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002966#ifdef FEAT_MBYTE
2967 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2968 {
2969 WCHAR wszHostName[256 + 1];
2970 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2971
2972 if (GetComputerNameW(wszHostName, &wcch))
2973 {
2974 char_u *p = utf16_to_enc(wszHostName, NULL);
2975
2976 if (p != NULL)
2977 {
2978 vim_strncpy(s, p, len - 1);
2979 vim_free(p);
2980 return;
2981 }
2982 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002983 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2984 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002985 /* Retry with non-wide function (for Windows 98). */
2986 }
2987#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002989 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990}
2991
2992
2993/*
2994 * return process ID
2995 */
2996 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002997mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998{
2999 return (long)GetCurrentProcessId();
3000}
3001
3002
3003/*
3004 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3005 * Return OK for success, FAIL for failure.
3006 */
3007 int
3008mch_dirname(
3009 char_u *buf,
3010 int len)
3011{
3012 /*
3013 * Originally this was:
3014 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3015 * But the Win32s known bug list says that getcwd() doesn't work
3016 * so use the Win32 system call instead. <Negri>
3017 */
3018#ifdef FEAT_MBYTE
3019 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3020 {
3021 WCHAR wbuf[_MAX_PATH + 1];
3022
3023 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3024 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003025 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026
3027 if (p != NULL)
3028 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003029 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 vim_free(p);
3031 return OK;
3032 }
3033 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003034 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3035 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036 /* Retry with non-wide function (for Windows 98). */
3037 }
3038#endif
3039 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3040}
3041
3042/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003043 * Get file permissions for "name".
3044 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045 */
3046 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003047mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003049 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003050 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003052 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003053 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054}
3055
3056
3057/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003058 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003059 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003060 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061 */
3062 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003063mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003065 long n = -1;
3066
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067#ifdef FEAT_MBYTE
3068 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3069 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003070 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071
3072 if (p != NULL)
3073 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003074 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003076 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003077 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078 /* Retry with non-wide function (for Windows 98). */
3079 }
3080 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003081 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003083 n = _chmod(name, perm);
3084 if (n == -1)
3085 return FAIL;
3086
3087 win32_set_archive(name);
3088
3089 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090}
3091
3092/*
3093 * Set hidden flag for "name".
3094 */
3095 void
3096mch_hide(char_u *name)
3097{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003098 int attrs = win32_getattrs(name);
3099 if (attrs == -1)
3100 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003102 attrs |= FILE_ATTRIBUTE_HIDDEN;
3103 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104}
3105
3106/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003107 * Return TRUE if file "name" exists and is hidden.
3108 */
3109 int
3110mch_ishidden(char_u *name)
3111{
3112 int f = win32_getattrs(name);
3113
3114 if (f == -1)
3115 return FALSE; /* file does not exist at all */
3116
3117 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3118}
3119
3120/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003121 * return TRUE if "name" is a directory
3122 * return FALSE if "name" is not a directory or upon error
3123 */
3124 int
3125mch_isdir(char_u *name)
3126{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003127 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128
3129 if (f == -1)
3130 return FALSE; /* file does not exist at all */
3131
3132 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3133}
3134
3135/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003136 * return TRUE if "name" is a directory, NOT a symlink to a directory
3137 * return FALSE if "name" is not a directory
3138 * return FALSE for error
3139 */
3140 int
3141mch_isrealdir(char_u *name)
3142{
3143 return mch_isdir(name) && !mch_is_symbolic_link(name);
3144}
3145
3146/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003147 * Create directory "name".
3148 * Return 0 on success, -1 on error.
3149 */
3150 int
3151mch_mkdir(char_u *name)
3152{
3153#ifdef FEAT_MBYTE
3154 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3155 {
3156 WCHAR *p;
3157 int retval;
3158
3159 p = enc_to_utf16(name, NULL);
3160 if (p == NULL)
3161 return -1;
3162 retval = _wmkdir(p);
3163 vim_free(p);
3164 return retval;
3165 }
3166#endif
3167 return _mkdir(name);
3168}
3169
3170/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003171 * Delete directory "name".
3172 * Return 0 on success, -1 on error.
3173 */
3174 int
3175mch_rmdir(char_u *name)
3176{
3177#ifdef FEAT_MBYTE
3178 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3179 {
3180 WCHAR *p;
3181 int retval;
3182
3183 p = enc_to_utf16(name, NULL);
3184 if (p == NULL)
3185 return -1;
3186 retval = _wrmdir(p);
3187 vim_free(p);
3188 return retval;
3189 }
3190#endif
3191 return _rmdir(name);
3192}
3193
3194/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003195 * Return TRUE if file "fname" has more than one link.
3196 */
3197 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003198mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003199{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003200 BY_HANDLE_FILE_INFORMATION info;
3201
3202 return win32_fileinfo(fname, &info) == FILEINFO_OK
3203 && info.nNumberOfLinks > 1;
3204}
3205
3206/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003207 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003208 */
3209 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003210mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003211{
3212 HANDLE hFind;
3213 int res = FALSE;
3214 WIN32_FIND_DATAA findDataA;
3215 DWORD fileFlags = 0, reparseTag = 0;
3216#ifdef FEAT_MBYTE
3217 WCHAR *wn = NULL;
3218 WIN32_FIND_DATAW findDataW;
3219
3220 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003221 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003222 if (wn != NULL)
3223 {
3224 hFind = FindFirstFileW(wn, &findDataW);
3225 vim_free(wn);
3226 if (hFind == INVALID_HANDLE_VALUE
3227 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3228 {
3229 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar203258c2016-01-17 22:15:16 +01003230 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003231 if (hFind != INVALID_HANDLE_VALUE)
3232 {
3233 fileFlags = findDataA.dwFileAttributes;
3234 reparseTag = findDataA.dwReserved0;
3235 }
3236 }
3237 else
3238 {
3239 fileFlags = findDataW.dwFileAttributes;
3240 reparseTag = findDataW.dwReserved0;
3241 }
3242 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003243 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003244#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003245 {
Bram Moolenaar203258c2016-01-17 22:15:16 +01003246 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003247 if (hFind != INVALID_HANDLE_VALUE)
3248 {
3249 fileFlags = findDataA.dwFileAttributes;
3250 reparseTag = findDataA.dwReserved0;
3251 }
3252 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003253
3254 if (hFind != INVALID_HANDLE_VALUE)
3255 FindClose(hFind);
3256
3257 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003258 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3259 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003260 res = TRUE;
3261
3262 return res;
3263}
3264
3265/*
3266 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3267 * link.
3268 */
3269 int
3270mch_is_linked(char_u *fname)
3271{
3272 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3273 return TRUE;
3274 return FALSE;
3275}
3276
3277/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003278 * Get the by-handle-file-information for "fname".
3279 * Returns FILEINFO_OK when OK.
3280 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3281 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3282 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3283 */
3284 int
3285win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3286{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003287 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003288 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003289#ifdef FEAT_MBYTE
3290 WCHAR *wn = NULL;
3291
3292 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003293 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003294 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003295 if (wn == NULL)
3296 res = FILEINFO_ENC_FAIL;
3297 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003298 if (wn != NULL)
3299 {
3300 hFile = CreateFileW(wn, /* file name */
3301 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003302 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003303 NULL, /* security descriptor */
3304 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003305 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003306 NULL); /* handle to template file */
3307 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003308 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003309 {
3310 /* Retry with non-wide function (for Windows 98). */
3311 vim_free(wn);
3312 wn = NULL;
3313 }
3314 }
3315 if (wn == NULL)
3316#endif
3317 hFile = CreateFile(fname, /* file name */
3318 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003319 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003320 NULL, /* security descriptor */
3321 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003322 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003323 NULL); /* handle to template file */
3324
3325 if (hFile != INVALID_HANDLE_VALUE)
3326 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003327 if (GetFileInformationByHandle(hFile, info) != 0)
3328 res = FILEINFO_OK;
3329 else
3330 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003331 CloseHandle(hFile);
3332 }
3333
3334#ifdef FEAT_MBYTE
3335 vim_free(wn);
3336#endif
3337 return res;
3338}
3339
3340/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003341 * get file attributes for `name'
3342 * -1 : error
3343 * else FILE_ATTRIBUTE_* defined in winnt.h
3344 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003345 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003346win32_getattrs(char_u *name)
3347{
3348 int attr;
3349#ifdef FEAT_MBYTE
3350 WCHAR *p = NULL;
3351
3352 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3353 p = enc_to_utf16(name, NULL);
3354
3355 if (p != NULL)
3356 {
3357 attr = GetFileAttributesW(p);
3358 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3359 {
3360 /* Retry with non-wide function (for Windows 98). */
3361 vim_free(p);
3362 p = NULL;
3363 }
3364 }
3365 if (p == NULL)
3366#endif
3367 attr = GetFileAttributes((char *)name);
3368#ifdef FEAT_MBYTE
3369 vim_free(p);
3370#endif
3371 return attr;
3372}
3373
3374/*
3375 * set file attributes for `name' to `attrs'
3376 *
3377 * return -1 for failure, 0 otherwise
3378 */
3379 static
3380 int
3381win32_setattrs(char_u *name, int attrs)
3382{
3383 int res;
3384#ifdef FEAT_MBYTE
3385 WCHAR *p = NULL;
3386
3387 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3388 p = enc_to_utf16(name, NULL);
3389
3390 if (p != NULL)
3391 {
3392 res = SetFileAttributesW(p, attrs);
3393 if (res == FALSE
3394 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3395 {
3396 /* Retry with non-wide function (for Windows 98). */
3397 vim_free(p);
3398 p = NULL;
3399 }
3400 }
3401 if (p == NULL)
3402#endif
3403 res = SetFileAttributes((char *)name, attrs);
3404#ifdef FEAT_MBYTE
3405 vim_free(p);
3406#endif
3407 return res ? 0 : -1;
3408}
3409
3410/*
3411 * Set archive flag for "name".
3412 */
3413 static
3414 int
3415win32_set_archive(char_u *name)
3416{
3417 int attrs = win32_getattrs(name);
3418 if (attrs == -1)
3419 return -1;
3420
3421 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3422 return win32_setattrs(name, attrs);
3423}
3424
3425/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003426 * Return TRUE if file or directory "name" is writable (not readonly).
3427 * Strange semantics of Win32: a readonly directory is writable, but you can't
3428 * delete a file. Let's say this means it is writable.
3429 */
3430 int
3431mch_writable(char_u *name)
3432{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003433 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003435 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3436 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437}
3438
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439/*
3440 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003441 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442 * Return -1 if unknown.
3443 */
3444 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003445mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003446{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003447 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003448 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003449 char_u *p;
3450
3451 if (len >= _MAX_PATH) /* safety check */
3452 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003453 if (!use_path)
3454 {
3455 /* TODO: check if file is really executable. */
3456 return mch_getperm(name) != -1 && !mch_isdir(name);
3457 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003458
3459 /* If there already is an extension try using the name directly. Also do
3460 * this with a Unix-shell like 'shell'. */
3461 if (vim_strchr(gettail(name), '.') != NULL
3462 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003463 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003464 return TRUE;
3465
3466 /*
3467 * Loop over all extensions in $PATHEXT.
3468 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003469 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003470 p = mch_getenv("PATHEXT");
3471 if (p == NULL)
3472 p = (char_u *)".com;.exe;.bat;.cmd";
3473 while (*p)
3474 {
3475 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3476 {
3477 /* A single "." means no extension is added. */
3478 buf[len] = NUL;
3479 ++p;
3480 if (*p)
3481 ++p;
3482 }
3483 else
3484 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003485 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003486 return TRUE;
3487 }
3488 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490
3491/*
3492 * Check what "name" is:
3493 * NODE_NORMAL: file or directory (or doesn't exist)
3494 * NODE_WRITABLE: writable device, socket, fifo, etc.
3495 * NODE_OTHER: non-writable things
3496 */
3497 int
3498mch_nodetype(char_u *name)
3499{
3500 HANDLE hFile;
3501 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003502#ifdef FEAT_MBYTE
3503 WCHAR *wn = NULL;
3504#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505
Bram Moolenaar043545e2006-10-10 16:44:07 +00003506 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3507 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3508 * here. */
3509 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3510 return NODE_WRITABLE;
3511
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003512#ifdef FEAT_MBYTE
3513 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3514 {
3515 wn = enc_to_utf16(name, NULL);
3516 if (wn != NULL)
3517 {
3518 hFile = CreateFileW(wn, /* file name */
3519 GENERIC_WRITE, /* access mode */
3520 0, /* share mode */
3521 NULL, /* security descriptor */
3522 OPEN_EXISTING, /* creation disposition */
3523 0, /* file attributes */
3524 NULL); /* handle to template file */
3525 if (hFile == INVALID_HANDLE_VALUE
3526 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3527 {
3528 /* Retry with non-wide function (for Windows 98). */
3529 vim_free(wn);
3530 wn = NULL;
3531 }
3532 }
3533 }
3534 if (wn == NULL)
3535#endif
3536 hFile = CreateFile(name, /* file name */
3537 GENERIC_WRITE, /* access mode */
3538 0, /* share mode */
3539 NULL, /* security descriptor */
3540 OPEN_EXISTING, /* creation disposition */
3541 0, /* file attributes */
3542 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003544#ifdef FEAT_MBYTE
3545 vim_free(wn);
3546#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 if (hFile == INVALID_HANDLE_VALUE)
3548 return NODE_NORMAL;
3549
3550 type = GetFileType(hFile);
3551 CloseHandle(hFile);
3552 if (type == FILE_TYPE_CHAR)
3553 return NODE_WRITABLE;
3554 if (type == FILE_TYPE_DISK)
3555 return NODE_NORMAL;
3556 return NODE_OTHER;
3557}
3558
3559#ifdef HAVE_ACL
3560struct my_acl
3561{
3562 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3563 PSID pSidOwner;
3564 PSID pSidGroup;
3565 PACL pDacl;
3566 PACL pSacl;
3567};
3568#endif
3569
3570/*
3571 * Return a pointer to the ACL of file "fname" in allocated memory.
3572 * Return NULL if the ACL is not available for whatever reason.
3573 */
3574 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003575mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003576{
3577#ifndef HAVE_ACL
3578 return (vim_acl_T)NULL;
3579#else
3580 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003581 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582
3583 /* This only works on Windows NT and 2000. */
3584 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3585 {
3586 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3587 if (p != NULL)
3588 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003589# ifdef FEAT_MBYTE
3590 WCHAR *wn = NULL;
3591
3592 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3593 wn = enc_to_utf16(fname, NULL);
3594 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003596 /* Try to retrieve the entire security descriptor. */
3597 err = pGetNamedSecurityInfoW(
3598 wn, // Abstract filename
3599 SE_FILE_OBJECT, // File Object
3600 OWNER_SECURITY_INFORMATION |
3601 GROUP_SECURITY_INFORMATION |
3602 DACL_SECURITY_INFORMATION |
3603 SACL_SECURITY_INFORMATION,
3604 &p->pSidOwner, // Ownership information.
3605 &p->pSidGroup, // Group membership.
3606 &p->pDacl, // Discretionary information.
3607 &p->pSacl, // For auditing purposes.
3608 &p->pSecurityDescriptor);
3609 if (err == ERROR_ACCESS_DENIED ||
3610 err == ERROR_PRIVILEGE_NOT_HELD)
3611 {
3612 /* Retrieve only DACL. */
3613 (void)pGetNamedSecurityInfoW(
3614 wn,
3615 SE_FILE_OBJECT,
3616 DACL_SECURITY_INFORMATION,
3617 NULL,
3618 NULL,
3619 &p->pDacl,
3620 NULL,
3621 &p->pSecurityDescriptor);
3622 }
3623 if (p->pSecurityDescriptor == NULL)
3624 {
3625 mch_free_acl((vim_acl_T)p);
3626 p = NULL;
3627 }
3628 vim_free(wn);
3629 }
3630 else
3631# endif
3632 {
3633 /* Try to retrieve the entire security descriptor. */
3634 err = pGetNamedSecurityInfo(
3635 (LPSTR)fname, // Abstract filename
3636 SE_FILE_OBJECT, // File Object
3637 OWNER_SECURITY_INFORMATION |
3638 GROUP_SECURITY_INFORMATION |
3639 DACL_SECURITY_INFORMATION |
3640 SACL_SECURITY_INFORMATION,
3641 &p->pSidOwner, // Ownership information.
3642 &p->pSidGroup, // Group membership.
3643 &p->pDacl, // Discretionary information.
3644 &p->pSacl, // For auditing purposes.
3645 &p->pSecurityDescriptor);
3646 if (err == ERROR_ACCESS_DENIED ||
3647 err == ERROR_PRIVILEGE_NOT_HELD)
3648 {
3649 /* Retrieve only DACL. */
3650 (void)pGetNamedSecurityInfo(
3651 (LPSTR)fname,
3652 SE_FILE_OBJECT,
3653 DACL_SECURITY_INFORMATION,
3654 NULL,
3655 NULL,
3656 &p->pDacl,
3657 NULL,
3658 &p->pSecurityDescriptor);
3659 }
3660 if (p->pSecurityDescriptor == NULL)
3661 {
3662 mch_free_acl((vim_acl_T)p);
3663 p = NULL;
3664 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003665 }
3666 }
3667 }
3668
3669 return (vim_acl_T)p;
3670#endif
3671}
3672
Bram Moolenaar27515922013-06-29 15:36:26 +02003673#ifdef HAVE_ACL
3674/*
3675 * Check if "acl" contains inherited ACE.
3676 */
3677 static BOOL
3678is_acl_inherited(PACL acl)
3679{
3680 DWORD i;
3681 ACL_SIZE_INFORMATION acl_info;
3682 PACCESS_ALLOWED_ACE ace;
3683
3684 acl_info.AceCount = 0;
3685 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3686 for (i = 0; i < acl_info.AceCount; i++)
3687 {
3688 GetAce(acl, i, (LPVOID *)&ace);
3689 if (ace->Header.AceFlags & INHERITED_ACE)
3690 return TRUE;
3691 }
3692 return FALSE;
3693}
3694#endif
3695
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696/*
3697 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3698 * Errors are ignored.
3699 * This must only be called with "acl" equal to what mch_get_acl() returned.
3700 */
3701 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003702mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703{
3704#ifdef HAVE_ACL
3705 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003706 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707
3708 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003709 {
3710# ifdef FEAT_MBYTE
3711 WCHAR *wn = NULL;
3712# endif
3713
3714 /* Set security flags */
3715 if (p->pSidOwner)
3716 sec_info |= OWNER_SECURITY_INFORMATION;
3717 if (p->pSidGroup)
3718 sec_info |= GROUP_SECURITY_INFORMATION;
3719 if (p->pDacl)
3720 {
3721 sec_info |= DACL_SECURITY_INFORMATION;
3722 /* Do not inherit its parent's DACL.
3723 * If the DACL is inherited, Cygwin permissions would be changed.
3724 */
3725 if (!is_acl_inherited(p->pDacl))
3726 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3727 }
3728 if (p->pSacl)
3729 sec_info |= SACL_SECURITY_INFORMATION;
3730
3731# ifdef FEAT_MBYTE
3732 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3733 wn = enc_to_utf16(fname, NULL);
3734 if (wn != NULL)
3735 {
3736 (void)pSetNamedSecurityInfoW(
3737 wn, // Abstract filename
3738 SE_FILE_OBJECT, // File Object
3739 sec_info,
3740 p->pSidOwner, // Ownership information.
3741 p->pSidGroup, // Group membership.
3742 p->pDacl, // Discretionary information.
3743 p->pSacl // For auditing purposes.
3744 );
3745 vim_free(wn);
3746 }
3747 else
3748# endif
3749 {
3750 (void)pSetNamedSecurityInfo(
3751 (LPSTR)fname, // Abstract filename
3752 SE_FILE_OBJECT, // File Object
3753 sec_info,
3754 p->pSidOwner, // Ownership information.
3755 p->pSidGroup, // Group membership.
3756 p->pDacl, // Discretionary information.
3757 p->pSacl // For auditing purposes.
3758 );
3759 }
3760 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761#endif
3762}
3763
3764 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003765mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766{
3767#ifdef HAVE_ACL
3768 struct my_acl *p = (struct my_acl *)acl;
3769
3770 if (p != NULL)
3771 {
3772 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3773 vim_free(p);
3774 }
3775#endif
3776}
3777
3778#ifndef FEAT_GUI_W32
3779
3780/*
3781 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3782 */
3783 static BOOL WINAPI
3784handler_routine(
3785 DWORD dwCtrlType)
3786{
3787 switch (dwCtrlType)
3788 {
3789 case CTRL_C_EVENT:
3790 if (ctrl_c_interrupts)
3791 g_fCtrlCPressed = TRUE;
3792 return TRUE;
3793
3794 case CTRL_BREAK_EVENT:
3795 g_fCBrkPressed = TRUE;
3796 return TRUE;
3797
3798 /* fatal events: shut down gracefully */
3799 case CTRL_CLOSE_EVENT:
3800 case CTRL_LOGOFF_EVENT:
3801 case CTRL_SHUTDOWN_EVENT:
3802 windgoto((int)Rows - 1, 0);
3803 g_fForceExit = TRUE;
3804
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003805 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806 (dwCtrlType == CTRL_CLOSE_EVENT
3807 ? _("close")
3808 : dwCtrlType == CTRL_LOGOFF_EVENT
3809 ? _("logoff")
3810 : _("shutdown")));
3811#ifdef DEBUG
3812 OutputDebugString(IObuff);
3813#endif
3814
3815 preserve_exit(); /* output IObuff, preserve files and exit */
3816
3817 return TRUE; /* not reached */
3818
3819 default:
3820 return FALSE;
3821 }
3822}
3823
3824
3825/*
3826 * set the tty in (raw) ? "raw" : "cooked" mode
3827 */
3828 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003829mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830{
3831 DWORD cmodein;
3832 DWORD cmodeout;
3833 BOOL bEnableHandler;
3834
3835 GetConsoleMode(g_hConIn, &cmodein);
3836 GetConsoleMode(g_hConOut, &cmodeout);
3837 if (tmode == TMODE_RAW)
3838 {
3839 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3840 ENABLE_ECHO_INPUT);
3841#ifdef FEAT_MOUSE
3842 if (g_fMouseActive)
3843 cmodein |= ENABLE_MOUSE_INPUT;
3844#endif
3845 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3846 bEnableHandler = TRUE;
3847 }
3848 else /* cooked */
3849 {
3850 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3851 ENABLE_ECHO_INPUT);
3852 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3853 bEnableHandler = FALSE;
3854 }
3855 SetConsoleMode(g_hConIn, cmodein);
3856 SetConsoleMode(g_hConOut, cmodeout);
3857 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3858
3859#ifdef MCH_WRITE_DUMP
3860 if (fdDump)
3861 {
3862 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3863 tmode == TMODE_RAW ? "raw" :
3864 tmode == TMODE_COOK ? "cooked" : "normal",
3865 cmodein, cmodeout);
3866 fflush(fdDump);
3867 }
3868#endif
3869}
3870
3871
3872/*
3873 * Get the size of the current window in `Rows' and `Columns'
3874 * Return OK when size could be determined, FAIL otherwise.
3875 */
3876 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003877mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878{
3879 CONSOLE_SCREEN_BUFFER_INFO csbi;
3880
3881 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3882 {
3883 /*
3884 * For some reason, we are trying to get the screen dimensions
3885 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3886 * variables are really intended to mean the size of Vim screen
3887 * while in termcap mode.
3888 */
3889 Rows = g_cbTermcap.Info.dwSize.Y;
3890 Columns = g_cbTermcap.Info.dwSize.X;
3891 }
3892 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3893 {
3894 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3895 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3896 }
3897 else
3898 {
3899 Rows = 25;
3900 Columns = 80;
3901 }
3902 return OK;
3903}
3904
3905/*
3906 * Set a console window to `xSize' * `ySize'
3907 */
3908 static void
3909ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003910 HANDLE hConsole,
3911 int xSize,
3912 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913{
3914 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3915 SMALL_RECT srWindowRect; /* hold the new console size */
3916 COORD coordScreen;
3917
3918#ifdef MCH_WRITE_DUMP
3919 if (fdDump)
3920 {
3921 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3922 fflush(fdDump);
3923 }
3924#endif
3925
3926 /* get the largest size we can size the console window to */
3927 coordScreen = GetLargestConsoleWindowSize(hConsole);
3928
3929 /* define the new console window size and scroll position */
3930 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3931 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3932 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3933
3934 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3935 {
3936 int sx, sy;
3937
3938 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3939 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3940 if (sy < ySize || sx < xSize)
3941 {
3942 /*
3943 * Increasing number of lines/columns, do buffer first.
3944 * Use the maximal size in x and y direction.
3945 */
3946 if (sy < ySize)
3947 coordScreen.Y = ySize;
3948 else
3949 coordScreen.Y = sy;
3950 if (sx < xSize)
3951 coordScreen.X = xSize;
3952 else
3953 coordScreen.X = sx;
3954 SetConsoleScreenBufferSize(hConsole, coordScreen);
3955 }
3956 }
3957
3958 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3959 {
3960#ifdef MCH_WRITE_DUMP
3961 if (fdDump)
3962 {
3963 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3964 GetLastError());
3965 fflush(fdDump);
3966 }
3967#endif
3968 }
3969
3970 /* define the new console buffer size */
3971 coordScreen.X = xSize;
3972 coordScreen.Y = ySize;
3973
3974 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3975 {
3976#ifdef MCH_WRITE_DUMP
3977 if (fdDump)
3978 {
3979 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3980 GetLastError());
3981 fflush(fdDump);
3982 }
3983#endif
3984 }
3985}
3986
3987
3988/*
3989 * Set the console window to `Rows' * `Columns'
3990 */
3991 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003992mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993{
3994 COORD coordScreen;
3995
3996 /* Don't change window size while still starting up */
3997 if (suppress_winsize != 0)
3998 {
3999 suppress_winsize = 2;
4000 return;
4001 }
4002
4003 if (term_console)
4004 {
4005 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4006
4007 /* Clamp Rows and Columns to reasonable values */
4008 if (Rows > coordScreen.Y)
4009 Rows = coordScreen.Y;
4010 if (Columns > coordScreen.X)
4011 Columns = coordScreen.X;
4012
4013 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4014 }
4015}
4016
4017/*
4018 * Rows and/or Columns has changed.
4019 */
4020 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004021mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004022{
4023 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4024}
4025
4026
4027/*
4028 * Called when started up, to set the winsize that was delayed.
4029 */
4030 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004031mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032{
4033 if (suppress_winsize == 2)
4034 {
4035 suppress_winsize = 0;
4036 mch_set_shellsize();
4037 shell_resized();
4038 }
4039 suppress_winsize = 0;
4040}
4041#endif /* FEAT_GUI_W32 */
4042
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004043 static BOOL
4044vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004045 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004046 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004047 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004048 STARTUPINFO *si,
4049 PROCESS_INFORMATION *pi)
4050{
4051# ifdef FEAT_MBYTE
4052 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4053 {
4054 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4055
4056 if (wcmd != NULL)
4057 {
4058 BOOL ret;
4059 ret = CreateProcessW(
4060 NULL, /* Executable name */
4061 wcmd, /* Command to execute */
4062 NULL, /* Process security attributes */
4063 NULL, /* Thread security attributes */
4064 inherit_handles, /* Inherit handles */
4065 flags, /* Creation flags */
4066 NULL, /* Environment */
4067 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004068 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004069 pi); /* Process information */
4070 vim_free(wcmd);
4071 return ret;
4072 }
4073 }
4074#endif
4075 return CreateProcess(
4076 NULL, /* Executable name */
4077 cmd, /* Command to execute */
4078 NULL, /* Process security attributes */
4079 NULL, /* Thread security attributes */
4080 inherit_handles, /* Inherit handles */
4081 flags, /* Creation flags */
4082 NULL, /* Environment */
4083 NULL, /* Current directory */
4084 si, /* Startup information */
4085 pi); /* Process information */
4086}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004087
4088
4089#if defined(FEAT_GUI_W32) || defined(PROTO)
4090
4091/*
4092 * Specialised version of system() for Win32 GUI mode.
4093 * This version proceeds as follows:
4094 * 1. Create a console window for use by the subprocess
4095 * 2. Run the subprocess (it gets the allocated console by default)
4096 * 3. Wait for the subprocess to terminate and get its exit code
4097 * 4. Prompt the user to press a key to close the console window
4098 */
4099 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004100mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101{
4102 STARTUPINFO si;
4103 PROCESS_INFORMATION pi;
4104 DWORD ret = 0;
4105 HWND hwnd = GetFocus();
4106
4107 si.cb = sizeof(si);
4108 si.lpReserved = NULL;
4109 si.lpDesktop = NULL;
4110 si.lpTitle = NULL;
4111 si.dwFlags = STARTF_USESHOWWINDOW;
4112 /*
4113 * It's nicer to run a filter command in a minimized window, but in
4114 * Windows 95 this makes the command MUCH slower. We can't do it under
4115 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004116 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117 */
4118 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004119 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 else
4121 si.wShowWindow = SW_SHOWNORMAL;
4122 si.cbReserved2 = 0;
4123 si.lpReserved2 = NULL;
4124
4125 /* There is a strange error on Windows 95 when using "c:\\command.com".
4126 * When the "c:\\" is left out it works OK...? */
4127 if (mch_windows95()
4128 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4129 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4130 cmd += 3;
4131
4132 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004133 vim_create_process(cmd, FALSE,
4134 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004135
4136 /* Wait for the command to terminate before continuing */
4137 if (g_PlatformId != VER_PLATFORM_WIN32s)
4138 {
4139#ifdef FEAT_GUI
4140 int delay = 1;
4141
4142 /* Keep updating the window while waiting for the shell to finish. */
4143 for (;;)
4144 {
4145 MSG msg;
4146
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004147 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148 {
4149 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004150 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004151 delay = 1;
4152 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 }
4154 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4155 break;
4156
4157 /* We start waiting for a very short time and then increase it, so
4158 * that we respond quickly when the process is quick, and don't
4159 * consume too much overhead when it's slow. */
4160 if (delay < 50)
4161 delay += 10;
4162 }
4163#else
4164 WaitForSingleObject(pi.hProcess, INFINITE);
4165#endif
4166
4167 /* Get the command exit code */
4168 GetExitCodeProcess(pi.hProcess, &ret);
4169 }
4170 else
4171 {
4172 /*
4173 * This ugly code is the only quick way of performing
4174 * a synchronous spawn under Win32s. Yuk.
4175 */
4176 num_windows = 0;
4177 EnumWindows(win32ssynch_cb, 0);
4178 old_num_windows = num_windows;
4179 do
4180 {
4181 Sleep(1000);
4182 num_windows = 0;
4183 EnumWindows(win32ssynch_cb, 0);
4184 } while (num_windows == old_num_windows);
4185 ret = 0;
4186 }
4187
4188 /* Close the handles to the subprocess, so that it goes away */
4189 CloseHandle(pi.hThread);
4190 CloseHandle(pi.hProcess);
4191
4192 /* Try to get input focus back. Doesn't always work though. */
4193 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4194
4195 return ret;
4196}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004197
4198/*
4199 * Thread launched by the gui to send the current buffer data to the
4200 * process. This way avoid to hang up vim totally if the children
4201 * process take a long time to process the lines.
4202 */
4203 static DWORD WINAPI
4204sub_process_writer(LPVOID param)
4205{
4206 HANDLE g_hChildStd_IN_Wr = param;
4207 linenr_T lnum = curbuf->b_op_start.lnum;
4208 DWORD len = 0;
4209 DWORD l;
4210 char_u *lp = ml_get(lnum);
4211 char_u *s;
4212 int written = 0;
4213
4214 for (;;)
4215 {
4216 l = (DWORD)STRLEN(lp + written);
4217 if (l == 0)
4218 len = 0;
4219 else if (lp[written] == NL)
4220 {
4221 /* NL -> NUL translation */
4222 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4223 }
4224 else
4225 {
4226 s = vim_strchr(lp + written, NL);
4227 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4228 s == NULL ? l : (DWORD)(s - (lp + written)),
4229 &len, NULL);
4230 }
4231 if (len == (int)l)
4232 {
4233 /* Finished a line, add a NL, unless this line should not have
4234 * one. */
4235 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004236 || (!curbuf->b_p_bin
4237 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004238 || (lnum != curbuf->b_no_eol_lnum
4239 && (lnum != curbuf->b_ml.ml_line_count
4240 || curbuf->b_p_eol)))
4241 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004242 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004243 }
4244
4245 ++lnum;
4246 if (lnum > curbuf->b_op_end.lnum)
4247 break;
4248
4249 lp = ml_get(lnum);
4250 written = 0;
4251 }
4252 else if (len > 0)
4253 written += len;
4254 }
4255
4256 /* finished all the lines, close pipe */
4257 CloseHandle(g_hChildStd_IN_Wr);
4258 ExitThread(0);
4259}
4260
4261
4262# define BUFLEN 100 /* length for buffer, stolen from unix version */
4263
4264/*
4265 * This function read from the children's stdout and write the
4266 * data on screen or in the buffer accordingly.
4267 */
4268 static void
4269dump_pipe(int options,
4270 HANDLE g_hChildStd_OUT_Rd,
4271 garray_T *ga,
4272 char_u buffer[],
4273 DWORD *buffer_off)
4274{
4275 DWORD availableBytes = 0;
4276 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004277 int ret;
4278 DWORD len;
4279 DWORD toRead;
4280 int repeatCount;
4281
4282 /* we query the pipe to see if there is any data to read
4283 * to avoid to perform a blocking read */
4284 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4285 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004286 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287 NULL, /* number of read bytes */
4288 &availableBytes, /* available bytes total */
4289 NULL); /* byteLeft */
4290
4291 repeatCount = 0;
4292 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004293 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004294 {
4295 repeatCount++;
4296 toRead =
4297# ifdef FEAT_MBYTE
4298 (DWORD)(BUFLEN - *buffer_off);
4299# else
4300 (DWORD)BUFLEN;
4301# endif
4302 toRead = availableBytes < toRead ? availableBytes : toRead;
4303 ReadFile(g_hChildStd_OUT_Rd, buffer
4304# ifdef FEAT_MBYTE
4305 + *buffer_off, toRead
4306# else
4307 , toRead
4308# endif
4309 , &len, NULL);
4310
4311 /* If we haven't read anything, there is a problem */
4312 if (len == 0)
4313 break;
4314
4315 availableBytes -= len;
4316
4317 if (options & SHELL_READ)
4318 {
4319 /* Do NUL -> NL translation, append NL separated
4320 * lines to the current buffer. */
4321 for (i = 0; i < len; ++i)
4322 {
4323 if (buffer[i] == NL)
4324 append_ga_line(ga);
4325 else if (buffer[i] == NUL)
4326 ga_append(ga, NL);
4327 else
4328 ga_append(ga, buffer[i]);
4329 }
4330 }
4331# ifdef FEAT_MBYTE
4332 else if (has_mbyte)
4333 {
4334 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004335 int c;
4336 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004337
4338 len += *buffer_off;
4339 buffer[len] = NUL;
4340
4341 /* Check if the last character in buffer[] is
4342 * incomplete, keep these bytes for the next
4343 * round. */
4344 for (p = buffer; p < buffer + len; p += l)
4345 {
4346 l = mb_cptr2len(p);
4347 if (l == 0)
4348 l = 1; /* NUL byte? */
4349 else if (MB_BYTE2LEN(*p) != l)
4350 break;
4351 }
4352 if (p == buffer) /* no complete character */
4353 {
4354 /* avoid getting stuck at an illegal byte */
4355 if (len >= 12)
4356 ++p;
4357 else
4358 {
4359 *buffer_off = len;
4360 return;
4361 }
4362 }
4363 c = *p;
4364 *p = NUL;
4365 msg_puts(buffer);
4366 if (p < buffer + len)
4367 {
4368 *p = c;
4369 *buffer_off = (DWORD)((buffer + len) - p);
4370 mch_memmove(buffer, p, *buffer_off);
4371 return;
4372 }
4373 *buffer_off = 0;
4374 }
4375# endif /* FEAT_MBYTE */
4376 else
4377 {
4378 buffer[len] = NUL;
4379 msg_puts(buffer);
4380 }
4381
4382 windgoto(msg_row, msg_col);
4383 cursor_on();
4384 out_flush();
4385 }
4386}
4387
4388/*
4389 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4390 * for communication and doesn't open any new window.
4391 */
4392 static int
4393mch_system_piped(char *cmd, int options)
4394{
4395 STARTUPINFO si;
4396 PROCESS_INFORMATION pi;
4397 DWORD ret = 0;
4398
4399 HANDLE g_hChildStd_IN_Rd = NULL;
4400 HANDLE g_hChildStd_IN_Wr = NULL;
4401 HANDLE g_hChildStd_OUT_Rd = NULL;
4402 HANDLE g_hChildStd_OUT_Wr = NULL;
4403
4404 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4405 DWORD len;
4406
4407 /* buffer used to receive keys */
4408 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4409 int ta_len = 0; /* valid bytes in ta_buf[] */
4410
4411 DWORD i;
4412 int c;
4413 int noread_cnt = 0;
4414 garray_T ga;
4415 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004417 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418
4419 SECURITY_ATTRIBUTES saAttr;
4420
4421 /* Set the bInheritHandle flag so pipe handles are inherited. */
4422 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4423 saAttr.bInheritHandle = TRUE;
4424 saAttr.lpSecurityDescriptor = NULL;
4425
4426 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4427 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4428 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4429 /* Create a pipe for the child process's STDIN. */
4430 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4431 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4432 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4433 {
4434 CloseHandle(g_hChildStd_IN_Rd);
4435 CloseHandle(g_hChildStd_IN_Wr);
4436 CloseHandle(g_hChildStd_OUT_Rd);
4437 CloseHandle(g_hChildStd_OUT_Wr);
4438 MSG_PUTS(_("\nCannot create pipes\n"));
4439 }
4440
4441 si.cb = sizeof(si);
4442 si.lpReserved = NULL;
4443 si.lpDesktop = NULL;
4444 si.lpTitle = NULL;
4445 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4446
4447 /* set-up our file redirection */
4448 si.hStdError = g_hChildStd_OUT_Wr;
4449 si.hStdOutput = g_hChildStd_OUT_Wr;
4450 si.hStdInput = g_hChildStd_IN_Rd;
4451 si.wShowWindow = SW_HIDE;
4452 si.cbReserved2 = 0;
4453 si.lpReserved2 = NULL;
4454
4455 if (options & SHELL_READ)
4456 ga_init2(&ga, 1, BUFLEN);
4457
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004458 if (cmd != NULL)
4459 {
4460 p = (char *)vim_strsave((char_u *)cmd);
4461 if (p != NULL)
4462 unescape_shellxquote((char_u *)p, p_sxe);
4463 else
4464 p = cmd;
4465 }
4466
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004467 /* Now, run the command.
4468 * About "Inherit handles" being TRUE: this command can be litigious,
4469 * handle inheritance was deactivated for pending temp file, but, if we
4470 * deactivate it, the pipes don't work for some reason. */
4471 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004472
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004473 if (p != cmd)
4474 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004475
4476 /* Close our unused side of the pipes */
4477 CloseHandle(g_hChildStd_IN_Rd);
4478 CloseHandle(g_hChildStd_OUT_Wr);
4479
4480 if (options & SHELL_WRITE)
4481 {
4482 HANDLE thread =
4483 CreateThread(NULL, /* security attributes */
4484 0, /* default stack size */
4485 sub_process_writer, /* function to be executed */
4486 g_hChildStd_IN_Wr, /* parameter */
4487 0, /* creation flag, start immediately */
4488 NULL); /* we don't care about thread id */
4489 CloseHandle(thread);
4490 g_hChildStd_IN_Wr = NULL;
4491 }
4492
4493 /* Keep updating the window while waiting for the shell to finish. */
4494 for (;;)
4495 {
4496 MSG msg;
4497
Bram Moolenaar175d0702013-12-11 18:36:33 +01004498 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004499 {
4500 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004501 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004502 }
4503
4504 /* write pipe information in the window */
4505 if ((options & (SHELL_READ|SHELL_WRITE))
4506# ifdef FEAT_GUI
4507 || gui.in_use
4508# endif
4509 )
4510 {
4511 len = 0;
4512 if (!(options & SHELL_EXPAND)
4513 && ((options &
4514 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4515 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4516# ifdef FEAT_GUI
4517 || gui.in_use
4518# endif
4519 )
4520 && (ta_len > 0 || noread_cnt > 4))
4521 {
4522 if (ta_len == 0)
4523 {
4524 /* Get extra characters when we don't have any. Reset the
4525 * counter and timer. */
4526 noread_cnt = 0;
4527# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4528 gettimeofday(&start_tv, NULL);
4529# endif
4530 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4531 }
4532 if (ta_len > 0 || len > 0)
4533 {
4534 /*
4535 * For pipes: Check for CTRL-C: send interrupt signal to
4536 * child. Check for CTRL-D: EOF, close pipe to child.
4537 */
4538 if (len == 1 && cmd != NULL)
4539 {
4540 if (ta_buf[ta_len] == Ctrl_C)
4541 {
4542 /* Learn what exit code is expected, for
4543 * now put 9 as SIGKILL */
4544 TerminateProcess(pi.hProcess, 9);
4545 }
4546 if (ta_buf[ta_len] == Ctrl_D)
4547 {
4548 CloseHandle(g_hChildStd_IN_Wr);
4549 g_hChildStd_IN_Wr = NULL;
4550 }
4551 }
4552
4553 /* replace K_BS by <BS> and K_DEL by <DEL> */
4554 for (i = ta_len; i < ta_len + len; ++i)
4555 {
4556 if (ta_buf[i] == CSI && len - i > 2)
4557 {
4558 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4559 if (c == K_DEL || c == K_KDEL || c == K_BS)
4560 {
4561 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4562 (size_t)(len - i - 2));
4563 if (c == K_DEL || c == K_KDEL)
4564 ta_buf[i] = DEL;
4565 else
4566 ta_buf[i] = Ctrl_H;
4567 len -= 2;
4568 }
4569 }
4570 else if (ta_buf[i] == '\r')
4571 ta_buf[i] = '\n';
4572# ifdef FEAT_MBYTE
4573 if (has_mbyte)
4574 i += (*mb_ptr2len_len)(ta_buf + i,
4575 ta_len + len - i) - 1;
4576# endif
4577 }
4578
4579 /*
4580 * For pipes: echo the typed characters. For a pty this
4581 * does not seem to work.
4582 */
4583 for (i = ta_len; i < ta_len + len; ++i)
4584 {
4585 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4586 msg_putchar(ta_buf[i]);
4587# ifdef FEAT_MBYTE
4588 else if (has_mbyte)
4589 {
4590 int l = (*mb_ptr2len)(ta_buf + i);
4591
4592 msg_outtrans_len(ta_buf + i, l);
4593 i += l - 1;
4594 }
4595# endif
4596 else
4597 msg_outtrans_len(ta_buf + i, 1);
4598 }
4599 windgoto(msg_row, msg_col);
4600 out_flush();
4601
4602 ta_len += len;
4603
4604 /*
4605 * Write the characters to the child, unless EOF has been
4606 * typed for pipes. Write one character at a time, to
4607 * avoid losing too much typeahead. When writing buffer
4608 * lines, drop the typed characters (only check for
4609 * CTRL-C).
4610 */
4611 if (options & SHELL_WRITE)
4612 ta_len = 0;
4613 else if (g_hChildStd_IN_Wr != NULL)
4614 {
4615 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4616 1, &len, NULL);
4617 // if we are typing in, we want to keep things reactive
4618 delay = 1;
4619 if (len > 0)
4620 {
4621 ta_len -= len;
4622 mch_memmove(ta_buf, ta_buf + len, ta_len);
4623 }
4624 }
4625 }
4626 }
4627 }
4628
4629 if (ta_len)
4630 ui_inchar_undo(ta_buf, ta_len);
4631
4632 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4633 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004634 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004635 break;
4636 }
4637
4638 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004639 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004640
4641 /* We start waiting for a very short time and then increase it, so
4642 * that we respond quickly when the process is quick, and don't
4643 * consume too much overhead when it's slow. */
4644 if (delay < 50)
4645 delay += 10;
4646 }
4647
4648 /* Close the pipe */
4649 CloseHandle(g_hChildStd_OUT_Rd);
4650 if (g_hChildStd_IN_Wr != NULL)
4651 CloseHandle(g_hChildStd_IN_Wr);
4652
4653 WaitForSingleObject(pi.hProcess, INFINITE);
4654
4655 /* Get the command exit code */
4656 GetExitCodeProcess(pi.hProcess, &ret);
4657
4658 if (options & SHELL_READ)
4659 {
4660 if (ga.ga_len > 0)
4661 {
4662 append_ga_line(&ga);
4663 /* remember that the NL was missing */
4664 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4665 }
4666 else
4667 curbuf->b_no_eol_lnum = 0;
4668 ga_clear(&ga);
4669 }
4670
4671 /* Close the handles to the subprocess, so that it goes away */
4672 CloseHandle(pi.hThread);
4673 CloseHandle(pi.hProcess);
4674
4675 return ret;
4676}
4677
4678 static int
4679mch_system(char *cmd, int options)
4680{
4681 /* if we can pipe and the shelltemp option is off */
4682 if (allowPiping && !p_stmp)
4683 return mch_system_piped(cmd, options);
4684 else
4685 return mch_system_classic(cmd, options);
4686}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687#else
4688
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004689# ifdef FEAT_MBYTE
4690 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004691mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004692{
4693 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4694 {
4695 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4696 if (wcmd != NULL)
4697 {
4698 int ret = _wsystem(wcmd);
4699 vim_free(wcmd);
4700 return ret;
4701 }
4702 }
4703 return system(cmd);
4704}
4705# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004706# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004707# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708
4709#endif
4710
4711/*
4712 * Either execute a command by calling the shell or start a new shell
4713 */
4714 int
4715mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004716 char_u *cmd,
4717 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004718{
4719 int x = 0;
4720 int tmode = cur_tmode;
4721#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004722 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004723# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004724 int did_set_title = FALSE;
4725
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004726 /* Change the title to reflect that we are in a subshell. */
4727 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4728 {
4729 WCHAR szShellTitle[512];
4730
4731 if (GetConsoleTitleW(szShellTitle,
4732 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4733 {
4734 if (cmd == NULL)
4735 wcscat(szShellTitle, L" :sh");
4736 else
4737 {
4738 WCHAR *wn = enc_to_utf16(cmd, NULL);
4739
4740 if (wn != NULL)
4741 {
4742 wcscat(szShellTitle, L" - !");
4743 if ((wcslen(szShellTitle) + wcslen(wn) <
4744 sizeof(szShellTitle)/sizeof(WCHAR)))
4745 wcscat(szShellTitle, wn);
4746 SetConsoleTitleW(szShellTitle);
4747 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004748 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004749 }
4750 }
4751 }
4752 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004753 if (!did_set_title)
4754# endif
4755 /* Change the title to reflect that we are in a subshell. */
4756 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004757 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004758 if (cmd == NULL)
4759 strcat(szShellTitle, " :sh");
4760 else
4761 {
4762 strcat(szShellTitle, " - !");
4763 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4764 strcat(szShellTitle, cmd);
4765 }
4766 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004767 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768#endif
4769
4770 out_flush();
4771
4772#ifdef MCH_WRITE_DUMP
4773 if (fdDump)
4774 {
4775 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4776 fflush(fdDump);
4777 }
4778#endif
4779
4780 /*
4781 * Catch all deadly signals while running the external command, because a
4782 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4783 */
4784 signal(SIGINT, SIG_IGN);
4785#if defined(__GNUC__) && !defined(__MINGW32__)
4786 signal(SIGKILL, SIG_IGN);
4787#else
4788 signal(SIGBREAK, SIG_IGN);
4789#endif
4790 signal(SIGILL, SIG_IGN);
4791 signal(SIGFPE, SIG_IGN);
4792 signal(SIGSEGV, SIG_IGN);
4793 signal(SIGTERM, SIG_IGN);
4794 signal(SIGABRT, SIG_IGN);
4795
4796 if (options & SHELL_COOKED)
4797 settmode(TMODE_COOK); /* set to normal mode */
4798
4799 if (cmd == NULL)
4800 {
4801 x = mch_system(p_sh, options);
4802 }
4803 else
4804 {
4805 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004806 char_u *newcmd = NULL;
4807 char_u *cmdbase = cmd;
4808 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004809
4810 /* Skip a leading ", ( and "(. */
4811 if (*cmdbase == '"' )
4812 ++cmdbase;
4813 if (*cmdbase == '(')
4814 ++cmdbase;
4815
4816 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4817 {
4818 STARTUPINFO si;
4819 PROCESS_INFORMATION pi;
4820 DWORD flags = CREATE_NEW_CONSOLE;
4821 char_u *p;
4822
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004823 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004824 si.cb = sizeof(si);
4825 si.lpReserved = NULL;
4826 si.lpDesktop = NULL;
4827 si.lpTitle = NULL;
4828 si.dwFlags = 0;
4829 si.cbReserved2 = 0;
4830 si.lpReserved2 = NULL;
4831
4832 cmdbase = skipwhite(cmdbase + 5);
4833 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4834 && vim_iswhite(cmdbase[4]))
4835 {
4836 cmdbase = skipwhite(cmdbase + 4);
4837 si.dwFlags = STARTF_USESHOWWINDOW;
4838 si.wShowWindow = SW_SHOWMINNOACTIVE;
4839 }
4840 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4841 && vim_iswhite(cmdbase[2]))
4842 {
4843 cmdbase = skipwhite(cmdbase + 2);
4844 flags = CREATE_NO_WINDOW;
4845 si.dwFlags = STARTF_USESTDHANDLES;
4846 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004847 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004848 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004849 NULL, // Security att.
4850 OPEN_EXISTING, // Open flags
4851 FILE_ATTRIBUTE_NORMAL, // File att.
4852 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004853 si.hStdOutput = si.hStdInput;
4854 si.hStdError = si.hStdInput;
4855 }
4856
4857 /* Remove a trailing ", ) and )" if they have a match
4858 * at the start of the command. */
4859 if (cmdbase > cmd)
4860 {
4861 p = cmdbase + STRLEN(cmdbase);
4862 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4863 *--p = NUL;
4864 if (p > cmdbase && p[-1] == ')'
4865 && (*cmd =='(' || cmd[1] == '('))
4866 *--p = NUL;
4867 }
4868
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004869 newcmd = cmdbase;
4870 unescape_shellxquote(cmdbase, p_sxe);
4871
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004872 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004873 * If creating new console, arguments are passed to the
4874 * 'cmd.exe' as-is. If it's not, arguments are not treated
4875 * correctly for current 'cmd.exe'. So unescape characters in
4876 * shellxescape except '|' for avoiding to be treated as
4877 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004878 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004879 if (flags != CREATE_NEW_CONSOLE)
4880 {
4881 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004882 char_u *cmd_shell = mch_getenv("COMSPEC");
4883
4884 if (cmd_shell == NULL || *cmd_shell == NUL)
4885 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004886
4887 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4888 if (subcmd != NULL)
4889 {
4890 /* make "cmd.exe /c arguments" */
4891 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004892 newcmd = lalloc(cmdlen, TRUE);
4893 if (newcmd != NULL)
4894 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004895 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004896 else
4897 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004898 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004899 }
4900 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004901
4902 /*
4903 * Now, start the command as a process, so that it doesn't
4904 * inherit our handles which causes unpleasant dangling swap
4905 * files if we exit before the spawned process
4906 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004907 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004908 x = 0;
4909 else
4910 {
4911 x = -1;
4912#ifdef FEAT_GUI_W32
4913 EMSG(_("E371: Command not found"));
4914#endif
4915 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004916
4917 if (newcmd != cmdbase)
4918 vim_free(newcmd);
4919
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004920 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004921 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004922 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004923 CloseHandle(si.hStdInput);
4924 }
4925 /* Close the handles to the subprocess, so that it goes away */
4926 CloseHandle(pi.hThread);
4927 CloseHandle(pi.hProcess);
4928 }
4929 else
4930 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004931 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004933 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004934#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004935 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4936
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004937 newcmd = lalloc(cmdlen, TRUE);
4938 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004939 {
4940#if defined(FEAT_GUI_W32)
4941 if (need_vimrun_warning)
4942 {
4943 MessageBox(NULL,
4944 _("VIMRUN.EXE not found in your $PATH.\n"
4945 "External commands will not pause after completion.\n"
4946 "See :help win32-vimrun for more information."),
4947 _("Vim Warning"),
4948 MB_ICONWARNING);
4949 need_vimrun_warning = FALSE;
4950 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004951 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952 /* Use vimrun to execute the command. It opens a console
4953 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004954 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004955 vimrun_path,
4956 (msg_silent != 0 || (options & SHELL_DOOUT))
4957 ? "-s " : "",
4958 p_sh, p_shcf, cmd);
4959 else
4960#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004961 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004962 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004964 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004965 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004966 }
4967 }
4968
4969 if (tmode == TMODE_RAW)
4970 settmode(TMODE_RAW); /* set to raw mode */
4971
4972 /* Print the return value, unless "vimrun" was used. */
4973 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4974#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004975 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4976 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977#endif
4978 )
4979 {
4980 smsg(_("shell returned %d"), x);
4981 msg_putchar('\n');
4982 }
4983#ifdef FEAT_TITLE
4984 resettitle();
4985#endif
4986
4987 signal(SIGINT, SIG_DFL);
4988#if defined(__GNUC__) && !defined(__MINGW32__)
4989 signal(SIGKILL, SIG_DFL);
4990#else
4991 signal(SIGBREAK, SIG_DFL);
4992#endif
4993 signal(SIGILL, SIG_DFL);
4994 signal(SIGFPE, SIG_DFL);
4995 signal(SIGSEGV, SIG_DFL);
4996 signal(SIGTERM, SIG_DFL);
4997 signal(SIGABRT, SIG_DFL);
4998
4999 return x;
5000}
5001
5002
5003#ifndef FEAT_GUI_W32
5004
5005/*
5006 * Start termcap mode
5007 */
5008 static void
5009termcap_mode_start(void)
5010{
5011 DWORD cmodein;
5012
5013 if (g_fTermcapMode)
5014 return;
5015
5016 SaveConsoleBuffer(&g_cbNonTermcap);
5017
5018 if (g_cbTermcap.IsValid)
5019 {
5020 /*
5021 * We've been in termcap mode before. Restore certain screen
5022 * characteristics, including the buffer size and the window
5023 * size. Since we will be redrawing the screen, we don't need
5024 * to restore the actual contents of the buffer.
5025 */
5026 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5027 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5028 Rows = g_cbTermcap.Info.dwSize.Y;
5029 Columns = g_cbTermcap.Info.dwSize.X;
5030 }
5031 else
5032 {
5033 /*
5034 * This is our first time entering termcap mode. Clear the console
5035 * screen buffer, and resize the buffer to match the current window
5036 * size. We will use this as the size of our editing environment.
5037 */
5038 ClearConsoleBuffer(g_attrCurrent);
5039 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5040 }
5041
5042#ifdef FEAT_TITLE
5043 resettitle();
5044#endif
5045
5046 GetConsoleMode(g_hConIn, &cmodein);
5047#ifdef FEAT_MOUSE
5048 if (g_fMouseActive)
5049 cmodein |= ENABLE_MOUSE_INPUT;
5050 else
5051 cmodein &= ~ENABLE_MOUSE_INPUT;
5052#endif
5053 cmodein |= ENABLE_WINDOW_INPUT;
5054 SetConsoleMode(g_hConIn, cmodein);
5055
5056 redraw_later_clear();
5057 g_fTermcapMode = TRUE;
5058}
5059
5060
5061/*
5062 * End termcap mode
5063 */
5064 static void
5065termcap_mode_end(void)
5066{
5067 DWORD cmodein;
5068 ConsoleBuffer *cb;
5069 COORD coord;
5070 DWORD dwDummy;
5071
5072 if (!g_fTermcapMode)
5073 return;
5074
5075 SaveConsoleBuffer(&g_cbTermcap);
5076
5077 GetConsoleMode(g_hConIn, &cmodein);
5078 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5079 SetConsoleMode(g_hConIn, cmodein);
5080
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005081#ifdef FEAT_RESTORE_ORIG_SCREEN
5082 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5083#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005084 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005085#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005086 RestoreConsoleBuffer(cb, p_rs);
5087 SetConsoleCursorInfo(g_hConOut, &g_cci);
5088
5089 if (p_rs || exiting)
5090 {
5091 /*
5092 * Clear anything that happens to be on the current line.
5093 */
5094 coord.X = 0;
5095 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5096 FillConsoleOutputCharacter(g_hConOut, ' ',
5097 cb->Info.dwSize.X, coord, &dwDummy);
5098 /*
5099 * The following is just for aesthetics. If we are exiting without
5100 * restoring the screen, then we want to have a prompt string
5101 * appear at the bottom line. However, the command interpreter
5102 * seems to always advance the cursor one line before displaying
5103 * the prompt string, which causes the screen to scroll. To
5104 * counter this, move the cursor up one line before exiting.
5105 */
5106 if (exiting && !p_rs)
5107 coord.Y--;
5108 /*
5109 * Position the cursor at the leftmost column of the desired row.
5110 */
5111 SetConsoleCursorPosition(g_hConOut, coord);
5112 }
5113
5114 g_fTermcapMode = FALSE;
5115}
5116#endif /* FEAT_GUI_W32 */
5117
5118
5119#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005120/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005121 void
5122mch_write(
5123 char_u *s,
5124 int len)
5125{
5126 /* never used */
5127}
5128
5129#else
5130
5131/*
5132 * clear `n' chars, starting from `coord'
5133 */
5134 static void
5135clear_chars(
5136 COORD coord,
5137 DWORD n)
5138{
5139 DWORD dwDummy;
5140
5141 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5142 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5143}
5144
5145
5146/*
5147 * Clear the screen
5148 */
5149 static void
5150clear_screen(void)
5151{
5152 g_coord.X = g_coord.Y = 0;
5153 clear_chars(g_coord, Rows * Columns);
5154}
5155
5156
5157/*
5158 * Clear to end of display
5159 */
5160 static void
5161clear_to_end_of_display(void)
5162{
5163 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5164 * Columns + (Columns - g_coord.X));
5165}
5166
5167
5168/*
5169 * Clear to end of line
5170 */
5171 static void
5172clear_to_end_of_line(void)
5173{
5174 clear_chars(g_coord, Columns - g_coord.X);
5175}
5176
5177
5178/*
5179 * Scroll the scroll region up by `cLines' lines
5180 */
5181 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005182scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005183{
5184 COORD oldcoord = g_coord;
5185
5186 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5187 delete_lines(cLines);
5188
5189 g_coord = oldcoord;
5190}
5191
5192
5193/*
5194 * Set the scroll region
5195 */
5196 static void
5197set_scroll_region(
5198 unsigned left,
5199 unsigned top,
5200 unsigned right,
5201 unsigned bottom)
5202{
5203 if (left >= right
5204 || top >= bottom
5205 || right > (unsigned) Columns - 1
5206 || bottom > (unsigned) Rows - 1)
5207 return;
5208
5209 g_srScrollRegion.Left = left;
5210 g_srScrollRegion.Top = top;
5211 g_srScrollRegion.Right = right;
5212 g_srScrollRegion.Bottom = bottom;
5213}
5214
5215
5216/*
5217 * Insert `cLines' lines at the current cursor position
5218 */
5219 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005220insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005221{
5222 SMALL_RECT source;
5223 COORD dest;
5224 CHAR_INFO fill;
5225
5226 dest.X = 0;
5227 dest.Y = g_coord.Y + cLines;
5228
5229 source.Left = 0;
5230 source.Top = g_coord.Y;
5231 source.Right = g_srScrollRegion.Right;
5232 source.Bottom = g_srScrollRegion.Bottom - cLines;
5233
5234 fill.Char.AsciiChar = ' ';
5235 fill.Attributes = g_attrCurrent;
5236
5237 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5238
5239 /* Here we have to deal with a win32 console flake: If the scroll
5240 * region looks like abc and we scroll c to a and fill with d we get
5241 * cbd... if we scroll block c one line at a time to a, we get cdd...
5242 * vim expects cdd consistently... So we have to deal with that
5243 * here... (this also occurs scrolling the same way in the other
5244 * direction). */
5245
5246 if (source.Bottom < dest.Y)
5247 {
5248 COORD coord;
5249
5250 coord.X = 0;
5251 coord.Y = source.Bottom;
5252 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5253 }
5254}
5255
5256
5257/*
5258 * Delete `cLines' lines at the current cursor position
5259 */
5260 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005261delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005262{
5263 SMALL_RECT source;
5264 COORD dest;
5265 CHAR_INFO fill;
5266 int nb;
5267
5268 dest.X = 0;
5269 dest.Y = g_coord.Y;
5270
5271 source.Left = 0;
5272 source.Top = g_coord.Y + cLines;
5273 source.Right = g_srScrollRegion.Right;
5274 source.Bottom = g_srScrollRegion.Bottom;
5275
5276 fill.Char.AsciiChar = ' ';
5277 fill.Attributes = g_attrCurrent;
5278
5279 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5280
5281 /* Here we have to deal with a win32 console flake: If the scroll
5282 * region looks like abc and we scroll c to a and fill with d we get
5283 * cbd... if we scroll block c one line at a time to a, we get cdd...
5284 * vim expects cdd consistently... So we have to deal with that
5285 * here... (this also occurs scrolling the same way in the other
5286 * direction). */
5287
5288 nb = dest.Y + (source.Bottom - source.Top) + 1;
5289
5290 if (nb < source.Top)
5291 {
5292 COORD coord;
5293
5294 coord.X = 0;
5295 coord.Y = nb;
5296 clear_chars(coord, Columns * (source.Top - nb));
5297 }
5298}
5299
5300
5301/*
5302 * Set the cursor position
5303 */
5304 static void
5305gotoxy(
5306 unsigned x,
5307 unsigned y)
5308{
5309 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5310 return;
5311
5312 /* external cursor coords are 1-based; internal are 0-based */
5313 g_coord.X = x - 1;
5314 g_coord.Y = y - 1;
5315 SetConsoleCursorPosition(g_hConOut, g_coord);
5316}
5317
5318
5319/*
5320 * Set the current text attribute = (foreground | background)
5321 * See ../doc/os_win32.txt for the numbers.
5322 */
5323 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005324textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005325{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005326 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005327
5328 SetConsoleTextAttribute(g_hConOut, wAttr);
5329}
5330
5331
5332 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005333textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005334{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005335 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005336
5337 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5338}
5339
5340
5341 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005342textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005343{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005344 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345
5346 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5347}
5348
5349
5350/*
5351 * restore the default text attribute (whatever we started with)
5352 */
5353 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005354normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005355{
5356 textattr(g_attrDefault);
5357}
5358
5359
5360static WORD g_attrPreStandout = 0;
5361
5362/*
5363 * Make the text standout, by brightening it
5364 */
5365 static void
5366standout(void)
5367{
5368 g_attrPreStandout = g_attrCurrent;
5369 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5370}
5371
5372
5373/*
5374 * Turn off standout mode
5375 */
5376 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005377standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005378{
5379 if (g_attrPreStandout)
5380 {
5381 textattr(g_attrPreStandout);
5382 g_attrPreStandout = 0;
5383 }
5384}
5385
5386
5387/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005388 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005389 */
5390 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005391mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005392{
5393 char_u *p;
5394 int n;
5395
5396 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5397 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5398 if (T_ME[0] == ESC && T_ME[1] == '|')
5399 {
5400 p = T_ME + 2;
5401 n = getdigits(&p);
5402 if (*p == 'm' && n > 0)
5403 {
5404 cterm_normal_fg_color = (n & 0xf) + 1;
5405 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5406 }
5407 }
5408}
5409
5410
5411/*
5412 * visual bell: flash the screen
5413 */
5414 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005415visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005416{
5417 COORD coordOrigin = {0, 0};
5418 WORD attrFlash = ~g_attrCurrent & 0xff;
5419
5420 DWORD dwDummy;
5421 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5422
5423 if (oldattrs == NULL)
5424 return;
5425 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5426 coordOrigin, &dwDummy);
5427 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5428 coordOrigin, &dwDummy);
5429
5430 Sleep(15); /* wait for 15 msec */
5431 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5432 coordOrigin, &dwDummy);
5433 vim_free(oldattrs);
5434}
5435
5436
5437/*
5438 * Make the cursor visible or invisible
5439 */
5440 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005441cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005442{
5443 s_cursor_visible = fVisible;
5444#ifdef MCH_CURSOR_SHAPE
5445 mch_update_cursor();
5446#endif
5447}
5448
5449
5450/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005451 * write `cbToWrite' bytes in `pchBuf' to the screen
5452 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005453 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005454 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005455write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005456 char_u *pchBuf,
5457 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005458{
5459 COORD coord = g_coord;
5460 DWORD written;
5461
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005462#ifdef FEAT_MBYTE
5463 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5464 {
5465 static WCHAR *unicodebuf = NULL;
5466 static int unibuflen = 0;
5467 int length;
5468 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005469
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005470 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5471 if (unicodebuf == NULL || length > unibuflen)
5472 {
5473 vim_free(unicodebuf);
5474 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5475 unibuflen = length;
5476 }
5477 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5478 unicodebuf, unibuflen);
5479
5480 cells = mb_string2cells(pchBuf, cbToWrite);
5481 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5482 coord, &written);
5483 /* When writing fails or didn't write a single character, pretend one
5484 * character was written, otherwise we get stuck. */
5485 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5486 coord, &cchwritten) == 0
5487 || cchwritten == 0)
5488 cchwritten = 1;
5489
5490 if (cchwritten == length)
5491 {
5492 written = cbToWrite;
5493 g_coord.X += (SHORT)cells;
5494 }
5495 else
5496 {
5497 char_u *p = pchBuf;
5498 for (n = 0; n < cchwritten; n++)
5499 mb_cptr_adv(p);
5500 written = p - pchBuf;
5501 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5502 }
5503 }
5504 else
5505#endif
5506 {
5507 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5508 coord, &written);
5509 /* When writing fails or didn't write a single character, pretend one
5510 * character was written, otherwise we get stuck. */
5511 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5512 coord, &written) == 0
5513 || written == 0)
5514 written = 1;
5515
5516 g_coord.X += (SHORT) written;
5517 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518
5519 while (g_coord.X > g_srScrollRegion.Right)
5520 {
5521 g_coord.X -= (SHORT) Columns;
5522 if (g_coord.Y < g_srScrollRegion.Bottom)
5523 g_coord.Y++;
5524 }
5525
5526 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5527
5528 return written;
5529}
5530
5531
5532/*
5533 * mch_write(): write the output buffer to the screen, translating ESC
5534 * sequences into calls to console output routines.
5535 */
5536 void
5537mch_write(
5538 char_u *s,
5539 int len)
5540{
5541 s[len] = NUL;
5542
5543 if (!term_console)
5544 {
5545 write(1, s, (unsigned)len);
5546 return;
5547 }
5548
5549 /* translate ESC | sequences into faked bios calls */
5550 while (len--)
5551 {
5552 /* optimization: use one single write_chars for runs of text,
5553 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005554 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005555
5556 if (p_wd)
5557 {
5558 WaitForChar(p_wd);
5559 if (prefix != 0)
5560 prefix = 1;
5561 }
5562
5563 if (prefix != 0)
5564 {
5565 DWORD nWritten;
5566
5567 nWritten = write_chars(s, prefix);
5568#ifdef MCH_WRITE_DUMP
5569 if (fdDump)
5570 {
5571 fputc('>', fdDump);
5572 fwrite(s, sizeof(char_u), nWritten, fdDump);
5573 fputs("<\n", fdDump);
5574 }
5575#endif
5576 len -= (nWritten - 1);
5577 s += nWritten;
5578 }
5579 else if (s[0] == '\n')
5580 {
5581 /* \n, newline: go to the beginning of the next line or scroll */
5582 if (g_coord.Y == g_srScrollRegion.Bottom)
5583 {
5584 scroll(1);
5585 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5586 }
5587 else
5588 {
5589 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5590 }
5591#ifdef MCH_WRITE_DUMP
5592 if (fdDump)
5593 fputs("\\n\n", fdDump);
5594#endif
5595 s++;
5596 }
5597 else if (s[0] == '\r')
5598 {
5599 /* \r, carriage return: go to beginning of line */
5600 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5601#ifdef MCH_WRITE_DUMP
5602 if (fdDump)
5603 fputs("\\r\n", fdDump);
5604#endif
5605 s++;
5606 }
5607 else if (s[0] == '\b')
5608 {
5609 /* \b, backspace: move cursor one position left */
5610 if (g_coord.X > g_srScrollRegion.Left)
5611 g_coord.X--;
5612 else if (g_coord.Y > g_srScrollRegion.Top)
5613 {
5614 g_coord.X = g_srScrollRegion.Right;
5615 g_coord.Y--;
5616 }
5617 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5618#ifdef MCH_WRITE_DUMP
5619 if (fdDump)
5620 fputs("\\b\n", fdDump);
5621#endif
5622 s++;
5623 }
5624 else if (s[0] == '\a')
5625 {
5626 /* \a, bell */
5627 MessageBeep(0xFFFFFFFF);
5628#ifdef MCH_WRITE_DUMP
5629 if (fdDump)
5630 fputs("\\a\n", fdDump);
5631#endif
5632 s++;
5633 }
5634 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5635 {
5636#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005637 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005639 char_u *p;
5640 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641
5642 switch (s[2])
5643 {
5644 /* one or two numeric arguments, separated by ';' */
5645
5646 case '0': case '1': case '2': case '3': case '4':
5647 case '5': case '6': case '7': case '8': case '9':
5648 p = s + 2;
5649 arg1 = getdigits(&p); /* no check for length! */
5650 if (p > s + len)
5651 break;
5652
5653 if (*p == ';')
5654 {
5655 ++p;
5656 arg2 = getdigits(&p); /* no check for length! */
5657 if (p > s + len)
5658 break;
5659
5660 if (*p == 'H')
5661 gotoxy(arg2, arg1);
5662 else if (*p == 'r')
5663 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5664 }
5665 else if (*p == 'A')
5666 {
5667 /* move cursor up arg1 lines in same column */
5668 gotoxy(g_coord.X + 1,
5669 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5670 }
5671 else if (*p == 'C')
5672 {
5673 /* move cursor right arg1 columns in same line */
5674 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5675 g_coord.Y + 1);
5676 }
5677 else if (*p == 'H')
5678 {
5679 gotoxy(1, arg1);
5680 }
5681 else if (*p == 'L')
5682 {
5683 insert_lines(arg1);
5684 }
5685 else if (*p == 'm')
5686 {
5687 if (arg1 == 0)
5688 normvideo();
5689 else
5690 textattr((WORD) arg1);
5691 }
5692 else if (*p == 'f')
5693 {
5694 textcolor((WORD) arg1);
5695 }
5696 else if (*p == 'b')
5697 {
5698 textbackground((WORD) arg1);
5699 }
5700 else if (*p == 'M')
5701 {
5702 delete_lines(arg1);
5703 }
5704
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005705 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 s = p + 1;
5707 break;
5708
5709
5710 /* Three-character escape sequences */
5711
5712 case 'A':
5713 /* move cursor up one line in same column */
5714 gotoxy(g_coord.X + 1,
5715 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5716 goto got3;
5717
5718 case 'B':
5719 visual_bell();
5720 goto got3;
5721
5722 case 'C':
5723 /* move cursor right one column in same line */
5724 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5725 g_coord.Y + 1);
5726 goto got3;
5727
5728 case 'E':
5729 termcap_mode_end();
5730 goto got3;
5731
5732 case 'F':
5733 standout();
5734 goto got3;
5735
5736 case 'f':
5737 standend();
5738 goto got3;
5739
5740 case 'H':
5741 gotoxy(1, 1);
5742 goto got3;
5743
5744 case 'j':
5745 clear_to_end_of_display();
5746 goto got3;
5747
5748 case 'J':
5749 clear_screen();
5750 goto got3;
5751
5752 case 'K':
5753 clear_to_end_of_line();
5754 goto got3;
5755
5756 case 'L':
5757 insert_lines(1);
5758 goto got3;
5759
5760 case 'M':
5761 delete_lines(1);
5762 goto got3;
5763
5764 case 'S':
5765 termcap_mode_start();
5766 goto got3;
5767
5768 case 'V':
5769 cursor_visible(TRUE);
5770 goto got3;
5771
5772 case 'v':
5773 cursor_visible(FALSE);
5774 goto got3;
5775
5776 got3:
5777 s += 3;
5778 len -= 2;
5779 }
5780
5781#ifdef MCH_WRITE_DUMP
5782 if (fdDump)
5783 {
5784 fputs("ESC | ", fdDump);
5785 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5786 fputc('\n', fdDump);
5787 }
5788#endif
5789 }
5790 else
5791 {
5792 /* Write a single character */
5793 DWORD nWritten;
5794
5795 nWritten = write_chars(s, 1);
5796#ifdef MCH_WRITE_DUMP
5797 if (fdDump)
5798 {
5799 fputc('>', fdDump);
5800 fwrite(s, sizeof(char_u), nWritten, fdDump);
5801 fputs("<\n", fdDump);
5802 }
5803#endif
5804
5805 len -= (nWritten - 1);
5806 s += nWritten;
5807 }
5808 }
5809
5810#ifdef MCH_WRITE_DUMP
5811 if (fdDump)
5812 fflush(fdDump);
5813#endif
5814}
5815
5816#endif /* FEAT_GUI_W32 */
5817
5818
5819/*
5820 * Delay for half a second.
5821 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005822/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823 void
5824mch_delay(
5825 long msec,
5826 int ignoreinput)
5827{
5828#ifdef FEAT_GUI_W32
5829 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005830#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005832# ifdef FEAT_MZSCHEME
5833 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5834 {
5835 int towait = p_mzq;
5836
5837 /* if msec is large enough, wait by portions in p_mzq */
5838 while (msec > 0)
5839 {
5840 mzvim_check_threads();
5841 if (msec < towait)
5842 towait = msec;
5843 Sleep(towait);
5844 msec -= towait;
5845 }
5846 }
5847 else
5848# endif
5849 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850 else
5851 WaitForChar(msec);
5852#endif
5853}
5854
5855
5856/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01005857 * This version of remove is not scared by a readonly (backup) file.
5858 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005859 * Return 0 for success, -1 for failure.
5860 */
5861 int
5862mch_remove(char_u *name)
5863{
5864#ifdef FEAT_MBYTE
5865 WCHAR *wn = NULL;
5866 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005867#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868
Bram Moolenaar203258c2016-01-17 22:15:16 +01005869 /*
5870 * On Windows, deleting a directory's symbolic link is done by
5871 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
5872 */
5873 if (mch_isdir(name) && mch_is_symbolic_link(name))
5874 return mch_rmdir(name);
5875
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005876 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5877
5878#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5880 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005881 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882 if (wn != NULL)
5883 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884 n = DeleteFileW(wn) ? 0 : -1;
5885 vim_free(wn);
5886 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5887 return n;
5888 /* Retry with non-wide function (for Windows 98). */
5889 }
5890 }
5891#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005892 return DeleteFile(name) ? 0 : -1;
5893}
5894
5895
5896/*
5897 * check for an "interrupt signal": CTRL-break or CTRL-C
5898 */
5899 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005900mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005901{
5902#ifndef FEAT_GUI_W32 /* never used */
5903 if (g_fCtrlCPressed || g_fCBrkPressed)
5904 {
5905 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5906 got_int = TRUE;
5907 }
5908#endif
5909}
5910
Bram Moolenaaree273972016-01-02 21:11:51 +01005911/* physical RAM to leave for the OS */
5912#define WINNT_RESERVE_BYTES (256*1024*1024)
5913#define WIN95_RESERVE_BYTES (8*1024*1024)
5914
5915/*
5916 * How much main memory in KiB that can be used by VIM.
5917 */
5918/*ARGSUSED*/
5919 long_u
5920mch_total_mem(int special)
5921{
5922 PlatformId();
5923#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
5924 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5925 {
5926 MEMORYSTATUSEX ms;
5927
5928 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5929 * what fits in 32 bits. But it's not always available. */
5930 ms.dwLength = sizeof(MEMORYSTATUSEX);
5931 GlobalMemoryStatusEx(&ms);
5932 if (ms.ullAvailVirtual < ms.ullTotalPhys)
5933 {
5934 /* Process address space fits in physical RAM, use all of it. */
5935 return (long_u)(ms.ullAvailVirtual / 1024);
5936 }
5937 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
5938 {
5939 /* Catch old NT box or perverse hardware setup. */
5940 return (long_u)((ms.ullTotalPhys / 2) / 1024);
5941 }
5942 /* Use physical RAM less reserve for OS + data. */
5943 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
5944 }
5945 else
5946#endif
5947 {
5948 /* Pre-XP or 95 OS handling. */
5949 MEMORYSTATUS ms;
5950 long_u os_reserve_bytes;
5951
5952 ms.dwLength = sizeof(MEMORYSTATUS);
5953 GlobalMemoryStatus(&ms);
5954 if (ms.dwAvailVirtual < ms.dwTotalPhys)
5955 {
5956 /* Process address space fits in physical RAM, use all of it. */
5957 return (long_u)(ms.dwAvailVirtual / 1024);
5958 }
5959 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
5960 ? WINNT_RESERVE_BYTES
5961 : WIN95_RESERVE_BYTES;
5962 if (ms.dwTotalPhys <= os_reserve_bytes)
5963 {
5964 /* Catch old boxes or perverse hardware setup. */
5965 return (long_u)((ms.dwTotalPhys / 2) / 1024);
5966 }
5967 /* Use physical RAM less reserve for OS + data. */
5968 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
5969 }
5970}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972#ifdef FEAT_MBYTE
5973/*
5974 * Same code as below, but with wide functions and no comments.
5975 * Return 0 for success, non-zero for failure.
5976 */
5977 int
5978mch_wrename(WCHAR *wold, WCHAR *wnew)
5979{
5980 WCHAR *p;
5981 int i;
5982 WCHAR szTempFile[_MAX_PATH + 1];
5983 WCHAR szNewPath[_MAX_PATH + 1];
5984 HANDLE hf;
5985
5986 if (!mch_windows95())
5987 {
5988 p = wold;
5989 for (i = 0; wold[i] != NUL; ++i)
5990 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5991 && wold[i + 1] != 0)
5992 p = wold + i + 1;
5993 if ((int)(wold + i - p) < 8 || p[6] != '~')
5994 return (MoveFileW(wold, wnew) == 0);
5995 }
5996
5997 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5998 return -1;
5999 *p = NUL;
6000
6001 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6002 return -2;
6003
6004 if (!DeleteFileW(szTempFile))
6005 return -3;
6006
6007 if (!MoveFileW(wold, szTempFile))
6008 return -4;
6009
6010 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6011 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6012 return -5;
6013 if (!CloseHandle(hf))
6014 return -6;
6015
6016 if (!MoveFileW(szTempFile, wnew))
6017 {
6018 (void)MoveFileW(szTempFile, wold);
6019 return -7;
6020 }
6021
6022 DeleteFileW(szTempFile);
6023
6024 if (!DeleteFileW(wold))
6025 return -8;
6026
6027 return 0;
6028}
6029#endif
6030
6031
6032/*
6033 * mch_rename() works around a bug in rename (aka MoveFile) in
6034 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6035 * file whose short file name is "FOO.BAR" (its long file name will
6036 * be correct: "foo.bar~"). Because a file can be accessed by
6037 * either its SFN or its LFN, "foo.bar" has effectively been
6038 * renamed to "foo.bar", which is not at all what was wanted. This
6039 * seems to happen only when renaming files with three-character
6040 * extensions by appending a suffix that does not include ".".
6041 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6042 *
6043 * There is another problem, which isn't really a bug but isn't right either:
6044 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6045 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6046 * service pack 6. Doesn't seem to happen on Windows 98.
6047 *
6048 * Like rename(), returns 0 upon success, non-zero upon failure.
6049 * Should probably set errno appropriately when errors occur.
6050 */
6051 int
6052mch_rename(
6053 const char *pszOldFile,
6054 const char *pszNewFile)
6055{
6056 char szTempFile[_MAX_PATH+1];
6057 char szNewPath[_MAX_PATH+1];
6058 char *pszFilePart;
6059 HANDLE hf;
6060#ifdef FEAT_MBYTE
6061 WCHAR *wold = NULL;
6062 WCHAR *wnew = NULL;
6063 int retval = -1;
6064
6065 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6066 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006067 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6068 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069 if (wold != NULL && wnew != NULL)
6070 retval = mch_wrename(wold, wnew);
6071 vim_free(wold);
6072 vim_free(wnew);
6073 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6074 return retval;
6075 /* Retry with non-wide function (for Windows 98). */
6076 }
6077#endif
6078
6079 /*
6080 * No need to play tricks if not running Windows 95, unless the file name
6081 * contains a "~" as the seventh character.
6082 */
6083 if (!mch_windows95())
6084 {
6085 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6086 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6087 return rename(pszOldFile, pszNewFile);
6088 }
6089
6090 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6091 * a directory, no error is returned and pszFilePart will be NULL. */
6092 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6093 || pszFilePart == NULL)
6094 return -1;
6095 *pszFilePart = NUL;
6096
6097 /* Get (and create) a unique temporary file name in directory of new file */
6098 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6099 return -2;
6100
6101 /* blow the temp file away */
6102 if (!DeleteFile(szTempFile))
6103 return -3;
6104
6105 /* rename old file to the temp file */
6106 if (!MoveFile(pszOldFile, szTempFile))
6107 return -4;
6108
6109 /* now create an empty file called pszOldFile; this prevents the operating
6110 * system using pszOldFile as an alias (SFN) if we're renaming within the
6111 * same directory. For example, we're editing a file called
6112 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6113 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6114 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006115 * cause all sorts of problems later in buf_write(). So, we create an
6116 * empty file called filena~1.txt and the system will have to find some
6117 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118 */
6119 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6120 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6121 return -5;
6122 if (!CloseHandle(hf))
6123 return -6;
6124
6125 /* rename the temp file to the new file */
6126 if (!MoveFile(szTempFile, pszNewFile))
6127 {
6128 /* Renaming failed. Rename the file back to its old name, so that it
6129 * looks like nothing happened. */
6130 (void)MoveFile(szTempFile, pszOldFile);
6131
6132 return -7;
6133 }
6134
6135 /* Seems to be left around on Novell filesystems */
6136 DeleteFile(szTempFile);
6137
6138 /* finally, remove the empty old file */
6139 if (!DeleteFile(pszOldFile))
6140 return -8;
6141
6142 return 0; /* success */
6143}
6144
6145/*
6146 * Get the default shell for the current hardware platform
6147 */
6148 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006149default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150{
6151 char* psz = NULL;
6152
6153 PlatformId();
6154
6155 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6156 psz = "cmd.exe";
6157 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6158 psz = "command.com";
6159
6160 return psz;
6161}
6162
6163/*
6164 * mch_access() extends access() to do more detailed check on network drives.
6165 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6166 */
6167 int
6168mch_access(char *n, int p)
6169{
6170 HANDLE hFile;
6171 DWORD am;
6172 int retval = -1; /* default: fail */
6173#ifdef FEAT_MBYTE
6174 WCHAR *wn = NULL;
6175
6176 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006177 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178#endif
6179
6180 if (mch_isdir(n))
6181 {
6182 char TempName[_MAX_PATH + 16] = "";
6183#ifdef FEAT_MBYTE
6184 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6185#endif
6186
6187 if (p & R_OK)
6188 {
6189 /* Read check is performed by seeing if we can do a find file on
6190 * the directory for any file. */
6191#ifdef FEAT_MBYTE
6192 if (wn != NULL)
6193 {
6194 int i;
6195 WIN32_FIND_DATAW d;
6196
6197 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6198 TempNameW[i] = wn[i];
6199 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6200 TempNameW[i++] = '\\';
6201 TempNameW[i++] = '*';
6202 TempNameW[i++] = 0;
6203
6204 hFile = FindFirstFileW(TempNameW, &d);
6205 if (hFile == INVALID_HANDLE_VALUE)
6206 {
6207 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6208 goto getout;
6209
6210 /* Retry with non-wide function (for Windows 98). */
6211 vim_free(wn);
6212 wn = NULL;
6213 }
6214 else
6215 (void)FindClose(hFile);
6216 }
6217 if (wn == NULL)
6218#endif
6219 {
6220 char *pch;
6221 WIN32_FIND_DATA d;
6222
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006223 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224 pch = TempName + STRLEN(TempName) - 1;
6225 if (*pch != '\\' && *pch != '/')
6226 *++pch = '\\';
6227 *++pch = '*';
6228 *++pch = NUL;
6229
6230 hFile = FindFirstFile(TempName, &d);
6231 if (hFile == INVALID_HANDLE_VALUE)
6232 goto getout;
6233 (void)FindClose(hFile);
6234 }
6235 }
6236
6237 if (p & W_OK)
6238 {
6239 /* Trying to create a temporary file in the directory should catch
6240 * directories on read-only network shares. However, in
6241 * directories whose ACL allows writes but denies deletes will end
6242 * up keeping the temporary file :-(. */
6243#ifdef FEAT_MBYTE
6244 if (wn != NULL)
6245 {
6246 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6247 {
6248 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6249 goto getout;
6250
6251 /* Retry with non-wide function (for Windows 98). */
6252 vim_free(wn);
6253 wn = NULL;
6254 }
6255 else
6256 DeleteFileW(TempNameW);
6257 }
6258 if (wn == NULL)
6259#endif
6260 {
6261 if (!GetTempFileName(n, "VIM", 0, TempName))
6262 goto getout;
6263 mch_remove((char_u *)TempName);
6264 }
6265 }
6266 }
6267 else
6268 {
6269 /* Trying to open the file for the required access does ACL, read-only
6270 * network share, and file attribute checks. */
6271 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6272 | ((p & R_OK) ? GENERIC_READ : 0);
6273#ifdef FEAT_MBYTE
6274 if (wn != NULL)
6275 {
6276 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6277 if (hFile == INVALID_HANDLE_VALUE
6278 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6279 {
6280 /* Retry with non-wide function (for Windows 98). */
6281 vim_free(wn);
6282 wn = NULL;
6283 }
6284 }
6285 if (wn == NULL)
6286#endif
6287 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6288 if (hFile == INVALID_HANDLE_VALUE)
6289 goto getout;
6290 CloseHandle(hFile);
6291 }
6292
6293 retval = 0; /* success */
6294getout:
6295#ifdef FEAT_MBYTE
6296 vim_free(wn);
6297#endif
6298 return retval;
6299}
6300
6301#if defined(FEAT_MBYTE) || defined(PROTO)
6302/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006303 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304 */
6305 int
6306mch_open(char *name, int flags, int mode)
6307{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006308 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6309# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310 WCHAR *wn;
6311 int f;
6312
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006313 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006315 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 if (wn != NULL)
6317 {
6318 f = _wopen(wn, flags, mode);
6319 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006320 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321 return f;
6322 /* Retry with non-wide function (for Windows 98). Can't use
6323 * GetLastError() here and it's unclear what errno gets set to if
6324 * the _wopen() fails for missing wide functions. */
6325 }
6326 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006327# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006329 /* open() can open a file which name is longer than _MAX_PATH bytes
6330 * and shorter than _MAX_PATH characters successfully, but sometimes it
6331 * causes unexpected error in another part. We make it an error explicitly
6332 * here. */
6333 if (strlen(name) >= _MAX_PATH)
6334 return -1;
6335
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 return open(name, flags, mode);
6337}
6338
6339/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006340 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341 */
6342 FILE *
6343mch_fopen(char *name, char *mode)
6344{
6345 WCHAR *wn, *wm;
6346 FILE *f = NULL;
6347
6348 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6349# ifdef __BORLANDC__
6350 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6351 && g_PlatformId == VER_PLATFORM_WIN32_NT
6352# endif
6353 )
6354 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006355# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006356 /* Work around an annoying assertion in the Microsoft debug CRT
6357 * when mode's text/binary setting doesn't match _get_fmode(). */
6358 char newMode = mode[strlen(mode) - 1];
6359 int oldMode = 0;
6360
6361 _get_fmode(&oldMode);
6362 if (newMode == 't')
6363 _set_fmode(_O_TEXT);
6364 else if (newMode == 'b')
6365 _set_fmode(_O_BINARY);
6366# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006367 wn = enc_to_utf16(name, NULL);
6368 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369 if (wn != NULL && wm != NULL)
6370 f = _wfopen(wn, wm);
6371 vim_free(wn);
6372 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006373
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006374# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006375 _set_fmode(oldMode);
6376# endif
6377
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006378 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 return f;
6380 /* Retry with non-wide function (for Windows 98). Can't use
6381 * GetLastError() here and it's unclear what errno gets set to if
6382 * the _wfopen() fails for missing wide functions. */
6383 }
6384
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006385 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6386 * and shorter than _MAX_PATH characters successfully, but sometimes it
6387 * causes unexpected error in another part. We make it an error explicitly
6388 * here. */
6389 if (strlen(name) >= _MAX_PATH)
6390 return NULL;
6391
Bram Moolenaar071d4272004-06-13 20:20:40 +00006392 return fopen(name, mode);
6393}
6394#endif
6395
6396#ifdef FEAT_MBYTE
6397/*
6398 * SUB STREAM (aka info stream) handling:
6399 *
6400 * NTFS can have sub streams for each file. Normal contents of file is
6401 * stored in the main stream, and extra contents (author information and
6402 * title and so on) can be stored in sub stream. After Windows 2000, user
6403 * can access and store those informations in sub streams via explorer's
6404 * property menuitem in right click menu. Those informations in sub streams
6405 * were lost when copying only the main stream. So we have to copy sub
6406 * streams.
6407 *
6408 * Incomplete explanation:
6409 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6410 * More useful info and an example:
6411 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6412 */
6413
6414/*
6415 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6416 * and write to stream "substream" of file "to".
6417 * Errors are ignored.
6418 */
6419 static void
6420copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6421{
6422 HANDLE hTo;
6423 WCHAR *to_name;
6424
6425 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6426 wcscpy(to_name, to);
6427 wcscat(to_name, substream);
6428
6429 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6430 FILE_ATTRIBUTE_NORMAL, NULL);
6431 if (hTo != INVALID_HANDLE_VALUE)
6432 {
6433 long done;
6434 DWORD todo;
6435 DWORD readcnt, written;
6436 char buf[4096];
6437
6438 /* Copy block of bytes at a time. Abort when something goes wrong. */
6439 for (done = 0; done < len; done += written)
6440 {
6441 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006442 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6443 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6445 FALSE, FALSE, context)
6446 || readcnt != todo
6447 || !WriteFile(hTo, buf, todo, &written, NULL)
6448 || written != todo)
6449 break;
6450 }
6451 CloseHandle(hTo);
6452 }
6453
6454 free(to_name);
6455}
6456
6457/*
6458 * Copy info streams from file "from" to file "to".
6459 */
6460 static void
6461copy_infostreams(char_u *from, char_u *to)
6462{
6463 WCHAR *fromw;
6464 WCHAR *tow;
6465 HANDLE sh;
6466 WIN32_STREAM_ID sid;
6467 int headersize;
6468 WCHAR streamname[_MAX_PATH];
6469 DWORD readcount;
6470 void *context = NULL;
6471 DWORD lo, hi;
6472 int len;
6473
6474 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006475 fromw = enc_to_utf16(from, NULL);
6476 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477 if (fromw != NULL && tow != NULL)
6478 {
6479 /* Open the file for reading. */
6480 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6481 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6482 if (sh != INVALID_HANDLE_VALUE)
6483 {
6484 /* Use BackupRead() to find the info streams. Repeat until we
6485 * have done them all.*/
6486 for (;;)
6487 {
6488 /* Get the header to find the length of the stream name. If
6489 * the "readcount" is zero we have done all info streams. */
6490 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006491 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6493 &readcount, FALSE, FALSE, &context)
6494 || readcount == 0)
6495 break;
6496
6497 /* We only deal with streams that have a name. The normal
6498 * file data appears to be without a name, even though docs
6499 * suggest it is called "::$DATA". */
6500 if (sid.dwStreamNameSize > 0)
6501 {
6502 /* Read the stream name. */
6503 if (!BackupRead(sh, (LPBYTE)streamname,
6504 sid.dwStreamNameSize,
6505 &readcount, FALSE, FALSE, &context))
6506 break;
6507
6508 /* Copy an info stream with a name ":anything:$DATA".
6509 * Skip "::$DATA", it has no stream name (examples suggest
6510 * it might be used for the normal file contents).
6511 * Note that BackupRead() counts bytes, but the name is in
6512 * wide characters. */
6513 len = readcount / sizeof(WCHAR);
6514 streamname[len] = 0;
6515 if (len > 7 && wcsicmp(streamname + len - 6,
6516 L":$DATA") == 0)
6517 {
6518 streamname[len - 6] = 0;
6519 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006520 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 }
6522 }
6523
6524 /* Advance to the next stream. We might try seeking too far,
6525 * but BackupSeek() doesn't skip over stream borders, thus
6526 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006527 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528 &lo, &hi, &context);
6529 }
6530
6531 /* Clear the context. */
6532 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6533
6534 CloseHandle(sh);
6535 }
6536 }
6537 vim_free(fromw);
6538 vim_free(tow);
6539}
6540#endif
6541
6542/*
6543 * Copy file attributes from file "from" to file "to".
6544 * For Windows NT and later we copy info streams.
6545 * Always returns zero, errors are ignored.
6546 */
6547 int
6548mch_copy_file_attribute(char_u *from, char_u *to)
6549{
6550#ifdef FEAT_MBYTE
6551 /* File streams only work on Windows NT and later. */
6552 PlatformId();
6553 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6554 copy_infostreams(from, to);
6555#endif
6556 return 0;
6557}
6558
6559#if defined(MYRESETSTKOFLW) || defined(PROTO)
6560/*
6561 * Recreate a destroyed stack guard page in win32.
6562 * Written by Benjamin Peterson.
6563 */
6564
6565/* These magic numbers are from the MS header files */
6566#define MIN_STACK_WIN9X 17
6567#define MIN_STACK_WINNT 2
6568
6569/*
6570 * This function does the same thing as _resetstkoflw(), which is only
6571 * available in DevStudio .net and later.
6572 * Returns 0 for failure, 1 for success.
6573 */
6574 int
6575myresetstkoflw(void)
6576{
6577 BYTE *pStackPtr;
6578 BYTE *pGuardPage;
6579 BYTE *pStackBase;
6580 BYTE *pLowestPossiblePage;
6581 MEMORY_BASIC_INFORMATION mbi;
6582 SYSTEM_INFO si;
6583 DWORD nPageSize;
6584 DWORD dummy;
6585
6586 /* This code will not work on win32s. */
6587 PlatformId();
6588 if (g_PlatformId == VER_PLATFORM_WIN32s)
6589 return 0;
6590
6591 /* We need to know the system page size. */
6592 GetSystemInfo(&si);
6593 nPageSize = si.dwPageSize;
6594
6595 /* ...and the current stack pointer */
6596 pStackPtr = (BYTE*)_alloca(1);
6597
6598 /* ...and the base of the stack. */
6599 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6600 return 0;
6601 pStackBase = (BYTE*)mbi.AllocationBase;
6602
6603 /* ...and the page thats min_stack_req pages away from stack base; this is
6604 * the lowest page we could use. */
6605 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6606 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6607
6608 /* On Win95, we want the next page down from the end of the stack. */
6609 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6610 {
6611 /* Find the page that's only 1 page down from the page that the stack
6612 * ptr is in. */
6613 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6614 / (DWORD)nPageSize) - 1));
6615 if (pGuardPage < pLowestPossiblePage)
6616 return 0;
6617
6618 /* Apply the noaccess attribute to the page -- there's no guard
6619 * attribute in win95-type OSes. */
6620 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6621 return 0;
6622 }
6623 else
6624 {
6625 /* On NT, however, we want the first committed page in the stack Start
6626 * at the stack base and move forward through memory until we find a
6627 * committed block. */
6628 BYTE *pBlock = pStackBase;
6629
Bram Moolenaara466c992005-07-09 21:03:22 +00006630 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 {
6632 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6633 return 0;
6634
6635 pBlock += mbi.RegionSize;
6636
6637 if (mbi.State & MEM_COMMIT)
6638 break;
6639 }
6640
6641 /* mbi now describes the first committed block in the stack. */
6642 if (mbi.Protect & PAGE_GUARD)
6643 return 1;
6644
6645 /* decide where the guard page should start */
6646 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6647 pGuardPage = pLowestPossiblePage;
6648 else
6649 pGuardPage = (BYTE*)mbi.BaseAddress;
6650
6651 /* allocate the guard page */
6652 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6653 return 0;
6654
6655 /* apply the guard attribute to the page */
6656 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6657 &dummy))
6658 return 0;
6659 }
6660
6661 return 1;
6662}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006663#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006665
6666#if defined(FEAT_MBYTE) || defined(PROTO)
6667/*
6668 * The command line arguments in UCS2
6669 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006670static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006671static LPWSTR *ArglistW = NULL;
6672static int global_argc = 0;
6673static char **global_argv;
6674
6675static int used_file_argc = 0; /* last argument in global_argv[] used
6676 for the argument list. */
6677static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6678 command line arguments added to
6679 the argument list */
6680static int used_file_count = 0; /* nr of entries in used_file_indexes */
6681static int used_file_literal = FALSE; /* take file names literally */
6682static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006683static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006684static int used_alist_count = 0;
6685
6686
6687/*
6688 * Get the command line arguments. Unicode version.
6689 * Returns argc. Zero when something fails.
6690 */
6691 int
6692get_cmd_argsW(char ***argvp)
6693{
6694 char **argv = NULL;
6695 int argc = 0;
6696 int i;
6697
Bram Moolenaar14993322014-09-09 12:25:33 +02006698 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006699 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6700 if (ArglistW != NULL)
6701 {
6702 argv = malloc((nArgsW + 1) * sizeof(char *));
6703 if (argv != NULL)
6704 {
6705 argc = nArgsW;
6706 argv[argc] = NULL;
6707 for (i = 0; i < argc; ++i)
6708 {
6709 int len;
6710
6711 /* Convert each Unicode argument to the current codepage. */
6712 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006713 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006714 (LPSTR *)&argv[i], &len, 0, 0);
6715 if (argv[i] == NULL)
6716 {
6717 /* Out of memory, clear everything. */
6718 while (i > 0)
6719 free(argv[--i]);
6720 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006721 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006722 argc = 0;
6723 }
6724 }
6725 }
6726 }
6727
6728 global_argc = argc;
6729 global_argv = argv;
6730 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006731 {
6732 if (used_file_indexes != NULL)
6733 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006734 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006735 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006736
6737 if (argvp != NULL)
6738 *argvp = argv;
6739 return argc;
6740}
6741
6742 void
6743free_cmd_argsW(void)
6744{
6745 if (ArglistW != NULL)
6746 {
6747 GlobalFree(ArglistW);
6748 ArglistW = NULL;
6749 }
6750}
6751
6752/*
6753 * Remember "name" is an argument that was added to the argument list.
6754 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6755 * is called.
6756 */
6757 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006758used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006759{
6760 int i;
6761
6762 if (used_file_indexes == NULL)
6763 return;
6764 for (i = used_file_argc + 1; i < global_argc; ++i)
6765 if (STRCMP(global_argv[i], name) == 0)
6766 {
6767 used_file_argc = i;
6768 used_file_indexes[used_file_count++] = i;
6769 break;
6770 }
6771 used_file_literal = literal;
6772 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006773 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006774}
6775
6776/*
6777 * Remember the length of the argument list as it was. If it changes then we
6778 * leave it alone when 'encoding' is set.
6779 */
6780 void
6781set_alist_count(void)
6782{
6783 used_alist_count = GARGCOUNT;
6784}
6785
6786/*
6787 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6788 * has been changed while starting up. Use the UCS-2 command line arguments
6789 * and convert them to 'encoding'.
6790 */
6791 void
6792fix_arg_enc(void)
6793{
6794 int i;
6795 int idx;
6796 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006797 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006798
6799 /* Safety checks:
6800 * - if argument count differs between the wide and non-wide argument
6801 * list, something must be wrong.
6802 * - the file name arguments must have been located.
6803 * - the length of the argument list wasn't changed by the user.
6804 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006805 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006806 || ArglistW == NULL
6807 || used_file_indexes == NULL
6808 || used_file_count == 0
6809 || used_alist_count != GARGCOUNT)
6810 return;
6811
Bram Moolenaar86b68352004-12-27 21:59:20 +00006812 /* Remember the buffer numbers for the arguments. */
6813 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6814 if (fnum_list == NULL)
6815 return; /* out of memory */
6816 for (i = 0; i < GARGCOUNT; ++i)
6817 fnum_list[i] = GARGLIST[i].ae_fnum;
6818
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006819 /* Clear the argument list. Make room for the new arguments. */
6820 alist_clear(&global_alist);
6821 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006822 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006823
6824 for (i = 0; i < used_file_count; ++i)
6825 {
6826 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006827 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006828 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006829 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006830#ifdef FEAT_DIFF
6831 /* When using diff mode may need to concatenate file name to
6832 * directory name. Just like it's done in main(). */
6833 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6834 && !mch_isdir(alist_name(&GARGLIST[0])))
6835 {
6836 char_u *r;
6837
6838 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6839 if (r != NULL)
6840 {
6841 vim_free(str);
6842 str = r;
6843 }
6844 }
6845#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006846 /* Re-use the old buffer by renaming it. When not using literal
6847 * names it's done by alist_expand() below. */
6848 if (used_file_literal)
6849 buf_set_name(fnum_list[i], str);
6850
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006851 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006852 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006853 }
6854
6855 if (!used_file_literal)
6856 {
6857 /* Now expand wildcards in the arguments. */
6858 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6859 * filename characters but are excluded from 'isfname' to make
6860 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6861 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006862 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006863 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6864 }
6865
6866 /* If wildcard expansion failed, we are editing the first file of the
6867 * arglist and there is no file name: Edit the first argument now. */
6868 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6869 {
6870 do_cmdline_cmd((char_u *)":rewind");
6871 if (GARGCOUNT == 1 && used_file_full_path)
6872 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6873 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006874
6875 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006876}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877#endif