blob: 4c876a05ce780c60b9c5f92884855e931b7965b4 [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 Moolenaar938ee832016-01-24 15:36:03 +0100503#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100504 if (!hLibintlDLL)
505 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100506#endif
507 if (!hLibintlDLL)
508 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 if (!hLibintlDLL)
510 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200511 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200513 verbose_enter();
514 EMSG2(_(e_loadlib), GETTEXT_DLL);
515 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000516 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200517 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000518 }
519 for (i = 0; libintl_entry[i].name != NULL
520 && libintl_entry[i].ptr != NULL; ++i)
521 {
522 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
523 libintl_entry[i].name)) == NULL)
524 {
525 dyn_libintl_end();
526 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000527 {
528 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000530 verbose_leave();
531 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532 return 0;
533 }
534 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000535
536 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000537 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000538 "bind_textdomain_codeset");
539 if (dyn_libintl_bind_textdomain_codeset == NULL)
540 dyn_libintl_bind_textdomain_codeset =
541 null_libintl_bind_textdomain_codeset;
542
Bram Moolenaar071d4272004-06-13 20:20:40 +0000543 return 1;
544}
545
546 void
547dyn_libintl_end()
548{
549 if (hLibintlDLL)
550 FreeLibrary(hLibintlDLL);
551 hLibintlDLL = NULL;
552 dyn_libintl_gettext = null_libintl_gettext;
553 dyn_libintl_textdomain = null_libintl_textdomain;
554 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000555 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000556}
557
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000558/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000560null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561{
562 return (char*)msgid;
563}
564
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000565/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000566 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000567null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000568{
569 return NULL;
570}
571
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000572/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000573 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000574null_libintl_bind_textdomain_codeset(const char *domainname,
575 const char *codeset)
576{
577 return NULL;
578}
579
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000580/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000581 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000582null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000583{
584 return NULL;
585}
586
587#endif /* DYNAMIC_GETTEXT */
588
589/* This symbol is not defined in older versions of the SDK or Visual C++ */
590
591#ifndef VER_PLATFORM_WIN32_WINDOWS
592# define VER_PLATFORM_WIN32_WINDOWS 1
593#endif
594
595DWORD g_PlatformId;
596
597#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100598# ifndef PROTO
599# include <aclapi.h>
600# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200601# ifndef PROTECTED_DACL_SECURITY_INFORMATION
602# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
603# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100604
Bram Moolenaar071d4272004-06-13 20:20:40 +0000605/*
606 * These are needed to dynamically load the ADVAPI DLL, which is not
607 * implemented under Windows 95 (and causes VIM to crash)
608 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200609typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200611typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
613 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200614# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200615typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200616 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200617typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200618 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
619 PSECURITY_DESCRIPTOR *);
620# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000621
622static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
623static PSNSECINFO pSetNamedSecurityInfo;
624static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200625# ifdef FEAT_MBYTE
626static PSNSECINFOW pSetNamedSecurityInfoW;
627static PGNSECINFOW pGetNamedSecurityInfoW;
628# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629#endif
630
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200631typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
632
633static BOOL allowPiping = FALSE;
634static PSETHANDLEINFORMATION pSetHandleInformation;
635
Bram Moolenaar27515922013-06-29 15:36:26 +0200636#ifdef HAVE_ACL
637/*
638 * Enables or disables the specified privilege.
639 */
640 static BOOL
641win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
642{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100643 BOOL bResult;
644 LUID luid;
645 HANDLE hToken;
646 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200647
648 if (!OpenProcessToken(GetCurrentProcess(),
649 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
650 return FALSE;
651
652 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
653 {
654 CloseHandle(hToken);
655 return FALSE;
656 }
657
Bram Moolenaar45500912014-07-09 20:51:07 +0200658 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200659 tokenPrivileges.Privileges[0].Luid = luid;
660 tokenPrivileges.Privileges[0].Attributes = bEnable ?
661 SE_PRIVILEGE_ENABLED : 0;
662
663 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
664 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
665
666 CloseHandle(hToken);
667
668 return bResult && GetLastError() == ERROR_SUCCESS;
669}
670#endif
671
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672/*
673 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
674 * VER_PLATFORM_WIN32_WINDOWS (Win95).
675 */
676 void
677PlatformId(void)
678{
679 static int done = FALSE;
680
681 if (!done)
682 {
683 OSVERSIONINFO ovi;
684
685 ovi.dwOSVersionInfoSize = sizeof(ovi);
686 GetVersionEx(&ovi);
687
688 g_PlatformId = ovi.dwPlatformId;
689
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100690 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
691 || ovi.dwMajorVersion > 6)
692 win8_or_later = TRUE;
693
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694#ifdef HAVE_ACL
695 /*
696 * Load the ADVAPI runtime if we are on anything
697 * other than Windows 95
698 */
699 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
700 {
701 /*
702 * do this load. Problems: Doesn't unload at end of run (this is
703 * theoretically okay, since Windows should unload it when VIM
704 * terminates). Should we be using the 'mch_libcall' routines?
705 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
706 * time we verify security...
707 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200708 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000709 if (advapi_lib != NULL)
710 {
711 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
712 "SetNamedSecurityInfoA");
713 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
714 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200715# ifdef FEAT_MBYTE
716 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
717 "SetNamedSecurityInfoW");
718 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
719 "GetNamedSecurityInfoW");
720# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200722 || pGetNamedSecurityInfo == NULL
723# ifdef FEAT_MBYTE
724 || pSetNamedSecurityInfoW == NULL
725 || pGetNamedSecurityInfoW == NULL
726# endif
727 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728 {
729 /* If we can't get the function addresses, set advapi_lib
730 * to NULL so that we don't use them. */
731 FreeLibrary(advapi_lib);
732 advapi_lib = NULL;
733 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200734 /* Enable privilege for getting or setting SACLs. */
735 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000736 }
737 }
738#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200739 /*
740 * If we are on windows NT, try to load the pipe functions, only
741 * available from Win2K.
742 */
743 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
744 {
745 HANDLE kernel32 = GetModuleHandle("kernel32");
746 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
747 kernel32, "SetHandleInformation");
748
749 allowPiping = pSetHandleInformation != NULL;
750 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751 done = TRUE;
752 }
753}
754
755/*
756 * Return TRUE when running on Windows 95 (or 98 or ME).
757 * Only to be used after mch_init().
758 */
759 int
760mch_windows95(void)
761{
762 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
763}
764
765#ifdef FEAT_GUI_W32
766/*
767 * Used to work around the "can't do synchronous spawn"
768 * problem on Win32s, without resorting to Universal Thunk.
769 */
770static int old_num_windows;
771static int num_windows;
772
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000773/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774 static BOOL CALLBACK
775win32ssynch_cb(HWND hwnd, LPARAM lparam)
776{
777 num_windows++;
778 return TRUE;
779}
780#endif
781
782#ifndef FEAT_GUI_W32
783
784#define SHIFT (SHIFT_PRESSED)
785#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
786#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
787#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
788
789
790/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
791 * We map function keys to their ANSI terminal equivalents, as produced
792 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
793 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
794 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
795 * combinations of function/arrow/etc keys.
796 */
797
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000798static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799{
800 WORD wVirtKey;
801 BOOL fAnsiKey;
802 int chAlone;
803 int chShift;
804 int chCtrl;
805 int chAlt;
806} VirtKeyMap[] =
807{
808
809/* Key ANSI alone shift ctrl alt */
810 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
811
812 { VK_F1, TRUE, ';', 'T', '^', 'h', },
813 { VK_F2, TRUE, '<', 'U', '_', 'i', },
814 { VK_F3, TRUE, '=', 'V', '`', 'j', },
815 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
816 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
817 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
818 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
819 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
820 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
821 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
822 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
823 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
824
825 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
826 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
827 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
828 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
829 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
830 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
831 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
832 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
833 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
834 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
835
836 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
837
838#if 0
839 /* Most people don't have F13-F20, but what the hell... */
840 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
841 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
842 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
843 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
844 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
845 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
846 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
847 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
848#endif
849 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
850 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
851 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
852 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
853
854 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
855 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
856 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
857 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
858 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
859 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
860 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
861 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
862 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
863 /* Sorry, out of number space! <negri>*/
864 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
865
866};
867
868
869#ifdef _MSC_VER
870// The ToAscii bug destroys several registers. Need to turn off optimization
871// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000872# pragma warning(push)
873# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874# pragma optimize("", off)
875#endif
876
877#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200878# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200880# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881#endif
882
883/* The return code indicates key code size. */
884 static int
885#ifdef __BORLANDC__
886 __stdcall
887#endif
888win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000889 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890{
891 UINT uMods = pker->dwControlKeyState;
892 static int s_iIsDead = 0;
893 static WORD awAnsiCode[2];
894 static BYTE abKeystate[256];
895
896
897 if (s_iIsDead == 2)
898 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200899 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900 s_iIsDead = 0;
901 return 1;
902 }
903
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200904 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905 return 1;
906
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200907 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908
909 // Should only be non-NULL on NT 4.0
910 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
911 {
912 CHAR szKLID[KL_NAMELENGTH];
913
914 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
915 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
916 }
917
918 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200919 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920
921 if (uMods & SHIFT_PRESSED)
922 abKeystate[VK_SHIFT] = 0x80;
923 if (uMods & CAPSLOCK_ON)
924 abKeystate[VK_CAPITAL] = 1;
925
926 if ((uMods & ALT_GR) == ALT_GR)
927 {
928 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
929 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
930 }
931
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200932 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
933 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934
935 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200936 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937
938 return s_iIsDead;
939}
940
941#ifdef _MSC_VER
942/* MUST switch optimization on again here, otherwise a call to
943 * decode_key_event() may crash (e.g. when hitting caps-lock) */
944# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000945# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946
947# if (_MSC_VER < 1100)
948/* MUST turn off global optimisation for this next function, or
949 * pressing ctrl-minus in insert mode crashes Vim when built with
950 * VC4.1. -- negri. */
951# pragma optimize("g", off)
952# endif
953#endif
954
955static BOOL g_fJustGotFocus = FALSE;
956
957/*
958 * Decode a KEY_EVENT into one or two keystrokes
959 */
960 static BOOL
961decode_key_event(
962 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200963 WCHAR *pch,
964 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965 int *pmodifiers,
966 BOOL fDoPost)
967{
968 int i;
969 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
970
971 *pch = *pch2 = NUL;
972 g_fJustGotFocus = FALSE;
973
974 /* ignore key up events */
975 if (!pker->bKeyDown)
976 return FALSE;
977
978 /* ignore some keystrokes */
979 switch (pker->wVirtualKeyCode)
980 {
981 /* modifiers */
982 case VK_SHIFT:
983 case VK_CONTROL:
984 case VK_MENU: /* Alt key */
985 return FALSE;
986
987 default:
988 break;
989 }
990
991 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200992 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993 {
994 /* Ctrl-6 is Ctrl-^ */
995 if (pker->wVirtualKeyCode == '6')
996 {
997 *pch = Ctrl_HAT;
998 return TRUE;
999 }
1000 /* Ctrl-2 is Ctrl-@ */
1001 else if (pker->wVirtualKeyCode == '2')
1002 {
1003 *pch = NUL;
1004 return TRUE;
1005 }
1006 /* Ctrl-- is Ctrl-_ */
1007 else if (pker->wVirtualKeyCode == 0xBD)
1008 {
1009 *pch = Ctrl__;
1010 return TRUE;
1011 }
1012 }
1013
1014 /* Shift-TAB */
1015 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1016 {
1017 *pch = K_NUL;
1018 *pch2 = '\017';
1019 return TRUE;
1020 }
1021
1022 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1023 {
1024 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1025 {
1026 if (nModifs == 0)
1027 *pch = VirtKeyMap[i].chAlone;
1028 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1029 *pch = VirtKeyMap[i].chShift;
1030 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1031 *pch = VirtKeyMap[i].chCtrl;
1032 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1033 *pch = VirtKeyMap[i].chAlt;
1034
1035 if (*pch != 0)
1036 {
1037 if (VirtKeyMap[i].fAnsiKey)
1038 {
1039 *pch2 = *pch;
1040 *pch = K_NUL;
1041 }
1042
1043 return TRUE;
1044 }
1045 }
1046 }
1047
1048 i = win32_kbd_patch_key(pker);
1049
1050 if (i < 0)
1051 *pch = NUL;
1052 else
1053 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001054 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001055
1056 if (pmodifiers != NULL)
1057 {
1058 /* Pass on the ALT key as a modifier, but only when not combined
1059 * with CTRL (which is ALTGR). */
1060 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1061 *pmodifiers |= MOD_MASK_ALT;
1062
1063 /* Pass on SHIFT only for special keys, because we don't know when
1064 * it's already included with the character. */
1065 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1066 *pmodifiers |= MOD_MASK_SHIFT;
1067
1068 /* Pass on CTRL only for non-special keys, because we don't know
1069 * when it's already included with the character. And not when
1070 * combined with ALT (which is ALTGR). */
1071 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1072 && *pch >= 0x20 && *pch < 0x80)
1073 *pmodifiers |= MOD_MASK_CTRL;
1074 }
1075 }
1076
1077 return (*pch != NUL);
1078}
1079
1080#ifdef _MSC_VER
1081# pragma optimize("", on)
1082#endif
1083
1084#endif /* FEAT_GUI_W32 */
1085
1086
1087#ifdef FEAT_MOUSE
1088
1089/*
1090 * For the GUI the mouse handling is in gui_w32.c.
1091 */
1092# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001093/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001095mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001096{
1097}
1098# else
1099static int g_fMouseAvail = FALSE; /* mouse present */
1100static int g_fMouseActive = FALSE; /* mouse enabled */
1101static int g_nMouseClick = -1; /* mouse status */
1102static int g_xMouse; /* mouse x coordinate */
1103static int g_yMouse; /* mouse y coordinate */
1104
1105/*
1106 * Enable or disable mouse input
1107 */
1108 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001109mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001110{
1111 DWORD cmodein;
1112
1113 if (!g_fMouseAvail)
1114 return;
1115
1116 g_fMouseActive = on;
1117 GetConsoleMode(g_hConIn, &cmodein);
1118
1119 if (g_fMouseActive)
1120 cmodein |= ENABLE_MOUSE_INPUT;
1121 else
1122 cmodein &= ~ENABLE_MOUSE_INPUT;
1123
1124 SetConsoleMode(g_hConIn, cmodein);
1125}
1126
1127
1128/*
1129 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1130 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1131 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1132 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1133 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1134 * and we return the mouse position in g_xMouse and g_yMouse.
1135 *
1136 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1137 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1138 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1139 *
1140 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1141 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1142 *
1143 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1144 * moves, even if it stays within the same character cell. We ignore
1145 * all MOUSE_MOVED messages if the position hasn't really changed, and
1146 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1147 * we're only interested in MOUSE_DRAG).
1148 *
1149 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1150 * 2-button mouses by pressing the left & right buttons simultaneously.
1151 * In practice, it's almost impossible to click both at the same time,
1152 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1153 * in such cases, if the user is clicking quickly.
1154 */
1155 static BOOL
1156decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001157 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158{
1159 static int s_nOldButton = -1;
1160 static int s_nOldMouseClick = -1;
1161 static int s_xOldMouse = -1;
1162 static int s_yOldMouse = -1;
1163 static linenr_T s_old_topline = 0;
1164#ifdef FEAT_DIFF
1165 static int s_old_topfill = 0;
1166#endif
1167 static int s_cClicks = 1;
1168 static BOOL s_fReleased = TRUE;
1169 static DWORD s_dwLastClickTime = 0;
1170 static BOOL s_fNextIsMiddle = FALSE;
1171
1172 static DWORD cButtons = 0; /* number of buttons supported */
1173
1174 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1175 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1176 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1177 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1178
1179 int nButton;
1180
1181 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1182 cButtons = 2;
1183
1184 if (!g_fMouseAvail || !g_fMouseActive)
1185 {
1186 g_nMouseClick = -1;
1187 return FALSE;
1188 }
1189
1190 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1191 if (g_fJustGotFocus)
1192 {
1193 g_fJustGotFocus = FALSE;
1194 return FALSE;
1195 }
1196
1197 /* unprocessed mouse click? */
1198 if (g_nMouseClick != -1)
1199 return TRUE;
1200
1201 nButton = -1;
1202 g_xMouse = pmer->dwMousePosition.X;
1203 g_yMouse = pmer->dwMousePosition.Y;
1204
1205 if (pmer->dwEventFlags == MOUSE_MOVED)
1206 {
1207 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1208 * events even when the mouse moves only within a char cell.) */
1209 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1210 return FALSE;
1211 }
1212
1213 /* If no buttons are pressed... */
1214 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1215 {
1216 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1217 if (s_fReleased)
1218 return FALSE;
1219
1220 nButton = MOUSE_RELEASE;
1221 s_fReleased = TRUE;
1222 }
1223 else /* one or more buttons pressed */
1224 {
1225 /* on a 2-button mouse, hold down left and right buttons
1226 * simultaneously to get MIDDLE. */
1227
1228 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1229 {
1230 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1231
1232 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001233 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 if (dwLR == LEFT || dwLR == RIGHT)
1235 {
1236 for (;;)
1237 {
1238 /* wait a short time for next input event */
1239 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1240 != WAIT_OBJECT_0)
1241 break;
1242 else
1243 {
1244 DWORD cRecords = 0;
1245 INPUT_RECORD ir;
1246 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1247
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001248 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001249
1250 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1251 || !(pmer2->dwButtonState & LEFT_RIGHT))
1252 break;
1253 else
1254 {
1255 if (pmer2->dwEventFlags != MOUSE_MOVED)
1256 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001257 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001258
1259 return decode_mouse_event(pmer2);
1260 }
1261 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1262 s_yOldMouse == pmer2->dwMousePosition.Y)
1263 {
1264 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001265 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266
1267 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001268 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269
1270 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1271 break;
1272 }
1273 else
1274 break;
1275 }
1276 }
1277 }
1278 }
1279 }
1280
1281 if (s_fNextIsMiddle)
1282 {
1283 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1284 ? MOUSE_DRAG : MOUSE_MIDDLE;
1285 s_fNextIsMiddle = FALSE;
1286 }
1287 else if (cButtons == 2 &&
1288 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1289 {
1290 nButton = MOUSE_MIDDLE;
1291
1292 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1293 {
1294 s_fNextIsMiddle = TRUE;
1295 nButton = MOUSE_RELEASE;
1296 }
1297 }
1298 else if ((pmer->dwButtonState & LEFT) == LEFT)
1299 nButton = MOUSE_LEFT;
1300 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1301 nButton = MOUSE_MIDDLE;
1302 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1303 nButton = MOUSE_RIGHT;
1304
1305 if (! s_fReleased && ! s_fNextIsMiddle
1306 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1307 return FALSE;
1308
1309 s_fReleased = s_fNextIsMiddle;
1310 }
1311
1312 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1313 {
1314 /* button pressed or released, without mouse moving */
1315 if (nButton != -1 && nButton != MOUSE_RELEASE)
1316 {
1317 DWORD dwCurrentTime = GetTickCount();
1318
1319 if (s_xOldMouse != g_xMouse
1320 || s_yOldMouse != g_yMouse
1321 || s_nOldButton != nButton
1322 || s_old_topline != curwin->w_topline
1323#ifdef FEAT_DIFF
1324 || s_old_topfill != curwin->w_topfill
1325#endif
1326 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1327 {
1328 s_cClicks = 1;
1329 }
1330 else if (++s_cClicks > 4)
1331 {
1332 s_cClicks = 1;
1333 }
1334
1335 s_dwLastClickTime = dwCurrentTime;
1336 }
1337 }
1338 else if (pmer->dwEventFlags == MOUSE_MOVED)
1339 {
1340 if (nButton != -1 && nButton != MOUSE_RELEASE)
1341 nButton = MOUSE_DRAG;
1342
1343 s_cClicks = 1;
1344 }
1345
1346 if (nButton == -1)
1347 return FALSE;
1348
1349 if (nButton != MOUSE_RELEASE)
1350 s_nOldButton = nButton;
1351
1352 g_nMouseClick = nButton;
1353
1354 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1355 g_nMouseClick |= MOUSE_SHIFT;
1356 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1357 g_nMouseClick |= MOUSE_CTRL;
1358 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1359 g_nMouseClick |= MOUSE_ALT;
1360
1361 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1362 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1363
1364 /* only pass on interesting (i.e., different) mouse events */
1365 if (s_xOldMouse == g_xMouse
1366 && s_yOldMouse == g_yMouse
1367 && s_nOldMouseClick == g_nMouseClick)
1368 {
1369 g_nMouseClick = -1;
1370 return FALSE;
1371 }
1372
1373 s_xOldMouse = g_xMouse;
1374 s_yOldMouse = g_yMouse;
1375 s_old_topline = curwin->w_topline;
1376#ifdef FEAT_DIFF
1377 s_old_topfill = curwin->w_topfill;
1378#endif
1379 s_nOldMouseClick = g_nMouseClick;
1380
1381 return TRUE;
1382}
1383
1384# endif /* FEAT_GUI_W32 */
1385#endif /* FEAT_MOUSE */
1386
1387
1388#ifdef MCH_CURSOR_SHAPE
1389/*
1390 * Set the shape of the cursor.
1391 * 'thickness' can be from 1 (thin) to 99 (block)
1392 */
1393 static void
1394mch_set_cursor_shape(int thickness)
1395{
1396 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1397 ConsoleCursorInfo.dwSize = thickness;
1398 ConsoleCursorInfo.bVisible = s_cursor_visible;
1399
1400 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1401 if (s_cursor_visible)
1402 SetConsoleCursorPosition(g_hConOut, g_coord);
1403}
1404
1405 void
1406mch_update_cursor(void)
1407{
1408 int idx;
1409 int thickness;
1410
1411 /*
1412 * How the cursor is drawn depends on the current mode.
1413 */
1414 idx = get_shape_idx(FALSE);
1415
1416 if (shape_table[idx].shape == SHAPE_BLOCK)
1417 thickness = 99; /* 100 doesn't work on W95 */
1418 else
1419 thickness = shape_table[idx].percentage;
1420 mch_set_cursor_shape(thickness);
1421}
1422#endif
1423
1424#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1425/*
1426 * Handle FOCUS_EVENT.
1427 */
1428 static void
1429handle_focus_event(INPUT_RECORD ir)
1430{
1431 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1432 ui_focus_change((int)g_fJustGotFocus);
1433}
1434
1435/*
1436 * Wait until console input from keyboard or mouse is available,
1437 * or the time is up.
1438 * Return TRUE if something is available FALSE if not.
1439 */
1440 static int
1441WaitForChar(long msec)
1442{
1443 DWORD dwNow = 0, dwEndTime = 0;
1444 INPUT_RECORD ir;
1445 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001446 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447
1448 if (msec > 0)
1449 /* Wait until the specified time has elapsed. */
1450 dwEndTime = GetTickCount() + msec;
1451 else if (msec < 0)
1452 /* Wait forever. */
1453 dwEndTime = INFINITE;
1454
1455 /* We need to loop until the end of the time period, because
1456 * we might get multiple unusable mouse events in that time.
1457 */
1458 for (;;)
1459 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001460#ifdef FEAT_MZSCHEME
1461 mzvim_check_threads();
1462#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001463#ifdef FEAT_CLIENTSERVER
1464 serverProcessPendingMessages();
1465#endif
1466 if (0
1467#ifdef FEAT_MOUSE
1468 || g_nMouseClick != -1
1469#endif
1470#ifdef FEAT_CLIENTSERVER
1471 || input_available()
1472#endif
1473 )
1474 return TRUE;
1475
1476 if (msec > 0)
1477 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001478 /* If the specified wait time has passed, return. Beware that
1479 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001480 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001481 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482 break;
1483 }
1484 if (msec != 0)
1485 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001486 DWORD dwWaitTime = dwEndTime - dwNow;
1487
1488#ifdef FEAT_MZSCHEME
1489 if (mzthreads_allowed() && p_mzq > 0
1490 && (msec < 0 || (long)dwWaitTime > p_mzq))
1491 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1492#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493#ifdef FEAT_CLIENTSERVER
1494 /* Wait for either an event on the console input or a message in
1495 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001496 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001497 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001498#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001499 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001500#endif
1501 continue;
1502 }
1503
1504 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001505 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506
1507#ifdef FEAT_MBYTE_IME
1508 if (State & CMDLINE && msg_row == Rows - 1)
1509 {
1510 CONSOLE_SCREEN_BUFFER_INFO csbi;
1511
1512 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1513 {
1514 if (csbi.dwCursorPosition.Y != msg_row)
1515 {
1516 /* The screen is now messed up, must redraw the
1517 * command line and later all the windows. */
1518 redraw_all_later(CLEAR);
1519 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1520 redrawcmd();
1521 }
1522 }
1523 }
1524#endif
1525
1526 if (cRecords > 0)
1527 {
1528 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1529 {
1530#ifdef FEAT_MBYTE_IME
1531 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1532 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001533 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1535 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001536 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 continue;
1538 }
1539#endif
1540 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1541 NULL, FALSE))
1542 return TRUE;
1543 }
1544
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001545 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546
1547 if (ir.EventType == FOCUS_EVENT)
1548 handle_focus_event(ir);
1549 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1550 shell_resized();
1551#ifdef FEAT_MOUSE
1552 else if (ir.EventType == MOUSE_EVENT
1553 && decode_mouse_event(&ir.Event.MouseEvent))
1554 return TRUE;
1555#endif
1556 }
1557 else if (msec == 0)
1558 break;
1559 }
1560
1561#ifdef FEAT_CLIENTSERVER
1562 /* Something might have been received while we were waiting. */
1563 if (input_available())
1564 return TRUE;
1565#endif
1566 return FALSE;
1567}
1568
1569#ifndef FEAT_GUI_MSWIN
1570/*
1571 * return non-zero if a character is available
1572 */
1573 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001574mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001575{
1576 return WaitForChar(0L);
1577}
1578#endif
1579
1580/*
1581 * Create the console input. Used when reading stdin doesn't work.
1582 */
1583 static void
1584create_conin(void)
1585{
1586 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1587 FILE_SHARE_READ|FILE_SHARE_WRITE,
1588 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001589 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 did_create_conin = TRUE;
1591}
1592
1593/*
1594 * Get a keystroke or a mouse event
1595 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001596 static WCHAR
1597tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001599 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600
1601 for (;;)
1602 {
1603 INPUT_RECORD ir;
1604 DWORD cRecords = 0;
1605
1606#ifdef FEAT_CLIENTSERVER
1607 (void)WaitForChar(-1L);
1608 if (input_available())
1609 return 0;
1610# ifdef FEAT_MOUSE
1611 if (g_nMouseClick != -1)
1612 return 0;
1613# endif
1614#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001615 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616 {
1617 if (did_create_conin)
1618 read_error_exit();
1619 create_conin();
1620 continue;
1621 }
1622
1623 if (ir.EventType == KEY_EVENT)
1624 {
1625 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1626 pmodifiers, TRUE))
1627 return ch;
1628 }
1629 else if (ir.EventType == FOCUS_EVENT)
1630 handle_focus_event(ir);
1631 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1632 shell_resized();
1633#ifdef FEAT_MOUSE
1634 else if (ir.EventType == MOUSE_EVENT)
1635 {
1636 if (decode_mouse_event(&ir.Event.MouseEvent))
1637 return 0;
1638 }
1639#endif
1640 }
1641}
1642#endif /* !FEAT_GUI_W32 */
1643
1644
1645/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001646 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647 * Get one or more characters from the keyboard or the mouse.
1648 * If time == 0, do not wait for characters.
1649 * If time == n, wait a short time for characters.
1650 * If time == -1, wait forever for characters.
1651 * Returns the number of characters read into buf.
1652 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001653/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001654 int
1655mch_inchar(
1656 char_u *buf,
1657 int maxlen,
1658 long time,
1659 int tb_change_cnt)
1660{
1661#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1662
1663 int len;
1664 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665#define TYPEAHEADLEN 20
1666 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1667 static int typeaheadlen = 0;
1668
1669 /* First use any typeahead that was kept because "buf" was too small. */
1670 if (typeaheadlen > 0)
1671 goto theend;
1672
1673#ifdef FEAT_SNIFF
1674 if (want_sniff_request)
1675 {
1676 if (sniff_request_waiting)
1677 {
1678 /* return K_SNIFF */
1679 typeahead[typeaheadlen++] = CSI;
1680 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1681 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1682 sniff_request_waiting = 0;
1683 want_sniff_request = 0;
1684 goto theend;
1685 }
1686 else if (time < 0 || time > 250)
1687 {
1688 /* don't wait too long, a request might be pending */
1689 time = 250;
1690 }
1691 }
1692#endif
1693
1694 if (time >= 0)
1695 {
1696 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698 }
1699 else /* time == -1, wait forever */
1700 {
1701 mch_set_winsize_now(); /* Allow winsize changes from now on */
1702
Bram Moolenaar3918c952005-03-15 22:34:55 +00001703 /*
1704 * If there is no character available within 2 seconds (default)
1705 * write the autoscript file to disk. Or cause the CursorHold event
1706 * to be triggered.
1707 */
1708 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 {
1710#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001711 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001713 buf[0] = K_SPECIAL;
1714 buf[1] = KS_EXTRA;
1715 buf[2] = (int)KE_CURSORHOLD;
1716 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 }
1718#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001719 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720 }
1721 }
1722
1723 /*
1724 * Try to read as many characters as there are, until the buffer is full.
1725 */
1726
1727 /* we will get at least one key. Get more if they are available. */
1728 g_fCBrkPressed = FALSE;
1729
1730#ifdef MCH_WRITE_DUMP
1731 if (fdDump)
1732 fputc('[', fdDump);
1733#endif
1734
1735 /* Keep looping until there is something in the typeahead buffer and more
1736 * to get and still room in the buffer (up to two bytes for a char and
1737 * three bytes for a modifier). */
1738 while ((typeaheadlen == 0 || WaitForChar(0L))
1739 && typeaheadlen + 5 <= TYPEAHEADLEN)
1740 {
1741 if (typebuf_changed(tb_change_cnt))
1742 {
1743 /* "buf" may be invalid now if a client put something in the
1744 * typeahead buffer and "buf" is in the typeahead buffer. */
1745 typeaheadlen = 0;
1746 break;
1747 }
1748#ifdef FEAT_MOUSE
1749 if (g_nMouseClick != -1)
1750 {
1751# ifdef MCH_WRITE_DUMP
1752 if (fdDump)
1753 fprintf(fdDump, "{%02x @ %d, %d}",
1754 g_nMouseClick, g_xMouse, g_yMouse);
1755# endif
1756 typeahead[typeaheadlen++] = ESC + 128;
1757 typeahead[typeaheadlen++] = 'M';
1758 typeahead[typeaheadlen++] = g_nMouseClick;
1759 typeahead[typeaheadlen++] = g_xMouse + '!';
1760 typeahead[typeaheadlen++] = g_yMouse + '!';
1761 g_nMouseClick = -1;
1762 }
1763 else
1764#endif
1765 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001766 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 int modifiers = 0;
1768
1769 c = tgetch(&modifiers, &ch2);
1770
1771 if (typebuf_changed(tb_change_cnt))
1772 {
1773 /* "buf" may be invalid now if a client put something in the
1774 * typeahead buffer and "buf" is in the typeahead buffer. */
1775 typeaheadlen = 0;
1776 break;
1777 }
1778
1779 if (c == Ctrl_C && ctrl_c_interrupts)
1780 {
1781#if defined(FEAT_CLIENTSERVER)
1782 trash_input_buf();
1783#endif
1784 got_int = TRUE;
1785 }
1786
1787#ifdef FEAT_MOUSE
1788 if (g_nMouseClick == -1)
1789#endif
1790 {
1791 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001792 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001794#ifdef FEAT_MBYTE
1795 if (ch2 == NUL)
1796 {
1797 int i;
1798 char_u *p;
1799 WCHAR ch[2];
1800
1801 ch[0] = c;
1802 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1803 {
1804 ch[1] = tgetch(&modifiers, &ch2);
1805 n++;
1806 }
1807 p = utf16_to_enc(ch, &n);
1808 if (p != NULL)
1809 {
1810 for (i = 0; i < n; i++)
1811 typeahead[typeaheadlen + i] = p[i];
1812 vim_free(p);
1813 }
1814 }
1815 else
1816#endif
1817 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 if (ch2 != NUL)
1819 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001820 typeahead[typeaheadlen + n] = 3;
1821 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001822 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001824
Bram Moolenaar45500912014-07-09 20:51:07 +02001825 if (conv)
1826 {
1827 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001828
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001829 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001830 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001831 char_u *e = typeahead + TYPEAHEADLEN;
1832
1833 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001834 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001835 if (*p == K_NUL)
1836 {
1837 ++p;
1838 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1839 *p = 3;
1840 ++n;
1841 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001842 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001843 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001844 }
1845 }
1846
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 /* Use the ALT key to set the 8th bit of the character
1848 * when it's one byte, the 8th bit isn't set yet and not
1849 * using a double-byte encoding (would become a lead
1850 * byte). */
1851 if ((modifiers & MOD_MASK_ALT)
1852 && n == 1
1853 && (typeahead[typeaheadlen] & 0x80) == 0
1854#ifdef FEAT_MBYTE
1855 && !enc_dbcs
1856#endif
1857 )
1858 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001859#ifdef FEAT_MBYTE
1860 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1861 typeahead + typeaheadlen);
1862#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001864#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865 modifiers &= ~MOD_MASK_ALT;
1866 }
1867
1868 if (modifiers != 0)
1869 {
1870 /* Prepend modifiers to the character. */
1871 mch_memmove(typeahead + typeaheadlen + 3,
1872 typeahead + typeaheadlen, n);
1873 typeahead[typeaheadlen++] = K_SPECIAL;
1874 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1875 typeahead[typeaheadlen++] = modifiers;
1876 }
1877
1878 typeaheadlen += n;
1879
1880#ifdef MCH_WRITE_DUMP
1881 if (fdDump)
1882 fputc(c, fdDump);
1883#endif
1884 }
1885 }
1886 }
1887
1888#ifdef MCH_WRITE_DUMP
1889 if (fdDump)
1890 {
1891 fputs("]\n", fdDump);
1892 fflush(fdDump);
1893 }
1894#endif
1895
Bram Moolenaar071d4272004-06-13 20:20:40 +00001896theend:
1897 /* Move typeahead to "buf", as much as fits. */
1898 len = 0;
1899 while (len < maxlen && typeaheadlen > 0)
1900 {
1901 buf[len++] = typeahead[0];
1902 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1903 }
1904 return len;
1905
1906#else /* FEAT_GUI_W32 */
1907 return 0;
1908#endif /* FEAT_GUI_W32 */
1909}
1910
Bram Moolenaar82881492012-11-20 16:53:39 +01001911#ifndef PROTO
1912# ifndef __MINGW32__
1913# include <shellapi.h> /* required for FindExecutable() */
1914# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915#endif
1916
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001917/*
1918 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001919 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001920 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001922executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001924 char *dum;
1925 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001926 char *curpath, *newpath;
1927 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001929#ifdef FEAT_MBYTE
1930 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001932 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001933 WCHAR fnamew[_MAX_PATH];
1934 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001935 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001936
1937 if (p != NULL)
1938 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001939 wcurpath = _wgetenv(L"PATH");
1940 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1941 * sizeof(WCHAR));
1942 if (wnewpath == NULL)
1943 return FALSE;
1944 wcscpy(wnewpath, L".;");
1945 wcscat(wnewpath, wcurpath);
1946 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1947 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001948 vim_free(p);
1949 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1950 {
1951 if (n == 0)
1952 return FALSE;
1953 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1954 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001955 if (path != NULL)
1956 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001957 return TRUE;
1958 }
1959 /* Retry with non-wide function (for Windows 98). */
1960 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001961 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001962#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001963
1964 curpath = getenv("PATH");
1965 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1966 if (newpath == NULL)
1967 return FALSE;
1968 STRCPY(newpath, ".;");
1969 STRCAT(newpath, curpath);
1970 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1971 vim_free(newpath);
1972 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001973 return FALSE;
1974 if (mch_isdir(fname))
1975 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001976 if (path != NULL)
1977 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001978 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979}
1980
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001981#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001982 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001983/*
1984 * Bad parameter handler.
1985 *
1986 * Certain MS CRT functions will intentionally crash when passed invalid
1987 * parameters to highlight possible security holes. Setting this function as
1988 * the bad parameter handler will prevent the crash.
1989 *
1990 * In debug builds the parameters contain CRT information that might help track
1991 * down the source of a problem, but in non-debug builds the arguments are all
1992 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1993 * worth allowing these to make debugging of issues easier.
1994 */
1995 static void
1996bad_param_handler(const wchar_t *expression,
1997 const wchar_t *function,
1998 const wchar_t *file,
1999 unsigned int line,
2000 uintptr_t pReserved)
2001{
2002}
2003
2004# define SET_INVALID_PARAM_HANDLER \
2005 ((void)_set_invalid_parameter_handler(bad_param_handler))
2006#else
2007# define SET_INVALID_PARAM_HANDLER
2008#endif
2009
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010#ifdef FEAT_GUI_W32
2011
2012/*
2013 * GUI version of mch_init().
2014 */
2015 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002016mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017{
2018#ifndef __MINGW32__
2019 extern int _fmode;
2020#endif
2021
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002022 /* Silently handle invalid parameters to CRT functions */
2023 SET_INVALID_PARAM_HANDLER;
2024
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 /* Let critical errors result in a failure, not in a dialog box. Required
2026 * for the timestamp test to work on removed floppies. */
2027 SetErrorMode(SEM_FAILCRITICALERRORS);
2028
2029 _fmode = O_BINARY; /* we do our own CR-LF translation */
2030
2031 /* Specify window size. Is there a place to get the default from? */
2032 Rows = 25;
2033 Columns = 80;
2034
2035 /* Look for 'vimrun' */
2036 if (!gui_is_win32s())
2037 {
2038 char_u vimrun_location[_MAX_PATH + 4];
2039
2040 /* First try in same directory as gvim.exe */
2041 STRCPY(vimrun_location, exe_name);
2042 STRCPY(gettail(vimrun_location), "vimrun.exe");
2043 if (mch_getperm(vimrun_location) >= 0)
2044 {
2045 if (*skiptowhite(vimrun_location) != NUL)
2046 {
2047 /* Enclose path with white space in double quotes. */
2048 mch_memmove(vimrun_location + 1, vimrun_location,
2049 STRLEN(vimrun_location) + 1);
2050 *vimrun_location = '"';
2051 STRCPY(gettail(vimrun_location), "vimrun\" ");
2052 }
2053 else
2054 STRCPY(gettail(vimrun_location), "vimrun ");
2055
2056 vimrun_path = (char *)vim_strsave(vimrun_location);
2057 s_dont_use_vimrun = FALSE;
2058 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002059 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 s_dont_use_vimrun = FALSE;
2061
2062 /* Don't give the warning for a missing vimrun.exe right now, but only
2063 * when vimrun was supposed to be used. Don't bother people that do
2064 * not need vimrun.exe. */
2065 if (s_dont_use_vimrun)
2066 need_vimrun_warning = TRUE;
2067 }
2068
2069 /*
2070 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2071 * Otherwise the default "findstr /n" is used.
2072 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002073 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2075
2076#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002077 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078#endif
2079}
2080
2081
2082#else /* FEAT_GUI_W32 */
2083
2084#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2085#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2086
2087/*
2088 * ClearConsoleBuffer()
2089 * Description:
2090 * Clears the entire contents of the console screen buffer, using the
2091 * specified attribute.
2092 * Returns:
2093 * TRUE on success
2094 */
2095 static BOOL
2096ClearConsoleBuffer(WORD wAttribute)
2097{
2098 CONSOLE_SCREEN_BUFFER_INFO csbi;
2099 COORD coord;
2100 DWORD NumCells, dummy;
2101
2102 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2103 return FALSE;
2104
2105 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2106 coord.X = 0;
2107 coord.Y = 0;
2108 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2109 coord, &dummy))
2110 {
2111 return FALSE;
2112 }
2113 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2114 coord, &dummy))
2115 {
2116 return FALSE;
2117 }
2118
2119 return TRUE;
2120}
2121
2122/*
2123 * FitConsoleWindow()
2124 * Description:
2125 * Checks if the console window will fit within given buffer dimensions.
2126 * Also, if requested, will shrink the window to fit.
2127 * Returns:
2128 * TRUE on success
2129 */
2130 static BOOL
2131FitConsoleWindow(
2132 COORD dwBufferSize,
2133 BOOL WantAdjust)
2134{
2135 CONSOLE_SCREEN_BUFFER_INFO csbi;
2136 COORD dwWindowSize;
2137 BOOL NeedAdjust = FALSE;
2138
2139 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2140 {
2141 /*
2142 * A buffer resize will fail if the current console window does
2143 * not lie completely within that buffer. To avoid this, we might
2144 * have to move and possibly shrink the window.
2145 */
2146 if (csbi.srWindow.Right >= dwBufferSize.X)
2147 {
2148 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2149 if (dwWindowSize.X > dwBufferSize.X)
2150 dwWindowSize.X = dwBufferSize.X;
2151 csbi.srWindow.Right = dwBufferSize.X - 1;
2152 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2153 NeedAdjust = TRUE;
2154 }
2155 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2156 {
2157 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2158 if (dwWindowSize.Y > dwBufferSize.Y)
2159 dwWindowSize.Y = dwBufferSize.Y;
2160 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2161 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2162 NeedAdjust = TRUE;
2163 }
2164 if (NeedAdjust && WantAdjust)
2165 {
2166 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2167 return FALSE;
2168 }
2169 return TRUE;
2170 }
2171
2172 return FALSE;
2173}
2174
2175typedef struct ConsoleBufferStruct
2176{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002177 BOOL IsValid;
2178 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002179 PCHAR_INFO Buffer;
2180 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002181} ConsoleBuffer;
2182
2183/*
2184 * SaveConsoleBuffer()
2185 * Description:
2186 * Saves important information about the console buffer, including the
2187 * actual buffer contents. The saved information is suitable for later
2188 * restoration by RestoreConsoleBuffer().
2189 * Returns:
2190 * TRUE if all information was saved; FALSE otherwise
2191 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2192 */
2193 static BOOL
2194SaveConsoleBuffer(
2195 ConsoleBuffer *cb)
2196{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002197 DWORD NumCells;
2198 COORD BufferCoord;
2199 SMALL_RECT ReadRegion;
2200 WORD Y, Y_incr;
2201
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202 if (cb == NULL)
2203 return FALSE;
2204
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002205 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002206 {
2207 cb->IsValid = FALSE;
2208 return FALSE;
2209 }
2210 cb->IsValid = TRUE;
2211
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002212 /*
2213 * Allocate a buffer large enough to hold the entire console screen
2214 * buffer. If this ConsoleBuffer structure has already been initialized
2215 * with a buffer of the correct size, then just use that one.
2216 */
2217 if (!cb->IsValid || cb->Buffer == NULL ||
2218 cb->BufferSize.X != cb->Info.dwSize.X ||
2219 cb->BufferSize.Y != cb->Info.dwSize.Y)
2220 {
2221 cb->BufferSize.X = cb->Info.dwSize.X;
2222 cb->BufferSize.Y = cb->Info.dwSize.Y;
2223 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2224 vim_free(cb->Buffer);
2225 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2226 if (cb->Buffer == NULL)
2227 return FALSE;
2228 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229
2230 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002231 * We will now copy the console screen buffer into our buffer.
2232 * ReadConsoleOutput() seems to be limited as far as how much you
2233 * can read at a time. Empirically, this number seems to be about
2234 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2235 * in chunks until it is all copied. The chunks will all have the
2236 * same horizontal characteristics, so initialize them now. The
2237 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002238 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002239 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002240 ReadRegion.Left = 0;
2241 ReadRegion.Right = cb->Info.dwSize.X - 1;
2242 Y_incr = 12000 / cb->Info.dwSize.X;
2243 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002245 /*
2246 * Read into position (0, Y) in our buffer.
2247 */
2248 BufferCoord.Y = Y;
2249 /*
2250 * Read the region whose top left corner is (0, Y) and whose bottom
2251 * right corner is (width - 1, Y + Y_incr - 1). This should define
2252 * a region of size width by Y_incr. Don't worry if this region is
2253 * too large for the remaining buffer; it will be cropped.
2254 */
2255 ReadRegion.Top = Y;
2256 ReadRegion.Bottom = Y + Y_incr - 1;
2257 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2258 cb->Buffer, /* our buffer */
2259 cb->BufferSize, /* dimensions of our buffer */
2260 BufferCoord, /* offset in our buffer */
2261 &ReadRegion)) /* region to save */
2262 {
2263 vim_free(cb->Buffer);
2264 cb->Buffer = NULL;
2265 return FALSE;
2266 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002267 }
2268
2269 return TRUE;
2270}
2271
2272/*
2273 * RestoreConsoleBuffer()
2274 * Description:
2275 * Restores important information about the console buffer, including the
2276 * actual buffer contents, if desired. The information to restore is in
2277 * the same format used by SaveConsoleBuffer().
2278 * Returns:
2279 * TRUE on success
2280 */
2281 static BOOL
2282RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002283 ConsoleBuffer *cb,
2284 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002286 COORD BufferCoord;
2287 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002288
2289 if (cb == NULL || !cb->IsValid)
2290 return FALSE;
2291
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002292 /*
2293 * Before restoring the buffer contents, clear the current buffer, and
2294 * restore the cursor position and window information. Doing this now
2295 * prevents old buffer contents from "flashing" onto the screen.
2296 */
2297 if (RestoreScreen)
2298 ClearConsoleBuffer(cb->Info.wAttributes);
2299
2300 FitConsoleWindow(cb->Info.dwSize, TRUE);
2301 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2302 return FALSE;
2303 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2304 return FALSE;
2305
2306 if (!RestoreScreen)
2307 {
2308 /*
2309 * No need to restore the screen buffer contents, so we're done.
2310 */
2311 return TRUE;
2312 }
2313
2314 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2315 return FALSE;
2316 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2317 return FALSE;
2318
2319 /*
2320 * Restore the screen buffer contents.
2321 */
2322 if (cb->Buffer != NULL)
2323 {
2324 BufferCoord.X = 0;
2325 BufferCoord.Y = 0;
2326 WriteRegion.Left = 0;
2327 WriteRegion.Top = 0;
2328 WriteRegion.Right = cb->Info.dwSize.X - 1;
2329 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2330 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2331 cb->Buffer, /* our buffer */
2332 cb->BufferSize, /* dimensions of our buffer */
2333 BufferCoord, /* offset in our buffer */
2334 &WriteRegion)) /* region to restore */
2335 {
2336 return FALSE;
2337 }
2338 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339
2340 return TRUE;
2341}
2342
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002343#define FEAT_RESTORE_ORIG_SCREEN
2344#ifdef FEAT_RESTORE_ORIG_SCREEN
2345static ConsoleBuffer g_cbOrig = { 0 };
2346#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347static ConsoleBuffer g_cbNonTermcap = { 0 };
2348static ConsoleBuffer g_cbTermcap = { 0 };
2349
2350#ifdef FEAT_TITLE
2351#ifdef __BORLANDC__
2352typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2353#else
2354typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2355#endif
2356char g_szOrigTitle[256] = { 0 };
2357HWND g_hWnd = NULL; /* also used in os_mswin.c */
2358static HICON g_hOrigIconSmall = NULL;
2359static HICON g_hOrigIcon = NULL;
2360static HICON g_hVimIcon = NULL;
2361static BOOL g_fCanChangeIcon = FALSE;
2362
2363/* ICON* are not defined in VC++ 4.0 */
2364#ifndef ICON_SMALL
2365#define ICON_SMALL 0
2366#endif
2367#ifndef ICON_BIG
2368#define ICON_BIG 1
2369#endif
2370/*
2371 * GetConsoleIcon()
2372 * Description:
2373 * Attempts to retrieve the small icon and/or the big icon currently in
2374 * use by a given window.
2375 * Returns:
2376 * TRUE on success
2377 */
2378 static BOOL
2379GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002380 HWND hWnd,
2381 HICON *phIconSmall,
2382 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383{
2384 if (hWnd == NULL)
2385 return FALSE;
2386
2387 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002388 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2389 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002391 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2392 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393 return TRUE;
2394}
2395
2396/*
2397 * SetConsoleIcon()
2398 * Description:
2399 * Attempts to change the small icon and/or the big icon currently in
2400 * use by a given window.
2401 * Returns:
2402 * TRUE on success
2403 */
2404 static BOOL
2405SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002406 HWND hWnd,
2407 HICON hIconSmall,
2408 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002410 HICON hPrevIconSmall;
2411 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412
2413 if (hWnd == NULL)
2414 return FALSE;
2415
2416 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002417 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2418 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002420 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2421 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 return TRUE;
2423}
2424
2425/*
2426 * SaveConsoleTitleAndIcon()
2427 * Description:
2428 * Saves the current console window title in g_szOrigTitle, for later
2429 * restoration. Also, attempts to obtain a handle to the console window,
2430 * and use it to save the small and big icons currently in use by the
2431 * console window. This is not always possible on some versions of Windows;
2432 * nor is it possible when running Vim remotely using Telnet (since the
2433 * console window the user sees is owned by a remote process).
2434 */
2435 static void
2436SaveConsoleTitleAndIcon(void)
2437{
2438 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2439
2440 /* Save the original title. */
2441 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2442 return;
2443
2444 /*
2445 * Obtain a handle to the console window using GetConsoleWindow() from
2446 * KERNEL32.DLL; we need to handle in order to change the window icon.
2447 * This function only exists on NT-based Windows, starting with Windows
2448 * 2000. On older operating systems, we can't change the window icon
2449 * anyway.
2450 */
2451 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2452 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2453 "GetConsoleWindow")) != NULL)
2454 {
2455 g_hWnd = (*GetConsoleWindowProc)();
2456 }
2457 if (g_hWnd == NULL)
2458 return;
2459
2460 /* Save the original console window icon. */
2461 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2462 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2463 return;
2464
2465 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002466 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2467 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002468 if (g_hVimIcon != NULL)
2469 g_fCanChangeIcon = TRUE;
2470}
2471#endif
2472
2473static int g_fWindInitCalled = FALSE;
2474static int g_fTermcapMode = FALSE;
2475static CONSOLE_CURSOR_INFO g_cci;
2476static DWORD g_cmodein = 0;
2477static DWORD g_cmodeout = 0;
2478
2479/*
2480 * non-GUI version of mch_init().
2481 */
2482 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002483mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002485#ifndef FEAT_RESTORE_ORIG_SCREEN
2486 CONSOLE_SCREEN_BUFFER_INFO csbi;
2487#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488#ifndef __MINGW32__
2489 extern int _fmode;
2490#endif
2491
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002492 /* Silently handle invalid parameters to CRT functions */
2493 SET_INVALID_PARAM_HANDLER;
2494
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 /* Let critical errors result in a failure, not in a dialog box. Required
2496 * for the timestamp test to work on removed floppies. */
2497 SetErrorMode(SEM_FAILCRITICALERRORS);
2498
2499 _fmode = O_BINARY; /* we do our own CR-LF translation */
2500 out_flush();
2501
2502 /* Obtain handles for the standard Console I/O devices */
2503 if (read_cmd_fd == 0)
2504 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2505 else
2506 create_conin();
2507 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2508
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002509#ifdef FEAT_RESTORE_ORIG_SCREEN
2510 /* Save the initial console buffer for later restoration */
2511 SaveConsoleBuffer(&g_cbOrig);
2512 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2513#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002515 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2516 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2517#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 if (cterm_normal_fg_color == 0)
2519 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2520 if (cterm_normal_bg_color == 0)
2521 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2522
2523 /* set termcap codes to current text attributes */
2524 update_tcap(g_attrCurrent);
2525
2526 GetConsoleCursorInfo(g_hConOut, &g_cci);
2527 GetConsoleMode(g_hConIn, &g_cmodein);
2528 GetConsoleMode(g_hConOut, &g_cmodeout);
2529
2530#ifdef FEAT_TITLE
2531 SaveConsoleTitleAndIcon();
2532 /*
2533 * Set both the small and big icons of the console window to Vim's icon.
2534 * Note that Vim presently only has one size of icon (32x32), but it
2535 * automatically gets scaled down to 16x16 when setting the small icon.
2536 */
2537 if (g_fCanChangeIcon)
2538 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2539#endif
2540
2541 ui_get_shellsize();
2542
2543#ifdef MCH_WRITE_DUMP
2544 fdDump = fopen("dump", "wt");
2545
2546 if (fdDump)
2547 {
2548 time_t t;
2549
2550 time(&t);
2551 fputs(ctime(&t), fdDump);
2552 fflush(fdDump);
2553 }
2554#endif
2555
2556 g_fWindInitCalled = TRUE;
2557
2558#ifdef FEAT_MOUSE
2559 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2560#endif
2561
2562#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002563 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564#endif
2565
2566 /* This will be NULL on anything but NT 4.0 */
2567 s_pfnGetConsoleKeyboardLayoutName =
2568 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2569 "GetConsoleKeyboardLayoutNameA");
2570}
2571
2572/*
2573 * non-GUI version of mch_exit().
2574 * Shut down and exit with status `r'
2575 * Careful: mch_exit() may be called before mch_init()!
2576 */
2577 void
2578mch_exit(int r)
2579{
2580 stoptermcap();
2581
2582 if (g_fWindInitCalled)
2583 settmode(TMODE_COOK);
2584
2585 ml_close_all(TRUE); /* remove all memfiles */
2586
2587 if (g_fWindInitCalled)
2588 {
2589#ifdef FEAT_TITLE
2590 mch_restore_title(3);
2591 /*
2592 * Restore both the small and big icons of the console window to
2593 * what they were at startup. Don't do this when the window is
2594 * closed, Vim would hang here.
2595 */
2596 if (g_fCanChangeIcon && !g_fForceExit)
2597 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2598#endif
2599
2600#ifdef MCH_WRITE_DUMP
2601 if (fdDump)
2602 {
2603 time_t t;
2604
2605 time(&t);
2606 fputs(ctime(&t), fdDump);
2607 fclose(fdDump);
2608 }
2609 fdDump = NULL;
2610#endif
2611 }
2612
2613 SetConsoleCursorInfo(g_hConOut, &g_cci);
2614 SetConsoleMode(g_hConIn, g_cmodein);
2615 SetConsoleMode(g_hConOut, g_cmodeout);
2616
2617#ifdef DYNAMIC_GETTEXT
2618 dyn_libintl_end();
2619#endif
2620
2621 exit(r);
2622}
2623#endif /* !FEAT_GUI_W32 */
2624
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625/*
2626 * Do we have an interactive window?
2627 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002628/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002629 int
2630mch_check_win(
2631 int argc,
2632 char **argv)
2633{
2634 get_exe_name();
2635
2636#ifdef FEAT_GUI_W32
2637 return OK; /* GUI always has a tty */
2638#else
2639 if (isatty(1))
2640 return OK;
2641 return FAIL;
2642#endif
2643}
2644
2645
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002646#ifdef FEAT_MBYTE
2647/*
2648 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2649 * if it already exists. When "len" is > 0, also expand short to long
2650 * filenames.
2651 * Return FAIL if wide functions are not available, OK otherwise.
2652 * NOTE: much of this is identical to fname_case(), keep in sync!
2653 */
2654 static int
2655fname_casew(
2656 WCHAR *name,
2657 int len)
2658{
2659 WCHAR szTrueName[_MAX_PATH + 2];
2660 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2661 WCHAR *ptrue, *ptruePrev;
2662 WCHAR *porig, *porigPrev;
2663 int flen;
2664 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002665 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002666 int c;
2667 int slen;
2668
2669 flen = (int)wcslen(name);
2670 if (flen > _MAX_PATH)
2671 return OK;
2672
2673 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2674
2675 /* Build the new name in szTrueName[] one component at a time. */
2676 porig = name;
2677 ptrue = szTrueName;
2678
2679 if (iswalpha(porig[0]) && porig[1] == L':')
2680 {
2681 /* copy leading drive letter */
2682 *ptrue++ = *porig++;
2683 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002684 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002685 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002686
2687 while (*porig != NUL)
2688 {
2689 /* copy \ characters */
2690 while (*porig == psepc)
2691 *ptrue++ = *porig++;
2692
2693 ptruePrev = ptrue;
2694 porigPrev = porig;
2695 while (*porig != NUL && *porig != psepc)
2696 {
2697 *ptrue++ = *porig++;
2698 }
2699 *ptrue = NUL;
2700
2701 /* To avoid a slow failure append "\*" when searching a directory,
2702 * server or network share. */
2703 wcscpy(szTrueNameTemp, szTrueName);
2704 slen = (int)wcslen(szTrueNameTemp);
2705 if (*porig == psepc && slen + 2 < _MAX_PATH)
2706 wcscpy(szTrueNameTemp + slen, L"\\*");
2707
2708 /* Skip "", "." and "..". */
2709 if (ptrue > ptruePrev
2710 && (ptruePrev[0] != L'.'
2711 || (ptruePrev[1] != NUL
2712 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2713 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2714 != INVALID_HANDLE_VALUE)
2715 {
2716 c = *porig;
2717 *porig = NUL;
2718
2719 /* Only use the match when it's the same name (ignoring case) or
2720 * expansion is allowed and there is a match with the short name
2721 * and there is enough room. */
2722 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2723 || (len > 0
2724 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2725 && (int)(ptruePrev - szTrueName)
2726 + (int)wcslen(fb.cFileName) < len)))
2727 {
2728 wcscpy(ptruePrev, fb.cFileName);
2729
2730 /* Look for exact match and prefer it if found. Must be a
2731 * long name, otherwise there would be only one match. */
2732 while (FindNextFileW(hFind, &fb))
2733 {
2734 if (*fb.cAlternateFileName != NUL
2735 && (wcscoll(porigPrev, fb.cFileName) == 0
2736 || (len > 0
2737 && (_wcsicoll(porigPrev,
2738 fb.cAlternateFileName) == 0
2739 && (int)(ptruePrev - szTrueName)
2740 + (int)wcslen(fb.cFileName) < len))))
2741 {
2742 wcscpy(ptruePrev, fb.cFileName);
2743 break;
2744 }
2745 }
2746 }
2747 FindClose(hFind);
2748 *porig = c;
2749 ptrue = ptruePrev + wcslen(ptruePrev);
2750 }
2751 else if (hFind == INVALID_HANDLE_VALUE
2752 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2753 return FAIL;
2754 }
2755
2756 wcscpy(name, szTrueName);
2757 return OK;
2758}
2759#endif
2760
Bram Moolenaar071d4272004-06-13 20:20:40 +00002761/*
2762 * fname_case(): Set the case of the file name, if it already exists.
2763 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002764 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765 */
2766 void
2767fname_case(
2768 char_u *name,
2769 int len)
2770{
2771 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002772 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002773 char *ptrue, *ptruePrev;
2774 char *porig, *porigPrev;
2775 int flen;
2776 WIN32_FIND_DATA fb;
2777 HANDLE hFind;
2778 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002779 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002781 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002782 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783 return;
2784
2785 slash_adjust(name);
2786
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002787#ifdef FEAT_MBYTE
2788 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2789 {
2790 WCHAR *p = enc_to_utf16(name, NULL);
2791
2792 if (p != NULL)
2793 {
2794 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002795 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002796
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002797 wcsncpy(buf, p, _MAX_PATH);
2798 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002799 vim_free(p);
2800
2801 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2802 {
2803 q = utf16_to_enc(buf, NULL);
2804 if (q != NULL)
2805 {
2806 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2807 vim_free(q);
2808 return;
2809 }
2810 }
2811 }
2812 /* Retry with non-wide function (for Windows 98). */
2813 }
2814#endif
2815
2816 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2817 * So we should check this after calling wide function. */
2818 if (flen > _MAX_PATH)
2819 return;
2820
Bram Moolenaar071d4272004-06-13 20:20:40 +00002821 /* Build the new name in szTrueName[] one component at a time. */
2822 porig = name;
2823 ptrue = szTrueName;
2824
2825 if (isalpha(porig[0]) && porig[1] == ':')
2826 {
2827 /* copy leading drive letter */
2828 *ptrue++ = *porig++;
2829 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002830 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002831 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832
2833 while (*porig != NUL)
2834 {
2835 /* copy \ characters */
2836 while (*porig == psepc)
2837 *ptrue++ = *porig++;
2838
2839 ptruePrev = ptrue;
2840 porigPrev = porig;
2841 while (*porig != NUL && *porig != psepc)
2842 {
2843#ifdef FEAT_MBYTE
2844 int l;
2845
2846 if (enc_dbcs)
2847 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002848 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849 while (--l >= 0)
2850 *ptrue++ = *porig++;
2851 }
2852 else
2853#endif
2854 *ptrue++ = *porig++;
2855 }
2856 *ptrue = NUL;
2857
Bram Moolenaar464c9252010-10-13 20:37:41 +02002858 /* To avoid a slow failure append "\*" when searching a directory,
2859 * server or network share. */
2860 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002861 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002862 if (*porig == psepc && slen + 2 < _MAX_PATH)
2863 STRCPY(szTrueNameTemp + slen, "\\*");
2864
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865 /* Skip "", "." and "..". */
2866 if (ptrue > ptruePrev
2867 && (ptruePrev[0] != '.'
2868 || (ptruePrev[1] != NUL
2869 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002870 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871 != INVALID_HANDLE_VALUE)
2872 {
2873 c = *porig;
2874 *porig = NUL;
2875
2876 /* Only use the match when it's the same name (ignoring case) or
2877 * expansion is allowed and there is a match with the short name
2878 * and there is enough room. */
2879 if (_stricoll(porigPrev, fb.cFileName) == 0
2880 || (len > 0
2881 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2882 && (int)(ptruePrev - szTrueName)
2883 + (int)strlen(fb.cFileName) < len)))
2884 {
2885 STRCPY(ptruePrev, fb.cFileName);
2886
2887 /* Look for exact match and prefer it if found. Must be a
2888 * long name, otherwise there would be only one match. */
2889 while (FindNextFile(hFind, &fb))
2890 {
2891 if (*fb.cAlternateFileName != NUL
2892 && (strcoll(porigPrev, fb.cFileName) == 0
2893 || (len > 0
2894 && (_stricoll(porigPrev,
2895 fb.cAlternateFileName) == 0
2896 && (int)(ptruePrev - szTrueName)
2897 + (int)strlen(fb.cFileName) < len))))
2898 {
2899 STRCPY(ptruePrev, fb.cFileName);
2900 break;
2901 }
2902 }
2903 }
2904 FindClose(hFind);
2905 *porig = c;
2906 ptrue = ptruePrev + strlen(ptruePrev);
2907 }
2908 }
2909
2910 STRCPY(name, szTrueName);
2911}
2912
2913
2914/*
2915 * Insert user name in s[len].
2916 */
2917 int
2918mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002919 char_u *s,
2920 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002922 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 DWORD cch = sizeof szUserName;
2924
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002925#ifdef FEAT_MBYTE
2926 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2927 {
2928 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2929 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2930
2931 if (GetUserNameW(wszUserName, &wcch))
2932 {
2933 char_u *p = utf16_to_enc(wszUserName, NULL);
2934
2935 if (p != NULL)
2936 {
2937 vim_strncpy(s, p, len - 1);
2938 vim_free(p);
2939 return OK;
2940 }
2941 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002942 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2943 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002944 /* Retry with non-wide function (for Windows 98). */
2945 }
2946#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 if (GetUserName(szUserName, &cch))
2948 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002949 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 return OK;
2951 }
2952 s[0] = NUL;
2953 return FAIL;
2954}
2955
2956
2957/*
2958 * Insert host name in s[len].
2959 */
2960 void
2961mch_get_host_name(
2962 char_u *s,
2963 int len)
2964{
2965 DWORD cch = len;
2966
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002967#ifdef FEAT_MBYTE
2968 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2969 {
2970 WCHAR wszHostName[256 + 1];
2971 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2972
2973 if (GetComputerNameW(wszHostName, &wcch))
2974 {
2975 char_u *p = utf16_to_enc(wszHostName, NULL);
2976
2977 if (p != NULL)
2978 {
2979 vim_strncpy(s, p, len - 1);
2980 vim_free(p);
2981 return;
2982 }
2983 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002984 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2985 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002986 /* Retry with non-wide function (for Windows 98). */
2987 }
2988#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002990 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991}
2992
2993
2994/*
2995 * return process ID
2996 */
2997 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002998mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999{
3000 return (long)GetCurrentProcessId();
3001}
3002
3003
3004/*
3005 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3006 * Return OK for success, FAIL for failure.
3007 */
3008 int
3009mch_dirname(
3010 char_u *buf,
3011 int len)
3012{
3013 /*
3014 * Originally this was:
3015 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3016 * But the Win32s known bug list says that getcwd() doesn't work
3017 * so use the Win32 system call instead. <Negri>
3018 */
3019#ifdef FEAT_MBYTE
3020 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3021 {
3022 WCHAR wbuf[_MAX_PATH + 1];
3023
3024 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3025 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003026 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027
3028 if (p != NULL)
3029 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003030 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 vim_free(p);
3032 return OK;
3033 }
3034 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003035 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3036 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037 /* Retry with non-wide function (for Windows 98). */
3038 }
3039#endif
3040 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3041}
3042
3043/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003044 * Get file permissions for "name".
3045 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046 */
3047 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003048mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003050 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003051 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003053 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003054 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055}
3056
3057
3058/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003059 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003060 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003061 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062 */
3063 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003064mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003066 long n = -1;
3067
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068#ifdef FEAT_MBYTE
3069 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3070 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003071 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072
3073 if (p != NULL)
3074 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003075 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003077 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003078 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079 /* Retry with non-wide function (for Windows 98). */
3080 }
3081 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003082 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003084 n = _chmod(name, perm);
3085 if (n == -1)
3086 return FAIL;
3087
3088 win32_set_archive(name);
3089
3090 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091}
3092
3093/*
3094 * Set hidden flag for "name".
3095 */
3096 void
3097mch_hide(char_u *name)
3098{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003099 int attrs = win32_getattrs(name);
3100 if (attrs == -1)
3101 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003103 attrs |= FILE_ATTRIBUTE_HIDDEN;
3104 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105}
3106
3107/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003108 * Return TRUE if file "name" exists and is hidden.
3109 */
3110 int
3111mch_ishidden(char_u *name)
3112{
3113 int f = win32_getattrs(name);
3114
3115 if (f == -1)
3116 return FALSE; /* file does not exist at all */
3117
3118 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3119}
3120
3121/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122 * return TRUE if "name" is a directory
3123 * return FALSE if "name" is not a directory or upon error
3124 */
3125 int
3126mch_isdir(char_u *name)
3127{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003128 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129
3130 if (f == -1)
3131 return FALSE; /* file does not exist at all */
3132
3133 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3134}
3135
3136/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003137 * return TRUE if "name" is a directory, NOT a symlink to a directory
3138 * return FALSE if "name" is not a directory
3139 * return FALSE for error
3140 */
3141 int
3142mch_isrealdir(char_u *name)
3143{
3144 return mch_isdir(name) && !mch_is_symbolic_link(name);
3145}
3146
3147/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003148 * Create directory "name".
3149 * Return 0 on success, -1 on error.
3150 */
3151 int
3152mch_mkdir(char_u *name)
3153{
3154#ifdef FEAT_MBYTE
3155 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3156 {
3157 WCHAR *p;
3158 int retval;
3159
3160 p = enc_to_utf16(name, NULL);
3161 if (p == NULL)
3162 return -1;
3163 retval = _wmkdir(p);
3164 vim_free(p);
3165 return retval;
3166 }
3167#endif
3168 return _mkdir(name);
3169}
3170
3171/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003172 * Delete directory "name".
3173 * Return 0 on success, -1 on error.
3174 */
3175 int
3176mch_rmdir(char_u *name)
3177{
3178#ifdef FEAT_MBYTE
3179 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3180 {
3181 WCHAR *p;
3182 int retval;
3183
3184 p = enc_to_utf16(name, NULL);
3185 if (p == NULL)
3186 return -1;
3187 retval = _wrmdir(p);
3188 vim_free(p);
3189 return retval;
3190 }
3191#endif
3192 return _rmdir(name);
3193}
3194
3195/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003196 * Return TRUE if file "fname" has more than one link.
3197 */
3198 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003199mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003200{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003201 BY_HANDLE_FILE_INFORMATION info;
3202
3203 return win32_fileinfo(fname, &info) == FILEINFO_OK
3204 && info.nNumberOfLinks > 1;
3205}
3206
3207/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003208 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003209 */
3210 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003211mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003212{
3213 HANDLE hFind;
3214 int res = FALSE;
3215 WIN32_FIND_DATAA findDataA;
3216 DWORD fileFlags = 0, reparseTag = 0;
3217#ifdef FEAT_MBYTE
3218 WCHAR *wn = NULL;
3219 WIN32_FIND_DATAW findDataW;
3220
3221 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003222 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003223 if (wn != NULL)
3224 {
3225 hFind = FindFirstFileW(wn, &findDataW);
3226 vim_free(wn);
3227 if (hFind == INVALID_HANDLE_VALUE
3228 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3229 {
3230 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar203258c2016-01-17 22:15:16 +01003231 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003232 if (hFind != INVALID_HANDLE_VALUE)
3233 {
3234 fileFlags = findDataA.dwFileAttributes;
3235 reparseTag = findDataA.dwReserved0;
3236 }
3237 }
3238 else
3239 {
3240 fileFlags = findDataW.dwFileAttributes;
3241 reparseTag = findDataW.dwReserved0;
3242 }
3243 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003244 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003245#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003246 {
Bram Moolenaar203258c2016-01-17 22:15:16 +01003247 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003248 if (hFind != INVALID_HANDLE_VALUE)
3249 {
3250 fileFlags = findDataA.dwFileAttributes;
3251 reparseTag = findDataA.dwReserved0;
3252 }
3253 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003254
3255 if (hFind != INVALID_HANDLE_VALUE)
3256 FindClose(hFind);
3257
3258 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003259 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3260 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003261 res = TRUE;
3262
3263 return res;
3264}
3265
3266/*
3267 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3268 * link.
3269 */
3270 int
3271mch_is_linked(char_u *fname)
3272{
3273 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3274 return TRUE;
3275 return FALSE;
3276}
3277
3278/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003279 * Get the by-handle-file-information for "fname".
3280 * Returns FILEINFO_OK when OK.
3281 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3282 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3283 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3284 */
3285 int
3286win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3287{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003288 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003289 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003290#ifdef FEAT_MBYTE
3291 WCHAR *wn = NULL;
3292
3293 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003294 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003295 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003296 if (wn == NULL)
3297 res = FILEINFO_ENC_FAIL;
3298 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003299 if (wn != NULL)
3300 {
3301 hFile = CreateFileW(wn, /* file name */
3302 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003303 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003304 NULL, /* security descriptor */
3305 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003306 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003307 NULL); /* handle to template file */
3308 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003309 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003310 {
3311 /* Retry with non-wide function (for Windows 98). */
3312 vim_free(wn);
3313 wn = NULL;
3314 }
3315 }
3316 if (wn == NULL)
3317#endif
3318 hFile = CreateFile(fname, /* file name */
3319 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003320 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003321 NULL, /* security descriptor */
3322 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003323 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003324 NULL); /* handle to template file */
3325
3326 if (hFile != INVALID_HANDLE_VALUE)
3327 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003328 if (GetFileInformationByHandle(hFile, info) != 0)
3329 res = FILEINFO_OK;
3330 else
3331 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003332 CloseHandle(hFile);
3333 }
3334
3335#ifdef FEAT_MBYTE
3336 vim_free(wn);
3337#endif
3338 return res;
3339}
3340
3341/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003342 * get file attributes for `name'
3343 * -1 : error
3344 * else FILE_ATTRIBUTE_* defined in winnt.h
3345 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003346 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347win32_getattrs(char_u *name)
3348{
3349 int attr;
3350#ifdef FEAT_MBYTE
3351 WCHAR *p = NULL;
3352
3353 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3354 p = enc_to_utf16(name, NULL);
3355
3356 if (p != NULL)
3357 {
3358 attr = GetFileAttributesW(p);
3359 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3360 {
3361 /* Retry with non-wide function (for Windows 98). */
3362 vim_free(p);
3363 p = NULL;
3364 }
3365 }
3366 if (p == NULL)
3367#endif
3368 attr = GetFileAttributes((char *)name);
3369#ifdef FEAT_MBYTE
3370 vim_free(p);
3371#endif
3372 return attr;
3373}
3374
3375/*
3376 * set file attributes for `name' to `attrs'
3377 *
3378 * return -1 for failure, 0 otherwise
3379 */
3380 static
3381 int
3382win32_setattrs(char_u *name, int attrs)
3383{
3384 int res;
3385#ifdef FEAT_MBYTE
3386 WCHAR *p = NULL;
3387
3388 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3389 p = enc_to_utf16(name, NULL);
3390
3391 if (p != NULL)
3392 {
3393 res = SetFileAttributesW(p, attrs);
3394 if (res == FALSE
3395 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3396 {
3397 /* Retry with non-wide function (for Windows 98). */
3398 vim_free(p);
3399 p = NULL;
3400 }
3401 }
3402 if (p == NULL)
3403#endif
3404 res = SetFileAttributes((char *)name, attrs);
3405#ifdef FEAT_MBYTE
3406 vim_free(p);
3407#endif
3408 return res ? 0 : -1;
3409}
3410
3411/*
3412 * Set archive flag for "name".
3413 */
3414 static
3415 int
3416win32_set_archive(char_u *name)
3417{
3418 int attrs = win32_getattrs(name);
3419 if (attrs == -1)
3420 return -1;
3421
3422 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3423 return win32_setattrs(name, attrs);
3424}
3425
3426/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427 * Return TRUE if file or directory "name" is writable (not readonly).
3428 * Strange semantics of Win32: a readonly directory is writable, but you can't
3429 * delete a file. Let's say this means it is writable.
3430 */
3431 int
3432mch_writable(char_u *name)
3433{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003434 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003436 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3437 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438}
3439
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440/*
3441 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003442 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003443 * Return -1 if unknown.
3444 */
3445 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003446mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003448 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003449 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003450 char_u *p;
3451
3452 if (len >= _MAX_PATH) /* safety check */
3453 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003454 if (!use_path)
3455 {
3456 /* TODO: check if file is really executable. */
3457 return mch_getperm(name) != -1 && !mch_isdir(name);
3458 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003459
3460 /* If there already is an extension try using the name directly. Also do
3461 * this with a Unix-shell like 'shell'. */
3462 if (vim_strchr(gettail(name), '.') != NULL
3463 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003464 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003465 return TRUE;
3466
3467 /*
3468 * Loop over all extensions in $PATHEXT.
3469 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003470 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003471 p = mch_getenv("PATHEXT");
3472 if (p == NULL)
3473 p = (char_u *)".com;.exe;.bat;.cmd";
3474 while (*p)
3475 {
3476 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3477 {
3478 /* A single "." means no extension is added. */
3479 buf[len] = NUL;
3480 ++p;
3481 if (*p)
3482 ++p;
3483 }
3484 else
3485 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003486 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003487 return TRUE;
3488 }
3489 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491
3492/*
3493 * Check what "name" is:
3494 * NODE_NORMAL: file or directory (or doesn't exist)
3495 * NODE_WRITABLE: writable device, socket, fifo, etc.
3496 * NODE_OTHER: non-writable things
3497 */
3498 int
3499mch_nodetype(char_u *name)
3500{
3501 HANDLE hFile;
3502 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003503#ifdef FEAT_MBYTE
3504 WCHAR *wn = NULL;
3505#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506
Bram Moolenaar043545e2006-10-10 16:44:07 +00003507 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3508 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3509 * here. */
3510 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3511 return NODE_WRITABLE;
3512
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003513#ifdef FEAT_MBYTE
3514 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3515 {
3516 wn = enc_to_utf16(name, NULL);
3517 if (wn != NULL)
3518 {
3519 hFile = CreateFileW(wn, /* file name */
3520 GENERIC_WRITE, /* access mode */
3521 0, /* share mode */
3522 NULL, /* security descriptor */
3523 OPEN_EXISTING, /* creation disposition */
3524 0, /* file attributes */
3525 NULL); /* handle to template file */
3526 if (hFile == INVALID_HANDLE_VALUE
3527 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3528 {
3529 /* Retry with non-wide function (for Windows 98). */
3530 vim_free(wn);
3531 wn = NULL;
3532 }
3533 }
3534 }
3535 if (wn == NULL)
3536#endif
3537 hFile = CreateFile(name, /* file name */
3538 GENERIC_WRITE, /* access mode */
3539 0, /* share mode */
3540 NULL, /* security descriptor */
3541 OPEN_EXISTING, /* creation disposition */
3542 0, /* file attributes */
3543 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003545#ifdef FEAT_MBYTE
3546 vim_free(wn);
3547#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003548 if (hFile == INVALID_HANDLE_VALUE)
3549 return NODE_NORMAL;
3550
3551 type = GetFileType(hFile);
3552 CloseHandle(hFile);
3553 if (type == FILE_TYPE_CHAR)
3554 return NODE_WRITABLE;
3555 if (type == FILE_TYPE_DISK)
3556 return NODE_NORMAL;
3557 return NODE_OTHER;
3558}
3559
3560#ifdef HAVE_ACL
3561struct my_acl
3562{
3563 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3564 PSID pSidOwner;
3565 PSID pSidGroup;
3566 PACL pDacl;
3567 PACL pSacl;
3568};
3569#endif
3570
3571/*
3572 * Return a pointer to the ACL of file "fname" in allocated memory.
3573 * Return NULL if the ACL is not available for whatever reason.
3574 */
3575 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003576mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003577{
3578#ifndef HAVE_ACL
3579 return (vim_acl_T)NULL;
3580#else
3581 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003582 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583
3584 /* This only works on Windows NT and 2000. */
3585 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3586 {
3587 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3588 if (p != NULL)
3589 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003590# ifdef FEAT_MBYTE
3591 WCHAR *wn = NULL;
3592
3593 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3594 wn = enc_to_utf16(fname, NULL);
3595 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003597 /* Try to retrieve the entire security descriptor. */
3598 err = pGetNamedSecurityInfoW(
3599 wn, // Abstract filename
3600 SE_FILE_OBJECT, // File Object
3601 OWNER_SECURITY_INFORMATION |
3602 GROUP_SECURITY_INFORMATION |
3603 DACL_SECURITY_INFORMATION |
3604 SACL_SECURITY_INFORMATION,
3605 &p->pSidOwner, // Ownership information.
3606 &p->pSidGroup, // Group membership.
3607 &p->pDacl, // Discretionary information.
3608 &p->pSacl, // For auditing purposes.
3609 &p->pSecurityDescriptor);
3610 if (err == ERROR_ACCESS_DENIED ||
3611 err == ERROR_PRIVILEGE_NOT_HELD)
3612 {
3613 /* Retrieve only DACL. */
3614 (void)pGetNamedSecurityInfoW(
3615 wn,
3616 SE_FILE_OBJECT,
3617 DACL_SECURITY_INFORMATION,
3618 NULL,
3619 NULL,
3620 &p->pDacl,
3621 NULL,
3622 &p->pSecurityDescriptor);
3623 }
3624 if (p->pSecurityDescriptor == NULL)
3625 {
3626 mch_free_acl((vim_acl_T)p);
3627 p = NULL;
3628 }
3629 vim_free(wn);
3630 }
3631 else
3632# endif
3633 {
3634 /* Try to retrieve the entire security descriptor. */
3635 err = pGetNamedSecurityInfo(
3636 (LPSTR)fname, // Abstract filename
3637 SE_FILE_OBJECT, // File Object
3638 OWNER_SECURITY_INFORMATION |
3639 GROUP_SECURITY_INFORMATION |
3640 DACL_SECURITY_INFORMATION |
3641 SACL_SECURITY_INFORMATION,
3642 &p->pSidOwner, // Ownership information.
3643 &p->pSidGroup, // Group membership.
3644 &p->pDacl, // Discretionary information.
3645 &p->pSacl, // For auditing purposes.
3646 &p->pSecurityDescriptor);
3647 if (err == ERROR_ACCESS_DENIED ||
3648 err == ERROR_PRIVILEGE_NOT_HELD)
3649 {
3650 /* Retrieve only DACL. */
3651 (void)pGetNamedSecurityInfo(
3652 (LPSTR)fname,
3653 SE_FILE_OBJECT,
3654 DACL_SECURITY_INFORMATION,
3655 NULL,
3656 NULL,
3657 &p->pDacl,
3658 NULL,
3659 &p->pSecurityDescriptor);
3660 }
3661 if (p->pSecurityDescriptor == NULL)
3662 {
3663 mch_free_acl((vim_acl_T)p);
3664 p = NULL;
3665 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003666 }
3667 }
3668 }
3669
3670 return (vim_acl_T)p;
3671#endif
3672}
3673
Bram Moolenaar27515922013-06-29 15:36:26 +02003674#ifdef HAVE_ACL
3675/*
3676 * Check if "acl" contains inherited ACE.
3677 */
3678 static BOOL
3679is_acl_inherited(PACL acl)
3680{
3681 DWORD i;
3682 ACL_SIZE_INFORMATION acl_info;
3683 PACCESS_ALLOWED_ACE ace;
3684
3685 acl_info.AceCount = 0;
3686 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3687 for (i = 0; i < acl_info.AceCount; i++)
3688 {
3689 GetAce(acl, i, (LPVOID *)&ace);
3690 if (ace->Header.AceFlags & INHERITED_ACE)
3691 return TRUE;
3692 }
3693 return FALSE;
3694}
3695#endif
3696
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697/*
3698 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3699 * Errors are ignored.
3700 * This must only be called with "acl" equal to what mch_get_acl() returned.
3701 */
3702 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003703mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704{
3705#ifdef HAVE_ACL
3706 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003707 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708
3709 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003710 {
3711# ifdef FEAT_MBYTE
3712 WCHAR *wn = NULL;
3713# endif
3714
3715 /* Set security flags */
3716 if (p->pSidOwner)
3717 sec_info |= OWNER_SECURITY_INFORMATION;
3718 if (p->pSidGroup)
3719 sec_info |= GROUP_SECURITY_INFORMATION;
3720 if (p->pDacl)
3721 {
3722 sec_info |= DACL_SECURITY_INFORMATION;
3723 /* Do not inherit its parent's DACL.
3724 * If the DACL is inherited, Cygwin permissions would be changed.
3725 */
3726 if (!is_acl_inherited(p->pDacl))
3727 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3728 }
3729 if (p->pSacl)
3730 sec_info |= SACL_SECURITY_INFORMATION;
3731
3732# ifdef FEAT_MBYTE
3733 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3734 wn = enc_to_utf16(fname, NULL);
3735 if (wn != NULL)
3736 {
3737 (void)pSetNamedSecurityInfoW(
3738 wn, // Abstract filename
3739 SE_FILE_OBJECT, // File Object
3740 sec_info,
3741 p->pSidOwner, // Ownership information.
3742 p->pSidGroup, // Group membership.
3743 p->pDacl, // Discretionary information.
3744 p->pSacl // For auditing purposes.
3745 );
3746 vim_free(wn);
3747 }
3748 else
3749# endif
3750 {
3751 (void)pSetNamedSecurityInfo(
3752 (LPSTR)fname, // Abstract filename
3753 SE_FILE_OBJECT, // File Object
3754 sec_info,
3755 p->pSidOwner, // Ownership information.
3756 p->pSidGroup, // Group membership.
3757 p->pDacl, // Discretionary information.
3758 p->pSacl // For auditing purposes.
3759 );
3760 }
3761 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762#endif
3763}
3764
3765 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003766mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767{
3768#ifdef HAVE_ACL
3769 struct my_acl *p = (struct my_acl *)acl;
3770
3771 if (p != NULL)
3772 {
3773 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3774 vim_free(p);
3775 }
3776#endif
3777}
3778
3779#ifndef FEAT_GUI_W32
3780
3781/*
3782 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3783 */
3784 static BOOL WINAPI
3785handler_routine(
3786 DWORD dwCtrlType)
3787{
3788 switch (dwCtrlType)
3789 {
3790 case CTRL_C_EVENT:
3791 if (ctrl_c_interrupts)
3792 g_fCtrlCPressed = TRUE;
3793 return TRUE;
3794
3795 case CTRL_BREAK_EVENT:
3796 g_fCBrkPressed = TRUE;
3797 return TRUE;
3798
3799 /* fatal events: shut down gracefully */
3800 case CTRL_CLOSE_EVENT:
3801 case CTRL_LOGOFF_EVENT:
3802 case CTRL_SHUTDOWN_EVENT:
3803 windgoto((int)Rows - 1, 0);
3804 g_fForceExit = TRUE;
3805
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003806 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807 (dwCtrlType == CTRL_CLOSE_EVENT
3808 ? _("close")
3809 : dwCtrlType == CTRL_LOGOFF_EVENT
3810 ? _("logoff")
3811 : _("shutdown")));
3812#ifdef DEBUG
3813 OutputDebugString(IObuff);
3814#endif
3815
3816 preserve_exit(); /* output IObuff, preserve files and exit */
3817
3818 return TRUE; /* not reached */
3819
3820 default:
3821 return FALSE;
3822 }
3823}
3824
3825
3826/*
3827 * set the tty in (raw) ? "raw" : "cooked" mode
3828 */
3829 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003830mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831{
3832 DWORD cmodein;
3833 DWORD cmodeout;
3834 BOOL bEnableHandler;
3835
3836 GetConsoleMode(g_hConIn, &cmodein);
3837 GetConsoleMode(g_hConOut, &cmodeout);
3838 if (tmode == TMODE_RAW)
3839 {
3840 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3841 ENABLE_ECHO_INPUT);
3842#ifdef FEAT_MOUSE
3843 if (g_fMouseActive)
3844 cmodein |= ENABLE_MOUSE_INPUT;
3845#endif
3846 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3847 bEnableHandler = TRUE;
3848 }
3849 else /* cooked */
3850 {
3851 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3852 ENABLE_ECHO_INPUT);
3853 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3854 bEnableHandler = FALSE;
3855 }
3856 SetConsoleMode(g_hConIn, cmodein);
3857 SetConsoleMode(g_hConOut, cmodeout);
3858 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3859
3860#ifdef MCH_WRITE_DUMP
3861 if (fdDump)
3862 {
3863 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3864 tmode == TMODE_RAW ? "raw" :
3865 tmode == TMODE_COOK ? "cooked" : "normal",
3866 cmodein, cmodeout);
3867 fflush(fdDump);
3868 }
3869#endif
3870}
3871
3872
3873/*
3874 * Get the size of the current window in `Rows' and `Columns'
3875 * Return OK when size could be determined, FAIL otherwise.
3876 */
3877 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003878mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879{
3880 CONSOLE_SCREEN_BUFFER_INFO csbi;
3881
3882 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3883 {
3884 /*
3885 * For some reason, we are trying to get the screen dimensions
3886 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3887 * variables are really intended to mean the size of Vim screen
3888 * while in termcap mode.
3889 */
3890 Rows = g_cbTermcap.Info.dwSize.Y;
3891 Columns = g_cbTermcap.Info.dwSize.X;
3892 }
3893 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3894 {
3895 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3896 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3897 }
3898 else
3899 {
3900 Rows = 25;
3901 Columns = 80;
3902 }
3903 return OK;
3904}
3905
3906/*
3907 * Set a console window to `xSize' * `ySize'
3908 */
3909 static void
3910ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003911 HANDLE hConsole,
3912 int xSize,
3913 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914{
3915 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3916 SMALL_RECT srWindowRect; /* hold the new console size */
3917 COORD coordScreen;
3918
3919#ifdef MCH_WRITE_DUMP
3920 if (fdDump)
3921 {
3922 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3923 fflush(fdDump);
3924 }
3925#endif
3926
3927 /* get the largest size we can size the console window to */
3928 coordScreen = GetLargestConsoleWindowSize(hConsole);
3929
3930 /* define the new console window size and scroll position */
3931 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3932 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3933 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3934
3935 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3936 {
3937 int sx, sy;
3938
3939 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3940 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3941 if (sy < ySize || sx < xSize)
3942 {
3943 /*
3944 * Increasing number of lines/columns, do buffer first.
3945 * Use the maximal size in x and y direction.
3946 */
3947 if (sy < ySize)
3948 coordScreen.Y = ySize;
3949 else
3950 coordScreen.Y = sy;
3951 if (sx < xSize)
3952 coordScreen.X = xSize;
3953 else
3954 coordScreen.X = sx;
3955 SetConsoleScreenBufferSize(hConsole, coordScreen);
3956 }
3957 }
3958
3959 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3960 {
3961#ifdef MCH_WRITE_DUMP
3962 if (fdDump)
3963 {
3964 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3965 GetLastError());
3966 fflush(fdDump);
3967 }
3968#endif
3969 }
3970
3971 /* define the new console buffer size */
3972 coordScreen.X = xSize;
3973 coordScreen.Y = ySize;
3974
3975 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3976 {
3977#ifdef MCH_WRITE_DUMP
3978 if (fdDump)
3979 {
3980 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3981 GetLastError());
3982 fflush(fdDump);
3983 }
3984#endif
3985 }
3986}
3987
3988
3989/*
3990 * Set the console window to `Rows' * `Columns'
3991 */
3992 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003993mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994{
3995 COORD coordScreen;
3996
3997 /* Don't change window size while still starting up */
3998 if (suppress_winsize != 0)
3999 {
4000 suppress_winsize = 2;
4001 return;
4002 }
4003
4004 if (term_console)
4005 {
4006 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4007
4008 /* Clamp Rows and Columns to reasonable values */
4009 if (Rows > coordScreen.Y)
4010 Rows = coordScreen.Y;
4011 if (Columns > coordScreen.X)
4012 Columns = coordScreen.X;
4013
4014 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4015 }
4016}
4017
4018/*
4019 * Rows and/or Columns has changed.
4020 */
4021 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004022mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004023{
4024 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4025}
4026
4027
4028/*
4029 * Called when started up, to set the winsize that was delayed.
4030 */
4031 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004032mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004033{
4034 if (suppress_winsize == 2)
4035 {
4036 suppress_winsize = 0;
4037 mch_set_shellsize();
4038 shell_resized();
4039 }
4040 suppress_winsize = 0;
4041}
4042#endif /* FEAT_GUI_W32 */
4043
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004044 static BOOL
4045vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004046 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004047 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004048 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004049 STARTUPINFO *si,
4050 PROCESS_INFORMATION *pi)
4051{
4052# ifdef FEAT_MBYTE
4053 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4054 {
4055 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4056
4057 if (wcmd != NULL)
4058 {
4059 BOOL ret;
4060 ret = CreateProcessW(
4061 NULL, /* Executable name */
4062 wcmd, /* Command to execute */
4063 NULL, /* Process security attributes */
4064 NULL, /* Thread security attributes */
4065 inherit_handles, /* Inherit handles */
4066 flags, /* Creation flags */
4067 NULL, /* Environment */
4068 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004069 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004070 pi); /* Process information */
4071 vim_free(wcmd);
4072 return ret;
4073 }
4074 }
4075#endif
4076 return CreateProcess(
4077 NULL, /* Executable name */
4078 cmd, /* Command to execute */
4079 NULL, /* Process security attributes */
4080 NULL, /* Thread security attributes */
4081 inherit_handles, /* Inherit handles */
4082 flags, /* Creation flags */
4083 NULL, /* Environment */
4084 NULL, /* Current directory */
4085 si, /* Startup information */
4086 pi); /* Process information */
4087}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088
4089
4090#if defined(FEAT_GUI_W32) || defined(PROTO)
4091
4092/*
4093 * Specialised version of system() for Win32 GUI mode.
4094 * This version proceeds as follows:
4095 * 1. Create a console window for use by the subprocess
4096 * 2. Run the subprocess (it gets the allocated console by default)
4097 * 3. Wait for the subprocess to terminate and get its exit code
4098 * 4. Prompt the user to press a key to close the console window
4099 */
4100 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004101mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102{
4103 STARTUPINFO si;
4104 PROCESS_INFORMATION pi;
4105 DWORD ret = 0;
4106 HWND hwnd = GetFocus();
4107
4108 si.cb = sizeof(si);
4109 si.lpReserved = NULL;
4110 si.lpDesktop = NULL;
4111 si.lpTitle = NULL;
4112 si.dwFlags = STARTF_USESHOWWINDOW;
4113 /*
4114 * It's nicer to run a filter command in a minimized window, but in
4115 * Windows 95 this makes the command MUCH slower. We can't do it under
4116 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004117 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118 */
4119 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004120 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 else
4122 si.wShowWindow = SW_SHOWNORMAL;
4123 si.cbReserved2 = 0;
4124 si.lpReserved2 = NULL;
4125
4126 /* There is a strange error on Windows 95 when using "c:\\command.com".
4127 * When the "c:\\" is left out it works OK...? */
4128 if (mch_windows95()
4129 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4130 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4131 cmd += 3;
4132
4133 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004134 vim_create_process(cmd, FALSE,
4135 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136
4137 /* Wait for the command to terminate before continuing */
4138 if (g_PlatformId != VER_PLATFORM_WIN32s)
4139 {
4140#ifdef FEAT_GUI
4141 int delay = 1;
4142
4143 /* Keep updating the window while waiting for the shell to finish. */
4144 for (;;)
4145 {
4146 MSG msg;
4147
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004148 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149 {
4150 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004151 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004152 delay = 1;
4153 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 }
4155 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4156 break;
4157
4158 /* We start waiting for a very short time and then increase it, so
4159 * that we respond quickly when the process is quick, and don't
4160 * consume too much overhead when it's slow. */
4161 if (delay < 50)
4162 delay += 10;
4163 }
4164#else
4165 WaitForSingleObject(pi.hProcess, INFINITE);
4166#endif
4167
4168 /* Get the command exit code */
4169 GetExitCodeProcess(pi.hProcess, &ret);
4170 }
4171 else
4172 {
4173 /*
4174 * This ugly code is the only quick way of performing
4175 * a synchronous spawn under Win32s. Yuk.
4176 */
4177 num_windows = 0;
4178 EnumWindows(win32ssynch_cb, 0);
4179 old_num_windows = num_windows;
4180 do
4181 {
4182 Sleep(1000);
4183 num_windows = 0;
4184 EnumWindows(win32ssynch_cb, 0);
4185 } while (num_windows == old_num_windows);
4186 ret = 0;
4187 }
4188
4189 /* Close the handles to the subprocess, so that it goes away */
4190 CloseHandle(pi.hThread);
4191 CloseHandle(pi.hProcess);
4192
4193 /* Try to get input focus back. Doesn't always work though. */
4194 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4195
4196 return ret;
4197}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004198
4199/*
4200 * Thread launched by the gui to send the current buffer data to the
4201 * process. This way avoid to hang up vim totally if the children
4202 * process take a long time to process the lines.
4203 */
4204 static DWORD WINAPI
4205sub_process_writer(LPVOID param)
4206{
4207 HANDLE g_hChildStd_IN_Wr = param;
4208 linenr_T lnum = curbuf->b_op_start.lnum;
4209 DWORD len = 0;
4210 DWORD l;
4211 char_u *lp = ml_get(lnum);
4212 char_u *s;
4213 int written = 0;
4214
4215 for (;;)
4216 {
4217 l = (DWORD)STRLEN(lp + written);
4218 if (l == 0)
4219 len = 0;
4220 else if (lp[written] == NL)
4221 {
4222 /* NL -> NUL translation */
4223 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4224 }
4225 else
4226 {
4227 s = vim_strchr(lp + written, NL);
4228 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4229 s == NULL ? l : (DWORD)(s - (lp + written)),
4230 &len, NULL);
4231 }
4232 if (len == (int)l)
4233 {
4234 /* Finished a line, add a NL, unless this line should not have
4235 * one. */
4236 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004237 || (!curbuf->b_p_bin
4238 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004239 || (lnum != curbuf->b_no_eol_lnum
4240 && (lnum != curbuf->b_ml.ml_line_count
4241 || curbuf->b_p_eol)))
4242 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004243 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004244 }
4245
4246 ++lnum;
4247 if (lnum > curbuf->b_op_end.lnum)
4248 break;
4249
4250 lp = ml_get(lnum);
4251 written = 0;
4252 }
4253 else if (len > 0)
4254 written += len;
4255 }
4256
4257 /* finished all the lines, close pipe */
4258 CloseHandle(g_hChildStd_IN_Wr);
4259 ExitThread(0);
4260}
4261
4262
4263# define BUFLEN 100 /* length for buffer, stolen from unix version */
4264
4265/*
4266 * This function read from the children's stdout and write the
4267 * data on screen or in the buffer accordingly.
4268 */
4269 static void
4270dump_pipe(int options,
4271 HANDLE g_hChildStd_OUT_Rd,
4272 garray_T *ga,
4273 char_u buffer[],
4274 DWORD *buffer_off)
4275{
4276 DWORD availableBytes = 0;
4277 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004278 int ret;
4279 DWORD len;
4280 DWORD toRead;
4281 int repeatCount;
4282
4283 /* we query the pipe to see if there is any data to read
4284 * to avoid to perform a blocking read */
4285 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4286 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004287 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004288 NULL, /* number of read bytes */
4289 &availableBytes, /* available bytes total */
4290 NULL); /* byteLeft */
4291
4292 repeatCount = 0;
4293 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004294 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004295 {
4296 repeatCount++;
4297 toRead =
4298# ifdef FEAT_MBYTE
4299 (DWORD)(BUFLEN - *buffer_off);
4300# else
4301 (DWORD)BUFLEN;
4302# endif
4303 toRead = availableBytes < toRead ? availableBytes : toRead;
4304 ReadFile(g_hChildStd_OUT_Rd, buffer
4305# ifdef FEAT_MBYTE
4306 + *buffer_off, toRead
4307# else
4308 , toRead
4309# endif
4310 , &len, NULL);
4311
4312 /* If we haven't read anything, there is a problem */
4313 if (len == 0)
4314 break;
4315
4316 availableBytes -= len;
4317
4318 if (options & SHELL_READ)
4319 {
4320 /* Do NUL -> NL translation, append NL separated
4321 * lines to the current buffer. */
4322 for (i = 0; i < len; ++i)
4323 {
4324 if (buffer[i] == NL)
4325 append_ga_line(ga);
4326 else if (buffer[i] == NUL)
4327 ga_append(ga, NL);
4328 else
4329 ga_append(ga, buffer[i]);
4330 }
4331 }
4332# ifdef FEAT_MBYTE
4333 else if (has_mbyte)
4334 {
4335 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004336 int c;
4337 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004338
4339 len += *buffer_off;
4340 buffer[len] = NUL;
4341
4342 /* Check if the last character in buffer[] is
4343 * incomplete, keep these bytes for the next
4344 * round. */
4345 for (p = buffer; p < buffer + len; p += l)
4346 {
4347 l = mb_cptr2len(p);
4348 if (l == 0)
4349 l = 1; /* NUL byte? */
4350 else if (MB_BYTE2LEN(*p) != l)
4351 break;
4352 }
4353 if (p == buffer) /* no complete character */
4354 {
4355 /* avoid getting stuck at an illegal byte */
4356 if (len >= 12)
4357 ++p;
4358 else
4359 {
4360 *buffer_off = len;
4361 return;
4362 }
4363 }
4364 c = *p;
4365 *p = NUL;
4366 msg_puts(buffer);
4367 if (p < buffer + len)
4368 {
4369 *p = c;
4370 *buffer_off = (DWORD)((buffer + len) - p);
4371 mch_memmove(buffer, p, *buffer_off);
4372 return;
4373 }
4374 *buffer_off = 0;
4375 }
4376# endif /* FEAT_MBYTE */
4377 else
4378 {
4379 buffer[len] = NUL;
4380 msg_puts(buffer);
4381 }
4382
4383 windgoto(msg_row, msg_col);
4384 cursor_on();
4385 out_flush();
4386 }
4387}
4388
4389/*
4390 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4391 * for communication and doesn't open any new window.
4392 */
4393 static int
4394mch_system_piped(char *cmd, int options)
4395{
4396 STARTUPINFO si;
4397 PROCESS_INFORMATION pi;
4398 DWORD ret = 0;
4399
4400 HANDLE g_hChildStd_IN_Rd = NULL;
4401 HANDLE g_hChildStd_IN_Wr = NULL;
4402 HANDLE g_hChildStd_OUT_Rd = NULL;
4403 HANDLE g_hChildStd_OUT_Wr = NULL;
4404
4405 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4406 DWORD len;
4407
4408 /* buffer used to receive keys */
4409 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4410 int ta_len = 0; /* valid bytes in ta_buf[] */
4411
4412 DWORD i;
4413 int c;
4414 int noread_cnt = 0;
4415 garray_T ga;
4416 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004417 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004418 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004419
4420 SECURITY_ATTRIBUTES saAttr;
4421
4422 /* Set the bInheritHandle flag so pipe handles are inherited. */
4423 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4424 saAttr.bInheritHandle = TRUE;
4425 saAttr.lpSecurityDescriptor = NULL;
4426
4427 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4428 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4429 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4430 /* Create a pipe for the child process's STDIN. */
4431 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4432 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4433 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4434 {
4435 CloseHandle(g_hChildStd_IN_Rd);
4436 CloseHandle(g_hChildStd_IN_Wr);
4437 CloseHandle(g_hChildStd_OUT_Rd);
4438 CloseHandle(g_hChildStd_OUT_Wr);
4439 MSG_PUTS(_("\nCannot create pipes\n"));
4440 }
4441
4442 si.cb = sizeof(si);
4443 si.lpReserved = NULL;
4444 si.lpDesktop = NULL;
4445 si.lpTitle = NULL;
4446 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4447
4448 /* set-up our file redirection */
4449 si.hStdError = g_hChildStd_OUT_Wr;
4450 si.hStdOutput = g_hChildStd_OUT_Wr;
4451 si.hStdInput = g_hChildStd_IN_Rd;
4452 si.wShowWindow = SW_HIDE;
4453 si.cbReserved2 = 0;
4454 si.lpReserved2 = NULL;
4455
4456 if (options & SHELL_READ)
4457 ga_init2(&ga, 1, BUFLEN);
4458
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004459 if (cmd != NULL)
4460 {
4461 p = (char *)vim_strsave((char_u *)cmd);
4462 if (p != NULL)
4463 unescape_shellxquote((char_u *)p, p_sxe);
4464 else
4465 p = cmd;
4466 }
4467
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004468 /* Now, run the command.
4469 * About "Inherit handles" being TRUE: this command can be litigious,
4470 * handle inheritance was deactivated for pending temp file, but, if we
4471 * deactivate it, the pipes don't work for some reason. */
4472 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004473
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004474 if (p != cmd)
4475 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004476
4477 /* Close our unused side of the pipes */
4478 CloseHandle(g_hChildStd_IN_Rd);
4479 CloseHandle(g_hChildStd_OUT_Wr);
4480
4481 if (options & SHELL_WRITE)
4482 {
4483 HANDLE thread =
4484 CreateThread(NULL, /* security attributes */
4485 0, /* default stack size */
4486 sub_process_writer, /* function to be executed */
4487 g_hChildStd_IN_Wr, /* parameter */
4488 0, /* creation flag, start immediately */
4489 NULL); /* we don't care about thread id */
4490 CloseHandle(thread);
4491 g_hChildStd_IN_Wr = NULL;
4492 }
4493
4494 /* Keep updating the window while waiting for the shell to finish. */
4495 for (;;)
4496 {
4497 MSG msg;
4498
Bram Moolenaar175d0702013-12-11 18:36:33 +01004499 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004500 {
4501 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004502 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004503 }
4504
4505 /* write pipe information in the window */
4506 if ((options & (SHELL_READ|SHELL_WRITE))
4507# ifdef FEAT_GUI
4508 || gui.in_use
4509# endif
4510 )
4511 {
4512 len = 0;
4513 if (!(options & SHELL_EXPAND)
4514 && ((options &
4515 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4516 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4517# ifdef FEAT_GUI
4518 || gui.in_use
4519# endif
4520 )
4521 && (ta_len > 0 || noread_cnt > 4))
4522 {
4523 if (ta_len == 0)
4524 {
4525 /* Get extra characters when we don't have any. Reset the
4526 * counter and timer. */
4527 noread_cnt = 0;
4528# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4529 gettimeofday(&start_tv, NULL);
4530# endif
4531 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4532 }
4533 if (ta_len > 0 || len > 0)
4534 {
4535 /*
4536 * For pipes: Check for CTRL-C: send interrupt signal to
4537 * child. Check for CTRL-D: EOF, close pipe to child.
4538 */
4539 if (len == 1 && cmd != NULL)
4540 {
4541 if (ta_buf[ta_len] == Ctrl_C)
4542 {
4543 /* Learn what exit code is expected, for
4544 * now put 9 as SIGKILL */
4545 TerminateProcess(pi.hProcess, 9);
4546 }
4547 if (ta_buf[ta_len] == Ctrl_D)
4548 {
4549 CloseHandle(g_hChildStd_IN_Wr);
4550 g_hChildStd_IN_Wr = NULL;
4551 }
4552 }
4553
4554 /* replace K_BS by <BS> and K_DEL by <DEL> */
4555 for (i = ta_len; i < ta_len + len; ++i)
4556 {
4557 if (ta_buf[i] == CSI && len - i > 2)
4558 {
4559 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4560 if (c == K_DEL || c == K_KDEL || c == K_BS)
4561 {
4562 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4563 (size_t)(len - i - 2));
4564 if (c == K_DEL || c == K_KDEL)
4565 ta_buf[i] = DEL;
4566 else
4567 ta_buf[i] = Ctrl_H;
4568 len -= 2;
4569 }
4570 }
4571 else if (ta_buf[i] == '\r')
4572 ta_buf[i] = '\n';
4573# ifdef FEAT_MBYTE
4574 if (has_mbyte)
4575 i += (*mb_ptr2len_len)(ta_buf + i,
4576 ta_len + len - i) - 1;
4577# endif
4578 }
4579
4580 /*
4581 * For pipes: echo the typed characters. For a pty this
4582 * does not seem to work.
4583 */
4584 for (i = ta_len; i < ta_len + len; ++i)
4585 {
4586 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4587 msg_putchar(ta_buf[i]);
4588# ifdef FEAT_MBYTE
4589 else if (has_mbyte)
4590 {
4591 int l = (*mb_ptr2len)(ta_buf + i);
4592
4593 msg_outtrans_len(ta_buf + i, l);
4594 i += l - 1;
4595 }
4596# endif
4597 else
4598 msg_outtrans_len(ta_buf + i, 1);
4599 }
4600 windgoto(msg_row, msg_col);
4601 out_flush();
4602
4603 ta_len += len;
4604
4605 /*
4606 * Write the characters to the child, unless EOF has been
4607 * typed for pipes. Write one character at a time, to
4608 * avoid losing too much typeahead. When writing buffer
4609 * lines, drop the typed characters (only check for
4610 * CTRL-C).
4611 */
4612 if (options & SHELL_WRITE)
4613 ta_len = 0;
4614 else if (g_hChildStd_IN_Wr != NULL)
4615 {
4616 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4617 1, &len, NULL);
4618 // if we are typing in, we want to keep things reactive
4619 delay = 1;
4620 if (len > 0)
4621 {
4622 ta_len -= len;
4623 mch_memmove(ta_buf, ta_buf + len, ta_len);
4624 }
4625 }
4626 }
4627 }
4628 }
4629
4630 if (ta_len)
4631 ui_inchar_undo(ta_buf, ta_len);
4632
4633 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4634 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004635 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004636 break;
4637 }
4638
4639 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004640 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004641
4642 /* We start waiting for a very short time and then increase it, so
4643 * that we respond quickly when the process is quick, and don't
4644 * consume too much overhead when it's slow. */
4645 if (delay < 50)
4646 delay += 10;
4647 }
4648
4649 /* Close the pipe */
4650 CloseHandle(g_hChildStd_OUT_Rd);
4651 if (g_hChildStd_IN_Wr != NULL)
4652 CloseHandle(g_hChildStd_IN_Wr);
4653
4654 WaitForSingleObject(pi.hProcess, INFINITE);
4655
4656 /* Get the command exit code */
4657 GetExitCodeProcess(pi.hProcess, &ret);
4658
4659 if (options & SHELL_READ)
4660 {
4661 if (ga.ga_len > 0)
4662 {
4663 append_ga_line(&ga);
4664 /* remember that the NL was missing */
4665 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4666 }
4667 else
4668 curbuf->b_no_eol_lnum = 0;
4669 ga_clear(&ga);
4670 }
4671
4672 /* Close the handles to the subprocess, so that it goes away */
4673 CloseHandle(pi.hThread);
4674 CloseHandle(pi.hProcess);
4675
4676 return ret;
4677}
4678
4679 static int
4680mch_system(char *cmd, int options)
4681{
4682 /* if we can pipe and the shelltemp option is off */
4683 if (allowPiping && !p_stmp)
4684 return mch_system_piped(cmd, options);
4685 else
4686 return mch_system_classic(cmd, options);
4687}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004688#else
4689
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004690# ifdef FEAT_MBYTE
4691 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004692mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004693{
4694 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4695 {
4696 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4697 if (wcmd != NULL)
4698 {
4699 int ret = _wsystem(wcmd);
4700 vim_free(wcmd);
4701 return ret;
4702 }
4703 }
4704 return system(cmd);
4705}
4706# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004707# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004708# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004709
4710#endif
4711
4712/*
4713 * Either execute a command by calling the shell or start a new shell
4714 */
4715 int
4716mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004717 char_u *cmd,
4718 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004719{
4720 int x = 0;
4721 int tmode = cur_tmode;
4722#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004723 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004724# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004725 int did_set_title = FALSE;
4726
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004727 /* Change the title to reflect that we are in a subshell. */
4728 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4729 {
4730 WCHAR szShellTitle[512];
4731
4732 if (GetConsoleTitleW(szShellTitle,
4733 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4734 {
4735 if (cmd == NULL)
4736 wcscat(szShellTitle, L" :sh");
4737 else
4738 {
4739 WCHAR *wn = enc_to_utf16(cmd, NULL);
4740
4741 if (wn != NULL)
4742 {
4743 wcscat(szShellTitle, L" - !");
4744 if ((wcslen(szShellTitle) + wcslen(wn) <
4745 sizeof(szShellTitle)/sizeof(WCHAR)))
4746 wcscat(szShellTitle, wn);
4747 SetConsoleTitleW(szShellTitle);
4748 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004749 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004750 }
4751 }
4752 }
4753 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004754 if (!did_set_title)
4755# endif
4756 /* Change the title to reflect that we are in a subshell. */
4757 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004759 if (cmd == NULL)
4760 strcat(szShellTitle, " :sh");
4761 else
4762 {
4763 strcat(szShellTitle, " - !");
4764 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4765 strcat(szShellTitle, cmd);
4766 }
4767 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769#endif
4770
4771 out_flush();
4772
4773#ifdef MCH_WRITE_DUMP
4774 if (fdDump)
4775 {
4776 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4777 fflush(fdDump);
4778 }
4779#endif
4780
4781 /*
4782 * Catch all deadly signals while running the external command, because a
4783 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4784 */
4785 signal(SIGINT, SIG_IGN);
4786#if defined(__GNUC__) && !defined(__MINGW32__)
4787 signal(SIGKILL, SIG_IGN);
4788#else
4789 signal(SIGBREAK, SIG_IGN);
4790#endif
4791 signal(SIGILL, SIG_IGN);
4792 signal(SIGFPE, SIG_IGN);
4793 signal(SIGSEGV, SIG_IGN);
4794 signal(SIGTERM, SIG_IGN);
4795 signal(SIGABRT, SIG_IGN);
4796
4797 if (options & SHELL_COOKED)
4798 settmode(TMODE_COOK); /* set to normal mode */
4799
4800 if (cmd == NULL)
4801 {
4802 x = mch_system(p_sh, options);
4803 }
4804 else
4805 {
4806 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004807 char_u *newcmd = NULL;
4808 char_u *cmdbase = cmd;
4809 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004810
4811 /* Skip a leading ", ( and "(. */
4812 if (*cmdbase == '"' )
4813 ++cmdbase;
4814 if (*cmdbase == '(')
4815 ++cmdbase;
4816
4817 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4818 {
4819 STARTUPINFO si;
4820 PROCESS_INFORMATION pi;
4821 DWORD flags = CREATE_NEW_CONSOLE;
4822 char_u *p;
4823
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004824 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004825 si.cb = sizeof(si);
4826 si.lpReserved = NULL;
4827 si.lpDesktop = NULL;
4828 si.lpTitle = NULL;
4829 si.dwFlags = 0;
4830 si.cbReserved2 = 0;
4831 si.lpReserved2 = NULL;
4832
4833 cmdbase = skipwhite(cmdbase + 5);
4834 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4835 && vim_iswhite(cmdbase[4]))
4836 {
4837 cmdbase = skipwhite(cmdbase + 4);
4838 si.dwFlags = STARTF_USESHOWWINDOW;
4839 si.wShowWindow = SW_SHOWMINNOACTIVE;
4840 }
4841 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4842 && vim_iswhite(cmdbase[2]))
4843 {
4844 cmdbase = skipwhite(cmdbase + 2);
4845 flags = CREATE_NO_WINDOW;
4846 si.dwFlags = STARTF_USESTDHANDLES;
4847 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004848 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004849 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004850 NULL, // Security att.
4851 OPEN_EXISTING, // Open flags
4852 FILE_ATTRIBUTE_NORMAL, // File att.
4853 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004854 si.hStdOutput = si.hStdInput;
4855 si.hStdError = si.hStdInput;
4856 }
4857
4858 /* Remove a trailing ", ) and )" if they have a match
4859 * at the start of the command. */
4860 if (cmdbase > cmd)
4861 {
4862 p = cmdbase + STRLEN(cmdbase);
4863 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4864 *--p = NUL;
4865 if (p > cmdbase && p[-1] == ')'
4866 && (*cmd =='(' || cmd[1] == '('))
4867 *--p = NUL;
4868 }
4869
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004870 newcmd = cmdbase;
4871 unescape_shellxquote(cmdbase, p_sxe);
4872
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004873 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004874 * If creating new console, arguments are passed to the
4875 * 'cmd.exe' as-is. If it's not, arguments are not treated
4876 * correctly for current 'cmd.exe'. So unescape characters in
4877 * shellxescape except '|' for avoiding to be treated as
4878 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004879 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004880 if (flags != CREATE_NEW_CONSOLE)
4881 {
4882 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004883 char_u *cmd_shell = mch_getenv("COMSPEC");
4884
4885 if (cmd_shell == NULL || *cmd_shell == NUL)
4886 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004887
4888 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4889 if (subcmd != NULL)
4890 {
4891 /* make "cmd.exe /c arguments" */
4892 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004893 newcmd = lalloc(cmdlen, TRUE);
4894 if (newcmd != NULL)
4895 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004896 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004897 else
4898 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004899 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004900 }
4901 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004902
4903 /*
4904 * Now, start the command as a process, so that it doesn't
4905 * inherit our handles which causes unpleasant dangling swap
4906 * files if we exit before the spawned process
4907 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004908 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004909 x = 0;
4910 else
4911 {
4912 x = -1;
4913#ifdef FEAT_GUI_W32
4914 EMSG(_("E371: Command not found"));
4915#endif
4916 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004917
4918 if (newcmd != cmdbase)
4919 vim_free(newcmd);
4920
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004921 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004922 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004923 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004924 CloseHandle(si.hStdInput);
4925 }
4926 /* Close the handles to the subprocess, so that it goes away */
4927 CloseHandle(pi.hThread);
4928 CloseHandle(pi.hProcess);
4929 }
4930 else
4931 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004932 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004933#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004934 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004935#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004936 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4937
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004938 newcmd = lalloc(cmdlen, TRUE);
4939 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940 {
4941#if defined(FEAT_GUI_W32)
4942 if (need_vimrun_warning)
4943 {
4944 MessageBox(NULL,
4945 _("VIMRUN.EXE not found in your $PATH.\n"
4946 "External commands will not pause after completion.\n"
4947 "See :help win32-vimrun for more information."),
4948 _("Vim Warning"),
4949 MB_ICONWARNING);
4950 need_vimrun_warning = FALSE;
4951 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004952 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953 /* Use vimrun to execute the command. It opens a console
4954 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004955 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004956 vimrun_path,
4957 (msg_silent != 0 || (options & SHELL_DOOUT))
4958 ? "-s " : "",
4959 p_sh, p_shcf, cmd);
4960 else
4961#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004962 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004963 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004965 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004966 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967 }
4968 }
4969
4970 if (tmode == TMODE_RAW)
4971 settmode(TMODE_RAW); /* set to raw mode */
4972
4973 /* Print the return value, unless "vimrun" was used. */
4974 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4975#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004976 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4977 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978#endif
4979 )
4980 {
4981 smsg(_("shell returned %d"), x);
4982 msg_putchar('\n');
4983 }
4984#ifdef FEAT_TITLE
4985 resettitle();
4986#endif
4987
4988 signal(SIGINT, SIG_DFL);
4989#if defined(__GNUC__) && !defined(__MINGW32__)
4990 signal(SIGKILL, SIG_DFL);
4991#else
4992 signal(SIGBREAK, SIG_DFL);
4993#endif
4994 signal(SIGILL, SIG_DFL);
4995 signal(SIGFPE, SIG_DFL);
4996 signal(SIGSEGV, SIG_DFL);
4997 signal(SIGTERM, SIG_DFL);
4998 signal(SIGABRT, SIG_DFL);
4999
5000 return x;
5001}
5002
5003
5004#ifndef FEAT_GUI_W32
5005
5006/*
5007 * Start termcap mode
5008 */
5009 static void
5010termcap_mode_start(void)
5011{
5012 DWORD cmodein;
5013
5014 if (g_fTermcapMode)
5015 return;
5016
5017 SaveConsoleBuffer(&g_cbNonTermcap);
5018
5019 if (g_cbTermcap.IsValid)
5020 {
5021 /*
5022 * We've been in termcap mode before. Restore certain screen
5023 * characteristics, including the buffer size and the window
5024 * size. Since we will be redrawing the screen, we don't need
5025 * to restore the actual contents of the buffer.
5026 */
5027 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5028 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5029 Rows = g_cbTermcap.Info.dwSize.Y;
5030 Columns = g_cbTermcap.Info.dwSize.X;
5031 }
5032 else
5033 {
5034 /*
5035 * This is our first time entering termcap mode. Clear the console
5036 * screen buffer, and resize the buffer to match the current window
5037 * size. We will use this as the size of our editing environment.
5038 */
5039 ClearConsoleBuffer(g_attrCurrent);
5040 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5041 }
5042
5043#ifdef FEAT_TITLE
5044 resettitle();
5045#endif
5046
5047 GetConsoleMode(g_hConIn, &cmodein);
5048#ifdef FEAT_MOUSE
5049 if (g_fMouseActive)
5050 cmodein |= ENABLE_MOUSE_INPUT;
5051 else
5052 cmodein &= ~ENABLE_MOUSE_INPUT;
5053#endif
5054 cmodein |= ENABLE_WINDOW_INPUT;
5055 SetConsoleMode(g_hConIn, cmodein);
5056
5057 redraw_later_clear();
5058 g_fTermcapMode = TRUE;
5059}
5060
5061
5062/*
5063 * End termcap mode
5064 */
5065 static void
5066termcap_mode_end(void)
5067{
5068 DWORD cmodein;
5069 ConsoleBuffer *cb;
5070 COORD coord;
5071 DWORD dwDummy;
5072
5073 if (!g_fTermcapMode)
5074 return;
5075
5076 SaveConsoleBuffer(&g_cbTermcap);
5077
5078 GetConsoleMode(g_hConIn, &cmodein);
5079 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5080 SetConsoleMode(g_hConIn, cmodein);
5081
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005082#ifdef FEAT_RESTORE_ORIG_SCREEN
5083 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5084#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005085 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005086#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005087 RestoreConsoleBuffer(cb, p_rs);
5088 SetConsoleCursorInfo(g_hConOut, &g_cci);
5089
5090 if (p_rs || exiting)
5091 {
5092 /*
5093 * Clear anything that happens to be on the current line.
5094 */
5095 coord.X = 0;
5096 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5097 FillConsoleOutputCharacter(g_hConOut, ' ',
5098 cb->Info.dwSize.X, coord, &dwDummy);
5099 /*
5100 * The following is just for aesthetics. If we are exiting without
5101 * restoring the screen, then we want to have a prompt string
5102 * appear at the bottom line. However, the command interpreter
5103 * seems to always advance the cursor one line before displaying
5104 * the prompt string, which causes the screen to scroll. To
5105 * counter this, move the cursor up one line before exiting.
5106 */
5107 if (exiting && !p_rs)
5108 coord.Y--;
5109 /*
5110 * Position the cursor at the leftmost column of the desired row.
5111 */
5112 SetConsoleCursorPosition(g_hConOut, coord);
5113 }
5114
5115 g_fTermcapMode = FALSE;
5116}
5117#endif /* FEAT_GUI_W32 */
5118
5119
5120#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005121/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005122 void
5123mch_write(
5124 char_u *s,
5125 int len)
5126{
5127 /* never used */
5128}
5129
5130#else
5131
5132/*
5133 * clear `n' chars, starting from `coord'
5134 */
5135 static void
5136clear_chars(
5137 COORD coord,
5138 DWORD n)
5139{
5140 DWORD dwDummy;
5141
5142 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5143 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5144}
5145
5146
5147/*
5148 * Clear the screen
5149 */
5150 static void
5151clear_screen(void)
5152{
5153 g_coord.X = g_coord.Y = 0;
5154 clear_chars(g_coord, Rows * Columns);
5155}
5156
5157
5158/*
5159 * Clear to end of display
5160 */
5161 static void
5162clear_to_end_of_display(void)
5163{
5164 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5165 * Columns + (Columns - g_coord.X));
5166}
5167
5168
5169/*
5170 * Clear to end of line
5171 */
5172 static void
5173clear_to_end_of_line(void)
5174{
5175 clear_chars(g_coord, Columns - g_coord.X);
5176}
5177
5178
5179/*
5180 * Scroll the scroll region up by `cLines' lines
5181 */
5182 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005183scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184{
5185 COORD oldcoord = g_coord;
5186
5187 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5188 delete_lines(cLines);
5189
5190 g_coord = oldcoord;
5191}
5192
5193
5194/*
5195 * Set the scroll region
5196 */
5197 static void
5198set_scroll_region(
5199 unsigned left,
5200 unsigned top,
5201 unsigned right,
5202 unsigned bottom)
5203{
5204 if (left >= right
5205 || top >= bottom
5206 || right > (unsigned) Columns - 1
5207 || bottom > (unsigned) Rows - 1)
5208 return;
5209
5210 g_srScrollRegion.Left = left;
5211 g_srScrollRegion.Top = top;
5212 g_srScrollRegion.Right = right;
5213 g_srScrollRegion.Bottom = bottom;
5214}
5215
5216
5217/*
5218 * Insert `cLines' lines at the current cursor position
5219 */
5220 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005221insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222{
5223 SMALL_RECT source;
5224 COORD dest;
5225 CHAR_INFO fill;
5226
5227 dest.X = 0;
5228 dest.Y = g_coord.Y + cLines;
5229
5230 source.Left = 0;
5231 source.Top = g_coord.Y;
5232 source.Right = g_srScrollRegion.Right;
5233 source.Bottom = g_srScrollRegion.Bottom - cLines;
5234
5235 fill.Char.AsciiChar = ' ';
5236 fill.Attributes = g_attrCurrent;
5237
5238 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5239
5240 /* Here we have to deal with a win32 console flake: If the scroll
5241 * region looks like abc and we scroll c to a and fill with d we get
5242 * cbd... if we scroll block c one line at a time to a, we get cdd...
5243 * vim expects cdd consistently... So we have to deal with that
5244 * here... (this also occurs scrolling the same way in the other
5245 * direction). */
5246
5247 if (source.Bottom < dest.Y)
5248 {
5249 COORD coord;
5250
5251 coord.X = 0;
5252 coord.Y = source.Bottom;
5253 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5254 }
5255}
5256
5257
5258/*
5259 * Delete `cLines' lines at the current cursor position
5260 */
5261 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005262delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005263{
5264 SMALL_RECT source;
5265 COORD dest;
5266 CHAR_INFO fill;
5267 int nb;
5268
5269 dest.X = 0;
5270 dest.Y = g_coord.Y;
5271
5272 source.Left = 0;
5273 source.Top = g_coord.Y + cLines;
5274 source.Right = g_srScrollRegion.Right;
5275 source.Bottom = g_srScrollRegion.Bottom;
5276
5277 fill.Char.AsciiChar = ' ';
5278 fill.Attributes = g_attrCurrent;
5279
5280 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5281
5282 /* Here we have to deal with a win32 console flake: If the scroll
5283 * region looks like abc and we scroll c to a and fill with d we get
5284 * cbd... if we scroll block c one line at a time to a, we get cdd...
5285 * vim expects cdd consistently... So we have to deal with that
5286 * here... (this also occurs scrolling the same way in the other
5287 * direction). */
5288
5289 nb = dest.Y + (source.Bottom - source.Top) + 1;
5290
5291 if (nb < source.Top)
5292 {
5293 COORD coord;
5294
5295 coord.X = 0;
5296 coord.Y = nb;
5297 clear_chars(coord, Columns * (source.Top - nb));
5298 }
5299}
5300
5301
5302/*
5303 * Set the cursor position
5304 */
5305 static void
5306gotoxy(
5307 unsigned x,
5308 unsigned y)
5309{
5310 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5311 return;
5312
5313 /* external cursor coords are 1-based; internal are 0-based */
5314 g_coord.X = x - 1;
5315 g_coord.Y = y - 1;
5316 SetConsoleCursorPosition(g_hConOut, g_coord);
5317}
5318
5319
5320/*
5321 * Set the current text attribute = (foreground | background)
5322 * See ../doc/os_win32.txt for the numbers.
5323 */
5324 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005325textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005326{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005327 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328
5329 SetConsoleTextAttribute(g_hConOut, wAttr);
5330}
5331
5332
5333 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005334textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005335{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005336 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005337
5338 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5339}
5340
5341
5342 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005343textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005344{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005345 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005346
5347 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5348}
5349
5350
5351/*
5352 * restore the default text attribute (whatever we started with)
5353 */
5354 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005355normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005356{
5357 textattr(g_attrDefault);
5358}
5359
5360
5361static WORD g_attrPreStandout = 0;
5362
5363/*
5364 * Make the text standout, by brightening it
5365 */
5366 static void
5367standout(void)
5368{
5369 g_attrPreStandout = g_attrCurrent;
5370 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5371}
5372
5373
5374/*
5375 * Turn off standout mode
5376 */
5377 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005378standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005379{
5380 if (g_attrPreStandout)
5381 {
5382 textattr(g_attrPreStandout);
5383 g_attrPreStandout = 0;
5384 }
5385}
5386
5387
5388/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005389 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005390 */
5391 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005392mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005393{
5394 char_u *p;
5395 int n;
5396
5397 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5398 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5399 if (T_ME[0] == ESC && T_ME[1] == '|')
5400 {
5401 p = T_ME + 2;
5402 n = getdigits(&p);
5403 if (*p == 'm' && n > 0)
5404 {
5405 cterm_normal_fg_color = (n & 0xf) + 1;
5406 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5407 }
5408 }
5409}
5410
5411
5412/*
5413 * visual bell: flash the screen
5414 */
5415 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005416visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005417{
5418 COORD coordOrigin = {0, 0};
5419 WORD attrFlash = ~g_attrCurrent & 0xff;
5420
5421 DWORD dwDummy;
5422 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5423
5424 if (oldattrs == NULL)
5425 return;
5426 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5427 coordOrigin, &dwDummy);
5428 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5429 coordOrigin, &dwDummy);
5430
5431 Sleep(15); /* wait for 15 msec */
5432 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5433 coordOrigin, &dwDummy);
5434 vim_free(oldattrs);
5435}
5436
5437
5438/*
5439 * Make the cursor visible or invisible
5440 */
5441 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005442cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005443{
5444 s_cursor_visible = fVisible;
5445#ifdef MCH_CURSOR_SHAPE
5446 mch_update_cursor();
5447#endif
5448}
5449
5450
5451/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005452 * write `cbToWrite' bytes in `pchBuf' to the screen
5453 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005455 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005456write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005457 char_u *pchBuf,
5458 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005459{
5460 COORD coord = g_coord;
5461 DWORD written;
5462
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005463#ifdef FEAT_MBYTE
5464 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5465 {
5466 static WCHAR *unicodebuf = NULL;
5467 static int unibuflen = 0;
5468 int length;
5469 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005470
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005471 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5472 if (unicodebuf == NULL || length > unibuflen)
5473 {
5474 vim_free(unicodebuf);
5475 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5476 unibuflen = length;
5477 }
5478 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5479 unicodebuf, unibuflen);
5480
5481 cells = mb_string2cells(pchBuf, cbToWrite);
5482 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5483 coord, &written);
5484 /* When writing fails or didn't write a single character, pretend one
5485 * character was written, otherwise we get stuck. */
5486 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5487 coord, &cchwritten) == 0
5488 || cchwritten == 0)
5489 cchwritten = 1;
5490
5491 if (cchwritten == length)
5492 {
5493 written = cbToWrite;
5494 g_coord.X += (SHORT)cells;
5495 }
5496 else
5497 {
5498 char_u *p = pchBuf;
5499 for (n = 0; n < cchwritten; n++)
5500 mb_cptr_adv(p);
5501 written = p - pchBuf;
5502 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5503 }
5504 }
5505 else
5506#endif
5507 {
5508 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5509 coord, &written);
5510 /* When writing fails or didn't write a single character, pretend one
5511 * character was written, otherwise we get stuck. */
5512 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5513 coord, &written) == 0
5514 || written == 0)
5515 written = 1;
5516
5517 g_coord.X += (SHORT) written;
5518 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005519
5520 while (g_coord.X > g_srScrollRegion.Right)
5521 {
5522 g_coord.X -= (SHORT) Columns;
5523 if (g_coord.Y < g_srScrollRegion.Bottom)
5524 g_coord.Y++;
5525 }
5526
5527 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5528
5529 return written;
5530}
5531
5532
5533/*
5534 * mch_write(): write the output buffer to the screen, translating ESC
5535 * sequences into calls to console output routines.
5536 */
5537 void
5538mch_write(
5539 char_u *s,
5540 int len)
5541{
5542 s[len] = NUL;
5543
5544 if (!term_console)
5545 {
5546 write(1, s, (unsigned)len);
5547 return;
5548 }
5549
5550 /* translate ESC | sequences into faked bios calls */
5551 while (len--)
5552 {
5553 /* optimization: use one single write_chars for runs of text,
5554 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005555 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556
5557 if (p_wd)
5558 {
5559 WaitForChar(p_wd);
5560 if (prefix != 0)
5561 prefix = 1;
5562 }
5563
5564 if (prefix != 0)
5565 {
5566 DWORD nWritten;
5567
5568 nWritten = write_chars(s, prefix);
5569#ifdef MCH_WRITE_DUMP
5570 if (fdDump)
5571 {
5572 fputc('>', fdDump);
5573 fwrite(s, sizeof(char_u), nWritten, fdDump);
5574 fputs("<\n", fdDump);
5575 }
5576#endif
5577 len -= (nWritten - 1);
5578 s += nWritten;
5579 }
5580 else if (s[0] == '\n')
5581 {
5582 /* \n, newline: go to the beginning of the next line or scroll */
5583 if (g_coord.Y == g_srScrollRegion.Bottom)
5584 {
5585 scroll(1);
5586 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5587 }
5588 else
5589 {
5590 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5591 }
5592#ifdef MCH_WRITE_DUMP
5593 if (fdDump)
5594 fputs("\\n\n", fdDump);
5595#endif
5596 s++;
5597 }
5598 else if (s[0] == '\r')
5599 {
5600 /* \r, carriage return: go to beginning of line */
5601 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5602#ifdef MCH_WRITE_DUMP
5603 if (fdDump)
5604 fputs("\\r\n", fdDump);
5605#endif
5606 s++;
5607 }
5608 else if (s[0] == '\b')
5609 {
5610 /* \b, backspace: move cursor one position left */
5611 if (g_coord.X > g_srScrollRegion.Left)
5612 g_coord.X--;
5613 else if (g_coord.Y > g_srScrollRegion.Top)
5614 {
5615 g_coord.X = g_srScrollRegion.Right;
5616 g_coord.Y--;
5617 }
5618 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5619#ifdef MCH_WRITE_DUMP
5620 if (fdDump)
5621 fputs("\\b\n", fdDump);
5622#endif
5623 s++;
5624 }
5625 else if (s[0] == '\a')
5626 {
5627 /* \a, bell */
5628 MessageBeep(0xFFFFFFFF);
5629#ifdef MCH_WRITE_DUMP
5630 if (fdDump)
5631 fputs("\\a\n", fdDump);
5632#endif
5633 s++;
5634 }
5635 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5636 {
5637#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005638 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005640 char_u *p;
5641 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642
5643 switch (s[2])
5644 {
5645 /* one or two numeric arguments, separated by ';' */
5646
5647 case '0': case '1': case '2': case '3': case '4':
5648 case '5': case '6': case '7': case '8': case '9':
5649 p = s + 2;
5650 arg1 = getdigits(&p); /* no check for length! */
5651 if (p > s + len)
5652 break;
5653
5654 if (*p == ';')
5655 {
5656 ++p;
5657 arg2 = getdigits(&p); /* no check for length! */
5658 if (p > s + len)
5659 break;
5660
5661 if (*p == 'H')
5662 gotoxy(arg2, arg1);
5663 else if (*p == 'r')
5664 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5665 }
5666 else if (*p == 'A')
5667 {
5668 /* move cursor up arg1 lines in same column */
5669 gotoxy(g_coord.X + 1,
5670 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5671 }
5672 else if (*p == 'C')
5673 {
5674 /* move cursor right arg1 columns in same line */
5675 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5676 g_coord.Y + 1);
5677 }
5678 else if (*p == 'H')
5679 {
5680 gotoxy(1, arg1);
5681 }
5682 else if (*p == 'L')
5683 {
5684 insert_lines(arg1);
5685 }
5686 else if (*p == 'm')
5687 {
5688 if (arg1 == 0)
5689 normvideo();
5690 else
5691 textattr((WORD) arg1);
5692 }
5693 else if (*p == 'f')
5694 {
5695 textcolor((WORD) arg1);
5696 }
5697 else if (*p == 'b')
5698 {
5699 textbackground((WORD) arg1);
5700 }
5701 else if (*p == 'M')
5702 {
5703 delete_lines(arg1);
5704 }
5705
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005706 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 s = p + 1;
5708 break;
5709
5710
5711 /* Three-character escape sequences */
5712
5713 case 'A':
5714 /* move cursor up one line in same column */
5715 gotoxy(g_coord.X + 1,
5716 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5717 goto got3;
5718
5719 case 'B':
5720 visual_bell();
5721 goto got3;
5722
5723 case 'C':
5724 /* move cursor right one column in same line */
5725 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5726 g_coord.Y + 1);
5727 goto got3;
5728
5729 case 'E':
5730 termcap_mode_end();
5731 goto got3;
5732
5733 case 'F':
5734 standout();
5735 goto got3;
5736
5737 case 'f':
5738 standend();
5739 goto got3;
5740
5741 case 'H':
5742 gotoxy(1, 1);
5743 goto got3;
5744
5745 case 'j':
5746 clear_to_end_of_display();
5747 goto got3;
5748
5749 case 'J':
5750 clear_screen();
5751 goto got3;
5752
5753 case 'K':
5754 clear_to_end_of_line();
5755 goto got3;
5756
5757 case 'L':
5758 insert_lines(1);
5759 goto got3;
5760
5761 case 'M':
5762 delete_lines(1);
5763 goto got3;
5764
5765 case 'S':
5766 termcap_mode_start();
5767 goto got3;
5768
5769 case 'V':
5770 cursor_visible(TRUE);
5771 goto got3;
5772
5773 case 'v':
5774 cursor_visible(FALSE);
5775 goto got3;
5776
5777 got3:
5778 s += 3;
5779 len -= 2;
5780 }
5781
5782#ifdef MCH_WRITE_DUMP
5783 if (fdDump)
5784 {
5785 fputs("ESC | ", fdDump);
5786 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5787 fputc('\n', fdDump);
5788 }
5789#endif
5790 }
5791 else
5792 {
5793 /* Write a single character */
5794 DWORD nWritten;
5795
5796 nWritten = write_chars(s, 1);
5797#ifdef MCH_WRITE_DUMP
5798 if (fdDump)
5799 {
5800 fputc('>', fdDump);
5801 fwrite(s, sizeof(char_u), nWritten, fdDump);
5802 fputs("<\n", fdDump);
5803 }
5804#endif
5805
5806 len -= (nWritten - 1);
5807 s += nWritten;
5808 }
5809 }
5810
5811#ifdef MCH_WRITE_DUMP
5812 if (fdDump)
5813 fflush(fdDump);
5814#endif
5815}
5816
5817#endif /* FEAT_GUI_W32 */
5818
5819
5820/*
5821 * Delay for half a second.
5822 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005823/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005824 void
5825mch_delay(
5826 long msec,
5827 int ignoreinput)
5828{
5829#ifdef FEAT_GUI_W32
5830 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005831#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005833# ifdef FEAT_MZSCHEME
5834 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5835 {
5836 int towait = p_mzq;
5837
5838 /* if msec is large enough, wait by portions in p_mzq */
5839 while (msec > 0)
5840 {
5841 mzvim_check_threads();
5842 if (msec < towait)
5843 towait = msec;
5844 Sleep(towait);
5845 msec -= towait;
5846 }
5847 }
5848 else
5849# endif
5850 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851 else
5852 WaitForChar(msec);
5853#endif
5854}
5855
5856
5857/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01005858 * This version of remove is not scared by a readonly (backup) file.
5859 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005860 * Return 0 for success, -1 for failure.
5861 */
5862 int
5863mch_remove(char_u *name)
5864{
5865#ifdef FEAT_MBYTE
5866 WCHAR *wn = NULL;
5867 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005868#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869
Bram Moolenaar203258c2016-01-17 22:15:16 +01005870 /*
5871 * On Windows, deleting a directory's symbolic link is done by
5872 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
5873 */
5874 if (mch_isdir(name) && mch_is_symbolic_link(name))
5875 return mch_rmdir(name);
5876
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005877 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5878
5879#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5881 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005882 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005883 if (wn != NULL)
5884 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005885 n = DeleteFileW(wn) ? 0 : -1;
5886 vim_free(wn);
5887 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5888 return n;
5889 /* Retry with non-wide function (for Windows 98). */
5890 }
5891 }
5892#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893 return DeleteFile(name) ? 0 : -1;
5894}
5895
5896
5897/*
5898 * check for an "interrupt signal": CTRL-break or CTRL-C
5899 */
5900 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005901mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902{
5903#ifndef FEAT_GUI_W32 /* never used */
5904 if (g_fCtrlCPressed || g_fCBrkPressed)
5905 {
5906 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5907 got_int = TRUE;
5908 }
5909#endif
5910}
5911
Bram Moolenaaree273972016-01-02 21:11:51 +01005912/* physical RAM to leave for the OS */
5913#define WINNT_RESERVE_BYTES (256*1024*1024)
5914#define WIN95_RESERVE_BYTES (8*1024*1024)
5915
5916/*
5917 * How much main memory in KiB that can be used by VIM.
5918 */
5919/*ARGSUSED*/
5920 long_u
5921mch_total_mem(int special)
5922{
5923 PlatformId();
5924#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
5925 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5926 {
5927 MEMORYSTATUSEX ms;
5928
5929 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5930 * what fits in 32 bits. But it's not always available. */
5931 ms.dwLength = sizeof(MEMORYSTATUSEX);
5932 GlobalMemoryStatusEx(&ms);
5933 if (ms.ullAvailVirtual < ms.ullTotalPhys)
5934 {
5935 /* Process address space fits in physical RAM, use all of it. */
5936 return (long_u)(ms.ullAvailVirtual / 1024);
5937 }
5938 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
5939 {
5940 /* Catch old NT box or perverse hardware setup. */
5941 return (long_u)((ms.ullTotalPhys / 2) / 1024);
5942 }
5943 /* Use physical RAM less reserve for OS + data. */
5944 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
5945 }
5946 else
5947#endif
5948 {
5949 /* Pre-XP or 95 OS handling. */
5950 MEMORYSTATUS ms;
5951 long_u os_reserve_bytes;
5952
5953 ms.dwLength = sizeof(MEMORYSTATUS);
5954 GlobalMemoryStatus(&ms);
5955 if (ms.dwAvailVirtual < ms.dwTotalPhys)
5956 {
5957 /* Process address space fits in physical RAM, use all of it. */
5958 return (long_u)(ms.dwAvailVirtual / 1024);
5959 }
5960 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
5961 ? WINNT_RESERVE_BYTES
5962 : WIN95_RESERVE_BYTES;
5963 if (ms.dwTotalPhys <= os_reserve_bytes)
5964 {
5965 /* Catch old boxes or perverse hardware setup. */
5966 return (long_u)((ms.dwTotalPhys / 2) / 1024);
5967 }
5968 /* Use physical RAM less reserve for OS + data. */
5969 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
5970 }
5971}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972
Bram Moolenaar071d4272004-06-13 20:20:40 +00005973#ifdef FEAT_MBYTE
5974/*
5975 * Same code as below, but with wide functions and no comments.
5976 * Return 0 for success, non-zero for failure.
5977 */
5978 int
5979mch_wrename(WCHAR *wold, WCHAR *wnew)
5980{
5981 WCHAR *p;
5982 int i;
5983 WCHAR szTempFile[_MAX_PATH + 1];
5984 WCHAR szNewPath[_MAX_PATH + 1];
5985 HANDLE hf;
5986
5987 if (!mch_windows95())
5988 {
5989 p = wold;
5990 for (i = 0; wold[i] != NUL; ++i)
5991 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5992 && wold[i + 1] != 0)
5993 p = wold + i + 1;
5994 if ((int)(wold + i - p) < 8 || p[6] != '~')
5995 return (MoveFileW(wold, wnew) == 0);
5996 }
5997
5998 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5999 return -1;
6000 *p = NUL;
6001
6002 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6003 return -2;
6004
6005 if (!DeleteFileW(szTempFile))
6006 return -3;
6007
6008 if (!MoveFileW(wold, szTempFile))
6009 return -4;
6010
6011 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6012 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6013 return -5;
6014 if (!CloseHandle(hf))
6015 return -6;
6016
6017 if (!MoveFileW(szTempFile, wnew))
6018 {
6019 (void)MoveFileW(szTempFile, wold);
6020 return -7;
6021 }
6022
6023 DeleteFileW(szTempFile);
6024
6025 if (!DeleteFileW(wold))
6026 return -8;
6027
6028 return 0;
6029}
6030#endif
6031
6032
6033/*
6034 * mch_rename() works around a bug in rename (aka MoveFile) in
6035 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6036 * file whose short file name is "FOO.BAR" (its long file name will
6037 * be correct: "foo.bar~"). Because a file can be accessed by
6038 * either its SFN or its LFN, "foo.bar" has effectively been
6039 * renamed to "foo.bar", which is not at all what was wanted. This
6040 * seems to happen only when renaming files with three-character
6041 * extensions by appending a suffix that does not include ".".
6042 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6043 *
6044 * There is another problem, which isn't really a bug but isn't right either:
6045 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6046 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6047 * service pack 6. Doesn't seem to happen on Windows 98.
6048 *
6049 * Like rename(), returns 0 upon success, non-zero upon failure.
6050 * Should probably set errno appropriately when errors occur.
6051 */
6052 int
6053mch_rename(
6054 const char *pszOldFile,
6055 const char *pszNewFile)
6056{
6057 char szTempFile[_MAX_PATH+1];
6058 char szNewPath[_MAX_PATH+1];
6059 char *pszFilePart;
6060 HANDLE hf;
6061#ifdef FEAT_MBYTE
6062 WCHAR *wold = NULL;
6063 WCHAR *wnew = NULL;
6064 int retval = -1;
6065
6066 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6067 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006068 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6069 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006070 if (wold != NULL && wnew != NULL)
6071 retval = mch_wrename(wold, wnew);
6072 vim_free(wold);
6073 vim_free(wnew);
6074 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6075 return retval;
6076 /* Retry with non-wide function (for Windows 98). */
6077 }
6078#endif
6079
6080 /*
6081 * No need to play tricks if not running Windows 95, unless the file name
6082 * contains a "~" as the seventh character.
6083 */
6084 if (!mch_windows95())
6085 {
6086 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6087 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6088 return rename(pszOldFile, pszNewFile);
6089 }
6090
6091 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6092 * a directory, no error is returned and pszFilePart will be NULL. */
6093 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6094 || pszFilePart == NULL)
6095 return -1;
6096 *pszFilePart = NUL;
6097
6098 /* Get (and create) a unique temporary file name in directory of new file */
6099 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6100 return -2;
6101
6102 /* blow the temp file away */
6103 if (!DeleteFile(szTempFile))
6104 return -3;
6105
6106 /* rename old file to the temp file */
6107 if (!MoveFile(pszOldFile, szTempFile))
6108 return -4;
6109
6110 /* now create an empty file called pszOldFile; this prevents the operating
6111 * system using pszOldFile as an alias (SFN) if we're renaming within the
6112 * same directory. For example, we're editing a file called
6113 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6114 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6115 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006116 * cause all sorts of problems later in buf_write(). So, we create an
6117 * empty file called filena~1.txt and the system will have to find some
6118 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006119 */
6120 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6121 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6122 return -5;
6123 if (!CloseHandle(hf))
6124 return -6;
6125
6126 /* rename the temp file to the new file */
6127 if (!MoveFile(szTempFile, pszNewFile))
6128 {
6129 /* Renaming failed. Rename the file back to its old name, so that it
6130 * looks like nothing happened. */
6131 (void)MoveFile(szTempFile, pszOldFile);
6132
6133 return -7;
6134 }
6135
6136 /* Seems to be left around on Novell filesystems */
6137 DeleteFile(szTempFile);
6138
6139 /* finally, remove the empty old file */
6140 if (!DeleteFile(pszOldFile))
6141 return -8;
6142
6143 return 0; /* success */
6144}
6145
6146/*
6147 * Get the default shell for the current hardware platform
6148 */
6149 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006150default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151{
6152 char* psz = NULL;
6153
6154 PlatformId();
6155
6156 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6157 psz = "cmd.exe";
6158 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6159 psz = "command.com";
6160
6161 return psz;
6162}
6163
6164/*
6165 * mch_access() extends access() to do more detailed check on network drives.
6166 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6167 */
6168 int
6169mch_access(char *n, int p)
6170{
6171 HANDLE hFile;
6172 DWORD am;
6173 int retval = -1; /* default: fail */
6174#ifdef FEAT_MBYTE
6175 WCHAR *wn = NULL;
6176
6177 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006178 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179#endif
6180
6181 if (mch_isdir(n))
6182 {
6183 char TempName[_MAX_PATH + 16] = "";
6184#ifdef FEAT_MBYTE
6185 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6186#endif
6187
6188 if (p & R_OK)
6189 {
6190 /* Read check is performed by seeing if we can do a find file on
6191 * the directory for any file. */
6192#ifdef FEAT_MBYTE
6193 if (wn != NULL)
6194 {
6195 int i;
6196 WIN32_FIND_DATAW d;
6197
6198 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6199 TempNameW[i] = wn[i];
6200 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6201 TempNameW[i++] = '\\';
6202 TempNameW[i++] = '*';
6203 TempNameW[i++] = 0;
6204
6205 hFile = FindFirstFileW(TempNameW, &d);
6206 if (hFile == INVALID_HANDLE_VALUE)
6207 {
6208 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6209 goto getout;
6210
6211 /* Retry with non-wide function (for Windows 98). */
6212 vim_free(wn);
6213 wn = NULL;
6214 }
6215 else
6216 (void)FindClose(hFile);
6217 }
6218 if (wn == NULL)
6219#endif
6220 {
6221 char *pch;
6222 WIN32_FIND_DATA d;
6223
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006224 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225 pch = TempName + STRLEN(TempName) - 1;
6226 if (*pch != '\\' && *pch != '/')
6227 *++pch = '\\';
6228 *++pch = '*';
6229 *++pch = NUL;
6230
6231 hFile = FindFirstFile(TempName, &d);
6232 if (hFile == INVALID_HANDLE_VALUE)
6233 goto getout;
6234 (void)FindClose(hFile);
6235 }
6236 }
6237
6238 if (p & W_OK)
6239 {
6240 /* Trying to create a temporary file in the directory should catch
6241 * directories on read-only network shares. However, in
6242 * directories whose ACL allows writes but denies deletes will end
6243 * up keeping the temporary file :-(. */
6244#ifdef FEAT_MBYTE
6245 if (wn != NULL)
6246 {
6247 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6248 {
6249 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6250 goto getout;
6251
6252 /* Retry with non-wide function (for Windows 98). */
6253 vim_free(wn);
6254 wn = NULL;
6255 }
6256 else
6257 DeleteFileW(TempNameW);
6258 }
6259 if (wn == NULL)
6260#endif
6261 {
6262 if (!GetTempFileName(n, "VIM", 0, TempName))
6263 goto getout;
6264 mch_remove((char_u *)TempName);
6265 }
6266 }
6267 }
6268 else
6269 {
6270 /* Trying to open the file for the required access does ACL, read-only
6271 * network share, and file attribute checks. */
6272 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6273 | ((p & R_OK) ? GENERIC_READ : 0);
6274#ifdef FEAT_MBYTE
6275 if (wn != NULL)
6276 {
6277 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6278 if (hFile == INVALID_HANDLE_VALUE
6279 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6280 {
6281 /* Retry with non-wide function (for Windows 98). */
6282 vim_free(wn);
6283 wn = NULL;
6284 }
6285 }
6286 if (wn == NULL)
6287#endif
6288 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6289 if (hFile == INVALID_HANDLE_VALUE)
6290 goto getout;
6291 CloseHandle(hFile);
6292 }
6293
6294 retval = 0; /* success */
6295getout:
6296#ifdef FEAT_MBYTE
6297 vim_free(wn);
6298#endif
6299 return retval;
6300}
6301
6302#if defined(FEAT_MBYTE) || defined(PROTO)
6303/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006304 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 */
6306 int
6307mch_open(char *name, int flags, int mode)
6308{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006309 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6310# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 WCHAR *wn;
6312 int f;
6313
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006314 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006316 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 if (wn != NULL)
6318 {
6319 f = _wopen(wn, flags, mode);
6320 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006321 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 return f;
6323 /* Retry with non-wide function (for Windows 98). Can't use
6324 * GetLastError() here and it's unclear what errno gets set to if
6325 * the _wopen() fails for missing wide functions. */
6326 }
6327 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006328# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006330 /* open() can open a file which name is longer than _MAX_PATH bytes
6331 * and shorter than _MAX_PATH characters successfully, but sometimes it
6332 * causes unexpected error in another part. We make it an error explicitly
6333 * here. */
6334 if (strlen(name) >= _MAX_PATH)
6335 return -1;
6336
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337 return open(name, flags, mode);
6338}
6339
6340/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006341 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342 */
6343 FILE *
6344mch_fopen(char *name, char *mode)
6345{
6346 WCHAR *wn, *wm;
6347 FILE *f = NULL;
6348
6349 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6350# ifdef __BORLANDC__
6351 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6352 && g_PlatformId == VER_PLATFORM_WIN32_NT
6353# endif
6354 )
6355 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006356# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006357 /* Work around an annoying assertion in the Microsoft debug CRT
6358 * when mode's text/binary setting doesn't match _get_fmode(). */
6359 char newMode = mode[strlen(mode) - 1];
6360 int oldMode = 0;
6361
6362 _get_fmode(&oldMode);
6363 if (newMode == 't')
6364 _set_fmode(_O_TEXT);
6365 else if (newMode == 'b')
6366 _set_fmode(_O_BINARY);
6367# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006368 wn = enc_to_utf16(name, NULL);
6369 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 if (wn != NULL && wm != NULL)
6371 f = _wfopen(wn, wm);
6372 vim_free(wn);
6373 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006374
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006375# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006376 _set_fmode(oldMode);
6377# endif
6378
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006379 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380 return f;
6381 /* Retry with non-wide function (for Windows 98). Can't use
6382 * GetLastError() here and it's unclear what errno gets set to if
6383 * the _wfopen() fails for missing wide functions. */
6384 }
6385
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006386 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6387 * and shorter than _MAX_PATH characters successfully, but sometimes it
6388 * causes unexpected error in another part. We make it an error explicitly
6389 * here. */
6390 if (strlen(name) >= _MAX_PATH)
6391 return NULL;
6392
Bram Moolenaar071d4272004-06-13 20:20:40 +00006393 return fopen(name, mode);
6394}
6395#endif
6396
6397#ifdef FEAT_MBYTE
6398/*
6399 * SUB STREAM (aka info stream) handling:
6400 *
6401 * NTFS can have sub streams for each file. Normal contents of file is
6402 * stored in the main stream, and extra contents (author information and
6403 * title and so on) can be stored in sub stream. After Windows 2000, user
6404 * can access and store those informations in sub streams via explorer's
6405 * property menuitem in right click menu. Those informations in sub streams
6406 * were lost when copying only the main stream. So we have to copy sub
6407 * streams.
6408 *
6409 * Incomplete explanation:
6410 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6411 * More useful info and an example:
6412 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6413 */
6414
6415/*
6416 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6417 * and write to stream "substream" of file "to".
6418 * Errors are ignored.
6419 */
6420 static void
6421copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6422{
6423 HANDLE hTo;
6424 WCHAR *to_name;
6425
6426 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6427 wcscpy(to_name, to);
6428 wcscat(to_name, substream);
6429
6430 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6431 FILE_ATTRIBUTE_NORMAL, NULL);
6432 if (hTo != INVALID_HANDLE_VALUE)
6433 {
6434 long done;
6435 DWORD todo;
6436 DWORD readcnt, written;
6437 char buf[4096];
6438
6439 /* Copy block of bytes at a time. Abort when something goes wrong. */
6440 for (done = 0; done < len; done += written)
6441 {
6442 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006443 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6444 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006445 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6446 FALSE, FALSE, context)
6447 || readcnt != todo
6448 || !WriteFile(hTo, buf, todo, &written, NULL)
6449 || written != todo)
6450 break;
6451 }
6452 CloseHandle(hTo);
6453 }
6454
6455 free(to_name);
6456}
6457
6458/*
6459 * Copy info streams from file "from" to file "to".
6460 */
6461 static void
6462copy_infostreams(char_u *from, char_u *to)
6463{
6464 WCHAR *fromw;
6465 WCHAR *tow;
6466 HANDLE sh;
6467 WIN32_STREAM_ID sid;
6468 int headersize;
6469 WCHAR streamname[_MAX_PATH];
6470 DWORD readcount;
6471 void *context = NULL;
6472 DWORD lo, hi;
6473 int len;
6474
6475 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006476 fromw = enc_to_utf16(from, NULL);
6477 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006478 if (fromw != NULL && tow != NULL)
6479 {
6480 /* Open the file for reading. */
6481 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6482 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6483 if (sh != INVALID_HANDLE_VALUE)
6484 {
6485 /* Use BackupRead() to find the info streams. Repeat until we
6486 * have done them all.*/
6487 for (;;)
6488 {
6489 /* Get the header to find the length of the stream name. If
6490 * the "readcount" is zero we have done all info streams. */
6491 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006492 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6494 &readcount, FALSE, FALSE, &context)
6495 || readcount == 0)
6496 break;
6497
6498 /* We only deal with streams that have a name. The normal
6499 * file data appears to be without a name, even though docs
6500 * suggest it is called "::$DATA". */
6501 if (sid.dwStreamNameSize > 0)
6502 {
6503 /* Read the stream name. */
6504 if (!BackupRead(sh, (LPBYTE)streamname,
6505 sid.dwStreamNameSize,
6506 &readcount, FALSE, FALSE, &context))
6507 break;
6508
6509 /* Copy an info stream with a name ":anything:$DATA".
6510 * Skip "::$DATA", it has no stream name (examples suggest
6511 * it might be used for the normal file contents).
6512 * Note that BackupRead() counts bytes, but the name is in
6513 * wide characters. */
6514 len = readcount / sizeof(WCHAR);
6515 streamname[len] = 0;
6516 if (len > 7 && wcsicmp(streamname + len - 6,
6517 L":$DATA") == 0)
6518 {
6519 streamname[len - 6] = 0;
6520 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006521 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 }
6523 }
6524
6525 /* Advance to the next stream. We might try seeking too far,
6526 * but BackupSeek() doesn't skip over stream borders, thus
6527 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006528 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006529 &lo, &hi, &context);
6530 }
6531
6532 /* Clear the context. */
6533 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6534
6535 CloseHandle(sh);
6536 }
6537 }
6538 vim_free(fromw);
6539 vim_free(tow);
6540}
6541#endif
6542
6543/*
6544 * Copy file attributes from file "from" to file "to".
6545 * For Windows NT and later we copy info streams.
6546 * Always returns zero, errors are ignored.
6547 */
6548 int
6549mch_copy_file_attribute(char_u *from, char_u *to)
6550{
6551#ifdef FEAT_MBYTE
6552 /* File streams only work on Windows NT and later. */
6553 PlatformId();
6554 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6555 copy_infostreams(from, to);
6556#endif
6557 return 0;
6558}
6559
6560#if defined(MYRESETSTKOFLW) || defined(PROTO)
6561/*
6562 * Recreate a destroyed stack guard page in win32.
6563 * Written by Benjamin Peterson.
6564 */
6565
6566/* These magic numbers are from the MS header files */
6567#define MIN_STACK_WIN9X 17
6568#define MIN_STACK_WINNT 2
6569
6570/*
6571 * This function does the same thing as _resetstkoflw(), which is only
6572 * available in DevStudio .net and later.
6573 * Returns 0 for failure, 1 for success.
6574 */
6575 int
6576myresetstkoflw(void)
6577{
6578 BYTE *pStackPtr;
6579 BYTE *pGuardPage;
6580 BYTE *pStackBase;
6581 BYTE *pLowestPossiblePage;
6582 MEMORY_BASIC_INFORMATION mbi;
6583 SYSTEM_INFO si;
6584 DWORD nPageSize;
6585 DWORD dummy;
6586
6587 /* This code will not work on win32s. */
6588 PlatformId();
6589 if (g_PlatformId == VER_PLATFORM_WIN32s)
6590 return 0;
6591
6592 /* We need to know the system page size. */
6593 GetSystemInfo(&si);
6594 nPageSize = si.dwPageSize;
6595
6596 /* ...and the current stack pointer */
6597 pStackPtr = (BYTE*)_alloca(1);
6598
6599 /* ...and the base of the stack. */
6600 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6601 return 0;
6602 pStackBase = (BYTE*)mbi.AllocationBase;
6603
6604 /* ...and the page thats min_stack_req pages away from stack base; this is
6605 * the lowest page we could use. */
6606 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6607 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6608
6609 /* On Win95, we want the next page down from the end of the stack. */
6610 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6611 {
6612 /* Find the page that's only 1 page down from the page that the stack
6613 * ptr is in. */
6614 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6615 / (DWORD)nPageSize) - 1));
6616 if (pGuardPage < pLowestPossiblePage)
6617 return 0;
6618
6619 /* Apply the noaccess attribute to the page -- there's no guard
6620 * attribute in win95-type OSes. */
6621 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6622 return 0;
6623 }
6624 else
6625 {
6626 /* On NT, however, we want the first committed page in the stack Start
6627 * at the stack base and move forward through memory until we find a
6628 * committed block. */
6629 BYTE *pBlock = pStackBase;
6630
Bram Moolenaara466c992005-07-09 21:03:22 +00006631 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 {
6633 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6634 return 0;
6635
6636 pBlock += mbi.RegionSize;
6637
6638 if (mbi.State & MEM_COMMIT)
6639 break;
6640 }
6641
6642 /* mbi now describes the first committed block in the stack. */
6643 if (mbi.Protect & PAGE_GUARD)
6644 return 1;
6645
6646 /* decide where the guard page should start */
6647 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6648 pGuardPage = pLowestPossiblePage;
6649 else
6650 pGuardPage = (BYTE*)mbi.BaseAddress;
6651
6652 /* allocate the guard page */
6653 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6654 return 0;
6655
6656 /* apply the guard attribute to the page */
6657 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6658 &dummy))
6659 return 0;
6660 }
6661
6662 return 1;
6663}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006664#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006666
6667#if defined(FEAT_MBYTE) || defined(PROTO)
6668/*
6669 * The command line arguments in UCS2
6670 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006671static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006672static LPWSTR *ArglistW = NULL;
6673static int global_argc = 0;
6674static char **global_argv;
6675
6676static int used_file_argc = 0; /* last argument in global_argv[] used
6677 for the argument list. */
6678static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6679 command line arguments added to
6680 the argument list */
6681static int used_file_count = 0; /* nr of entries in used_file_indexes */
6682static int used_file_literal = FALSE; /* take file names literally */
6683static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006684static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006685static int used_alist_count = 0;
6686
6687
6688/*
6689 * Get the command line arguments. Unicode version.
6690 * Returns argc. Zero when something fails.
6691 */
6692 int
6693get_cmd_argsW(char ***argvp)
6694{
6695 char **argv = NULL;
6696 int argc = 0;
6697 int i;
6698
Bram Moolenaar14993322014-09-09 12:25:33 +02006699 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006700 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6701 if (ArglistW != NULL)
6702 {
6703 argv = malloc((nArgsW + 1) * sizeof(char *));
6704 if (argv != NULL)
6705 {
6706 argc = nArgsW;
6707 argv[argc] = NULL;
6708 for (i = 0; i < argc; ++i)
6709 {
6710 int len;
6711
6712 /* Convert each Unicode argument to the current codepage. */
6713 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006714 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006715 (LPSTR *)&argv[i], &len, 0, 0);
6716 if (argv[i] == NULL)
6717 {
6718 /* Out of memory, clear everything. */
6719 while (i > 0)
6720 free(argv[--i]);
6721 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006722 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006723 argc = 0;
6724 }
6725 }
6726 }
6727 }
6728
6729 global_argc = argc;
6730 global_argv = argv;
6731 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006732 {
6733 if (used_file_indexes != NULL)
6734 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006735 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006736 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006737
6738 if (argvp != NULL)
6739 *argvp = argv;
6740 return argc;
6741}
6742
6743 void
6744free_cmd_argsW(void)
6745{
6746 if (ArglistW != NULL)
6747 {
6748 GlobalFree(ArglistW);
6749 ArglistW = NULL;
6750 }
6751}
6752
6753/*
6754 * Remember "name" is an argument that was added to the argument list.
6755 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6756 * is called.
6757 */
6758 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006759used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006760{
6761 int i;
6762
6763 if (used_file_indexes == NULL)
6764 return;
6765 for (i = used_file_argc + 1; i < global_argc; ++i)
6766 if (STRCMP(global_argv[i], name) == 0)
6767 {
6768 used_file_argc = i;
6769 used_file_indexes[used_file_count++] = i;
6770 break;
6771 }
6772 used_file_literal = literal;
6773 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006774 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006775}
6776
6777/*
6778 * Remember the length of the argument list as it was. If it changes then we
6779 * leave it alone when 'encoding' is set.
6780 */
6781 void
6782set_alist_count(void)
6783{
6784 used_alist_count = GARGCOUNT;
6785}
6786
6787/*
6788 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6789 * has been changed while starting up. Use the UCS-2 command line arguments
6790 * and convert them to 'encoding'.
6791 */
6792 void
6793fix_arg_enc(void)
6794{
6795 int i;
6796 int idx;
6797 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006798 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006799
6800 /* Safety checks:
6801 * - if argument count differs between the wide and non-wide argument
6802 * list, something must be wrong.
6803 * - the file name arguments must have been located.
6804 * - the length of the argument list wasn't changed by the user.
6805 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006806 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006807 || ArglistW == NULL
6808 || used_file_indexes == NULL
6809 || used_file_count == 0
6810 || used_alist_count != GARGCOUNT)
6811 return;
6812
Bram Moolenaar86b68352004-12-27 21:59:20 +00006813 /* Remember the buffer numbers for the arguments. */
6814 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6815 if (fnum_list == NULL)
6816 return; /* out of memory */
6817 for (i = 0; i < GARGCOUNT; ++i)
6818 fnum_list[i] = GARGLIST[i].ae_fnum;
6819
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006820 /* Clear the argument list. Make room for the new arguments. */
6821 alist_clear(&global_alist);
6822 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006823 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006824
6825 for (i = 0; i < used_file_count; ++i)
6826 {
6827 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006828 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006829 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006830 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006831#ifdef FEAT_DIFF
6832 /* When using diff mode may need to concatenate file name to
6833 * directory name. Just like it's done in main(). */
6834 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6835 && !mch_isdir(alist_name(&GARGLIST[0])))
6836 {
6837 char_u *r;
6838
6839 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6840 if (r != NULL)
6841 {
6842 vim_free(str);
6843 str = r;
6844 }
6845 }
6846#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006847 /* Re-use the old buffer by renaming it. When not using literal
6848 * names it's done by alist_expand() below. */
6849 if (used_file_literal)
6850 buf_set_name(fnum_list[i], str);
6851
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006852 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006853 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006854 }
6855
6856 if (!used_file_literal)
6857 {
6858 /* Now expand wildcards in the arguments. */
6859 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6860 * filename characters but are excluded from 'isfname' to make
6861 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6862 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006863 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006864 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6865 }
6866
6867 /* If wildcard expansion failed, we are editing the first file of the
6868 * arglist and there is no file name: Edit the first argument now. */
6869 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6870 {
6871 do_cmdline_cmd((char_u *)":rewind");
6872 if (GARGCOUNT == 1 && used_file_full_path)
6873 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6874 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006875
6876 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006877}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878#endif