blob: da05e6ea3a01d8d10111fee1dba44ce208f9b86e [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 Moolenaar286eacd2016-01-16 18:05:50 +0100503 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
504 if (!hLibintlDLL)
505 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506 if (!hLibintlDLL)
507 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200508 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200510 verbose_enter();
511 EMSG2(_(e_loadlib), GETTEXT_DLL);
512 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000513 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200514 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515 }
516 for (i = 0; libintl_entry[i].name != NULL
517 && libintl_entry[i].ptr != NULL; ++i)
518 {
519 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
520 libintl_entry[i].name)) == NULL)
521 {
522 dyn_libintl_end();
523 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000524 {
525 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000527 verbose_leave();
528 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529 return 0;
530 }
531 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000532
533 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000534 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000535 "bind_textdomain_codeset");
536 if (dyn_libintl_bind_textdomain_codeset == NULL)
537 dyn_libintl_bind_textdomain_codeset =
538 null_libintl_bind_textdomain_codeset;
539
Bram Moolenaar071d4272004-06-13 20:20:40 +0000540 return 1;
541}
542
543 void
544dyn_libintl_end()
545{
546 if (hLibintlDLL)
547 FreeLibrary(hLibintlDLL);
548 hLibintlDLL = NULL;
549 dyn_libintl_gettext = null_libintl_gettext;
550 dyn_libintl_textdomain = null_libintl_textdomain;
551 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000552 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000553}
554
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000555/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000556 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000557null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558{
559 return (char*)msgid;
560}
561
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000562/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000563 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000564null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565{
566 return NULL;
567}
568
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000569/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000571null_libintl_bind_textdomain_codeset(const char *domainname,
572 const char *codeset)
573{
574 return NULL;
575}
576
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000577/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000578 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000579null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000580{
581 return NULL;
582}
583
584#endif /* DYNAMIC_GETTEXT */
585
586/* This symbol is not defined in older versions of the SDK or Visual C++ */
587
588#ifndef VER_PLATFORM_WIN32_WINDOWS
589# define VER_PLATFORM_WIN32_WINDOWS 1
590#endif
591
592DWORD g_PlatformId;
593
594#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100595# ifndef PROTO
596# include <aclapi.h>
597# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200598# ifndef PROTECTED_DACL_SECURITY_INFORMATION
599# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
600# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100601
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602/*
603 * These are needed to dynamically load the ADVAPI DLL, which is not
604 * implemented under Windows 95 (and causes VIM to crash)
605 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200606typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000607 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200608typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
610 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200611# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200612typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200613 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200614typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200615 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
616 PSECURITY_DESCRIPTOR *);
617# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618
619static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
620static PSNSECINFO pSetNamedSecurityInfo;
621static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200622# ifdef FEAT_MBYTE
623static PSNSECINFOW pSetNamedSecurityInfoW;
624static PGNSECINFOW pGetNamedSecurityInfoW;
625# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626#endif
627
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200628typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
629
630static BOOL allowPiping = FALSE;
631static PSETHANDLEINFORMATION pSetHandleInformation;
632
Bram Moolenaar27515922013-06-29 15:36:26 +0200633#ifdef HAVE_ACL
634/*
635 * Enables or disables the specified privilege.
636 */
637 static BOOL
638win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
639{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100640 BOOL bResult;
641 LUID luid;
642 HANDLE hToken;
643 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200644
645 if (!OpenProcessToken(GetCurrentProcess(),
646 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
647 return FALSE;
648
649 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
650 {
651 CloseHandle(hToken);
652 return FALSE;
653 }
654
Bram Moolenaar45500912014-07-09 20:51:07 +0200655 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200656 tokenPrivileges.Privileges[0].Luid = luid;
657 tokenPrivileges.Privileges[0].Attributes = bEnable ?
658 SE_PRIVILEGE_ENABLED : 0;
659
660 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
661 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
662
663 CloseHandle(hToken);
664
665 return bResult && GetLastError() == ERROR_SUCCESS;
666}
667#endif
668
Bram Moolenaar071d4272004-06-13 20:20:40 +0000669/*
670 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
671 * VER_PLATFORM_WIN32_WINDOWS (Win95).
672 */
673 void
674PlatformId(void)
675{
676 static int done = FALSE;
677
678 if (!done)
679 {
680 OSVERSIONINFO ovi;
681
682 ovi.dwOSVersionInfoSize = sizeof(ovi);
683 GetVersionEx(&ovi);
684
685 g_PlatformId = ovi.dwPlatformId;
686
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100687 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
688 || ovi.dwMajorVersion > 6)
689 win8_or_later = TRUE;
690
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691#ifdef HAVE_ACL
692 /*
693 * Load the ADVAPI runtime if we are on anything
694 * other than Windows 95
695 */
696 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
697 {
698 /*
699 * do this load. Problems: Doesn't unload at end of run (this is
700 * theoretically okay, since Windows should unload it when VIM
701 * terminates). Should we be using the 'mch_libcall' routines?
702 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
703 * time we verify security...
704 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200705 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000706 if (advapi_lib != NULL)
707 {
708 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
709 "SetNamedSecurityInfoA");
710 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
711 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200712# ifdef FEAT_MBYTE
713 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
714 "SetNamedSecurityInfoW");
715 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
716 "GetNamedSecurityInfoW");
717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200719 || pGetNamedSecurityInfo == NULL
720# ifdef FEAT_MBYTE
721 || pSetNamedSecurityInfoW == NULL
722 || pGetNamedSecurityInfoW == NULL
723# endif
724 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 {
726 /* If we can't get the function addresses, set advapi_lib
727 * to NULL so that we don't use them. */
728 FreeLibrary(advapi_lib);
729 advapi_lib = NULL;
730 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200731 /* Enable privilege for getting or setting SACLs. */
732 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000733 }
734 }
735#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200736 /*
737 * If we are on windows NT, try to load the pipe functions, only
738 * available from Win2K.
739 */
740 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
741 {
742 HANDLE kernel32 = GetModuleHandle("kernel32");
743 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
744 kernel32, "SetHandleInformation");
745
746 allowPiping = pSetHandleInformation != NULL;
747 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 done = TRUE;
749 }
750}
751
752/*
753 * Return TRUE when running on Windows 95 (or 98 or ME).
754 * Only to be used after mch_init().
755 */
756 int
757mch_windows95(void)
758{
759 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
760}
761
762#ifdef FEAT_GUI_W32
763/*
764 * Used to work around the "can't do synchronous spawn"
765 * problem on Win32s, without resorting to Universal Thunk.
766 */
767static int old_num_windows;
768static int num_windows;
769
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000770/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771 static BOOL CALLBACK
772win32ssynch_cb(HWND hwnd, LPARAM lparam)
773{
774 num_windows++;
775 return TRUE;
776}
777#endif
778
779#ifndef FEAT_GUI_W32
780
781#define SHIFT (SHIFT_PRESSED)
782#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
783#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
784#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
785
786
787/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
788 * We map function keys to their ANSI terminal equivalents, as produced
789 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
790 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
791 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
792 * combinations of function/arrow/etc keys.
793 */
794
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000795static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796{
797 WORD wVirtKey;
798 BOOL fAnsiKey;
799 int chAlone;
800 int chShift;
801 int chCtrl;
802 int chAlt;
803} VirtKeyMap[] =
804{
805
806/* Key ANSI alone shift ctrl alt */
807 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
808
809 { VK_F1, TRUE, ';', 'T', '^', 'h', },
810 { VK_F2, TRUE, '<', 'U', '_', 'i', },
811 { VK_F3, TRUE, '=', 'V', '`', 'j', },
812 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
813 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
814 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
815 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
816 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
817 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
818 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
819 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
820 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
821
822 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
823 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
824 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
825 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
826 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
827 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
828 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
829 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
830 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
831 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
832
833 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
834
835#if 0
836 /* Most people don't have F13-F20, but what the hell... */
837 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
838 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
839 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
840 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
841 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
842 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
843 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
844 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
845#endif
846 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
847 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
848 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
849 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
850
851 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
852 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
853 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
854 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
855 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
856 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
857 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
858 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
859 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
860 /* Sorry, out of number space! <negri>*/
861 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
862
863};
864
865
866#ifdef _MSC_VER
867// The ToAscii bug destroys several registers. Need to turn off optimization
868// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000869# pragma warning(push)
870# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871# pragma optimize("", off)
872#endif
873
874#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200875# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200877# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878#endif
879
880/* The return code indicates key code size. */
881 static int
882#ifdef __BORLANDC__
883 __stdcall
884#endif
885win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000886 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887{
888 UINT uMods = pker->dwControlKeyState;
889 static int s_iIsDead = 0;
890 static WORD awAnsiCode[2];
891 static BYTE abKeystate[256];
892
893
894 if (s_iIsDead == 2)
895 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200896 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897 s_iIsDead = 0;
898 return 1;
899 }
900
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200901 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902 return 1;
903
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200904 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905
906 // Should only be non-NULL on NT 4.0
907 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
908 {
909 CHAR szKLID[KL_NAMELENGTH];
910
911 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
912 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
913 }
914
915 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200916 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917
918 if (uMods & SHIFT_PRESSED)
919 abKeystate[VK_SHIFT] = 0x80;
920 if (uMods & CAPSLOCK_ON)
921 abKeystate[VK_CAPITAL] = 1;
922
923 if ((uMods & ALT_GR) == ALT_GR)
924 {
925 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
926 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
927 }
928
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200929 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
930 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931
932 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200933 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934
935 return s_iIsDead;
936}
937
938#ifdef _MSC_VER
939/* MUST switch optimization on again here, otherwise a call to
940 * decode_key_event() may crash (e.g. when hitting caps-lock) */
941# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000942# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000943
944# if (_MSC_VER < 1100)
945/* MUST turn off global optimisation for this next function, or
946 * pressing ctrl-minus in insert mode crashes Vim when built with
947 * VC4.1. -- negri. */
948# pragma optimize("g", off)
949# endif
950#endif
951
952static BOOL g_fJustGotFocus = FALSE;
953
954/*
955 * Decode a KEY_EVENT into one or two keystrokes
956 */
957 static BOOL
958decode_key_event(
959 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200960 WCHAR *pch,
961 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962 int *pmodifiers,
963 BOOL fDoPost)
964{
965 int i;
966 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
967
968 *pch = *pch2 = NUL;
969 g_fJustGotFocus = FALSE;
970
971 /* ignore key up events */
972 if (!pker->bKeyDown)
973 return FALSE;
974
975 /* ignore some keystrokes */
976 switch (pker->wVirtualKeyCode)
977 {
978 /* modifiers */
979 case VK_SHIFT:
980 case VK_CONTROL:
981 case VK_MENU: /* Alt key */
982 return FALSE;
983
984 default:
985 break;
986 }
987
988 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200989 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990 {
991 /* Ctrl-6 is Ctrl-^ */
992 if (pker->wVirtualKeyCode == '6')
993 {
994 *pch = Ctrl_HAT;
995 return TRUE;
996 }
997 /* Ctrl-2 is Ctrl-@ */
998 else if (pker->wVirtualKeyCode == '2')
999 {
1000 *pch = NUL;
1001 return TRUE;
1002 }
1003 /* Ctrl-- is Ctrl-_ */
1004 else if (pker->wVirtualKeyCode == 0xBD)
1005 {
1006 *pch = Ctrl__;
1007 return TRUE;
1008 }
1009 }
1010
1011 /* Shift-TAB */
1012 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1013 {
1014 *pch = K_NUL;
1015 *pch2 = '\017';
1016 return TRUE;
1017 }
1018
1019 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1020 {
1021 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1022 {
1023 if (nModifs == 0)
1024 *pch = VirtKeyMap[i].chAlone;
1025 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1026 *pch = VirtKeyMap[i].chShift;
1027 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1028 *pch = VirtKeyMap[i].chCtrl;
1029 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1030 *pch = VirtKeyMap[i].chAlt;
1031
1032 if (*pch != 0)
1033 {
1034 if (VirtKeyMap[i].fAnsiKey)
1035 {
1036 *pch2 = *pch;
1037 *pch = K_NUL;
1038 }
1039
1040 return TRUE;
1041 }
1042 }
1043 }
1044
1045 i = win32_kbd_patch_key(pker);
1046
1047 if (i < 0)
1048 *pch = NUL;
1049 else
1050 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001051 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001052
1053 if (pmodifiers != NULL)
1054 {
1055 /* Pass on the ALT key as a modifier, but only when not combined
1056 * with CTRL (which is ALTGR). */
1057 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1058 *pmodifiers |= MOD_MASK_ALT;
1059
1060 /* Pass on SHIFT only for special keys, because we don't know when
1061 * it's already included with the character. */
1062 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1063 *pmodifiers |= MOD_MASK_SHIFT;
1064
1065 /* Pass on CTRL only for non-special keys, because we don't know
1066 * when it's already included with the character. And not when
1067 * combined with ALT (which is ALTGR). */
1068 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1069 && *pch >= 0x20 && *pch < 0x80)
1070 *pmodifiers |= MOD_MASK_CTRL;
1071 }
1072 }
1073
1074 return (*pch != NUL);
1075}
1076
1077#ifdef _MSC_VER
1078# pragma optimize("", on)
1079#endif
1080
1081#endif /* FEAT_GUI_W32 */
1082
1083
1084#ifdef FEAT_MOUSE
1085
1086/*
1087 * For the GUI the mouse handling is in gui_w32.c.
1088 */
1089# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001090/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001092mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093{
1094}
1095# else
1096static int g_fMouseAvail = FALSE; /* mouse present */
1097static int g_fMouseActive = FALSE; /* mouse enabled */
1098static int g_nMouseClick = -1; /* mouse status */
1099static int g_xMouse; /* mouse x coordinate */
1100static int g_yMouse; /* mouse y coordinate */
1101
1102/*
1103 * Enable or disable mouse input
1104 */
1105 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001106mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107{
1108 DWORD cmodein;
1109
1110 if (!g_fMouseAvail)
1111 return;
1112
1113 g_fMouseActive = on;
1114 GetConsoleMode(g_hConIn, &cmodein);
1115
1116 if (g_fMouseActive)
1117 cmodein |= ENABLE_MOUSE_INPUT;
1118 else
1119 cmodein &= ~ENABLE_MOUSE_INPUT;
1120
1121 SetConsoleMode(g_hConIn, cmodein);
1122}
1123
1124
1125/*
1126 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1127 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1128 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1129 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1130 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1131 * and we return the mouse position in g_xMouse and g_yMouse.
1132 *
1133 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1134 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1135 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1136 *
1137 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1138 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1139 *
1140 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1141 * moves, even if it stays within the same character cell. We ignore
1142 * all MOUSE_MOVED messages if the position hasn't really changed, and
1143 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1144 * we're only interested in MOUSE_DRAG).
1145 *
1146 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1147 * 2-button mouses by pressing the left & right buttons simultaneously.
1148 * In practice, it's almost impossible to click both at the same time,
1149 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1150 * in such cases, if the user is clicking quickly.
1151 */
1152 static BOOL
1153decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001154 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155{
1156 static int s_nOldButton = -1;
1157 static int s_nOldMouseClick = -1;
1158 static int s_xOldMouse = -1;
1159 static int s_yOldMouse = -1;
1160 static linenr_T s_old_topline = 0;
1161#ifdef FEAT_DIFF
1162 static int s_old_topfill = 0;
1163#endif
1164 static int s_cClicks = 1;
1165 static BOOL s_fReleased = TRUE;
1166 static DWORD s_dwLastClickTime = 0;
1167 static BOOL s_fNextIsMiddle = FALSE;
1168
1169 static DWORD cButtons = 0; /* number of buttons supported */
1170
1171 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1172 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1173 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1174 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1175
1176 int nButton;
1177
1178 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1179 cButtons = 2;
1180
1181 if (!g_fMouseAvail || !g_fMouseActive)
1182 {
1183 g_nMouseClick = -1;
1184 return FALSE;
1185 }
1186
1187 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1188 if (g_fJustGotFocus)
1189 {
1190 g_fJustGotFocus = FALSE;
1191 return FALSE;
1192 }
1193
1194 /* unprocessed mouse click? */
1195 if (g_nMouseClick != -1)
1196 return TRUE;
1197
1198 nButton = -1;
1199 g_xMouse = pmer->dwMousePosition.X;
1200 g_yMouse = pmer->dwMousePosition.Y;
1201
1202 if (pmer->dwEventFlags == MOUSE_MOVED)
1203 {
1204 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1205 * events even when the mouse moves only within a char cell.) */
1206 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1207 return FALSE;
1208 }
1209
1210 /* If no buttons are pressed... */
1211 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1212 {
1213 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1214 if (s_fReleased)
1215 return FALSE;
1216
1217 nButton = MOUSE_RELEASE;
1218 s_fReleased = TRUE;
1219 }
1220 else /* one or more buttons pressed */
1221 {
1222 /* on a 2-button mouse, hold down left and right buttons
1223 * simultaneously to get MIDDLE. */
1224
1225 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1226 {
1227 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1228
1229 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001230 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231 if (dwLR == LEFT || dwLR == RIGHT)
1232 {
1233 for (;;)
1234 {
1235 /* wait a short time for next input event */
1236 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1237 != WAIT_OBJECT_0)
1238 break;
1239 else
1240 {
1241 DWORD cRecords = 0;
1242 INPUT_RECORD ir;
1243 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1244
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001245 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246
1247 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1248 || !(pmer2->dwButtonState & LEFT_RIGHT))
1249 break;
1250 else
1251 {
1252 if (pmer2->dwEventFlags != MOUSE_MOVED)
1253 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001254 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255
1256 return decode_mouse_event(pmer2);
1257 }
1258 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1259 s_yOldMouse == pmer2->dwMousePosition.Y)
1260 {
1261 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001262 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001263
1264 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001265 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266
1267 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1268 break;
1269 }
1270 else
1271 break;
1272 }
1273 }
1274 }
1275 }
1276 }
1277
1278 if (s_fNextIsMiddle)
1279 {
1280 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1281 ? MOUSE_DRAG : MOUSE_MIDDLE;
1282 s_fNextIsMiddle = FALSE;
1283 }
1284 else if (cButtons == 2 &&
1285 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1286 {
1287 nButton = MOUSE_MIDDLE;
1288
1289 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1290 {
1291 s_fNextIsMiddle = TRUE;
1292 nButton = MOUSE_RELEASE;
1293 }
1294 }
1295 else if ((pmer->dwButtonState & LEFT) == LEFT)
1296 nButton = MOUSE_LEFT;
1297 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1298 nButton = MOUSE_MIDDLE;
1299 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1300 nButton = MOUSE_RIGHT;
1301
1302 if (! s_fReleased && ! s_fNextIsMiddle
1303 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1304 return FALSE;
1305
1306 s_fReleased = s_fNextIsMiddle;
1307 }
1308
1309 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1310 {
1311 /* button pressed or released, without mouse moving */
1312 if (nButton != -1 && nButton != MOUSE_RELEASE)
1313 {
1314 DWORD dwCurrentTime = GetTickCount();
1315
1316 if (s_xOldMouse != g_xMouse
1317 || s_yOldMouse != g_yMouse
1318 || s_nOldButton != nButton
1319 || s_old_topline != curwin->w_topline
1320#ifdef FEAT_DIFF
1321 || s_old_topfill != curwin->w_topfill
1322#endif
1323 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1324 {
1325 s_cClicks = 1;
1326 }
1327 else if (++s_cClicks > 4)
1328 {
1329 s_cClicks = 1;
1330 }
1331
1332 s_dwLastClickTime = dwCurrentTime;
1333 }
1334 }
1335 else if (pmer->dwEventFlags == MOUSE_MOVED)
1336 {
1337 if (nButton != -1 && nButton != MOUSE_RELEASE)
1338 nButton = MOUSE_DRAG;
1339
1340 s_cClicks = 1;
1341 }
1342
1343 if (nButton == -1)
1344 return FALSE;
1345
1346 if (nButton != MOUSE_RELEASE)
1347 s_nOldButton = nButton;
1348
1349 g_nMouseClick = nButton;
1350
1351 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1352 g_nMouseClick |= MOUSE_SHIFT;
1353 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1354 g_nMouseClick |= MOUSE_CTRL;
1355 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1356 g_nMouseClick |= MOUSE_ALT;
1357
1358 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1359 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1360
1361 /* only pass on interesting (i.e., different) mouse events */
1362 if (s_xOldMouse == g_xMouse
1363 && s_yOldMouse == g_yMouse
1364 && s_nOldMouseClick == g_nMouseClick)
1365 {
1366 g_nMouseClick = -1;
1367 return FALSE;
1368 }
1369
1370 s_xOldMouse = g_xMouse;
1371 s_yOldMouse = g_yMouse;
1372 s_old_topline = curwin->w_topline;
1373#ifdef FEAT_DIFF
1374 s_old_topfill = curwin->w_topfill;
1375#endif
1376 s_nOldMouseClick = g_nMouseClick;
1377
1378 return TRUE;
1379}
1380
1381# endif /* FEAT_GUI_W32 */
1382#endif /* FEAT_MOUSE */
1383
1384
1385#ifdef MCH_CURSOR_SHAPE
1386/*
1387 * Set the shape of the cursor.
1388 * 'thickness' can be from 1 (thin) to 99 (block)
1389 */
1390 static void
1391mch_set_cursor_shape(int thickness)
1392{
1393 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1394 ConsoleCursorInfo.dwSize = thickness;
1395 ConsoleCursorInfo.bVisible = s_cursor_visible;
1396
1397 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1398 if (s_cursor_visible)
1399 SetConsoleCursorPosition(g_hConOut, g_coord);
1400}
1401
1402 void
1403mch_update_cursor(void)
1404{
1405 int idx;
1406 int thickness;
1407
1408 /*
1409 * How the cursor is drawn depends on the current mode.
1410 */
1411 idx = get_shape_idx(FALSE);
1412
1413 if (shape_table[idx].shape == SHAPE_BLOCK)
1414 thickness = 99; /* 100 doesn't work on W95 */
1415 else
1416 thickness = shape_table[idx].percentage;
1417 mch_set_cursor_shape(thickness);
1418}
1419#endif
1420
1421#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1422/*
1423 * Handle FOCUS_EVENT.
1424 */
1425 static void
1426handle_focus_event(INPUT_RECORD ir)
1427{
1428 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1429 ui_focus_change((int)g_fJustGotFocus);
1430}
1431
1432/*
1433 * Wait until console input from keyboard or mouse is available,
1434 * or the time is up.
1435 * Return TRUE if something is available FALSE if not.
1436 */
1437 static int
1438WaitForChar(long msec)
1439{
1440 DWORD dwNow = 0, dwEndTime = 0;
1441 INPUT_RECORD ir;
1442 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001443 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001444
1445 if (msec > 0)
1446 /* Wait until the specified time has elapsed. */
1447 dwEndTime = GetTickCount() + msec;
1448 else if (msec < 0)
1449 /* Wait forever. */
1450 dwEndTime = INFINITE;
1451
1452 /* We need to loop until the end of the time period, because
1453 * we might get multiple unusable mouse events in that time.
1454 */
1455 for (;;)
1456 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001457#ifdef FEAT_MZSCHEME
1458 mzvim_check_threads();
1459#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460#ifdef FEAT_CLIENTSERVER
1461 serverProcessPendingMessages();
1462#endif
1463 if (0
1464#ifdef FEAT_MOUSE
1465 || g_nMouseClick != -1
1466#endif
1467#ifdef FEAT_CLIENTSERVER
1468 || input_available()
1469#endif
1470 )
1471 return TRUE;
1472
1473 if (msec > 0)
1474 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001475 /* If the specified wait time has passed, return. Beware that
1476 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001477 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001478 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479 break;
1480 }
1481 if (msec != 0)
1482 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001483 DWORD dwWaitTime = dwEndTime - dwNow;
1484
1485#ifdef FEAT_MZSCHEME
1486 if (mzthreads_allowed() && p_mzq > 0
1487 && (msec < 0 || (long)dwWaitTime > p_mzq))
1488 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1489#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490#ifdef FEAT_CLIENTSERVER
1491 /* Wait for either an event on the console input or a message in
1492 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001493 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001494 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001496 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497#endif
1498 continue;
1499 }
1500
1501 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001502 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503
1504#ifdef FEAT_MBYTE_IME
1505 if (State & CMDLINE && msg_row == Rows - 1)
1506 {
1507 CONSOLE_SCREEN_BUFFER_INFO csbi;
1508
1509 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1510 {
1511 if (csbi.dwCursorPosition.Y != msg_row)
1512 {
1513 /* The screen is now messed up, must redraw the
1514 * command line and later all the windows. */
1515 redraw_all_later(CLEAR);
1516 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1517 redrawcmd();
1518 }
1519 }
1520 }
1521#endif
1522
1523 if (cRecords > 0)
1524 {
1525 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1526 {
1527#ifdef FEAT_MBYTE_IME
1528 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1529 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001530 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1532 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001533 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 continue;
1535 }
1536#endif
1537 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1538 NULL, FALSE))
1539 return TRUE;
1540 }
1541
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001542 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543
1544 if (ir.EventType == FOCUS_EVENT)
1545 handle_focus_event(ir);
1546 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1547 shell_resized();
1548#ifdef FEAT_MOUSE
1549 else if (ir.EventType == MOUSE_EVENT
1550 && decode_mouse_event(&ir.Event.MouseEvent))
1551 return TRUE;
1552#endif
1553 }
1554 else if (msec == 0)
1555 break;
1556 }
1557
1558#ifdef FEAT_CLIENTSERVER
1559 /* Something might have been received while we were waiting. */
1560 if (input_available())
1561 return TRUE;
1562#endif
1563 return FALSE;
1564}
1565
1566#ifndef FEAT_GUI_MSWIN
1567/*
1568 * return non-zero if a character is available
1569 */
1570 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001571mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572{
1573 return WaitForChar(0L);
1574}
1575#endif
1576
1577/*
1578 * Create the console input. Used when reading stdin doesn't work.
1579 */
1580 static void
1581create_conin(void)
1582{
1583 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1584 FILE_SHARE_READ|FILE_SHARE_WRITE,
1585 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001586 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587 did_create_conin = TRUE;
1588}
1589
1590/*
1591 * Get a keystroke or a mouse event
1592 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001593 static WCHAR
1594tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001596 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597
1598 for (;;)
1599 {
1600 INPUT_RECORD ir;
1601 DWORD cRecords = 0;
1602
1603#ifdef FEAT_CLIENTSERVER
1604 (void)WaitForChar(-1L);
1605 if (input_available())
1606 return 0;
1607# ifdef FEAT_MOUSE
1608 if (g_nMouseClick != -1)
1609 return 0;
1610# endif
1611#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001612 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 {
1614 if (did_create_conin)
1615 read_error_exit();
1616 create_conin();
1617 continue;
1618 }
1619
1620 if (ir.EventType == KEY_EVENT)
1621 {
1622 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1623 pmodifiers, TRUE))
1624 return ch;
1625 }
1626 else if (ir.EventType == FOCUS_EVENT)
1627 handle_focus_event(ir);
1628 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1629 shell_resized();
1630#ifdef FEAT_MOUSE
1631 else if (ir.EventType == MOUSE_EVENT)
1632 {
1633 if (decode_mouse_event(&ir.Event.MouseEvent))
1634 return 0;
1635 }
1636#endif
1637 }
1638}
1639#endif /* !FEAT_GUI_W32 */
1640
1641
1642/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001643 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644 * Get one or more characters from the keyboard or the mouse.
1645 * If time == 0, do not wait for characters.
1646 * If time == n, wait a short time for characters.
1647 * If time == -1, wait forever for characters.
1648 * Returns the number of characters read into buf.
1649 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001650/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651 int
1652mch_inchar(
1653 char_u *buf,
1654 int maxlen,
1655 long time,
1656 int tb_change_cnt)
1657{
1658#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1659
1660 int len;
1661 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662#define TYPEAHEADLEN 20
1663 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1664 static int typeaheadlen = 0;
1665
1666 /* First use any typeahead that was kept because "buf" was too small. */
1667 if (typeaheadlen > 0)
1668 goto theend;
1669
1670#ifdef FEAT_SNIFF
1671 if (want_sniff_request)
1672 {
1673 if (sniff_request_waiting)
1674 {
1675 /* return K_SNIFF */
1676 typeahead[typeaheadlen++] = CSI;
1677 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1678 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1679 sniff_request_waiting = 0;
1680 want_sniff_request = 0;
1681 goto theend;
1682 }
1683 else if (time < 0 || time > 250)
1684 {
1685 /* don't wait too long, a request might be pending */
1686 time = 250;
1687 }
1688 }
1689#endif
1690
1691 if (time >= 0)
1692 {
1693 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695 }
1696 else /* time == -1, wait forever */
1697 {
1698 mch_set_winsize_now(); /* Allow winsize changes from now on */
1699
Bram Moolenaar3918c952005-03-15 22:34:55 +00001700 /*
1701 * If there is no character available within 2 seconds (default)
1702 * write the autoscript file to disk. Or cause the CursorHold event
1703 * to be triggered.
1704 */
1705 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 {
1707#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001708 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001710 buf[0] = K_SPECIAL;
1711 buf[1] = KS_EXTRA;
1712 buf[2] = (int)KE_CURSORHOLD;
1713 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 }
1715#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001716 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 }
1718 }
1719
1720 /*
1721 * Try to read as many characters as there are, until the buffer is full.
1722 */
1723
1724 /* we will get at least one key. Get more if they are available. */
1725 g_fCBrkPressed = FALSE;
1726
1727#ifdef MCH_WRITE_DUMP
1728 if (fdDump)
1729 fputc('[', fdDump);
1730#endif
1731
1732 /* Keep looping until there is something in the typeahead buffer and more
1733 * to get and still room in the buffer (up to two bytes for a char and
1734 * three bytes for a modifier). */
1735 while ((typeaheadlen == 0 || WaitForChar(0L))
1736 && typeaheadlen + 5 <= TYPEAHEADLEN)
1737 {
1738 if (typebuf_changed(tb_change_cnt))
1739 {
1740 /* "buf" may be invalid now if a client put something in the
1741 * typeahead buffer and "buf" is in the typeahead buffer. */
1742 typeaheadlen = 0;
1743 break;
1744 }
1745#ifdef FEAT_MOUSE
1746 if (g_nMouseClick != -1)
1747 {
1748# ifdef MCH_WRITE_DUMP
1749 if (fdDump)
1750 fprintf(fdDump, "{%02x @ %d, %d}",
1751 g_nMouseClick, g_xMouse, g_yMouse);
1752# endif
1753 typeahead[typeaheadlen++] = ESC + 128;
1754 typeahead[typeaheadlen++] = 'M';
1755 typeahead[typeaheadlen++] = g_nMouseClick;
1756 typeahead[typeaheadlen++] = g_xMouse + '!';
1757 typeahead[typeaheadlen++] = g_yMouse + '!';
1758 g_nMouseClick = -1;
1759 }
1760 else
1761#endif
1762 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001763 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764 int modifiers = 0;
1765
1766 c = tgetch(&modifiers, &ch2);
1767
1768 if (typebuf_changed(tb_change_cnt))
1769 {
1770 /* "buf" may be invalid now if a client put something in the
1771 * typeahead buffer and "buf" is in the typeahead buffer. */
1772 typeaheadlen = 0;
1773 break;
1774 }
1775
1776 if (c == Ctrl_C && ctrl_c_interrupts)
1777 {
1778#if defined(FEAT_CLIENTSERVER)
1779 trash_input_buf();
1780#endif
1781 got_int = TRUE;
1782 }
1783
1784#ifdef FEAT_MOUSE
1785 if (g_nMouseClick == -1)
1786#endif
1787 {
1788 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001789 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001790
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001791#ifdef FEAT_MBYTE
1792 if (ch2 == NUL)
1793 {
1794 int i;
1795 char_u *p;
1796 WCHAR ch[2];
1797
1798 ch[0] = c;
1799 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1800 {
1801 ch[1] = tgetch(&modifiers, &ch2);
1802 n++;
1803 }
1804 p = utf16_to_enc(ch, &n);
1805 if (p != NULL)
1806 {
1807 for (i = 0; i < n; i++)
1808 typeahead[typeaheadlen + i] = p[i];
1809 vim_free(p);
1810 }
1811 }
1812 else
1813#endif
1814 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 if (ch2 != NUL)
1816 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001817 typeahead[typeaheadlen + n] = 3;
1818 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001819 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821
Bram Moolenaar45500912014-07-09 20:51:07 +02001822 if (conv)
1823 {
1824 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001825
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001826 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001827 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001828 char_u *e = typeahead + TYPEAHEADLEN;
1829
1830 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001831 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001832 if (*p == K_NUL)
1833 {
1834 ++p;
1835 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1836 *p = 3;
1837 ++n;
1838 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001839 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001840 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001841 }
1842 }
1843
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 /* Use the ALT key to set the 8th bit of the character
1845 * when it's one byte, the 8th bit isn't set yet and not
1846 * using a double-byte encoding (would become a lead
1847 * byte). */
1848 if ((modifiers & MOD_MASK_ALT)
1849 && n == 1
1850 && (typeahead[typeaheadlen] & 0x80) == 0
1851#ifdef FEAT_MBYTE
1852 && !enc_dbcs
1853#endif
1854 )
1855 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001856#ifdef FEAT_MBYTE
1857 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1858 typeahead + typeaheadlen);
1859#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001860 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001861#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862 modifiers &= ~MOD_MASK_ALT;
1863 }
1864
1865 if (modifiers != 0)
1866 {
1867 /* Prepend modifiers to the character. */
1868 mch_memmove(typeahead + typeaheadlen + 3,
1869 typeahead + typeaheadlen, n);
1870 typeahead[typeaheadlen++] = K_SPECIAL;
1871 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1872 typeahead[typeaheadlen++] = modifiers;
1873 }
1874
1875 typeaheadlen += n;
1876
1877#ifdef MCH_WRITE_DUMP
1878 if (fdDump)
1879 fputc(c, fdDump);
1880#endif
1881 }
1882 }
1883 }
1884
1885#ifdef MCH_WRITE_DUMP
1886 if (fdDump)
1887 {
1888 fputs("]\n", fdDump);
1889 fflush(fdDump);
1890 }
1891#endif
1892
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893theend:
1894 /* Move typeahead to "buf", as much as fits. */
1895 len = 0;
1896 while (len < maxlen && typeaheadlen > 0)
1897 {
1898 buf[len++] = typeahead[0];
1899 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1900 }
1901 return len;
1902
1903#else /* FEAT_GUI_W32 */
1904 return 0;
1905#endif /* FEAT_GUI_W32 */
1906}
1907
Bram Moolenaar82881492012-11-20 16:53:39 +01001908#ifndef PROTO
1909# ifndef __MINGW32__
1910# include <shellapi.h> /* required for FindExecutable() */
1911# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912#endif
1913
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001914/*
1915 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001916 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001917 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001919executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001921 char *dum;
1922 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001923 char *curpath, *newpath;
1924 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001926#ifdef FEAT_MBYTE
1927 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001929 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001930 WCHAR fnamew[_MAX_PATH];
1931 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001932 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001933
1934 if (p != NULL)
1935 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001936 wcurpath = _wgetenv(L"PATH");
1937 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1938 * sizeof(WCHAR));
1939 if (wnewpath == NULL)
1940 return FALSE;
1941 wcscpy(wnewpath, L".;");
1942 wcscat(wnewpath, wcurpath);
1943 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1944 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001945 vim_free(p);
1946 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1947 {
1948 if (n == 0)
1949 return FALSE;
1950 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1951 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001952 if (path != NULL)
1953 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001954 return TRUE;
1955 }
1956 /* Retry with non-wide function (for Windows 98). */
1957 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001958 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001959#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001960
1961 curpath = getenv("PATH");
1962 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1963 if (newpath == NULL)
1964 return FALSE;
1965 STRCPY(newpath, ".;");
1966 STRCAT(newpath, curpath);
1967 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1968 vim_free(newpath);
1969 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001970 return FALSE;
1971 if (mch_isdir(fname))
1972 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001973 if (path != NULL)
1974 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001975 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976}
1977
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001978#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001979 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001980/*
1981 * Bad parameter handler.
1982 *
1983 * Certain MS CRT functions will intentionally crash when passed invalid
1984 * parameters to highlight possible security holes. Setting this function as
1985 * the bad parameter handler will prevent the crash.
1986 *
1987 * In debug builds the parameters contain CRT information that might help track
1988 * down the source of a problem, but in non-debug builds the arguments are all
1989 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1990 * worth allowing these to make debugging of issues easier.
1991 */
1992 static void
1993bad_param_handler(const wchar_t *expression,
1994 const wchar_t *function,
1995 const wchar_t *file,
1996 unsigned int line,
1997 uintptr_t pReserved)
1998{
1999}
2000
2001# define SET_INVALID_PARAM_HANDLER \
2002 ((void)_set_invalid_parameter_handler(bad_param_handler))
2003#else
2004# define SET_INVALID_PARAM_HANDLER
2005#endif
2006
Bram Moolenaar071d4272004-06-13 20:20:40 +00002007#ifdef FEAT_GUI_W32
2008
2009/*
2010 * GUI version of mch_init().
2011 */
2012 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002013mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014{
2015#ifndef __MINGW32__
2016 extern int _fmode;
2017#endif
2018
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002019 /* Silently handle invalid parameters to CRT functions */
2020 SET_INVALID_PARAM_HANDLER;
2021
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022 /* Let critical errors result in a failure, not in a dialog box. Required
2023 * for the timestamp test to work on removed floppies. */
2024 SetErrorMode(SEM_FAILCRITICALERRORS);
2025
2026 _fmode = O_BINARY; /* we do our own CR-LF translation */
2027
2028 /* Specify window size. Is there a place to get the default from? */
2029 Rows = 25;
2030 Columns = 80;
2031
2032 /* Look for 'vimrun' */
2033 if (!gui_is_win32s())
2034 {
2035 char_u vimrun_location[_MAX_PATH + 4];
2036
2037 /* First try in same directory as gvim.exe */
2038 STRCPY(vimrun_location, exe_name);
2039 STRCPY(gettail(vimrun_location), "vimrun.exe");
2040 if (mch_getperm(vimrun_location) >= 0)
2041 {
2042 if (*skiptowhite(vimrun_location) != NUL)
2043 {
2044 /* Enclose path with white space in double quotes. */
2045 mch_memmove(vimrun_location + 1, vimrun_location,
2046 STRLEN(vimrun_location) + 1);
2047 *vimrun_location = '"';
2048 STRCPY(gettail(vimrun_location), "vimrun\" ");
2049 }
2050 else
2051 STRCPY(gettail(vimrun_location), "vimrun ");
2052
2053 vimrun_path = (char *)vim_strsave(vimrun_location);
2054 s_dont_use_vimrun = FALSE;
2055 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002056 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 s_dont_use_vimrun = FALSE;
2058
2059 /* Don't give the warning for a missing vimrun.exe right now, but only
2060 * when vimrun was supposed to be used. Don't bother people that do
2061 * not need vimrun.exe. */
2062 if (s_dont_use_vimrun)
2063 need_vimrun_warning = TRUE;
2064 }
2065
2066 /*
2067 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2068 * Otherwise the default "findstr /n" is used.
2069 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002070 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2072
2073#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002074 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075#endif
2076}
2077
2078
2079#else /* FEAT_GUI_W32 */
2080
2081#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2082#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2083
2084/*
2085 * ClearConsoleBuffer()
2086 * Description:
2087 * Clears the entire contents of the console screen buffer, using the
2088 * specified attribute.
2089 * Returns:
2090 * TRUE on success
2091 */
2092 static BOOL
2093ClearConsoleBuffer(WORD wAttribute)
2094{
2095 CONSOLE_SCREEN_BUFFER_INFO csbi;
2096 COORD coord;
2097 DWORD NumCells, dummy;
2098
2099 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2100 return FALSE;
2101
2102 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2103 coord.X = 0;
2104 coord.Y = 0;
2105 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2106 coord, &dummy))
2107 {
2108 return FALSE;
2109 }
2110 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2111 coord, &dummy))
2112 {
2113 return FALSE;
2114 }
2115
2116 return TRUE;
2117}
2118
2119/*
2120 * FitConsoleWindow()
2121 * Description:
2122 * Checks if the console window will fit within given buffer dimensions.
2123 * Also, if requested, will shrink the window to fit.
2124 * Returns:
2125 * TRUE on success
2126 */
2127 static BOOL
2128FitConsoleWindow(
2129 COORD dwBufferSize,
2130 BOOL WantAdjust)
2131{
2132 CONSOLE_SCREEN_BUFFER_INFO csbi;
2133 COORD dwWindowSize;
2134 BOOL NeedAdjust = FALSE;
2135
2136 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2137 {
2138 /*
2139 * A buffer resize will fail if the current console window does
2140 * not lie completely within that buffer. To avoid this, we might
2141 * have to move and possibly shrink the window.
2142 */
2143 if (csbi.srWindow.Right >= dwBufferSize.X)
2144 {
2145 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2146 if (dwWindowSize.X > dwBufferSize.X)
2147 dwWindowSize.X = dwBufferSize.X;
2148 csbi.srWindow.Right = dwBufferSize.X - 1;
2149 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2150 NeedAdjust = TRUE;
2151 }
2152 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2153 {
2154 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2155 if (dwWindowSize.Y > dwBufferSize.Y)
2156 dwWindowSize.Y = dwBufferSize.Y;
2157 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2158 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2159 NeedAdjust = TRUE;
2160 }
2161 if (NeedAdjust && WantAdjust)
2162 {
2163 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2164 return FALSE;
2165 }
2166 return TRUE;
2167 }
2168
2169 return FALSE;
2170}
2171
2172typedef struct ConsoleBufferStruct
2173{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002174 BOOL IsValid;
2175 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002176 PCHAR_INFO Buffer;
2177 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002178} ConsoleBuffer;
2179
2180/*
2181 * SaveConsoleBuffer()
2182 * Description:
2183 * Saves important information about the console buffer, including the
2184 * actual buffer contents. The saved information is suitable for later
2185 * restoration by RestoreConsoleBuffer().
2186 * Returns:
2187 * TRUE if all information was saved; FALSE otherwise
2188 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2189 */
2190 static BOOL
2191SaveConsoleBuffer(
2192 ConsoleBuffer *cb)
2193{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002194 DWORD NumCells;
2195 COORD BufferCoord;
2196 SMALL_RECT ReadRegion;
2197 WORD Y, Y_incr;
2198
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 if (cb == NULL)
2200 return FALSE;
2201
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002202 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002203 {
2204 cb->IsValid = FALSE;
2205 return FALSE;
2206 }
2207 cb->IsValid = TRUE;
2208
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002209 /*
2210 * Allocate a buffer large enough to hold the entire console screen
2211 * buffer. If this ConsoleBuffer structure has already been initialized
2212 * with a buffer of the correct size, then just use that one.
2213 */
2214 if (!cb->IsValid || cb->Buffer == NULL ||
2215 cb->BufferSize.X != cb->Info.dwSize.X ||
2216 cb->BufferSize.Y != cb->Info.dwSize.Y)
2217 {
2218 cb->BufferSize.X = cb->Info.dwSize.X;
2219 cb->BufferSize.Y = cb->Info.dwSize.Y;
2220 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2221 vim_free(cb->Buffer);
2222 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2223 if (cb->Buffer == NULL)
2224 return FALSE;
2225 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226
2227 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002228 * We will now copy the console screen buffer into our buffer.
2229 * ReadConsoleOutput() seems to be limited as far as how much you
2230 * can read at a time. Empirically, this number seems to be about
2231 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2232 * in chunks until it is all copied. The chunks will all have the
2233 * same horizontal characteristics, so initialize them now. The
2234 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002236 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002237 ReadRegion.Left = 0;
2238 ReadRegion.Right = cb->Info.dwSize.X - 1;
2239 Y_incr = 12000 / cb->Info.dwSize.X;
2240 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002241 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002242 /*
2243 * Read into position (0, Y) in our buffer.
2244 */
2245 BufferCoord.Y = Y;
2246 /*
2247 * Read the region whose top left corner is (0, Y) and whose bottom
2248 * right corner is (width - 1, Y + Y_incr - 1). This should define
2249 * a region of size width by Y_incr. Don't worry if this region is
2250 * too large for the remaining buffer; it will be cropped.
2251 */
2252 ReadRegion.Top = Y;
2253 ReadRegion.Bottom = Y + Y_incr - 1;
2254 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2255 cb->Buffer, /* our buffer */
2256 cb->BufferSize, /* dimensions of our buffer */
2257 BufferCoord, /* offset in our buffer */
2258 &ReadRegion)) /* region to save */
2259 {
2260 vim_free(cb->Buffer);
2261 cb->Buffer = NULL;
2262 return FALSE;
2263 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264 }
2265
2266 return TRUE;
2267}
2268
2269/*
2270 * RestoreConsoleBuffer()
2271 * Description:
2272 * Restores important information about the console buffer, including the
2273 * actual buffer contents, if desired. The information to restore is in
2274 * the same format used by SaveConsoleBuffer().
2275 * Returns:
2276 * TRUE on success
2277 */
2278 static BOOL
2279RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002280 ConsoleBuffer *cb,
2281 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002283 COORD BufferCoord;
2284 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285
2286 if (cb == NULL || !cb->IsValid)
2287 return FALSE;
2288
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002289 /*
2290 * Before restoring the buffer contents, clear the current buffer, and
2291 * restore the cursor position and window information. Doing this now
2292 * prevents old buffer contents from "flashing" onto the screen.
2293 */
2294 if (RestoreScreen)
2295 ClearConsoleBuffer(cb->Info.wAttributes);
2296
2297 FitConsoleWindow(cb->Info.dwSize, TRUE);
2298 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2299 return FALSE;
2300 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2301 return FALSE;
2302
2303 if (!RestoreScreen)
2304 {
2305 /*
2306 * No need to restore the screen buffer contents, so we're done.
2307 */
2308 return TRUE;
2309 }
2310
2311 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2312 return FALSE;
2313 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2314 return FALSE;
2315
2316 /*
2317 * Restore the screen buffer contents.
2318 */
2319 if (cb->Buffer != NULL)
2320 {
2321 BufferCoord.X = 0;
2322 BufferCoord.Y = 0;
2323 WriteRegion.Left = 0;
2324 WriteRegion.Top = 0;
2325 WriteRegion.Right = cb->Info.dwSize.X - 1;
2326 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2327 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2328 cb->Buffer, /* our buffer */
2329 cb->BufferSize, /* dimensions of our buffer */
2330 BufferCoord, /* offset in our buffer */
2331 &WriteRegion)) /* region to restore */
2332 {
2333 return FALSE;
2334 }
2335 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336
2337 return TRUE;
2338}
2339
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002340#define FEAT_RESTORE_ORIG_SCREEN
2341#ifdef FEAT_RESTORE_ORIG_SCREEN
2342static ConsoleBuffer g_cbOrig = { 0 };
2343#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344static ConsoleBuffer g_cbNonTermcap = { 0 };
2345static ConsoleBuffer g_cbTermcap = { 0 };
2346
2347#ifdef FEAT_TITLE
2348#ifdef __BORLANDC__
2349typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2350#else
2351typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2352#endif
2353char g_szOrigTitle[256] = { 0 };
2354HWND g_hWnd = NULL; /* also used in os_mswin.c */
2355static HICON g_hOrigIconSmall = NULL;
2356static HICON g_hOrigIcon = NULL;
2357static HICON g_hVimIcon = NULL;
2358static BOOL g_fCanChangeIcon = FALSE;
2359
2360/* ICON* are not defined in VC++ 4.0 */
2361#ifndef ICON_SMALL
2362#define ICON_SMALL 0
2363#endif
2364#ifndef ICON_BIG
2365#define ICON_BIG 1
2366#endif
2367/*
2368 * GetConsoleIcon()
2369 * Description:
2370 * Attempts to retrieve the small icon and/or the big icon currently in
2371 * use by a given window.
2372 * Returns:
2373 * TRUE on success
2374 */
2375 static BOOL
2376GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002377 HWND hWnd,
2378 HICON *phIconSmall,
2379 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380{
2381 if (hWnd == NULL)
2382 return FALSE;
2383
2384 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002385 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2386 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002388 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2389 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390 return TRUE;
2391}
2392
2393/*
2394 * SetConsoleIcon()
2395 * Description:
2396 * Attempts to change the small icon and/or the big icon currently in
2397 * use by a given window.
2398 * Returns:
2399 * TRUE on success
2400 */
2401 static BOOL
2402SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002403 HWND hWnd,
2404 HICON hIconSmall,
2405 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002407 HICON hPrevIconSmall;
2408 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409
2410 if (hWnd == NULL)
2411 return FALSE;
2412
2413 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002414 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2415 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002417 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2418 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 return TRUE;
2420}
2421
2422/*
2423 * SaveConsoleTitleAndIcon()
2424 * Description:
2425 * Saves the current console window title in g_szOrigTitle, for later
2426 * restoration. Also, attempts to obtain a handle to the console window,
2427 * and use it to save the small and big icons currently in use by the
2428 * console window. This is not always possible on some versions of Windows;
2429 * nor is it possible when running Vim remotely using Telnet (since the
2430 * console window the user sees is owned by a remote process).
2431 */
2432 static void
2433SaveConsoleTitleAndIcon(void)
2434{
2435 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2436
2437 /* Save the original title. */
2438 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2439 return;
2440
2441 /*
2442 * Obtain a handle to the console window using GetConsoleWindow() from
2443 * KERNEL32.DLL; we need to handle in order to change the window icon.
2444 * This function only exists on NT-based Windows, starting with Windows
2445 * 2000. On older operating systems, we can't change the window icon
2446 * anyway.
2447 */
2448 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2449 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2450 "GetConsoleWindow")) != NULL)
2451 {
2452 g_hWnd = (*GetConsoleWindowProc)();
2453 }
2454 if (g_hWnd == NULL)
2455 return;
2456
2457 /* Save the original console window icon. */
2458 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2459 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2460 return;
2461
2462 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002463 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2464 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465 if (g_hVimIcon != NULL)
2466 g_fCanChangeIcon = TRUE;
2467}
2468#endif
2469
2470static int g_fWindInitCalled = FALSE;
2471static int g_fTermcapMode = FALSE;
2472static CONSOLE_CURSOR_INFO g_cci;
2473static DWORD g_cmodein = 0;
2474static DWORD g_cmodeout = 0;
2475
2476/*
2477 * non-GUI version of mch_init().
2478 */
2479 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002480mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002482#ifndef FEAT_RESTORE_ORIG_SCREEN
2483 CONSOLE_SCREEN_BUFFER_INFO csbi;
2484#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485#ifndef __MINGW32__
2486 extern int _fmode;
2487#endif
2488
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002489 /* Silently handle invalid parameters to CRT functions */
2490 SET_INVALID_PARAM_HANDLER;
2491
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 /* Let critical errors result in a failure, not in a dialog box. Required
2493 * for the timestamp test to work on removed floppies. */
2494 SetErrorMode(SEM_FAILCRITICALERRORS);
2495
2496 _fmode = O_BINARY; /* we do our own CR-LF translation */
2497 out_flush();
2498
2499 /* Obtain handles for the standard Console I/O devices */
2500 if (read_cmd_fd == 0)
2501 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2502 else
2503 create_conin();
2504 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2505
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002506#ifdef FEAT_RESTORE_ORIG_SCREEN
2507 /* Save the initial console buffer for later restoration */
2508 SaveConsoleBuffer(&g_cbOrig);
2509 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2510#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002512 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2513 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2514#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 if (cterm_normal_fg_color == 0)
2516 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2517 if (cterm_normal_bg_color == 0)
2518 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2519
2520 /* set termcap codes to current text attributes */
2521 update_tcap(g_attrCurrent);
2522
2523 GetConsoleCursorInfo(g_hConOut, &g_cci);
2524 GetConsoleMode(g_hConIn, &g_cmodein);
2525 GetConsoleMode(g_hConOut, &g_cmodeout);
2526
2527#ifdef FEAT_TITLE
2528 SaveConsoleTitleAndIcon();
2529 /*
2530 * Set both the small and big icons of the console window to Vim's icon.
2531 * Note that Vim presently only has one size of icon (32x32), but it
2532 * automatically gets scaled down to 16x16 when setting the small icon.
2533 */
2534 if (g_fCanChangeIcon)
2535 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2536#endif
2537
2538 ui_get_shellsize();
2539
2540#ifdef MCH_WRITE_DUMP
2541 fdDump = fopen("dump", "wt");
2542
2543 if (fdDump)
2544 {
2545 time_t t;
2546
2547 time(&t);
2548 fputs(ctime(&t), fdDump);
2549 fflush(fdDump);
2550 }
2551#endif
2552
2553 g_fWindInitCalled = TRUE;
2554
2555#ifdef FEAT_MOUSE
2556 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2557#endif
2558
2559#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002560 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561#endif
2562
2563 /* This will be NULL on anything but NT 4.0 */
2564 s_pfnGetConsoleKeyboardLayoutName =
2565 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2566 "GetConsoleKeyboardLayoutNameA");
2567}
2568
2569/*
2570 * non-GUI version of mch_exit().
2571 * Shut down and exit with status `r'
2572 * Careful: mch_exit() may be called before mch_init()!
2573 */
2574 void
2575mch_exit(int r)
2576{
2577 stoptermcap();
2578
2579 if (g_fWindInitCalled)
2580 settmode(TMODE_COOK);
2581
2582 ml_close_all(TRUE); /* remove all memfiles */
2583
2584 if (g_fWindInitCalled)
2585 {
2586#ifdef FEAT_TITLE
2587 mch_restore_title(3);
2588 /*
2589 * Restore both the small and big icons of the console window to
2590 * what they were at startup. Don't do this when the window is
2591 * closed, Vim would hang here.
2592 */
2593 if (g_fCanChangeIcon && !g_fForceExit)
2594 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2595#endif
2596
2597#ifdef MCH_WRITE_DUMP
2598 if (fdDump)
2599 {
2600 time_t t;
2601
2602 time(&t);
2603 fputs(ctime(&t), fdDump);
2604 fclose(fdDump);
2605 }
2606 fdDump = NULL;
2607#endif
2608 }
2609
2610 SetConsoleCursorInfo(g_hConOut, &g_cci);
2611 SetConsoleMode(g_hConIn, g_cmodein);
2612 SetConsoleMode(g_hConOut, g_cmodeout);
2613
2614#ifdef DYNAMIC_GETTEXT
2615 dyn_libintl_end();
2616#endif
2617
2618 exit(r);
2619}
2620#endif /* !FEAT_GUI_W32 */
2621
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622/*
2623 * Do we have an interactive window?
2624 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002625/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 int
2627mch_check_win(
2628 int argc,
2629 char **argv)
2630{
2631 get_exe_name();
2632
2633#ifdef FEAT_GUI_W32
2634 return OK; /* GUI always has a tty */
2635#else
2636 if (isatty(1))
2637 return OK;
2638 return FAIL;
2639#endif
2640}
2641
2642
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002643#ifdef FEAT_MBYTE
2644/*
2645 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2646 * if it already exists. When "len" is > 0, also expand short to long
2647 * filenames.
2648 * Return FAIL if wide functions are not available, OK otherwise.
2649 * NOTE: much of this is identical to fname_case(), keep in sync!
2650 */
2651 static int
2652fname_casew(
2653 WCHAR *name,
2654 int len)
2655{
2656 WCHAR szTrueName[_MAX_PATH + 2];
2657 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2658 WCHAR *ptrue, *ptruePrev;
2659 WCHAR *porig, *porigPrev;
2660 int flen;
2661 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002662 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002663 int c;
2664 int slen;
2665
2666 flen = (int)wcslen(name);
2667 if (flen > _MAX_PATH)
2668 return OK;
2669
2670 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2671
2672 /* Build the new name in szTrueName[] one component at a time. */
2673 porig = name;
2674 ptrue = szTrueName;
2675
2676 if (iswalpha(porig[0]) && porig[1] == L':')
2677 {
2678 /* copy leading drive letter */
2679 *ptrue++ = *porig++;
2680 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002681 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002682 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002683
2684 while (*porig != NUL)
2685 {
2686 /* copy \ characters */
2687 while (*porig == psepc)
2688 *ptrue++ = *porig++;
2689
2690 ptruePrev = ptrue;
2691 porigPrev = porig;
2692 while (*porig != NUL && *porig != psepc)
2693 {
2694 *ptrue++ = *porig++;
2695 }
2696 *ptrue = NUL;
2697
2698 /* To avoid a slow failure append "\*" when searching a directory,
2699 * server or network share. */
2700 wcscpy(szTrueNameTemp, szTrueName);
2701 slen = (int)wcslen(szTrueNameTemp);
2702 if (*porig == psepc && slen + 2 < _MAX_PATH)
2703 wcscpy(szTrueNameTemp + slen, L"\\*");
2704
2705 /* Skip "", "." and "..". */
2706 if (ptrue > ptruePrev
2707 && (ptruePrev[0] != L'.'
2708 || (ptruePrev[1] != NUL
2709 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2710 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2711 != INVALID_HANDLE_VALUE)
2712 {
2713 c = *porig;
2714 *porig = NUL;
2715
2716 /* Only use the match when it's the same name (ignoring case) or
2717 * expansion is allowed and there is a match with the short name
2718 * and there is enough room. */
2719 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2720 || (len > 0
2721 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2722 && (int)(ptruePrev - szTrueName)
2723 + (int)wcslen(fb.cFileName) < len)))
2724 {
2725 wcscpy(ptruePrev, fb.cFileName);
2726
2727 /* Look for exact match and prefer it if found. Must be a
2728 * long name, otherwise there would be only one match. */
2729 while (FindNextFileW(hFind, &fb))
2730 {
2731 if (*fb.cAlternateFileName != NUL
2732 && (wcscoll(porigPrev, fb.cFileName) == 0
2733 || (len > 0
2734 && (_wcsicoll(porigPrev,
2735 fb.cAlternateFileName) == 0
2736 && (int)(ptruePrev - szTrueName)
2737 + (int)wcslen(fb.cFileName) < len))))
2738 {
2739 wcscpy(ptruePrev, fb.cFileName);
2740 break;
2741 }
2742 }
2743 }
2744 FindClose(hFind);
2745 *porig = c;
2746 ptrue = ptruePrev + wcslen(ptruePrev);
2747 }
2748 else if (hFind == INVALID_HANDLE_VALUE
2749 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2750 return FAIL;
2751 }
2752
2753 wcscpy(name, szTrueName);
2754 return OK;
2755}
2756#endif
2757
Bram Moolenaar071d4272004-06-13 20:20:40 +00002758/*
2759 * fname_case(): Set the case of the file name, if it already exists.
2760 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002761 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002762 */
2763 void
2764fname_case(
2765 char_u *name,
2766 int len)
2767{
2768 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002769 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 char *ptrue, *ptruePrev;
2771 char *porig, *porigPrev;
2772 int flen;
2773 WIN32_FIND_DATA fb;
2774 HANDLE hFind;
2775 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002776 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002778 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002779 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780 return;
2781
2782 slash_adjust(name);
2783
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002784#ifdef FEAT_MBYTE
2785 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2786 {
2787 WCHAR *p = enc_to_utf16(name, NULL);
2788
2789 if (p != NULL)
2790 {
2791 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002792 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002793
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002794 wcsncpy(buf, p, _MAX_PATH);
2795 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002796 vim_free(p);
2797
2798 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2799 {
2800 q = utf16_to_enc(buf, NULL);
2801 if (q != NULL)
2802 {
2803 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2804 vim_free(q);
2805 return;
2806 }
2807 }
2808 }
2809 /* Retry with non-wide function (for Windows 98). */
2810 }
2811#endif
2812
2813 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2814 * So we should check this after calling wide function. */
2815 if (flen > _MAX_PATH)
2816 return;
2817
Bram Moolenaar071d4272004-06-13 20:20:40 +00002818 /* Build the new name in szTrueName[] one component at a time. */
2819 porig = name;
2820 ptrue = szTrueName;
2821
2822 if (isalpha(porig[0]) && porig[1] == ':')
2823 {
2824 /* copy leading drive letter */
2825 *ptrue++ = *porig++;
2826 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002827 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002828 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829
2830 while (*porig != NUL)
2831 {
2832 /* copy \ characters */
2833 while (*porig == psepc)
2834 *ptrue++ = *porig++;
2835
2836 ptruePrev = ptrue;
2837 porigPrev = porig;
2838 while (*porig != NUL && *porig != psepc)
2839 {
2840#ifdef FEAT_MBYTE
2841 int l;
2842
2843 if (enc_dbcs)
2844 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002845 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846 while (--l >= 0)
2847 *ptrue++ = *porig++;
2848 }
2849 else
2850#endif
2851 *ptrue++ = *porig++;
2852 }
2853 *ptrue = NUL;
2854
Bram Moolenaar464c9252010-10-13 20:37:41 +02002855 /* To avoid a slow failure append "\*" when searching a directory,
2856 * server or network share. */
2857 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002858 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002859 if (*porig == psepc && slen + 2 < _MAX_PATH)
2860 STRCPY(szTrueNameTemp + slen, "\\*");
2861
Bram Moolenaar071d4272004-06-13 20:20:40 +00002862 /* Skip "", "." and "..". */
2863 if (ptrue > ptruePrev
2864 && (ptruePrev[0] != '.'
2865 || (ptruePrev[1] != NUL
2866 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002867 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868 != INVALID_HANDLE_VALUE)
2869 {
2870 c = *porig;
2871 *porig = NUL;
2872
2873 /* Only use the match when it's the same name (ignoring case) or
2874 * expansion is allowed and there is a match with the short name
2875 * and there is enough room. */
2876 if (_stricoll(porigPrev, fb.cFileName) == 0
2877 || (len > 0
2878 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2879 && (int)(ptruePrev - szTrueName)
2880 + (int)strlen(fb.cFileName) < len)))
2881 {
2882 STRCPY(ptruePrev, fb.cFileName);
2883
2884 /* Look for exact match and prefer it if found. Must be a
2885 * long name, otherwise there would be only one match. */
2886 while (FindNextFile(hFind, &fb))
2887 {
2888 if (*fb.cAlternateFileName != NUL
2889 && (strcoll(porigPrev, fb.cFileName) == 0
2890 || (len > 0
2891 && (_stricoll(porigPrev,
2892 fb.cAlternateFileName) == 0
2893 && (int)(ptruePrev - szTrueName)
2894 + (int)strlen(fb.cFileName) < len))))
2895 {
2896 STRCPY(ptruePrev, fb.cFileName);
2897 break;
2898 }
2899 }
2900 }
2901 FindClose(hFind);
2902 *porig = c;
2903 ptrue = ptruePrev + strlen(ptruePrev);
2904 }
2905 }
2906
2907 STRCPY(name, szTrueName);
2908}
2909
2910
2911/*
2912 * Insert user name in s[len].
2913 */
2914 int
2915mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002916 char_u *s,
2917 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002919 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920 DWORD cch = sizeof szUserName;
2921
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002922#ifdef FEAT_MBYTE
2923 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2924 {
2925 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2926 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2927
2928 if (GetUserNameW(wszUserName, &wcch))
2929 {
2930 char_u *p = utf16_to_enc(wszUserName, NULL);
2931
2932 if (p != NULL)
2933 {
2934 vim_strncpy(s, p, len - 1);
2935 vim_free(p);
2936 return OK;
2937 }
2938 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002939 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2940 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002941 /* Retry with non-wide function (for Windows 98). */
2942 }
2943#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 if (GetUserName(szUserName, &cch))
2945 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002946 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 return OK;
2948 }
2949 s[0] = NUL;
2950 return FAIL;
2951}
2952
2953
2954/*
2955 * Insert host name in s[len].
2956 */
2957 void
2958mch_get_host_name(
2959 char_u *s,
2960 int len)
2961{
2962 DWORD cch = len;
2963
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002964#ifdef FEAT_MBYTE
2965 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2966 {
2967 WCHAR wszHostName[256 + 1];
2968 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2969
2970 if (GetComputerNameW(wszHostName, &wcch))
2971 {
2972 char_u *p = utf16_to_enc(wszHostName, NULL);
2973
2974 if (p != NULL)
2975 {
2976 vim_strncpy(s, p, len - 1);
2977 vim_free(p);
2978 return;
2979 }
2980 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002981 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2982 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002983 /* Retry with non-wide function (for Windows 98). */
2984 }
2985#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002987 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988}
2989
2990
2991/*
2992 * return process ID
2993 */
2994 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002995mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996{
2997 return (long)GetCurrentProcessId();
2998}
2999
3000
3001/*
3002 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3003 * Return OK for success, FAIL for failure.
3004 */
3005 int
3006mch_dirname(
3007 char_u *buf,
3008 int len)
3009{
3010 /*
3011 * Originally this was:
3012 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3013 * But the Win32s known bug list says that getcwd() doesn't work
3014 * so use the Win32 system call instead. <Negri>
3015 */
3016#ifdef FEAT_MBYTE
3017 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3018 {
3019 WCHAR wbuf[_MAX_PATH + 1];
3020
3021 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3022 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003023 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024
3025 if (p != NULL)
3026 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003027 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028 vim_free(p);
3029 return OK;
3030 }
3031 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003032 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3033 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034 /* Retry with non-wide function (for Windows 98). */
3035 }
3036#endif
3037 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3038}
3039
3040/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003041 * Get file permissions for "name".
3042 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043 */
3044 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003045mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003047 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003048 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003050 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003051 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052}
3053
3054
3055/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003056 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003057 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003058 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059 */
3060 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003061mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003063 long n = -1;
3064
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065#ifdef FEAT_MBYTE
3066 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3067 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003068 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069
3070 if (p != NULL)
3071 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003072 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003074 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003075 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076 /* Retry with non-wide function (for Windows 98). */
3077 }
3078 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003079 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003081 n = _chmod(name, perm);
3082 if (n == -1)
3083 return FAIL;
3084
3085 win32_set_archive(name);
3086
3087 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088}
3089
3090/*
3091 * Set hidden flag for "name".
3092 */
3093 void
3094mch_hide(char_u *name)
3095{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003096 int attrs = win32_getattrs(name);
3097 if (attrs == -1)
3098 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003100 attrs |= FILE_ATTRIBUTE_HIDDEN;
3101 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102}
3103
3104/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003105 * Return TRUE if file "name" exists and is hidden.
3106 */
3107 int
3108mch_ishidden(char_u *name)
3109{
3110 int f = win32_getattrs(name);
3111
3112 if (f == -1)
3113 return FALSE; /* file does not exist at all */
3114
3115 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3116}
3117
3118/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119 * return TRUE if "name" is a directory
3120 * return FALSE if "name" is not a directory or upon error
3121 */
3122 int
3123mch_isdir(char_u *name)
3124{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003125 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126
3127 if (f == -1)
3128 return FALSE; /* file does not exist at all */
3129
3130 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3131}
3132
3133/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003134 * return TRUE if "name" is a directory, NOT a symlink to a directory
3135 * return FALSE if "name" is not a directory
3136 * return FALSE for error
3137 */
3138 int
3139mch_isrealdir(char_u *name)
3140{
3141 return mch_isdir(name) && !mch_is_symbolic_link(name);
3142}
3143
3144/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003145 * Create directory "name".
3146 * Return 0 on success, -1 on error.
3147 */
3148 int
3149mch_mkdir(char_u *name)
3150{
3151#ifdef FEAT_MBYTE
3152 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3153 {
3154 WCHAR *p;
3155 int retval;
3156
3157 p = enc_to_utf16(name, NULL);
3158 if (p == NULL)
3159 return -1;
3160 retval = _wmkdir(p);
3161 vim_free(p);
3162 return retval;
3163 }
3164#endif
3165 return _mkdir(name);
3166}
3167
3168/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003169 * Delete directory "name".
3170 * Return 0 on success, -1 on error.
3171 */
3172 int
3173mch_rmdir(char_u *name)
3174{
3175#ifdef FEAT_MBYTE
3176 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3177 {
3178 WCHAR *p;
3179 int retval;
3180
3181 p = enc_to_utf16(name, NULL);
3182 if (p == NULL)
3183 return -1;
3184 retval = _wrmdir(p);
3185 vim_free(p);
3186 return retval;
3187 }
3188#endif
3189 return _rmdir(name);
3190}
3191
3192/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003193 * Return TRUE if file "fname" has more than one link.
3194 */
3195 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003196mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003197{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003198 BY_HANDLE_FILE_INFORMATION info;
3199
3200 return win32_fileinfo(fname, &info) == FILEINFO_OK
3201 && info.nNumberOfLinks > 1;
3202}
3203
3204/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003205 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003206 */
3207 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003208mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003209{
3210 HANDLE hFind;
3211 int res = FALSE;
3212 WIN32_FIND_DATAA findDataA;
3213 DWORD fileFlags = 0, reparseTag = 0;
3214#ifdef FEAT_MBYTE
3215 WCHAR *wn = NULL;
3216 WIN32_FIND_DATAW findDataW;
3217
3218 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003219 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003220 if (wn != NULL)
3221 {
3222 hFind = FindFirstFileW(wn, &findDataW);
3223 vim_free(wn);
3224 if (hFind == INVALID_HANDLE_VALUE
3225 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3226 {
3227 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar203258c2016-01-17 22:15:16 +01003228 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003229 if (hFind != INVALID_HANDLE_VALUE)
3230 {
3231 fileFlags = findDataA.dwFileAttributes;
3232 reparseTag = findDataA.dwReserved0;
3233 }
3234 }
3235 else
3236 {
3237 fileFlags = findDataW.dwFileAttributes;
3238 reparseTag = findDataW.dwReserved0;
3239 }
3240 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003241 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003242#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003243 {
Bram Moolenaar203258c2016-01-17 22:15:16 +01003244 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003245 if (hFind != INVALID_HANDLE_VALUE)
3246 {
3247 fileFlags = findDataA.dwFileAttributes;
3248 reparseTag = findDataA.dwReserved0;
3249 }
3250 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003251
3252 if (hFind != INVALID_HANDLE_VALUE)
3253 FindClose(hFind);
3254
3255 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003256 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3257 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003258 res = TRUE;
3259
3260 return res;
3261}
3262
3263/*
3264 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3265 * link.
3266 */
3267 int
3268mch_is_linked(char_u *fname)
3269{
3270 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3271 return TRUE;
3272 return FALSE;
3273}
3274
3275/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003276 * Get the by-handle-file-information for "fname".
3277 * Returns FILEINFO_OK when OK.
3278 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3279 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3280 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3281 */
3282 int
3283win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3284{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003285 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003286 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003287#ifdef FEAT_MBYTE
3288 WCHAR *wn = NULL;
3289
3290 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003291 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003292 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003293 if (wn == NULL)
3294 res = FILEINFO_ENC_FAIL;
3295 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003296 if (wn != NULL)
3297 {
3298 hFile = CreateFileW(wn, /* file name */
3299 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003300 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003301 NULL, /* security descriptor */
3302 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003303 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003304 NULL); /* handle to template file */
3305 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003306 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003307 {
3308 /* Retry with non-wide function (for Windows 98). */
3309 vim_free(wn);
3310 wn = NULL;
3311 }
3312 }
3313 if (wn == NULL)
3314#endif
3315 hFile = CreateFile(fname, /* file name */
3316 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003317 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003318 NULL, /* security descriptor */
3319 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003320 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003321 NULL); /* handle to template file */
3322
3323 if (hFile != INVALID_HANDLE_VALUE)
3324 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003325 if (GetFileInformationByHandle(hFile, info) != 0)
3326 res = FILEINFO_OK;
3327 else
3328 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003329 CloseHandle(hFile);
3330 }
3331
3332#ifdef FEAT_MBYTE
3333 vim_free(wn);
3334#endif
3335 return res;
3336}
3337
3338/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003339 * get file attributes for `name'
3340 * -1 : error
3341 * else FILE_ATTRIBUTE_* defined in winnt.h
3342 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003343 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003344win32_getattrs(char_u *name)
3345{
3346 int attr;
3347#ifdef FEAT_MBYTE
3348 WCHAR *p = NULL;
3349
3350 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3351 p = enc_to_utf16(name, NULL);
3352
3353 if (p != NULL)
3354 {
3355 attr = GetFileAttributesW(p);
3356 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3357 {
3358 /* Retry with non-wide function (for Windows 98). */
3359 vim_free(p);
3360 p = NULL;
3361 }
3362 }
3363 if (p == NULL)
3364#endif
3365 attr = GetFileAttributes((char *)name);
3366#ifdef FEAT_MBYTE
3367 vim_free(p);
3368#endif
3369 return attr;
3370}
3371
3372/*
3373 * set file attributes for `name' to `attrs'
3374 *
3375 * return -1 for failure, 0 otherwise
3376 */
3377 static
3378 int
3379win32_setattrs(char_u *name, int attrs)
3380{
3381 int res;
3382#ifdef FEAT_MBYTE
3383 WCHAR *p = NULL;
3384
3385 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3386 p = enc_to_utf16(name, NULL);
3387
3388 if (p != NULL)
3389 {
3390 res = SetFileAttributesW(p, attrs);
3391 if (res == FALSE
3392 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3393 {
3394 /* Retry with non-wide function (for Windows 98). */
3395 vim_free(p);
3396 p = NULL;
3397 }
3398 }
3399 if (p == NULL)
3400#endif
3401 res = SetFileAttributes((char *)name, attrs);
3402#ifdef FEAT_MBYTE
3403 vim_free(p);
3404#endif
3405 return res ? 0 : -1;
3406}
3407
3408/*
3409 * Set archive flag for "name".
3410 */
3411 static
3412 int
3413win32_set_archive(char_u *name)
3414{
3415 int attrs = win32_getattrs(name);
3416 if (attrs == -1)
3417 return -1;
3418
3419 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3420 return win32_setattrs(name, attrs);
3421}
3422
3423/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003424 * Return TRUE if file or directory "name" is writable (not readonly).
3425 * Strange semantics of Win32: a readonly directory is writable, but you can't
3426 * delete a file. Let's say this means it is writable.
3427 */
3428 int
3429mch_writable(char_u *name)
3430{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003431 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003433 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3434 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435}
3436
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437/*
3438 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003439 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440 * Return -1 if unknown.
3441 */
3442 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003443mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003445 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003446 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003447 char_u *p;
3448
3449 if (len >= _MAX_PATH) /* safety check */
3450 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003451 if (!use_path)
3452 {
3453 /* TODO: check if file is really executable. */
3454 return mch_getperm(name) != -1 && !mch_isdir(name);
3455 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003456
3457 /* If there already is an extension try using the name directly. Also do
3458 * this with a Unix-shell like 'shell'. */
3459 if (vim_strchr(gettail(name), '.') != NULL
3460 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003461 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003462 return TRUE;
3463
3464 /*
3465 * Loop over all extensions in $PATHEXT.
3466 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003467 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003468 p = mch_getenv("PATHEXT");
3469 if (p == NULL)
3470 p = (char_u *)".com;.exe;.bat;.cmd";
3471 while (*p)
3472 {
3473 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3474 {
3475 /* A single "." means no extension is added. */
3476 buf[len] = NUL;
3477 ++p;
3478 if (*p)
3479 ++p;
3480 }
3481 else
3482 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003483 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003484 return TRUE;
3485 }
3486 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488
3489/*
3490 * Check what "name" is:
3491 * NODE_NORMAL: file or directory (or doesn't exist)
3492 * NODE_WRITABLE: writable device, socket, fifo, etc.
3493 * NODE_OTHER: non-writable things
3494 */
3495 int
3496mch_nodetype(char_u *name)
3497{
3498 HANDLE hFile;
3499 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003500#ifdef FEAT_MBYTE
3501 WCHAR *wn = NULL;
3502#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503
Bram Moolenaar043545e2006-10-10 16:44:07 +00003504 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3505 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3506 * here. */
3507 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3508 return NODE_WRITABLE;
3509
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003510#ifdef FEAT_MBYTE
3511 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3512 {
3513 wn = enc_to_utf16(name, NULL);
3514 if (wn != NULL)
3515 {
3516 hFile = CreateFileW(wn, /* file name */
3517 GENERIC_WRITE, /* access mode */
3518 0, /* share mode */
3519 NULL, /* security descriptor */
3520 OPEN_EXISTING, /* creation disposition */
3521 0, /* file attributes */
3522 NULL); /* handle to template file */
3523 if (hFile == INVALID_HANDLE_VALUE
3524 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3525 {
3526 /* Retry with non-wide function (for Windows 98). */
3527 vim_free(wn);
3528 wn = NULL;
3529 }
3530 }
3531 }
3532 if (wn == NULL)
3533#endif
3534 hFile = CreateFile(name, /* file name */
3535 GENERIC_WRITE, /* access mode */
3536 0, /* share mode */
3537 NULL, /* security descriptor */
3538 OPEN_EXISTING, /* creation disposition */
3539 0, /* file attributes */
3540 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003541
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003542#ifdef FEAT_MBYTE
3543 vim_free(wn);
3544#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545 if (hFile == INVALID_HANDLE_VALUE)
3546 return NODE_NORMAL;
3547
3548 type = GetFileType(hFile);
3549 CloseHandle(hFile);
3550 if (type == FILE_TYPE_CHAR)
3551 return NODE_WRITABLE;
3552 if (type == FILE_TYPE_DISK)
3553 return NODE_NORMAL;
3554 return NODE_OTHER;
3555}
3556
3557#ifdef HAVE_ACL
3558struct my_acl
3559{
3560 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3561 PSID pSidOwner;
3562 PSID pSidGroup;
3563 PACL pDacl;
3564 PACL pSacl;
3565};
3566#endif
3567
3568/*
3569 * Return a pointer to the ACL of file "fname" in allocated memory.
3570 * Return NULL if the ACL is not available for whatever reason.
3571 */
3572 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003573mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003574{
3575#ifndef HAVE_ACL
3576 return (vim_acl_T)NULL;
3577#else
3578 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003579 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580
3581 /* This only works on Windows NT and 2000. */
3582 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3583 {
3584 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3585 if (p != NULL)
3586 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003587# ifdef FEAT_MBYTE
3588 WCHAR *wn = NULL;
3589
3590 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3591 wn = enc_to_utf16(fname, NULL);
3592 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003594 /* Try to retrieve the entire security descriptor. */
3595 err = pGetNamedSecurityInfoW(
3596 wn, // Abstract filename
3597 SE_FILE_OBJECT, // File Object
3598 OWNER_SECURITY_INFORMATION |
3599 GROUP_SECURITY_INFORMATION |
3600 DACL_SECURITY_INFORMATION |
3601 SACL_SECURITY_INFORMATION,
3602 &p->pSidOwner, // Ownership information.
3603 &p->pSidGroup, // Group membership.
3604 &p->pDacl, // Discretionary information.
3605 &p->pSacl, // For auditing purposes.
3606 &p->pSecurityDescriptor);
3607 if (err == ERROR_ACCESS_DENIED ||
3608 err == ERROR_PRIVILEGE_NOT_HELD)
3609 {
3610 /* Retrieve only DACL. */
3611 (void)pGetNamedSecurityInfoW(
3612 wn,
3613 SE_FILE_OBJECT,
3614 DACL_SECURITY_INFORMATION,
3615 NULL,
3616 NULL,
3617 &p->pDacl,
3618 NULL,
3619 &p->pSecurityDescriptor);
3620 }
3621 if (p->pSecurityDescriptor == NULL)
3622 {
3623 mch_free_acl((vim_acl_T)p);
3624 p = NULL;
3625 }
3626 vim_free(wn);
3627 }
3628 else
3629# endif
3630 {
3631 /* Try to retrieve the entire security descriptor. */
3632 err = pGetNamedSecurityInfo(
3633 (LPSTR)fname, // Abstract filename
3634 SE_FILE_OBJECT, // File Object
3635 OWNER_SECURITY_INFORMATION |
3636 GROUP_SECURITY_INFORMATION |
3637 DACL_SECURITY_INFORMATION |
3638 SACL_SECURITY_INFORMATION,
3639 &p->pSidOwner, // Ownership information.
3640 &p->pSidGroup, // Group membership.
3641 &p->pDacl, // Discretionary information.
3642 &p->pSacl, // For auditing purposes.
3643 &p->pSecurityDescriptor);
3644 if (err == ERROR_ACCESS_DENIED ||
3645 err == ERROR_PRIVILEGE_NOT_HELD)
3646 {
3647 /* Retrieve only DACL. */
3648 (void)pGetNamedSecurityInfo(
3649 (LPSTR)fname,
3650 SE_FILE_OBJECT,
3651 DACL_SECURITY_INFORMATION,
3652 NULL,
3653 NULL,
3654 &p->pDacl,
3655 NULL,
3656 &p->pSecurityDescriptor);
3657 }
3658 if (p->pSecurityDescriptor == NULL)
3659 {
3660 mch_free_acl((vim_acl_T)p);
3661 p = NULL;
3662 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663 }
3664 }
3665 }
3666
3667 return (vim_acl_T)p;
3668#endif
3669}
3670
Bram Moolenaar27515922013-06-29 15:36:26 +02003671#ifdef HAVE_ACL
3672/*
3673 * Check if "acl" contains inherited ACE.
3674 */
3675 static BOOL
3676is_acl_inherited(PACL acl)
3677{
3678 DWORD i;
3679 ACL_SIZE_INFORMATION acl_info;
3680 PACCESS_ALLOWED_ACE ace;
3681
3682 acl_info.AceCount = 0;
3683 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3684 for (i = 0; i < acl_info.AceCount; i++)
3685 {
3686 GetAce(acl, i, (LPVOID *)&ace);
3687 if (ace->Header.AceFlags & INHERITED_ACE)
3688 return TRUE;
3689 }
3690 return FALSE;
3691}
3692#endif
3693
Bram Moolenaar071d4272004-06-13 20:20:40 +00003694/*
3695 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3696 * Errors are ignored.
3697 * This must only be called with "acl" equal to what mch_get_acl() returned.
3698 */
3699 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003700mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701{
3702#ifdef HAVE_ACL
3703 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003704 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705
3706 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003707 {
3708# ifdef FEAT_MBYTE
3709 WCHAR *wn = NULL;
3710# endif
3711
3712 /* Set security flags */
3713 if (p->pSidOwner)
3714 sec_info |= OWNER_SECURITY_INFORMATION;
3715 if (p->pSidGroup)
3716 sec_info |= GROUP_SECURITY_INFORMATION;
3717 if (p->pDacl)
3718 {
3719 sec_info |= DACL_SECURITY_INFORMATION;
3720 /* Do not inherit its parent's DACL.
3721 * If the DACL is inherited, Cygwin permissions would be changed.
3722 */
3723 if (!is_acl_inherited(p->pDacl))
3724 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3725 }
3726 if (p->pSacl)
3727 sec_info |= SACL_SECURITY_INFORMATION;
3728
3729# ifdef FEAT_MBYTE
3730 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3731 wn = enc_to_utf16(fname, NULL);
3732 if (wn != NULL)
3733 {
3734 (void)pSetNamedSecurityInfoW(
3735 wn, // Abstract filename
3736 SE_FILE_OBJECT, // File Object
3737 sec_info,
3738 p->pSidOwner, // Ownership information.
3739 p->pSidGroup, // Group membership.
3740 p->pDacl, // Discretionary information.
3741 p->pSacl // For auditing purposes.
3742 );
3743 vim_free(wn);
3744 }
3745 else
3746# endif
3747 {
3748 (void)pSetNamedSecurityInfo(
3749 (LPSTR)fname, // Abstract filename
3750 SE_FILE_OBJECT, // File Object
3751 sec_info,
3752 p->pSidOwner, // Ownership information.
3753 p->pSidGroup, // Group membership.
3754 p->pDacl, // Discretionary information.
3755 p->pSacl // For auditing purposes.
3756 );
3757 }
3758 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003759#endif
3760}
3761
3762 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003763mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003764{
3765#ifdef HAVE_ACL
3766 struct my_acl *p = (struct my_acl *)acl;
3767
3768 if (p != NULL)
3769 {
3770 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3771 vim_free(p);
3772 }
3773#endif
3774}
3775
3776#ifndef FEAT_GUI_W32
3777
3778/*
3779 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3780 */
3781 static BOOL WINAPI
3782handler_routine(
3783 DWORD dwCtrlType)
3784{
3785 switch (dwCtrlType)
3786 {
3787 case CTRL_C_EVENT:
3788 if (ctrl_c_interrupts)
3789 g_fCtrlCPressed = TRUE;
3790 return TRUE;
3791
3792 case CTRL_BREAK_EVENT:
3793 g_fCBrkPressed = TRUE;
3794 return TRUE;
3795
3796 /* fatal events: shut down gracefully */
3797 case CTRL_CLOSE_EVENT:
3798 case CTRL_LOGOFF_EVENT:
3799 case CTRL_SHUTDOWN_EVENT:
3800 windgoto((int)Rows - 1, 0);
3801 g_fForceExit = TRUE;
3802
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003803 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804 (dwCtrlType == CTRL_CLOSE_EVENT
3805 ? _("close")
3806 : dwCtrlType == CTRL_LOGOFF_EVENT
3807 ? _("logoff")
3808 : _("shutdown")));
3809#ifdef DEBUG
3810 OutputDebugString(IObuff);
3811#endif
3812
3813 preserve_exit(); /* output IObuff, preserve files and exit */
3814
3815 return TRUE; /* not reached */
3816
3817 default:
3818 return FALSE;
3819 }
3820}
3821
3822
3823/*
3824 * set the tty in (raw) ? "raw" : "cooked" mode
3825 */
3826 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003827mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828{
3829 DWORD cmodein;
3830 DWORD cmodeout;
3831 BOOL bEnableHandler;
3832
3833 GetConsoleMode(g_hConIn, &cmodein);
3834 GetConsoleMode(g_hConOut, &cmodeout);
3835 if (tmode == TMODE_RAW)
3836 {
3837 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3838 ENABLE_ECHO_INPUT);
3839#ifdef FEAT_MOUSE
3840 if (g_fMouseActive)
3841 cmodein |= ENABLE_MOUSE_INPUT;
3842#endif
3843 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3844 bEnableHandler = TRUE;
3845 }
3846 else /* cooked */
3847 {
3848 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3849 ENABLE_ECHO_INPUT);
3850 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3851 bEnableHandler = FALSE;
3852 }
3853 SetConsoleMode(g_hConIn, cmodein);
3854 SetConsoleMode(g_hConOut, cmodeout);
3855 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3856
3857#ifdef MCH_WRITE_DUMP
3858 if (fdDump)
3859 {
3860 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3861 tmode == TMODE_RAW ? "raw" :
3862 tmode == TMODE_COOK ? "cooked" : "normal",
3863 cmodein, cmodeout);
3864 fflush(fdDump);
3865 }
3866#endif
3867}
3868
3869
3870/*
3871 * Get the size of the current window in `Rows' and `Columns'
3872 * Return OK when size could be determined, FAIL otherwise.
3873 */
3874 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003875mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876{
3877 CONSOLE_SCREEN_BUFFER_INFO csbi;
3878
3879 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3880 {
3881 /*
3882 * For some reason, we are trying to get the screen dimensions
3883 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3884 * variables are really intended to mean the size of Vim screen
3885 * while in termcap mode.
3886 */
3887 Rows = g_cbTermcap.Info.dwSize.Y;
3888 Columns = g_cbTermcap.Info.dwSize.X;
3889 }
3890 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3891 {
3892 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3893 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3894 }
3895 else
3896 {
3897 Rows = 25;
3898 Columns = 80;
3899 }
3900 return OK;
3901}
3902
3903/*
3904 * Set a console window to `xSize' * `ySize'
3905 */
3906 static void
3907ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003908 HANDLE hConsole,
3909 int xSize,
3910 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911{
3912 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3913 SMALL_RECT srWindowRect; /* hold the new console size */
3914 COORD coordScreen;
3915
3916#ifdef MCH_WRITE_DUMP
3917 if (fdDump)
3918 {
3919 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3920 fflush(fdDump);
3921 }
3922#endif
3923
3924 /* get the largest size we can size the console window to */
3925 coordScreen = GetLargestConsoleWindowSize(hConsole);
3926
3927 /* define the new console window size and scroll position */
3928 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3929 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3930 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3931
3932 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3933 {
3934 int sx, sy;
3935
3936 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3937 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3938 if (sy < ySize || sx < xSize)
3939 {
3940 /*
3941 * Increasing number of lines/columns, do buffer first.
3942 * Use the maximal size in x and y direction.
3943 */
3944 if (sy < ySize)
3945 coordScreen.Y = ySize;
3946 else
3947 coordScreen.Y = sy;
3948 if (sx < xSize)
3949 coordScreen.X = xSize;
3950 else
3951 coordScreen.X = sx;
3952 SetConsoleScreenBufferSize(hConsole, coordScreen);
3953 }
3954 }
3955
3956 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3957 {
3958#ifdef MCH_WRITE_DUMP
3959 if (fdDump)
3960 {
3961 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3962 GetLastError());
3963 fflush(fdDump);
3964 }
3965#endif
3966 }
3967
3968 /* define the new console buffer size */
3969 coordScreen.X = xSize;
3970 coordScreen.Y = ySize;
3971
3972 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3973 {
3974#ifdef MCH_WRITE_DUMP
3975 if (fdDump)
3976 {
3977 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3978 GetLastError());
3979 fflush(fdDump);
3980 }
3981#endif
3982 }
3983}
3984
3985
3986/*
3987 * Set the console window to `Rows' * `Columns'
3988 */
3989 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003990mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003991{
3992 COORD coordScreen;
3993
3994 /* Don't change window size while still starting up */
3995 if (suppress_winsize != 0)
3996 {
3997 suppress_winsize = 2;
3998 return;
3999 }
4000
4001 if (term_console)
4002 {
4003 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4004
4005 /* Clamp Rows and Columns to reasonable values */
4006 if (Rows > coordScreen.Y)
4007 Rows = coordScreen.Y;
4008 if (Columns > coordScreen.X)
4009 Columns = coordScreen.X;
4010
4011 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4012 }
4013}
4014
4015/*
4016 * Rows and/or Columns has changed.
4017 */
4018 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004019mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020{
4021 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4022}
4023
4024
4025/*
4026 * Called when started up, to set the winsize that was delayed.
4027 */
4028 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004029mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030{
4031 if (suppress_winsize == 2)
4032 {
4033 suppress_winsize = 0;
4034 mch_set_shellsize();
4035 shell_resized();
4036 }
4037 suppress_winsize = 0;
4038}
4039#endif /* FEAT_GUI_W32 */
4040
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004041 static BOOL
4042vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004043 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004044 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004045 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004046 STARTUPINFO *si,
4047 PROCESS_INFORMATION *pi)
4048{
4049# ifdef FEAT_MBYTE
4050 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4051 {
4052 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4053
4054 if (wcmd != NULL)
4055 {
4056 BOOL ret;
4057 ret = CreateProcessW(
4058 NULL, /* Executable name */
4059 wcmd, /* Command to execute */
4060 NULL, /* Process security attributes */
4061 NULL, /* Thread security attributes */
4062 inherit_handles, /* Inherit handles */
4063 flags, /* Creation flags */
4064 NULL, /* Environment */
4065 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004066 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004067 pi); /* Process information */
4068 vim_free(wcmd);
4069 return ret;
4070 }
4071 }
4072#endif
4073 return CreateProcess(
4074 NULL, /* Executable name */
4075 cmd, /* Command to execute */
4076 NULL, /* Process security attributes */
4077 NULL, /* Thread security attributes */
4078 inherit_handles, /* Inherit handles */
4079 flags, /* Creation flags */
4080 NULL, /* Environment */
4081 NULL, /* Current directory */
4082 si, /* Startup information */
4083 pi); /* Process information */
4084}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004085
4086
4087#if defined(FEAT_GUI_W32) || defined(PROTO)
4088
4089/*
4090 * Specialised version of system() for Win32 GUI mode.
4091 * This version proceeds as follows:
4092 * 1. Create a console window for use by the subprocess
4093 * 2. Run the subprocess (it gets the allocated console by default)
4094 * 3. Wait for the subprocess to terminate and get its exit code
4095 * 4. Prompt the user to press a key to close the console window
4096 */
4097 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004098mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004099{
4100 STARTUPINFO si;
4101 PROCESS_INFORMATION pi;
4102 DWORD ret = 0;
4103 HWND hwnd = GetFocus();
4104
4105 si.cb = sizeof(si);
4106 si.lpReserved = NULL;
4107 si.lpDesktop = NULL;
4108 si.lpTitle = NULL;
4109 si.dwFlags = STARTF_USESHOWWINDOW;
4110 /*
4111 * It's nicer to run a filter command in a minimized window, but in
4112 * Windows 95 this makes the command MUCH slower. We can't do it under
4113 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004114 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115 */
4116 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004117 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118 else
4119 si.wShowWindow = SW_SHOWNORMAL;
4120 si.cbReserved2 = 0;
4121 si.lpReserved2 = NULL;
4122
4123 /* There is a strange error on Windows 95 when using "c:\\command.com".
4124 * When the "c:\\" is left out it works OK...? */
4125 if (mch_windows95()
4126 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4127 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4128 cmd += 3;
4129
4130 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004131 vim_create_process(cmd, FALSE,
4132 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133
4134 /* Wait for the command to terminate before continuing */
4135 if (g_PlatformId != VER_PLATFORM_WIN32s)
4136 {
4137#ifdef FEAT_GUI
4138 int delay = 1;
4139
4140 /* Keep updating the window while waiting for the shell to finish. */
4141 for (;;)
4142 {
4143 MSG msg;
4144
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004145 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 {
4147 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004148 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004149 delay = 1;
4150 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 }
4152 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4153 break;
4154
4155 /* We start waiting for a very short time and then increase it, so
4156 * that we respond quickly when the process is quick, and don't
4157 * consume too much overhead when it's slow. */
4158 if (delay < 50)
4159 delay += 10;
4160 }
4161#else
4162 WaitForSingleObject(pi.hProcess, INFINITE);
4163#endif
4164
4165 /* Get the command exit code */
4166 GetExitCodeProcess(pi.hProcess, &ret);
4167 }
4168 else
4169 {
4170 /*
4171 * This ugly code is the only quick way of performing
4172 * a synchronous spawn under Win32s. Yuk.
4173 */
4174 num_windows = 0;
4175 EnumWindows(win32ssynch_cb, 0);
4176 old_num_windows = num_windows;
4177 do
4178 {
4179 Sleep(1000);
4180 num_windows = 0;
4181 EnumWindows(win32ssynch_cb, 0);
4182 } while (num_windows == old_num_windows);
4183 ret = 0;
4184 }
4185
4186 /* Close the handles to the subprocess, so that it goes away */
4187 CloseHandle(pi.hThread);
4188 CloseHandle(pi.hProcess);
4189
4190 /* Try to get input focus back. Doesn't always work though. */
4191 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4192
4193 return ret;
4194}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004195
4196/*
4197 * Thread launched by the gui to send the current buffer data to the
4198 * process. This way avoid to hang up vim totally if the children
4199 * process take a long time to process the lines.
4200 */
4201 static DWORD WINAPI
4202sub_process_writer(LPVOID param)
4203{
4204 HANDLE g_hChildStd_IN_Wr = param;
4205 linenr_T lnum = curbuf->b_op_start.lnum;
4206 DWORD len = 0;
4207 DWORD l;
4208 char_u *lp = ml_get(lnum);
4209 char_u *s;
4210 int written = 0;
4211
4212 for (;;)
4213 {
4214 l = (DWORD)STRLEN(lp + written);
4215 if (l == 0)
4216 len = 0;
4217 else if (lp[written] == NL)
4218 {
4219 /* NL -> NUL translation */
4220 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4221 }
4222 else
4223 {
4224 s = vim_strchr(lp + written, NL);
4225 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4226 s == NULL ? l : (DWORD)(s - (lp + written)),
4227 &len, NULL);
4228 }
4229 if (len == (int)l)
4230 {
4231 /* Finished a line, add a NL, unless this line should not have
4232 * one. */
4233 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004234 || (!curbuf->b_p_bin
4235 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004236 || (lnum != curbuf->b_no_eol_lnum
4237 && (lnum != curbuf->b_ml.ml_line_count
4238 || curbuf->b_p_eol)))
4239 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004240 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004241 }
4242
4243 ++lnum;
4244 if (lnum > curbuf->b_op_end.lnum)
4245 break;
4246
4247 lp = ml_get(lnum);
4248 written = 0;
4249 }
4250 else if (len > 0)
4251 written += len;
4252 }
4253
4254 /* finished all the lines, close pipe */
4255 CloseHandle(g_hChildStd_IN_Wr);
4256 ExitThread(0);
4257}
4258
4259
4260# define BUFLEN 100 /* length for buffer, stolen from unix version */
4261
4262/*
4263 * This function read from the children's stdout and write the
4264 * data on screen or in the buffer accordingly.
4265 */
4266 static void
4267dump_pipe(int options,
4268 HANDLE g_hChildStd_OUT_Rd,
4269 garray_T *ga,
4270 char_u buffer[],
4271 DWORD *buffer_off)
4272{
4273 DWORD availableBytes = 0;
4274 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004275 int ret;
4276 DWORD len;
4277 DWORD toRead;
4278 int repeatCount;
4279
4280 /* we query the pipe to see if there is any data to read
4281 * to avoid to perform a blocking read */
4282 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4283 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004284 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004285 NULL, /* number of read bytes */
4286 &availableBytes, /* available bytes total */
4287 NULL); /* byteLeft */
4288
4289 repeatCount = 0;
4290 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004291 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004292 {
4293 repeatCount++;
4294 toRead =
4295# ifdef FEAT_MBYTE
4296 (DWORD)(BUFLEN - *buffer_off);
4297# else
4298 (DWORD)BUFLEN;
4299# endif
4300 toRead = availableBytes < toRead ? availableBytes : toRead;
4301 ReadFile(g_hChildStd_OUT_Rd, buffer
4302# ifdef FEAT_MBYTE
4303 + *buffer_off, toRead
4304# else
4305 , toRead
4306# endif
4307 , &len, NULL);
4308
4309 /* If we haven't read anything, there is a problem */
4310 if (len == 0)
4311 break;
4312
4313 availableBytes -= len;
4314
4315 if (options & SHELL_READ)
4316 {
4317 /* Do NUL -> NL translation, append NL separated
4318 * lines to the current buffer. */
4319 for (i = 0; i < len; ++i)
4320 {
4321 if (buffer[i] == NL)
4322 append_ga_line(ga);
4323 else if (buffer[i] == NUL)
4324 ga_append(ga, NL);
4325 else
4326 ga_append(ga, buffer[i]);
4327 }
4328 }
4329# ifdef FEAT_MBYTE
4330 else if (has_mbyte)
4331 {
4332 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004333 int c;
4334 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004335
4336 len += *buffer_off;
4337 buffer[len] = NUL;
4338
4339 /* Check if the last character in buffer[] is
4340 * incomplete, keep these bytes for the next
4341 * round. */
4342 for (p = buffer; p < buffer + len; p += l)
4343 {
4344 l = mb_cptr2len(p);
4345 if (l == 0)
4346 l = 1; /* NUL byte? */
4347 else if (MB_BYTE2LEN(*p) != l)
4348 break;
4349 }
4350 if (p == buffer) /* no complete character */
4351 {
4352 /* avoid getting stuck at an illegal byte */
4353 if (len >= 12)
4354 ++p;
4355 else
4356 {
4357 *buffer_off = len;
4358 return;
4359 }
4360 }
4361 c = *p;
4362 *p = NUL;
4363 msg_puts(buffer);
4364 if (p < buffer + len)
4365 {
4366 *p = c;
4367 *buffer_off = (DWORD)((buffer + len) - p);
4368 mch_memmove(buffer, p, *buffer_off);
4369 return;
4370 }
4371 *buffer_off = 0;
4372 }
4373# endif /* FEAT_MBYTE */
4374 else
4375 {
4376 buffer[len] = NUL;
4377 msg_puts(buffer);
4378 }
4379
4380 windgoto(msg_row, msg_col);
4381 cursor_on();
4382 out_flush();
4383 }
4384}
4385
4386/*
4387 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4388 * for communication and doesn't open any new window.
4389 */
4390 static int
4391mch_system_piped(char *cmd, int options)
4392{
4393 STARTUPINFO si;
4394 PROCESS_INFORMATION pi;
4395 DWORD ret = 0;
4396
4397 HANDLE g_hChildStd_IN_Rd = NULL;
4398 HANDLE g_hChildStd_IN_Wr = NULL;
4399 HANDLE g_hChildStd_OUT_Rd = NULL;
4400 HANDLE g_hChildStd_OUT_Wr = NULL;
4401
4402 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4403 DWORD len;
4404
4405 /* buffer used to receive keys */
4406 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4407 int ta_len = 0; /* valid bytes in ta_buf[] */
4408
4409 DWORD i;
4410 int c;
4411 int noread_cnt = 0;
4412 garray_T ga;
4413 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004414 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004415 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416
4417 SECURITY_ATTRIBUTES saAttr;
4418
4419 /* Set the bInheritHandle flag so pipe handles are inherited. */
4420 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4421 saAttr.bInheritHandle = TRUE;
4422 saAttr.lpSecurityDescriptor = NULL;
4423
4424 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4425 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4426 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4427 /* Create a pipe for the child process's STDIN. */
4428 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4429 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4430 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4431 {
4432 CloseHandle(g_hChildStd_IN_Rd);
4433 CloseHandle(g_hChildStd_IN_Wr);
4434 CloseHandle(g_hChildStd_OUT_Rd);
4435 CloseHandle(g_hChildStd_OUT_Wr);
4436 MSG_PUTS(_("\nCannot create pipes\n"));
4437 }
4438
4439 si.cb = sizeof(si);
4440 si.lpReserved = NULL;
4441 si.lpDesktop = NULL;
4442 si.lpTitle = NULL;
4443 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4444
4445 /* set-up our file redirection */
4446 si.hStdError = g_hChildStd_OUT_Wr;
4447 si.hStdOutput = g_hChildStd_OUT_Wr;
4448 si.hStdInput = g_hChildStd_IN_Rd;
4449 si.wShowWindow = SW_HIDE;
4450 si.cbReserved2 = 0;
4451 si.lpReserved2 = NULL;
4452
4453 if (options & SHELL_READ)
4454 ga_init2(&ga, 1, BUFLEN);
4455
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004456 if (cmd != NULL)
4457 {
4458 p = (char *)vim_strsave((char_u *)cmd);
4459 if (p != NULL)
4460 unescape_shellxquote((char_u *)p, p_sxe);
4461 else
4462 p = cmd;
4463 }
4464
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004465 /* Now, run the command.
4466 * About "Inherit handles" being TRUE: this command can be litigious,
4467 * handle inheritance was deactivated for pending temp file, but, if we
4468 * deactivate it, the pipes don't work for some reason. */
4469 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004470
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004471 if (p != cmd)
4472 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004473
4474 /* Close our unused side of the pipes */
4475 CloseHandle(g_hChildStd_IN_Rd);
4476 CloseHandle(g_hChildStd_OUT_Wr);
4477
4478 if (options & SHELL_WRITE)
4479 {
4480 HANDLE thread =
4481 CreateThread(NULL, /* security attributes */
4482 0, /* default stack size */
4483 sub_process_writer, /* function to be executed */
4484 g_hChildStd_IN_Wr, /* parameter */
4485 0, /* creation flag, start immediately */
4486 NULL); /* we don't care about thread id */
4487 CloseHandle(thread);
4488 g_hChildStd_IN_Wr = NULL;
4489 }
4490
4491 /* Keep updating the window while waiting for the shell to finish. */
4492 for (;;)
4493 {
4494 MSG msg;
4495
Bram Moolenaar175d0702013-12-11 18:36:33 +01004496 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004497 {
4498 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004499 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004500 }
4501
4502 /* write pipe information in the window */
4503 if ((options & (SHELL_READ|SHELL_WRITE))
4504# ifdef FEAT_GUI
4505 || gui.in_use
4506# endif
4507 )
4508 {
4509 len = 0;
4510 if (!(options & SHELL_EXPAND)
4511 && ((options &
4512 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4513 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4514# ifdef FEAT_GUI
4515 || gui.in_use
4516# endif
4517 )
4518 && (ta_len > 0 || noread_cnt > 4))
4519 {
4520 if (ta_len == 0)
4521 {
4522 /* Get extra characters when we don't have any. Reset the
4523 * counter and timer. */
4524 noread_cnt = 0;
4525# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4526 gettimeofday(&start_tv, NULL);
4527# endif
4528 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4529 }
4530 if (ta_len > 0 || len > 0)
4531 {
4532 /*
4533 * For pipes: Check for CTRL-C: send interrupt signal to
4534 * child. Check for CTRL-D: EOF, close pipe to child.
4535 */
4536 if (len == 1 && cmd != NULL)
4537 {
4538 if (ta_buf[ta_len] == Ctrl_C)
4539 {
4540 /* Learn what exit code is expected, for
4541 * now put 9 as SIGKILL */
4542 TerminateProcess(pi.hProcess, 9);
4543 }
4544 if (ta_buf[ta_len] == Ctrl_D)
4545 {
4546 CloseHandle(g_hChildStd_IN_Wr);
4547 g_hChildStd_IN_Wr = NULL;
4548 }
4549 }
4550
4551 /* replace K_BS by <BS> and K_DEL by <DEL> */
4552 for (i = ta_len; i < ta_len + len; ++i)
4553 {
4554 if (ta_buf[i] == CSI && len - i > 2)
4555 {
4556 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4557 if (c == K_DEL || c == K_KDEL || c == K_BS)
4558 {
4559 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4560 (size_t)(len - i - 2));
4561 if (c == K_DEL || c == K_KDEL)
4562 ta_buf[i] = DEL;
4563 else
4564 ta_buf[i] = Ctrl_H;
4565 len -= 2;
4566 }
4567 }
4568 else if (ta_buf[i] == '\r')
4569 ta_buf[i] = '\n';
4570# ifdef FEAT_MBYTE
4571 if (has_mbyte)
4572 i += (*mb_ptr2len_len)(ta_buf + i,
4573 ta_len + len - i) - 1;
4574# endif
4575 }
4576
4577 /*
4578 * For pipes: echo the typed characters. For a pty this
4579 * does not seem to work.
4580 */
4581 for (i = ta_len; i < ta_len + len; ++i)
4582 {
4583 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4584 msg_putchar(ta_buf[i]);
4585# ifdef FEAT_MBYTE
4586 else if (has_mbyte)
4587 {
4588 int l = (*mb_ptr2len)(ta_buf + i);
4589
4590 msg_outtrans_len(ta_buf + i, l);
4591 i += l - 1;
4592 }
4593# endif
4594 else
4595 msg_outtrans_len(ta_buf + i, 1);
4596 }
4597 windgoto(msg_row, msg_col);
4598 out_flush();
4599
4600 ta_len += len;
4601
4602 /*
4603 * Write the characters to the child, unless EOF has been
4604 * typed for pipes. Write one character at a time, to
4605 * avoid losing too much typeahead. When writing buffer
4606 * lines, drop the typed characters (only check for
4607 * CTRL-C).
4608 */
4609 if (options & SHELL_WRITE)
4610 ta_len = 0;
4611 else if (g_hChildStd_IN_Wr != NULL)
4612 {
4613 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4614 1, &len, NULL);
4615 // if we are typing in, we want to keep things reactive
4616 delay = 1;
4617 if (len > 0)
4618 {
4619 ta_len -= len;
4620 mch_memmove(ta_buf, ta_buf + len, ta_len);
4621 }
4622 }
4623 }
4624 }
4625 }
4626
4627 if (ta_len)
4628 ui_inchar_undo(ta_buf, ta_len);
4629
4630 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4631 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004632 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004633 break;
4634 }
4635
4636 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004637 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004638
4639 /* We start waiting for a very short time and then increase it, so
4640 * that we respond quickly when the process is quick, and don't
4641 * consume too much overhead when it's slow. */
4642 if (delay < 50)
4643 delay += 10;
4644 }
4645
4646 /* Close the pipe */
4647 CloseHandle(g_hChildStd_OUT_Rd);
4648 if (g_hChildStd_IN_Wr != NULL)
4649 CloseHandle(g_hChildStd_IN_Wr);
4650
4651 WaitForSingleObject(pi.hProcess, INFINITE);
4652
4653 /* Get the command exit code */
4654 GetExitCodeProcess(pi.hProcess, &ret);
4655
4656 if (options & SHELL_READ)
4657 {
4658 if (ga.ga_len > 0)
4659 {
4660 append_ga_line(&ga);
4661 /* remember that the NL was missing */
4662 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4663 }
4664 else
4665 curbuf->b_no_eol_lnum = 0;
4666 ga_clear(&ga);
4667 }
4668
4669 /* Close the handles to the subprocess, so that it goes away */
4670 CloseHandle(pi.hThread);
4671 CloseHandle(pi.hProcess);
4672
4673 return ret;
4674}
4675
4676 static int
4677mch_system(char *cmd, int options)
4678{
4679 /* if we can pipe and the shelltemp option is off */
4680 if (allowPiping && !p_stmp)
4681 return mch_system_piped(cmd, options);
4682 else
4683 return mch_system_classic(cmd, options);
4684}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685#else
4686
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004687# ifdef FEAT_MBYTE
4688 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004689mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004690{
4691 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4692 {
4693 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4694 if (wcmd != NULL)
4695 {
4696 int ret = _wsystem(wcmd);
4697 vim_free(wcmd);
4698 return ret;
4699 }
4700 }
4701 return system(cmd);
4702}
4703# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004704# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004705# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706
4707#endif
4708
4709/*
4710 * Either execute a command by calling the shell or start a new shell
4711 */
4712 int
4713mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004714 char_u *cmd,
4715 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716{
4717 int x = 0;
4718 int tmode = cur_tmode;
4719#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004720 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004721# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004722 int did_set_title = FALSE;
4723
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004724 /* Change the title to reflect that we are in a subshell. */
4725 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4726 {
4727 WCHAR szShellTitle[512];
4728
4729 if (GetConsoleTitleW(szShellTitle,
4730 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4731 {
4732 if (cmd == NULL)
4733 wcscat(szShellTitle, L" :sh");
4734 else
4735 {
4736 WCHAR *wn = enc_to_utf16(cmd, NULL);
4737
4738 if (wn != NULL)
4739 {
4740 wcscat(szShellTitle, L" - !");
4741 if ((wcslen(szShellTitle) + wcslen(wn) <
4742 sizeof(szShellTitle)/sizeof(WCHAR)))
4743 wcscat(szShellTitle, wn);
4744 SetConsoleTitleW(szShellTitle);
4745 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004746 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004747 }
4748 }
4749 }
4750 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004751 if (!did_set_title)
4752# endif
4753 /* Change the title to reflect that we are in a subshell. */
4754 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004756 if (cmd == NULL)
4757 strcat(szShellTitle, " :sh");
4758 else
4759 {
4760 strcat(szShellTitle, " - !");
4761 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4762 strcat(szShellTitle, cmd);
4763 }
4764 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766#endif
4767
4768 out_flush();
4769
4770#ifdef MCH_WRITE_DUMP
4771 if (fdDump)
4772 {
4773 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4774 fflush(fdDump);
4775 }
4776#endif
4777
4778 /*
4779 * Catch all deadly signals while running the external command, because a
4780 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4781 */
4782 signal(SIGINT, SIG_IGN);
4783#if defined(__GNUC__) && !defined(__MINGW32__)
4784 signal(SIGKILL, SIG_IGN);
4785#else
4786 signal(SIGBREAK, SIG_IGN);
4787#endif
4788 signal(SIGILL, SIG_IGN);
4789 signal(SIGFPE, SIG_IGN);
4790 signal(SIGSEGV, SIG_IGN);
4791 signal(SIGTERM, SIG_IGN);
4792 signal(SIGABRT, SIG_IGN);
4793
4794 if (options & SHELL_COOKED)
4795 settmode(TMODE_COOK); /* set to normal mode */
4796
4797 if (cmd == NULL)
4798 {
4799 x = mch_system(p_sh, options);
4800 }
4801 else
4802 {
4803 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004804 char_u *newcmd = NULL;
4805 char_u *cmdbase = cmd;
4806 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004807
4808 /* Skip a leading ", ( and "(. */
4809 if (*cmdbase == '"' )
4810 ++cmdbase;
4811 if (*cmdbase == '(')
4812 ++cmdbase;
4813
4814 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4815 {
4816 STARTUPINFO si;
4817 PROCESS_INFORMATION pi;
4818 DWORD flags = CREATE_NEW_CONSOLE;
4819 char_u *p;
4820
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004821 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004822 si.cb = sizeof(si);
4823 si.lpReserved = NULL;
4824 si.lpDesktop = NULL;
4825 si.lpTitle = NULL;
4826 si.dwFlags = 0;
4827 si.cbReserved2 = 0;
4828 si.lpReserved2 = NULL;
4829
4830 cmdbase = skipwhite(cmdbase + 5);
4831 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4832 && vim_iswhite(cmdbase[4]))
4833 {
4834 cmdbase = skipwhite(cmdbase + 4);
4835 si.dwFlags = STARTF_USESHOWWINDOW;
4836 si.wShowWindow = SW_SHOWMINNOACTIVE;
4837 }
4838 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4839 && vim_iswhite(cmdbase[2]))
4840 {
4841 cmdbase = skipwhite(cmdbase + 2);
4842 flags = CREATE_NO_WINDOW;
4843 si.dwFlags = STARTF_USESTDHANDLES;
4844 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004845 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004846 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004847 NULL, // Security att.
4848 OPEN_EXISTING, // Open flags
4849 FILE_ATTRIBUTE_NORMAL, // File att.
4850 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004851 si.hStdOutput = si.hStdInput;
4852 si.hStdError = si.hStdInput;
4853 }
4854
4855 /* Remove a trailing ", ) and )" if they have a match
4856 * at the start of the command. */
4857 if (cmdbase > cmd)
4858 {
4859 p = cmdbase + STRLEN(cmdbase);
4860 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4861 *--p = NUL;
4862 if (p > cmdbase && p[-1] == ')'
4863 && (*cmd =='(' || cmd[1] == '('))
4864 *--p = NUL;
4865 }
4866
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004867 newcmd = cmdbase;
4868 unescape_shellxquote(cmdbase, p_sxe);
4869
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004870 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004871 * If creating new console, arguments are passed to the
4872 * 'cmd.exe' as-is. If it's not, arguments are not treated
4873 * correctly for current 'cmd.exe'. So unescape characters in
4874 * shellxescape except '|' for avoiding to be treated as
4875 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004876 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877 if (flags != CREATE_NEW_CONSOLE)
4878 {
4879 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004880 char_u *cmd_shell = mch_getenv("COMSPEC");
4881
4882 if (cmd_shell == NULL || *cmd_shell == NUL)
4883 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004884
4885 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4886 if (subcmd != NULL)
4887 {
4888 /* make "cmd.exe /c arguments" */
4889 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004890 newcmd = lalloc(cmdlen, TRUE);
4891 if (newcmd != NULL)
4892 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004893 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004894 else
4895 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004896 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004897 }
4898 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004899
4900 /*
4901 * Now, start the command as a process, so that it doesn't
4902 * inherit our handles which causes unpleasant dangling swap
4903 * files if we exit before the spawned process
4904 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004905 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004906 x = 0;
4907 else
4908 {
4909 x = -1;
4910#ifdef FEAT_GUI_W32
4911 EMSG(_("E371: Command not found"));
4912#endif
4913 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004914
4915 if (newcmd != cmdbase)
4916 vim_free(newcmd);
4917
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004918 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004919 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004920 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004921 CloseHandle(si.hStdInput);
4922 }
4923 /* Close the handles to the subprocess, so that it goes away */
4924 CloseHandle(pi.hThread);
4925 CloseHandle(pi.hProcess);
4926 }
4927 else
4928 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004929 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004931 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004933 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4934
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004935 newcmd = lalloc(cmdlen, TRUE);
4936 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004937 {
4938#if defined(FEAT_GUI_W32)
4939 if (need_vimrun_warning)
4940 {
4941 MessageBox(NULL,
4942 _("VIMRUN.EXE not found in your $PATH.\n"
4943 "External commands will not pause after completion.\n"
4944 "See :help win32-vimrun for more information."),
4945 _("Vim Warning"),
4946 MB_ICONWARNING);
4947 need_vimrun_warning = FALSE;
4948 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004949 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004950 /* Use vimrun to execute the command. It opens a console
4951 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004952 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953 vimrun_path,
4954 (msg_silent != 0 || (options & SHELL_DOOUT))
4955 ? "-s " : "",
4956 p_sh, p_shcf, cmd);
4957 else
4958#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004959 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004960 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004961 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004962 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964 }
4965 }
4966
4967 if (tmode == TMODE_RAW)
4968 settmode(TMODE_RAW); /* set to raw mode */
4969
4970 /* Print the return value, unless "vimrun" was used. */
4971 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4972#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004973 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4974 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004975#endif
4976 )
4977 {
4978 smsg(_("shell returned %d"), x);
4979 msg_putchar('\n');
4980 }
4981#ifdef FEAT_TITLE
4982 resettitle();
4983#endif
4984
4985 signal(SIGINT, SIG_DFL);
4986#if defined(__GNUC__) && !defined(__MINGW32__)
4987 signal(SIGKILL, SIG_DFL);
4988#else
4989 signal(SIGBREAK, SIG_DFL);
4990#endif
4991 signal(SIGILL, SIG_DFL);
4992 signal(SIGFPE, SIG_DFL);
4993 signal(SIGSEGV, SIG_DFL);
4994 signal(SIGTERM, SIG_DFL);
4995 signal(SIGABRT, SIG_DFL);
4996
4997 return x;
4998}
4999
5000
5001#ifndef FEAT_GUI_W32
5002
5003/*
5004 * Start termcap mode
5005 */
5006 static void
5007termcap_mode_start(void)
5008{
5009 DWORD cmodein;
5010
5011 if (g_fTermcapMode)
5012 return;
5013
5014 SaveConsoleBuffer(&g_cbNonTermcap);
5015
5016 if (g_cbTermcap.IsValid)
5017 {
5018 /*
5019 * We've been in termcap mode before. Restore certain screen
5020 * characteristics, including the buffer size and the window
5021 * size. Since we will be redrawing the screen, we don't need
5022 * to restore the actual contents of the buffer.
5023 */
5024 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5025 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5026 Rows = g_cbTermcap.Info.dwSize.Y;
5027 Columns = g_cbTermcap.Info.dwSize.X;
5028 }
5029 else
5030 {
5031 /*
5032 * This is our first time entering termcap mode. Clear the console
5033 * screen buffer, and resize the buffer to match the current window
5034 * size. We will use this as the size of our editing environment.
5035 */
5036 ClearConsoleBuffer(g_attrCurrent);
5037 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5038 }
5039
5040#ifdef FEAT_TITLE
5041 resettitle();
5042#endif
5043
5044 GetConsoleMode(g_hConIn, &cmodein);
5045#ifdef FEAT_MOUSE
5046 if (g_fMouseActive)
5047 cmodein |= ENABLE_MOUSE_INPUT;
5048 else
5049 cmodein &= ~ENABLE_MOUSE_INPUT;
5050#endif
5051 cmodein |= ENABLE_WINDOW_INPUT;
5052 SetConsoleMode(g_hConIn, cmodein);
5053
5054 redraw_later_clear();
5055 g_fTermcapMode = TRUE;
5056}
5057
5058
5059/*
5060 * End termcap mode
5061 */
5062 static void
5063termcap_mode_end(void)
5064{
5065 DWORD cmodein;
5066 ConsoleBuffer *cb;
5067 COORD coord;
5068 DWORD dwDummy;
5069
5070 if (!g_fTermcapMode)
5071 return;
5072
5073 SaveConsoleBuffer(&g_cbTermcap);
5074
5075 GetConsoleMode(g_hConIn, &cmodein);
5076 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5077 SetConsoleMode(g_hConIn, cmodein);
5078
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005079#ifdef FEAT_RESTORE_ORIG_SCREEN
5080 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5081#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005083#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005084 RestoreConsoleBuffer(cb, p_rs);
5085 SetConsoleCursorInfo(g_hConOut, &g_cci);
5086
5087 if (p_rs || exiting)
5088 {
5089 /*
5090 * Clear anything that happens to be on the current line.
5091 */
5092 coord.X = 0;
5093 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5094 FillConsoleOutputCharacter(g_hConOut, ' ',
5095 cb->Info.dwSize.X, coord, &dwDummy);
5096 /*
5097 * The following is just for aesthetics. If we are exiting without
5098 * restoring the screen, then we want to have a prompt string
5099 * appear at the bottom line. However, the command interpreter
5100 * seems to always advance the cursor one line before displaying
5101 * the prompt string, which causes the screen to scroll. To
5102 * counter this, move the cursor up one line before exiting.
5103 */
5104 if (exiting && !p_rs)
5105 coord.Y--;
5106 /*
5107 * Position the cursor at the leftmost column of the desired row.
5108 */
5109 SetConsoleCursorPosition(g_hConOut, coord);
5110 }
5111
5112 g_fTermcapMode = FALSE;
5113}
5114#endif /* FEAT_GUI_W32 */
5115
5116
5117#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005118/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005119 void
5120mch_write(
5121 char_u *s,
5122 int len)
5123{
5124 /* never used */
5125}
5126
5127#else
5128
5129/*
5130 * clear `n' chars, starting from `coord'
5131 */
5132 static void
5133clear_chars(
5134 COORD coord,
5135 DWORD n)
5136{
5137 DWORD dwDummy;
5138
5139 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5140 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5141}
5142
5143
5144/*
5145 * Clear the screen
5146 */
5147 static void
5148clear_screen(void)
5149{
5150 g_coord.X = g_coord.Y = 0;
5151 clear_chars(g_coord, Rows * Columns);
5152}
5153
5154
5155/*
5156 * Clear to end of display
5157 */
5158 static void
5159clear_to_end_of_display(void)
5160{
5161 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5162 * Columns + (Columns - g_coord.X));
5163}
5164
5165
5166/*
5167 * Clear to end of line
5168 */
5169 static void
5170clear_to_end_of_line(void)
5171{
5172 clear_chars(g_coord, Columns - g_coord.X);
5173}
5174
5175
5176/*
5177 * Scroll the scroll region up by `cLines' lines
5178 */
5179 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005180scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005181{
5182 COORD oldcoord = g_coord;
5183
5184 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5185 delete_lines(cLines);
5186
5187 g_coord = oldcoord;
5188}
5189
5190
5191/*
5192 * Set the scroll region
5193 */
5194 static void
5195set_scroll_region(
5196 unsigned left,
5197 unsigned top,
5198 unsigned right,
5199 unsigned bottom)
5200{
5201 if (left >= right
5202 || top >= bottom
5203 || right > (unsigned) Columns - 1
5204 || bottom > (unsigned) Rows - 1)
5205 return;
5206
5207 g_srScrollRegion.Left = left;
5208 g_srScrollRegion.Top = top;
5209 g_srScrollRegion.Right = right;
5210 g_srScrollRegion.Bottom = bottom;
5211}
5212
5213
5214/*
5215 * Insert `cLines' lines at the current cursor position
5216 */
5217 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005218insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219{
5220 SMALL_RECT source;
5221 COORD dest;
5222 CHAR_INFO fill;
5223
5224 dest.X = 0;
5225 dest.Y = g_coord.Y + cLines;
5226
5227 source.Left = 0;
5228 source.Top = g_coord.Y;
5229 source.Right = g_srScrollRegion.Right;
5230 source.Bottom = g_srScrollRegion.Bottom - cLines;
5231
5232 fill.Char.AsciiChar = ' ';
5233 fill.Attributes = g_attrCurrent;
5234
5235 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5236
5237 /* Here we have to deal with a win32 console flake: If the scroll
5238 * region looks like abc and we scroll c to a and fill with d we get
5239 * cbd... if we scroll block c one line at a time to a, we get cdd...
5240 * vim expects cdd consistently... So we have to deal with that
5241 * here... (this also occurs scrolling the same way in the other
5242 * direction). */
5243
5244 if (source.Bottom < dest.Y)
5245 {
5246 COORD coord;
5247
5248 coord.X = 0;
5249 coord.Y = source.Bottom;
5250 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5251 }
5252}
5253
5254
5255/*
5256 * Delete `cLines' lines at the current cursor position
5257 */
5258 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005259delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005260{
5261 SMALL_RECT source;
5262 COORD dest;
5263 CHAR_INFO fill;
5264 int nb;
5265
5266 dest.X = 0;
5267 dest.Y = g_coord.Y;
5268
5269 source.Left = 0;
5270 source.Top = g_coord.Y + cLines;
5271 source.Right = g_srScrollRegion.Right;
5272 source.Bottom = g_srScrollRegion.Bottom;
5273
5274 fill.Char.AsciiChar = ' ';
5275 fill.Attributes = g_attrCurrent;
5276
5277 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5278
5279 /* Here we have to deal with a win32 console flake: If the scroll
5280 * region looks like abc and we scroll c to a and fill with d we get
5281 * cbd... if we scroll block c one line at a time to a, we get cdd...
5282 * vim expects cdd consistently... So we have to deal with that
5283 * here... (this also occurs scrolling the same way in the other
5284 * direction). */
5285
5286 nb = dest.Y + (source.Bottom - source.Top) + 1;
5287
5288 if (nb < source.Top)
5289 {
5290 COORD coord;
5291
5292 coord.X = 0;
5293 coord.Y = nb;
5294 clear_chars(coord, Columns * (source.Top - nb));
5295 }
5296}
5297
5298
5299/*
5300 * Set the cursor position
5301 */
5302 static void
5303gotoxy(
5304 unsigned x,
5305 unsigned y)
5306{
5307 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5308 return;
5309
5310 /* external cursor coords are 1-based; internal are 0-based */
5311 g_coord.X = x - 1;
5312 g_coord.Y = y - 1;
5313 SetConsoleCursorPosition(g_hConOut, g_coord);
5314}
5315
5316
5317/*
5318 * Set the current text attribute = (foreground | background)
5319 * See ../doc/os_win32.txt for the numbers.
5320 */
5321 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005322textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005323{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005324 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005325
5326 SetConsoleTextAttribute(g_hConOut, wAttr);
5327}
5328
5329
5330 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005331textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005332{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005333 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005334
5335 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5336}
5337
5338
5339 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005340textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005341{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005342 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005343
5344 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5345}
5346
5347
5348/*
5349 * restore the default text attribute (whatever we started with)
5350 */
5351 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005352normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353{
5354 textattr(g_attrDefault);
5355}
5356
5357
5358static WORD g_attrPreStandout = 0;
5359
5360/*
5361 * Make the text standout, by brightening it
5362 */
5363 static void
5364standout(void)
5365{
5366 g_attrPreStandout = g_attrCurrent;
5367 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5368}
5369
5370
5371/*
5372 * Turn off standout mode
5373 */
5374 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005375standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005376{
5377 if (g_attrPreStandout)
5378 {
5379 textattr(g_attrPreStandout);
5380 g_attrPreStandout = 0;
5381 }
5382}
5383
5384
5385/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005386 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005387 */
5388 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005389mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005390{
5391 char_u *p;
5392 int n;
5393
5394 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5395 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5396 if (T_ME[0] == ESC && T_ME[1] == '|')
5397 {
5398 p = T_ME + 2;
5399 n = getdigits(&p);
5400 if (*p == 'm' && n > 0)
5401 {
5402 cterm_normal_fg_color = (n & 0xf) + 1;
5403 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5404 }
5405 }
5406}
5407
5408
5409/*
5410 * visual bell: flash the screen
5411 */
5412 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005413visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414{
5415 COORD coordOrigin = {0, 0};
5416 WORD attrFlash = ~g_attrCurrent & 0xff;
5417
5418 DWORD dwDummy;
5419 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5420
5421 if (oldattrs == NULL)
5422 return;
5423 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5424 coordOrigin, &dwDummy);
5425 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5426 coordOrigin, &dwDummy);
5427
5428 Sleep(15); /* wait for 15 msec */
5429 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5430 coordOrigin, &dwDummy);
5431 vim_free(oldattrs);
5432}
5433
5434
5435/*
5436 * Make the cursor visible or invisible
5437 */
5438 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005439cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440{
5441 s_cursor_visible = fVisible;
5442#ifdef MCH_CURSOR_SHAPE
5443 mch_update_cursor();
5444#endif
5445}
5446
5447
5448/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005449 * write `cbToWrite' bytes in `pchBuf' to the screen
5450 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005451 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005452 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005453write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005454 char_u *pchBuf,
5455 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005456{
5457 COORD coord = g_coord;
5458 DWORD written;
5459
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005460#ifdef FEAT_MBYTE
5461 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5462 {
5463 static WCHAR *unicodebuf = NULL;
5464 static int unibuflen = 0;
5465 int length;
5466 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005467
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005468 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5469 if (unicodebuf == NULL || length > unibuflen)
5470 {
5471 vim_free(unicodebuf);
5472 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5473 unibuflen = length;
5474 }
5475 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5476 unicodebuf, unibuflen);
5477
5478 cells = mb_string2cells(pchBuf, cbToWrite);
5479 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5480 coord, &written);
5481 /* When writing fails or didn't write a single character, pretend one
5482 * character was written, otherwise we get stuck. */
5483 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5484 coord, &cchwritten) == 0
5485 || cchwritten == 0)
5486 cchwritten = 1;
5487
5488 if (cchwritten == length)
5489 {
5490 written = cbToWrite;
5491 g_coord.X += (SHORT)cells;
5492 }
5493 else
5494 {
5495 char_u *p = pchBuf;
5496 for (n = 0; n < cchwritten; n++)
5497 mb_cptr_adv(p);
5498 written = p - pchBuf;
5499 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5500 }
5501 }
5502 else
5503#endif
5504 {
5505 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5506 coord, &written);
5507 /* When writing fails or didn't write a single character, pretend one
5508 * character was written, otherwise we get stuck. */
5509 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5510 coord, &written) == 0
5511 || written == 0)
5512 written = 1;
5513
5514 g_coord.X += (SHORT) written;
5515 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005516
5517 while (g_coord.X > g_srScrollRegion.Right)
5518 {
5519 g_coord.X -= (SHORT) Columns;
5520 if (g_coord.Y < g_srScrollRegion.Bottom)
5521 g_coord.Y++;
5522 }
5523
5524 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5525
5526 return written;
5527}
5528
5529
5530/*
5531 * mch_write(): write the output buffer to the screen, translating ESC
5532 * sequences into calls to console output routines.
5533 */
5534 void
5535mch_write(
5536 char_u *s,
5537 int len)
5538{
5539 s[len] = NUL;
5540
5541 if (!term_console)
5542 {
5543 write(1, s, (unsigned)len);
5544 return;
5545 }
5546
5547 /* translate ESC | sequences into faked bios calls */
5548 while (len--)
5549 {
5550 /* optimization: use one single write_chars for runs of text,
5551 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005552 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005553
5554 if (p_wd)
5555 {
5556 WaitForChar(p_wd);
5557 if (prefix != 0)
5558 prefix = 1;
5559 }
5560
5561 if (prefix != 0)
5562 {
5563 DWORD nWritten;
5564
5565 nWritten = write_chars(s, prefix);
5566#ifdef MCH_WRITE_DUMP
5567 if (fdDump)
5568 {
5569 fputc('>', fdDump);
5570 fwrite(s, sizeof(char_u), nWritten, fdDump);
5571 fputs("<\n", fdDump);
5572 }
5573#endif
5574 len -= (nWritten - 1);
5575 s += nWritten;
5576 }
5577 else if (s[0] == '\n')
5578 {
5579 /* \n, newline: go to the beginning of the next line or scroll */
5580 if (g_coord.Y == g_srScrollRegion.Bottom)
5581 {
5582 scroll(1);
5583 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5584 }
5585 else
5586 {
5587 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5588 }
5589#ifdef MCH_WRITE_DUMP
5590 if (fdDump)
5591 fputs("\\n\n", fdDump);
5592#endif
5593 s++;
5594 }
5595 else if (s[0] == '\r')
5596 {
5597 /* \r, carriage return: go to beginning of line */
5598 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5599#ifdef MCH_WRITE_DUMP
5600 if (fdDump)
5601 fputs("\\r\n", fdDump);
5602#endif
5603 s++;
5604 }
5605 else if (s[0] == '\b')
5606 {
5607 /* \b, backspace: move cursor one position left */
5608 if (g_coord.X > g_srScrollRegion.Left)
5609 g_coord.X--;
5610 else if (g_coord.Y > g_srScrollRegion.Top)
5611 {
5612 g_coord.X = g_srScrollRegion.Right;
5613 g_coord.Y--;
5614 }
5615 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5616#ifdef MCH_WRITE_DUMP
5617 if (fdDump)
5618 fputs("\\b\n", fdDump);
5619#endif
5620 s++;
5621 }
5622 else if (s[0] == '\a')
5623 {
5624 /* \a, bell */
5625 MessageBeep(0xFFFFFFFF);
5626#ifdef MCH_WRITE_DUMP
5627 if (fdDump)
5628 fputs("\\a\n", fdDump);
5629#endif
5630 s++;
5631 }
5632 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5633 {
5634#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005635 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005637 char_u *p;
5638 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639
5640 switch (s[2])
5641 {
5642 /* one or two numeric arguments, separated by ';' */
5643
5644 case '0': case '1': case '2': case '3': case '4':
5645 case '5': case '6': case '7': case '8': case '9':
5646 p = s + 2;
5647 arg1 = getdigits(&p); /* no check for length! */
5648 if (p > s + len)
5649 break;
5650
5651 if (*p == ';')
5652 {
5653 ++p;
5654 arg2 = getdigits(&p); /* no check for length! */
5655 if (p > s + len)
5656 break;
5657
5658 if (*p == 'H')
5659 gotoxy(arg2, arg1);
5660 else if (*p == 'r')
5661 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5662 }
5663 else if (*p == 'A')
5664 {
5665 /* move cursor up arg1 lines in same column */
5666 gotoxy(g_coord.X + 1,
5667 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5668 }
5669 else if (*p == 'C')
5670 {
5671 /* move cursor right arg1 columns in same line */
5672 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5673 g_coord.Y + 1);
5674 }
5675 else if (*p == 'H')
5676 {
5677 gotoxy(1, arg1);
5678 }
5679 else if (*p == 'L')
5680 {
5681 insert_lines(arg1);
5682 }
5683 else if (*p == 'm')
5684 {
5685 if (arg1 == 0)
5686 normvideo();
5687 else
5688 textattr((WORD) arg1);
5689 }
5690 else if (*p == 'f')
5691 {
5692 textcolor((WORD) arg1);
5693 }
5694 else if (*p == 'b')
5695 {
5696 textbackground((WORD) arg1);
5697 }
5698 else if (*p == 'M')
5699 {
5700 delete_lines(arg1);
5701 }
5702
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005703 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 s = p + 1;
5705 break;
5706
5707
5708 /* Three-character escape sequences */
5709
5710 case 'A':
5711 /* move cursor up one line in same column */
5712 gotoxy(g_coord.X + 1,
5713 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5714 goto got3;
5715
5716 case 'B':
5717 visual_bell();
5718 goto got3;
5719
5720 case 'C':
5721 /* move cursor right one column in same line */
5722 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5723 g_coord.Y + 1);
5724 goto got3;
5725
5726 case 'E':
5727 termcap_mode_end();
5728 goto got3;
5729
5730 case 'F':
5731 standout();
5732 goto got3;
5733
5734 case 'f':
5735 standend();
5736 goto got3;
5737
5738 case 'H':
5739 gotoxy(1, 1);
5740 goto got3;
5741
5742 case 'j':
5743 clear_to_end_of_display();
5744 goto got3;
5745
5746 case 'J':
5747 clear_screen();
5748 goto got3;
5749
5750 case 'K':
5751 clear_to_end_of_line();
5752 goto got3;
5753
5754 case 'L':
5755 insert_lines(1);
5756 goto got3;
5757
5758 case 'M':
5759 delete_lines(1);
5760 goto got3;
5761
5762 case 'S':
5763 termcap_mode_start();
5764 goto got3;
5765
5766 case 'V':
5767 cursor_visible(TRUE);
5768 goto got3;
5769
5770 case 'v':
5771 cursor_visible(FALSE);
5772 goto got3;
5773
5774 got3:
5775 s += 3;
5776 len -= 2;
5777 }
5778
5779#ifdef MCH_WRITE_DUMP
5780 if (fdDump)
5781 {
5782 fputs("ESC | ", fdDump);
5783 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5784 fputc('\n', fdDump);
5785 }
5786#endif
5787 }
5788 else
5789 {
5790 /* Write a single character */
5791 DWORD nWritten;
5792
5793 nWritten = write_chars(s, 1);
5794#ifdef MCH_WRITE_DUMP
5795 if (fdDump)
5796 {
5797 fputc('>', fdDump);
5798 fwrite(s, sizeof(char_u), nWritten, fdDump);
5799 fputs("<\n", fdDump);
5800 }
5801#endif
5802
5803 len -= (nWritten - 1);
5804 s += nWritten;
5805 }
5806 }
5807
5808#ifdef MCH_WRITE_DUMP
5809 if (fdDump)
5810 fflush(fdDump);
5811#endif
5812}
5813
5814#endif /* FEAT_GUI_W32 */
5815
5816
5817/*
5818 * Delay for half a second.
5819 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005820/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821 void
5822mch_delay(
5823 long msec,
5824 int ignoreinput)
5825{
5826#ifdef FEAT_GUI_W32
5827 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005828#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005830# ifdef FEAT_MZSCHEME
5831 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5832 {
5833 int towait = p_mzq;
5834
5835 /* if msec is large enough, wait by portions in p_mzq */
5836 while (msec > 0)
5837 {
5838 mzvim_check_threads();
5839 if (msec < towait)
5840 towait = msec;
5841 Sleep(towait);
5842 msec -= towait;
5843 }
5844 }
5845 else
5846# endif
5847 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848 else
5849 WaitForChar(msec);
5850#endif
5851}
5852
5853
5854/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01005855 * This version of remove is not scared by a readonly (backup) file.
5856 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005857 * Return 0 for success, -1 for failure.
5858 */
5859 int
5860mch_remove(char_u *name)
5861{
5862#ifdef FEAT_MBYTE
5863 WCHAR *wn = NULL;
5864 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005865#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005866
Bram Moolenaar203258c2016-01-17 22:15:16 +01005867 /*
5868 * On Windows, deleting a directory's symbolic link is done by
5869 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
5870 */
5871 if (mch_isdir(name) && mch_is_symbolic_link(name))
5872 return mch_rmdir(name);
5873
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005874 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5875
5876#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005877 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5878 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005879 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880 if (wn != NULL)
5881 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882 n = DeleteFileW(wn) ? 0 : -1;
5883 vim_free(wn);
5884 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5885 return n;
5886 /* Retry with non-wide function (for Windows 98). */
5887 }
5888 }
5889#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005890 return DeleteFile(name) ? 0 : -1;
5891}
5892
5893
5894/*
5895 * check for an "interrupt signal": CTRL-break or CTRL-C
5896 */
5897 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005898mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005899{
5900#ifndef FEAT_GUI_W32 /* never used */
5901 if (g_fCtrlCPressed || g_fCBrkPressed)
5902 {
5903 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5904 got_int = TRUE;
5905 }
5906#endif
5907}
5908
Bram Moolenaaree273972016-01-02 21:11:51 +01005909/* physical RAM to leave for the OS */
5910#define WINNT_RESERVE_BYTES (256*1024*1024)
5911#define WIN95_RESERVE_BYTES (8*1024*1024)
5912
5913/*
5914 * How much main memory in KiB that can be used by VIM.
5915 */
5916/*ARGSUSED*/
5917 long_u
5918mch_total_mem(int special)
5919{
5920 PlatformId();
5921#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
5922 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5923 {
5924 MEMORYSTATUSEX ms;
5925
5926 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5927 * what fits in 32 bits. But it's not always available. */
5928 ms.dwLength = sizeof(MEMORYSTATUSEX);
5929 GlobalMemoryStatusEx(&ms);
5930 if (ms.ullAvailVirtual < ms.ullTotalPhys)
5931 {
5932 /* Process address space fits in physical RAM, use all of it. */
5933 return (long_u)(ms.ullAvailVirtual / 1024);
5934 }
5935 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
5936 {
5937 /* Catch old NT box or perverse hardware setup. */
5938 return (long_u)((ms.ullTotalPhys / 2) / 1024);
5939 }
5940 /* Use physical RAM less reserve for OS + data. */
5941 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
5942 }
5943 else
5944#endif
5945 {
5946 /* Pre-XP or 95 OS handling. */
5947 MEMORYSTATUS ms;
5948 long_u os_reserve_bytes;
5949
5950 ms.dwLength = sizeof(MEMORYSTATUS);
5951 GlobalMemoryStatus(&ms);
5952 if (ms.dwAvailVirtual < ms.dwTotalPhys)
5953 {
5954 /* Process address space fits in physical RAM, use all of it. */
5955 return (long_u)(ms.dwAvailVirtual / 1024);
5956 }
5957 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
5958 ? WINNT_RESERVE_BYTES
5959 : WIN95_RESERVE_BYTES;
5960 if (ms.dwTotalPhys <= os_reserve_bytes)
5961 {
5962 /* Catch old boxes or perverse hardware setup. */
5963 return (long_u)((ms.dwTotalPhys / 2) / 1024);
5964 }
5965 /* Use physical RAM less reserve for OS + data. */
5966 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
5967 }
5968}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970#ifdef FEAT_MBYTE
5971/*
5972 * Same code as below, but with wide functions and no comments.
5973 * Return 0 for success, non-zero for failure.
5974 */
5975 int
5976mch_wrename(WCHAR *wold, WCHAR *wnew)
5977{
5978 WCHAR *p;
5979 int i;
5980 WCHAR szTempFile[_MAX_PATH + 1];
5981 WCHAR szNewPath[_MAX_PATH + 1];
5982 HANDLE hf;
5983
5984 if (!mch_windows95())
5985 {
5986 p = wold;
5987 for (i = 0; wold[i] != NUL; ++i)
5988 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5989 && wold[i + 1] != 0)
5990 p = wold + i + 1;
5991 if ((int)(wold + i - p) < 8 || p[6] != '~')
5992 return (MoveFileW(wold, wnew) == 0);
5993 }
5994
5995 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5996 return -1;
5997 *p = NUL;
5998
5999 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6000 return -2;
6001
6002 if (!DeleteFileW(szTempFile))
6003 return -3;
6004
6005 if (!MoveFileW(wold, szTempFile))
6006 return -4;
6007
6008 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6009 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6010 return -5;
6011 if (!CloseHandle(hf))
6012 return -6;
6013
6014 if (!MoveFileW(szTempFile, wnew))
6015 {
6016 (void)MoveFileW(szTempFile, wold);
6017 return -7;
6018 }
6019
6020 DeleteFileW(szTempFile);
6021
6022 if (!DeleteFileW(wold))
6023 return -8;
6024
6025 return 0;
6026}
6027#endif
6028
6029
6030/*
6031 * mch_rename() works around a bug in rename (aka MoveFile) in
6032 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6033 * file whose short file name is "FOO.BAR" (its long file name will
6034 * be correct: "foo.bar~"). Because a file can be accessed by
6035 * either its SFN or its LFN, "foo.bar" has effectively been
6036 * renamed to "foo.bar", which is not at all what was wanted. This
6037 * seems to happen only when renaming files with three-character
6038 * extensions by appending a suffix that does not include ".".
6039 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6040 *
6041 * There is another problem, which isn't really a bug but isn't right either:
6042 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6043 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6044 * service pack 6. Doesn't seem to happen on Windows 98.
6045 *
6046 * Like rename(), returns 0 upon success, non-zero upon failure.
6047 * Should probably set errno appropriately when errors occur.
6048 */
6049 int
6050mch_rename(
6051 const char *pszOldFile,
6052 const char *pszNewFile)
6053{
6054 char szTempFile[_MAX_PATH+1];
6055 char szNewPath[_MAX_PATH+1];
6056 char *pszFilePart;
6057 HANDLE hf;
6058#ifdef FEAT_MBYTE
6059 WCHAR *wold = NULL;
6060 WCHAR *wnew = NULL;
6061 int retval = -1;
6062
6063 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6064 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006065 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6066 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006067 if (wold != NULL && wnew != NULL)
6068 retval = mch_wrename(wold, wnew);
6069 vim_free(wold);
6070 vim_free(wnew);
6071 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6072 return retval;
6073 /* Retry with non-wide function (for Windows 98). */
6074 }
6075#endif
6076
6077 /*
6078 * No need to play tricks if not running Windows 95, unless the file name
6079 * contains a "~" as the seventh character.
6080 */
6081 if (!mch_windows95())
6082 {
6083 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6084 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6085 return rename(pszOldFile, pszNewFile);
6086 }
6087
6088 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6089 * a directory, no error is returned and pszFilePart will be NULL. */
6090 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6091 || pszFilePart == NULL)
6092 return -1;
6093 *pszFilePart = NUL;
6094
6095 /* Get (and create) a unique temporary file name in directory of new file */
6096 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6097 return -2;
6098
6099 /* blow the temp file away */
6100 if (!DeleteFile(szTempFile))
6101 return -3;
6102
6103 /* rename old file to the temp file */
6104 if (!MoveFile(pszOldFile, szTempFile))
6105 return -4;
6106
6107 /* now create an empty file called pszOldFile; this prevents the operating
6108 * system using pszOldFile as an alias (SFN) if we're renaming within the
6109 * same directory. For example, we're editing a file called
6110 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6111 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6112 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006113 * cause all sorts of problems later in buf_write(). So, we create an
6114 * empty file called filena~1.txt and the system will have to find some
6115 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 */
6117 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6118 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6119 return -5;
6120 if (!CloseHandle(hf))
6121 return -6;
6122
6123 /* rename the temp file to the new file */
6124 if (!MoveFile(szTempFile, pszNewFile))
6125 {
6126 /* Renaming failed. Rename the file back to its old name, so that it
6127 * looks like nothing happened. */
6128 (void)MoveFile(szTempFile, pszOldFile);
6129
6130 return -7;
6131 }
6132
6133 /* Seems to be left around on Novell filesystems */
6134 DeleteFile(szTempFile);
6135
6136 /* finally, remove the empty old file */
6137 if (!DeleteFile(pszOldFile))
6138 return -8;
6139
6140 return 0; /* success */
6141}
6142
6143/*
6144 * Get the default shell for the current hardware platform
6145 */
6146 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006147default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148{
6149 char* psz = NULL;
6150
6151 PlatformId();
6152
6153 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6154 psz = "cmd.exe";
6155 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6156 psz = "command.com";
6157
6158 return psz;
6159}
6160
6161/*
6162 * mch_access() extends access() to do more detailed check on network drives.
6163 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6164 */
6165 int
6166mch_access(char *n, int p)
6167{
6168 HANDLE hFile;
6169 DWORD am;
6170 int retval = -1; /* default: fail */
6171#ifdef FEAT_MBYTE
6172 WCHAR *wn = NULL;
6173
6174 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006175 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176#endif
6177
6178 if (mch_isdir(n))
6179 {
6180 char TempName[_MAX_PATH + 16] = "";
6181#ifdef FEAT_MBYTE
6182 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6183#endif
6184
6185 if (p & R_OK)
6186 {
6187 /* Read check is performed by seeing if we can do a find file on
6188 * the directory for any file. */
6189#ifdef FEAT_MBYTE
6190 if (wn != NULL)
6191 {
6192 int i;
6193 WIN32_FIND_DATAW d;
6194
6195 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6196 TempNameW[i] = wn[i];
6197 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6198 TempNameW[i++] = '\\';
6199 TempNameW[i++] = '*';
6200 TempNameW[i++] = 0;
6201
6202 hFile = FindFirstFileW(TempNameW, &d);
6203 if (hFile == INVALID_HANDLE_VALUE)
6204 {
6205 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6206 goto getout;
6207
6208 /* Retry with non-wide function (for Windows 98). */
6209 vim_free(wn);
6210 wn = NULL;
6211 }
6212 else
6213 (void)FindClose(hFile);
6214 }
6215 if (wn == NULL)
6216#endif
6217 {
6218 char *pch;
6219 WIN32_FIND_DATA d;
6220
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006221 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222 pch = TempName + STRLEN(TempName) - 1;
6223 if (*pch != '\\' && *pch != '/')
6224 *++pch = '\\';
6225 *++pch = '*';
6226 *++pch = NUL;
6227
6228 hFile = FindFirstFile(TempName, &d);
6229 if (hFile == INVALID_HANDLE_VALUE)
6230 goto getout;
6231 (void)FindClose(hFile);
6232 }
6233 }
6234
6235 if (p & W_OK)
6236 {
6237 /* Trying to create a temporary file in the directory should catch
6238 * directories on read-only network shares. However, in
6239 * directories whose ACL allows writes but denies deletes will end
6240 * up keeping the temporary file :-(. */
6241#ifdef FEAT_MBYTE
6242 if (wn != NULL)
6243 {
6244 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6245 {
6246 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6247 goto getout;
6248
6249 /* Retry with non-wide function (for Windows 98). */
6250 vim_free(wn);
6251 wn = NULL;
6252 }
6253 else
6254 DeleteFileW(TempNameW);
6255 }
6256 if (wn == NULL)
6257#endif
6258 {
6259 if (!GetTempFileName(n, "VIM", 0, TempName))
6260 goto getout;
6261 mch_remove((char_u *)TempName);
6262 }
6263 }
6264 }
6265 else
6266 {
6267 /* Trying to open the file for the required access does ACL, read-only
6268 * network share, and file attribute checks. */
6269 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6270 | ((p & R_OK) ? GENERIC_READ : 0);
6271#ifdef FEAT_MBYTE
6272 if (wn != NULL)
6273 {
6274 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6275 if (hFile == INVALID_HANDLE_VALUE
6276 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6277 {
6278 /* Retry with non-wide function (for Windows 98). */
6279 vim_free(wn);
6280 wn = NULL;
6281 }
6282 }
6283 if (wn == NULL)
6284#endif
6285 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6286 if (hFile == INVALID_HANDLE_VALUE)
6287 goto getout;
6288 CloseHandle(hFile);
6289 }
6290
6291 retval = 0; /* success */
6292getout:
6293#ifdef FEAT_MBYTE
6294 vim_free(wn);
6295#endif
6296 return retval;
6297}
6298
6299#if defined(FEAT_MBYTE) || defined(PROTO)
6300/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006301 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 */
6303 int
6304mch_open(char *name, int flags, int mode)
6305{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006306 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6307# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006308 WCHAR *wn;
6309 int f;
6310
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006311 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006313 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 if (wn != NULL)
6315 {
6316 f = _wopen(wn, flags, mode);
6317 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006318 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 return f;
6320 /* Retry with non-wide function (for Windows 98). Can't use
6321 * GetLastError() here and it's unclear what errno gets set to if
6322 * the _wopen() fails for missing wide functions. */
6323 }
6324 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006325# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006327 /* open() can open a file which name is longer than _MAX_PATH bytes
6328 * and shorter than _MAX_PATH characters successfully, but sometimes it
6329 * causes unexpected error in another part. We make it an error explicitly
6330 * here. */
6331 if (strlen(name) >= _MAX_PATH)
6332 return -1;
6333
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 return open(name, flags, mode);
6335}
6336
6337/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006338 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 */
6340 FILE *
6341mch_fopen(char *name, char *mode)
6342{
6343 WCHAR *wn, *wm;
6344 FILE *f = NULL;
6345
6346 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6347# ifdef __BORLANDC__
6348 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6349 && g_PlatformId == VER_PLATFORM_WIN32_NT
6350# endif
6351 )
6352 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006353# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006354 /* Work around an annoying assertion in the Microsoft debug CRT
6355 * when mode's text/binary setting doesn't match _get_fmode(). */
6356 char newMode = mode[strlen(mode) - 1];
6357 int oldMode = 0;
6358
6359 _get_fmode(&oldMode);
6360 if (newMode == 't')
6361 _set_fmode(_O_TEXT);
6362 else if (newMode == 'b')
6363 _set_fmode(_O_BINARY);
6364# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006365 wn = enc_to_utf16(name, NULL);
6366 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367 if (wn != NULL && wm != NULL)
6368 f = _wfopen(wn, wm);
6369 vim_free(wn);
6370 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006371
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006372# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006373 _set_fmode(oldMode);
6374# endif
6375
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006376 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377 return f;
6378 /* Retry with non-wide function (for Windows 98). Can't use
6379 * GetLastError() here and it's unclear what errno gets set to if
6380 * the _wfopen() fails for missing wide functions. */
6381 }
6382
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006383 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6384 * and shorter than _MAX_PATH characters successfully, but sometimes it
6385 * causes unexpected error in another part. We make it an error explicitly
6386 * here. */
6387 if (strlen(name) >= _MAX_PATH)
6388 return NULL;
6389
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390 return fopen(name, mode);
6391}
6392#endif
6393
6394#ifdef FEAT_MBYTE
6395/*
6396 * SUB STREAM (aka info stream) handling:
6397 *
6398 * NTFS can have sub streams for each file. Normal contents of file is
6399 * stored in the main stream, and extra contents (author information and
6400 * title and so on) can be stored in sub stream. After Windows 2000, user
6401 * can access and store those informations in sub streams via explorer's
6402 * property menuitem in right click menu. Those informations in sub streams
6403 * were lost when copying only the main stream. So we have to copy sub
6404 * streams.
6405 *
6406 * Incomplete explanation:
6407 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6408 * More useful info and an example:
6409 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6410 */
6411
6412/*
6413 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6414 * and write to stream "substream" of file "to".
6415 * Errors are ignored.
6416 */
6417 static void
6418copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6419{
6420 HANDLE hTo;
6421 WCHAR *to_name;
6422
6423 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6424 wcscpy(to_name, to);
6425 wcscat(to_name, substream);
6426
6427 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6428 FILE_ATTRIBUTE_NORMAL, NULL);
6429 if (hTo != INVALID_HANDLE_VALUE)
6430 {
6431 long done;
6432 DWORD todo;
6433 DWORD readcnt, written;
6434 char buf[4096];
6435
6436 /* Copy block of bytes at a time. Abort when something goes wrong. */
6437 for (done = 0; done < len; done += written)
6438 {
6439 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006440 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6441 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006442 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6443 FALSE, FALSE, context)
6444 || readcnt != todo
6445 || !WriteFile(hTo, buf, todo, &written, NULL)
6446 || written != todo)
6447 break;
6448 }
6449 CloseHandle(hTo);
6450 }
6451
6452 free(to_name);
6453}
6454
6455/*
6456 * Copy info streams from file "from" to file "to".
6457 */
6458 static void
6459copy_infostreams(char_u *from, char_u *to)
6460{
6461 WCHAR *fromw;
6462 WCHAR *tow;
6463 HANDLE sh;
6464 WIN32_STREAM_ID sid;
6465 int headersize;
6466 WCHAR streamname[_MAX_PATH];
6467 DWORD readcount;
6468 void *context = NULL;
6469 DWORD lo, hi;
6470 int len;
6471
6472 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006473 fromw = enc_to_utf16(from, NULL);
6474 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475 if (fromw != NULL && tow != NULL)
6476 {
6477 /* Open the file for reading. */
6478 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6479 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6480 if (sh != INVALID_HANDLE_VALUE)
6481 {
6482 /* Use BackupRead() to find the info streams. Repeat until we
6483 * have done them all.*/
6484 for (;;)
6485 {
6486 /* Get the header to find the length of the stream name. If
6487 * the "readcount" is zero we have done all info streams. */
6488 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006489 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006490 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6491 &readcount, FALSE, FALSE, &context)
6492 || readcount == 0)
6493 break;
6494
6495 /* We only deal with streams that have a name. The normal
6496 * file data appears to be without a name, even though docs
6497 * suggest it is called "::$DATA". */
6498 if (sid.dwStreamNameSize > 0)
6499 {
6500 /* Read the stream name. */
6501 if (!BackupRead(sh, (LPBYTE)streamname,
6502 sid.dwStreamNameSize,
6503 &readcount, FALSE, FALSE, &context))
6504 break;
6505
6506 /* Copy an info stream with a name ":anything:$DATA".
6507 * Skip "::$DATA", it has no stream name (examples suggest
6508 * it might be used for the normal file contents).
6509 * Note that BackupRead() counts bytes, but the name is in
6510 * wide characters. */
6511 len = readcount / sizeof(WCHAR);
6512 streamname[len] = 0;
6513 if (len > 7 && wcsicmp(streamname + len - 6,
6514 L":$DATA") == 0)
6515 {
6516 streamname[len - 6] = 0;
6517 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006518 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 }
6520 }
6521
6522 /* Advance to the next stream. We might try seeking too far,
6523 * but BackupSeek() doesn't skip over stream borders, thus
6524 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006525 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526 &lo, &hi, &context);
6527 }
6528
6529 /* Clear the context. */
6530 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6531
6532 CloseHandle(sh);
6533 }
6534 }
6535 vim_free(fromw);
6536 vim_free(tow);
6537}
6538#endif
6539
6540/*
6541 * Copy file attributes from file "from" to file "to".
6542 * For Windows NT and later we copy info streams.
6543 * Always returns zero, errors are ignored.
6544 */
6545 int
6546mch_copy_file_attribute(char_u *from, char_u *to)
6547{
6548#ifdef FEAT_MBYTE
6549 /* File streams only work on Windows NT and later. */
6550 PlatformId();
6551 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6552 copy_infostreams(from, to);
6553#endif
6554 return 0;
6555}
6556
6557#if defined(MYRESETSTKOFLW) || defined(PROTO)
6558/*
6559 * Recreate a destroyed stack guard page in win32.
6560 * Written by Benjamin Peterson.
6561 */
6562
6563/* These magic numbers are from the MS header files */
6564#define MIN_STACK_WIN9X 17
6565#define MIN_STACK_WINNT 2
6566
6567/*
6568 * This function does the same thing as _resetstkoflw(), which is only
6569 * available in DevStudio .net and later.
6570 * Returns 0 for failure, 1 for success.
6571 */
6572 int
6573myresetstkoflw(void)
6574{
6575 BYTE *pStackPtr;
6576 BYTE *pGuardPage;
6577 BYTE *pStackBase;
6578 BYTE *pLowestPossiblePage;
6579 MEMORY_BASIC_INFORMATION mbi;
6580 SYSTEM_INFO si;
6581 DWORD nPageSize;
6582 DWORD dummy;
6583
6584 /* This code will not work on win32s. */
6585 PlatformId();
6586 if (g_PlatformId == VER_PLATFORM_WIN32s)
6587 return 0;
6588
6589 /* We need to know the system page size. */
6590 GetSystemInfo(&si);
6591 nPageSize = si.dwPageSize;
6592
6593 /* ...and the current stack pointer */
6594 pStackPtr = (BYTE*)_alloca(1);
6595
6596 /* ...and the base of the stack. */
6597 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6598 return 0;
6599 pStackBase = (BYTE*)mbi.AllocationBase;
6600
6601 /* ...and the page thats min_stack_req pages away from stack base; this is
6602 * the lowest page we could use. */
6603 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6604 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6605
6606 /* On Win95, we want the next page down from the end of the stack. */
6607 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6608 {
6609 /* Find the page that's only 1 page down from the page that the stack
6610 * ptr is in. */
6611 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6612 / (DWORD)nPageSize) - 1));
6613 if (pGuardPage < pLowestPossiblePage)
6614 return 0;
6615
6616 /* Apply the noaccess attribute to the page -- there's no guard
6617 * attribute in win95-type OSes. */
6618 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6619 return 0;
6620 }
6621 else
6622 {
6623 /* On NT, however, we want the first committed page in the stack Start
6624 * at the stack base and move forward through memory until we find a
6625 * committed block. */
6626 BYTE *pBlock = pStackBase;
6627
Bram Moolenaara466c992005-07-09 21:03:22 +00006628 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629 {
6630 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6631 return 0;
6632
6633 pBlock += mbi.RegionSize;
6634
6635 if (mbi.State & MEM_COMMIT)
6636 break;
6637 }
6638
6639 /* mbi now describes the first committed block in the stack. */
6640 if (mbi.Protect & PAGE_GUARD)
6641 return 1;
6642
6643 /* decide where the guard page should start */
6644 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6645 pGuardPage = pLowestPossiblePage;
6646 else
6647 pGuardPage = (BYTE*)mbi.BaseAddress;
6648
6649 /* allocate the guard page */
6650 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6651 return 0;
6652
6653 /* apply the guard attribute to the page */
6654 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6655 &dummy))
6656 return 0;
6657 }
6658
6659 return 1;
6660}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006661#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006663
6664#if defined(FEAT_MBYTE) || defined(PROTO)
6665/*
6666 * The command line arguments in UCS2
6667 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006668static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006669static LPWSTR *ArglistW = NULL;
6670static int global_argc = 0;
6671static char **global_argv;
6672
6673static int used_file_argc = 0; /* last argument in global_argv[] used
6674 for the argument list. */
6675static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6676 command line arguments added to
6677 the argument list */
6678static int used_file_count = 0; /* nr of entries in used_file_indexes */
6679static int used_file_literal = FALSE; /* take file names literally */
6680static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006681static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006682static int used_alist_count = 0;
6683
6684
6685/*
6686 * Get the command line arguments. Unicode version.
6687 * Returns argc. Zero when something fails.
6688 */
6689 int
6690get_cmd_argsW(char ***argvp)
6691{
6692 char **argv = NULL;
6693 int argc = 0;
6694 int i;
6695
Bram Moolenaar14993322014-09-09 12:25:33 +02006696 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006697 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6698 if (ArglistW != NULL)
6699 {
6700 argv = malloc((nArgsW + 1) * sizeof(char *));
6701 if (argv != NULL)
6702 {
6703 argc = nArgsW;
6704 argv[argc] = NULL;
6705 for (i = 0; i < argc; ++i)
6706 {
6707 int len;
6708
6709 /* Convert each Unicode argument to the current codepage. */
6710 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006711 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006712 (LPSTR *)&argv[i], &len, 0, 0);
6713 if (argv[i] == NULL)
6714 {
6715 /* Out of memory, clear everything. */
6716 while (i > 0)
6717 free(argv[--i]);
6718 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006719 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006720 argc = 0;
6721 }
6722 }
6723 }
6724 }
6725
6726 global_argc = argc;
6727 global_argv = argv;
6728 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006729 {
6730 if (used_file_indexes != NULL)
6731 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006732 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006733 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006734
6735 if (argvp != NULL)
6736 *argvp = argv;
6737 return argc;
6738}
6739
6740 void
6741free_cmd_argsW(void)
6742{
6743 if (ArglistW != NULL)
6744 {
6745 GlobalFree(ArglistW);
6746 ArglistW = NULL;
6747 }
6748}
6749
6750/*
6751 * Remember "name" is an argument that was added to the argument list.
6752 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6753 * is called.
6754 */
6755 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006756used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006757{
6758 int i;
6759
6760 if (used_file_indexes == NULL)
6761 return;
6762 for (i = used_file_argc + 1; i < global_argc; ++i)
6763 if (STRCMP(global_argv[i], name) == 0)
6764 {
6765 used_file_argc = i;
6766 used_file_indexes[used_file_count++] = i;
6767 break;
6768 }
6769 used_file_literal = literal;
6770 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006771 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006772}
6773
6774/*
6775 * Remember the length of the argument list as it was. If it changes then we
6776 * leave it alone when 'encoding' is set.
6777 */
6778 void
6779set_alist_count(void)
6780{
6781 used_alist_count = GARGCOUNT;
6782}
6783
6784/*
6785 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6786 * has been changed while starting up. Use the UCS-2 command line arguments
6787 * and convert them to 'encoding'.
6788 */
6789 void
6790fix_arg_enc(void)
6791{
6792 int i;
6793 int idx;
6794 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006795 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006796
6797 /* Safety checks:
6798 * - if argument count differs between the wide and non-wide argument
6799 * list, something must be wrong.
6800 * - the file name arguments must have been located.
6801 * - the length of the argument list wasn't changed by the user.
6802 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006803 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006804 || ArglistW == NULL
6805 || used_file_indexes == NULL
6806 || used_file_count == 0
6807 || used_alist_count != GARGCOUNT)
6808 return;
6809
Bram Moolenaar86b68352004-12-27 21:59:20 +00006810 /* Remember the buffer numbers for the arguments. */
6811 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6812 if (fnum_list == NULL)
6813 return; /* out of memory */
6814 for (i = 0; i < GARGCOUNT; ++i)
6815 fnum_list[i] = GARGLIST[i].ae_fnum;
6816
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006817 /* Clear the argument list. Make room for the new arguments. */
6818 alist_clear(&global_alist);
6819 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006820 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006821
6822 for (i = 0; i < used_file_count; ++i)
6823 {
6824 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006825 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006826 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006827 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006828#ifdef FEAT_DIFF
6829 /* When using diff mode may need to concatenate file name to
6830 * directory name. Just like it's done in main(). */
6831 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6832 && !mch_isdir(alist_name(&GARGLIST[0])))
6833 {
6834 char_u *r;
6835
6836 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6837 if (r != NULL)
6838 {
6839 vim_free(str);
6840 str = r;
6841 }
6842 }
6843#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006844 /* Re-use the old buffer by renaming it. When not using literal
6845 * names it's done by alist_expand() below. */
6846 if (used_file_literal)
6847 buf_set_name(fnum_list[i], str);
6848
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006849 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006850 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006851 }
6852
6853 if (!used_file_literal)
6854 {
6855 /* Now expand wildcards in the arguments. */
6856 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6857 * filename characters but are excluded from 'isfname' to make
6858 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6859 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006860 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006861 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6862 }
6863
6864 /* If wildcard expansion failed, we are editing the first file of the
6865 * arglist and there is no file name: Edit the first argument now. */
6866 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6867 {
6868 do_cmdline_cmd((char_u *)":rewind");
6869 if (GARGCOUNT == 1 && used_file_full_path)
6870 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6871 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006872
6873 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006874}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875#endif