blob: 9fa806e7382d2d7d7cd89327c645edf096b97bd4 [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 Moolenaar05540972016-01-30 20:31:25 +0100484dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000485{
486 int i;
487 static struct
488 {
489 char *name;
490 FARPROC *ptr;
491 } libintl_entry[] =
492 {
493 {"gettext", (FARPROC*)&dyn_libintl_gettext},
494 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
495 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
496 {NULL, NULL}
497 };
498
499 /* No need to initialize twice. */
500 if (hLibintlDLL)
501 return 1;
502 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100503 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100504#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100505 if (!hLibintlDLL)
506 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100507#endif
508 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200510 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200512 verbose_enter();
513 EMSG2(_(e_loadlib), GETTEXT_DLL);
514 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200516 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000517 }
518 for (i = 0; libintl_entry[i].name != NULL
519 && libintl_entry[i].ptr != NULL; ++i)
520 {
521 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
522 libintl_entry[i].name)) == NULL)
523 {
524 dyn_libintl_end();
525 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000526 {
527 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000528 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000529 verbose_leave();
530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000531 return 0;
532 }
533 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000534
535 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000536 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000537 "bind_textdomain_codeset");
538 if (dyn_libintl_bind_textdomain_codeset == NULL)
539 dyn_libintl_bind_textdomain_codeset =
540 null_libintl_bind_textdomain_codeset;
541
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542 return 1;
543}
544
545 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100546dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000547{
548 if (hLibintlDLL)
549 FreeLibrary(hLibintlDLL);
550 hLibintlDLL = NULL;
551 dyn_libintl_gettext = null_libintl_gettext;
552 dyn_libintl_textdomain = null_libintl_textdomain;
553 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000554 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555}
556
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000557/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000559null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560{
561 return (char*)msgid;
562}
563
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000564/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000566null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000567{
568 return NULL;
569}
570
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000571/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000573null_libintl_bind_textdomain_codeset(const char *domainname,
574 const char *codeset)
575{
576 return NULL;
577}
578
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000579/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000580 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000581null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582{
583 return NULL;
584}
585
586#endif /* DYNAMIC_GETTEXT */
587
588/* This symbol is not defined in older versions of the SDK or Visual C++ */
589
590#ifndef VER_PLATFORM_WIN32_WINDOWS
591# define VER_PLATFORM_WIN32_WINDOWS 1
592#endif
593
594DWORD g_PlatformId;
595
596#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100597# ifndef PROTO
598# include <aclapi.h>
599# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200600# ifndef PROTECTED_DACL_SECURITY_INFORMATION
601# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
602# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100603
Bram Moolenaar071d4272004-06-13 20:20:40 +0000604/*
605 * These are needed to dynamically load the ADVAPI DLL, which is not
606 * implemented under Windows 95 (and causes VIM to crash)
607 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200608typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200610typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
612 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200613# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200614typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200615 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200616typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200617 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
618 PSECURITY_DESCRIPTOR *);
619# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620
621static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
622static PSNSECINFO pSetNamedSecurityInfo;
623static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200624# ifdef FEAT_MBYTE
625static PSNSECINFOW pSetNamedSecurityInfoW;
626static PGNSECINFOW pGetNamedSecurityInfoW;
627# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000628#endif
629
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200630typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
631
632static BOOL allowPiping = FALSE;
633static PSETHANDLEINFORMATION pSetHandleInformation;
634
Bram Moolenaar27515922013-06-29 15:36:26 +0200635#ifdef HAVE_ACL
636/*
637 * Enables or disables the specified privilege.
638 */
639 static BOOL
640win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
641{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100642 BOOL bResult;
643 LUID luid;
644 HANDLE hToken;
645 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200646
647 if (!OpenProcessToken(GetCurrentProcess(),
648 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
649 return FALSE;
650
651 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
652 {
653 CloseHandle(hToken);
654 return FALSE;
655 }
656
Bram Moolenaar45500912014-07-09 20:51:07 +0200657 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200658 tokenPrivileges.Privileges[0].Luid = luid;
659 tokenPrivileges.Privileges[0].Attributes = bEnable ?
660 SE_PRIVILEGE_ENABLED : 0;
661
662 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
663 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
664
665 CloseHandle(hToken);
666
667 return bResult && GetLastError() == ERROR_SUCCESS;
668}
669#endif
670
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671/*
672 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
673 * VER_PLATFORM_WIN32_WINDOWS (Win95).
674 */
675 void
676PlatformId(void)
677{
678 static int done = FALSE;
679
680 if (!done)
681 {
682 OSVERSIONINFO ovi;
683
684 ovi.dwOSVersionInfoSize = sizeof(ovi);
685 GetVersionEx(&ovi);
686
687 g_PlatformId = ovi.dwPlatformId;
688
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100689 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
690 || ovi.dwMajorVersion > 6)
691 win8_or_later = TRUE;
692
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693#ifdef HAVE_ACL
694 /*
695 * Load the ADVAPI runtime if we are on anything
696 * other than Windows 95
697 */
698 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
699 {
700 /*
701 * do this load. Problems: Doesn't unload at end of run (this is
702 * theoretically okay, since Windows should unload it when VIM
703 * terminates). Should we be using the 'mch_libcall' routines?
704 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
705 * time we verify security...
706 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200707 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708 if (advapi_lib != NULL)
709 {
710 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
711 "SetNamedSecurityInfoA");
712 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
713 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200714# ifdef FEAT_MBYTE
715 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
716 "SetNamedSecurityInfoW");
717 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
718 "GetNamedSecurityInfoW");
719# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200721 || pGetNamedSecurityInfo == NULL
722# ifdef FEAT_MBYTE
723 || pSetNamedSecurityInfoW == NULL
724 || pGetNamedSecurityInfoW == NULL
725# endif
726 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727 {
728 /* If we can't get the function addresses, set advapi_lib
729 * to NULL so that we don't use them. */
730 FreeLibrary(advapi_lib);
731 advapi_lib = NULL;
732 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200733 /* Enable privilege for getting or setting SACLs. */
734 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 }
736 }
737#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200738 /*
739 * If we are on windows NT, try to load the pipe functions, only
740 * available from Win2K.
741 */
742 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
743 {
744 HANDLE kernel32 = GetModuleHandle("kernel32");
745 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
746 kernel32, "SetHandleInformation");
747
748 allowPiping = pSetHandleInformation != NULL;
749 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 done = TRUE;
751 }
752}
753
754/*
755 * Return TRUE when running on Windows 95 (or 98 or ME).
756 * Only to be used after mch_init().
757 */
758 int
759mch_windows95(void)
760{
761 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
762}
763
764#ifdef FEAT_GUI_W32
765/*
766 * Used to work around the "can't do synchronous spawn"
767 * problem on Win32s, without resorting to Universal Thunk.
768 */
769static int old_num_windows;
770static int num_windows;
771
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000772/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773 static BOOL CALLBACK
774win32ssynch_cb(HWND hwnd, LPARAM lparam)
775{
776 num_windows++;
777 return TRUE;
778}
779#endif
780
781#ifndef FEAT_GUI_W32
782
783#define SHIFT (SHIFT_PRESSED)
784#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
785#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
786#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
787
788
789/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
790 * We map function keys to their ANSI terminal equivalents, as produced
791 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
792 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
793 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
794 * combinations of function/arrow/etc keys.
795 */
796
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000797static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798{
799 WORD wVirtKey;
800 BOOL fAnsiKey;
801 int chAlone;
802 int chShift;
803 int chCtrl;
804 int chAlt;
805} VirtKeyMap[] =
806{
807
808/* Key ANSI alone shift ctrl alt */
809 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
810
811 { VK_F1, TRUE, ';', 'T', '^', 'h', },
812 { VK_F2, TRUE, '<', 'U', '_', 'i', },
813 { VK_F3, TRUE, '=', 'V', '`', 'j', },
814 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
815 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
816 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
817 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
818 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
819 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
820 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
821 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
822 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
823
824 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
825 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
826 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
827 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
828 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
829 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
830 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
831 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
832 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
833 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
834
835 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
836
837#if 0
838 /* Most people don't have F13-F20, but what the hell... */
839 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
840 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
841 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
842 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
843 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
844 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
845 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
846 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
847#endif
848 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
849 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
850 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
851 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
852
853 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
854 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
855 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
856 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
857 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
858 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
859 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
860 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
861 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
862 /* Sorry, out of number space! <negri>*/
863 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
864
865};
866
867
868#ifdef _MSC_VER
869// The ToAscii bug destroys several registers. Need to turn off optimization
870// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000871# pragma warning(push)
872# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873# pragma optimize("", off)
874#endif
875
876#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200877# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200879# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000880#endif
881
882/* The return code indicates key code size. */
883 static int
884#ifdef __BORLANDC__
885 __stdcall
886#endif
887win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000888 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889{
890 UINT uMods = pker->dwControlKeyState;
891 static int s_iIsDead = 0;
892 static WORD awAnsiCode[2];
893 static BYTE abKeystate[256];
894
895
896 if (s_iIsDead == 2)
897 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200898 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899 s_iIsDead = 0;
900 return 1;
901 }
902
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200903 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904 return 1;
905
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200906 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907
908 // Should only be non-NULL on NT 4.0
909 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
910 {
911 CHAR szKLID[KL_NAMELENGTH];
912
913 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
914 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
915 }
916
917 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200918 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919
920 if (uMods & SHIFT_PRESSED)
921 abKeystate[VK_SHIFT] = 0x80;
922 if (uMods & CAPSLOCK_ON)
923 abKeystate[VK_CAPITAL] = 1;
924
925 if ((uMods & ALT_GR) == ALT_GR)
926 {
927 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
928 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
929 }
930
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200931 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
932 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933
934 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200935 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936
937 return s_iIsDead;
938}
939
940#ifdef _MSC_VER
941/* MUST switch optimization on again here, otherwise a call to
942 * decode_key_event() may crash (e.g. when hitting caps-lock) */
943# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000944# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945
946# if (_MSC_VER < 1100)
947/* MUST turn off global optimisation for this next function, or
948 * pressing ctrl-minus in insert mode crashes Vim when built with
949 * VC4.1. -- negri. */
950# pragma optimize("g", off)
951# endif
952#endif
953
954static BOOL g_fJustGotFocus = FALSE;
955
956/*
957 * Decode a KEY_EVENT into one or two keystrokes
958 */
959 static BOOL
960decode_key_event(
961 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200962 WCHAR *pch,
963 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964 int *pmodifiers,
965 BOOL fDoPost)
966{
967 int i;
968 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
969
970 *pch = *pch2 = NUL;
971 g_fJustGotFocus = FALSE;
972
973 /* ignore key up events */
974 if (!pker->bKeyDown)
975 return FALSE;
976
977 /* ignore some keystrokes */
978 switch (pker->wVirtualKeyCode)
979 {
980 /* modifiers */
981 case VK_SHIFT:
982 case VK_CONTROL:
983 case VK_MENU: /* Alt key */
984 return FALSE;
985
986 default:
987 break;
988 }
989
990 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200991 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992 {
993 /* Ctrl-6 is Ctrl-^ */
994 if (pker->wVirtualKeyCode == '6')
995 {
996 *pch = Ctrl_HAT;
997 return TRUE;
998 }
999 /* Ctrl-2 is Ctrl-@ */
1000 else if (pker->wVirtualKeyCode == '2')
1001 {
1002 *pch = NUL;
1003 return TRUE;
1004 }
1005 /* Ctrl-- is Ctrl-_ */
1006 else if (pker->wVirtualKeyCode == 0xBD)
1007 {
1008 *pch = Ctrl__;
1009 return TRUE;
1010 }
1011 }
1012
1013 /* Shift-TAB */
1014 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1015 {
1016 *pch = K_NUL;
1017 *pch2 = '\017';
1018 return TRUE;
1019 }
1020
1021 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1022 {
1023 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1024 {
1025 if (nModifs == 0)
1026 *pch = VirtKeyMap[i].chAlone;
1027 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1028 *pch = VirtKeyMap[i].chShift;
1029 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1030 *pch = VirtKeyMap[i].chCtrl;
1031 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1032 *pch = VirtKeyMap[i].chAlt;
1033
1034 if (*pch != 0)
1035 {
1036 if (VirtKeyMap[i].fAnsiKey)
1037 {
1038 *pch2 = *pch;
1039 *pch = K_NUL;
1040 }
1041
1042 return TRUE;
1043 }
1044 }
1045 }
1046
1047 i = win32_kbd_patch_key(pker);
1048
1049 if (i < 0)
1050 *pch = NUL;
1051 else
1052 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001053 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054
1055 if (pmodifiers != NULL)
1056 {
1057 /* Pass on the ALT key as a modifier, but only when not combined
1058 * with CTRL (which is ALTGR). */
1059 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1060 *pmodifiers |= MOD_MASK_ALT;
1061
1062 /* Pass on SHIFT only for special keys, because we don't know when
1063 * it's already included with the character. */
1064 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1065 *pmodifiers |= MOD_MASK_SHIFT;
1066
1067 /* Pass on CTRL only for non-special keys, because we don't know
1068 * when it's already included with the character. And not when
1069 * combined with ALT (which is ALTGR). */
1070 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1071 && *pch >= 0x20 && *pch < 0x80)
1072 *pmodifiers |= MOD_MASK_CTRL;
1073 }
1074 }
1075
1076 return (*pch != NUL);
1077}
1078
1079#ifdef _MSC_VER
1080# pragma optimize("", on)
1081#endif
1082
1083#endif /* FEAT_GUI_W32 */
1084
1085
1086#ifdef FEAT_MOUSE
1087
1088/*
1089 * For the GUI the mouse handling is in gui_w32.c.
1090 */
1091# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001092/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001094mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095{
1096}
1097# else
1098static int g_fMouseAvail = FALSE; /* mouse present */
1099static int g_fMouseActive = FALSE; /* mouse enabled */
1100static int g_nMouseClick = -1; /* mouse status */
1101static int g_xMouse; /* mouse x coordinate */
1102static int g_yMouse; /* mouse y coordinate */
1103
1104/*
1105 * Enable or disable mouse input
1106 */
1107 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001108mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109{
1110 DWORD cmodein;
1111
1112 if (!g_fMouseAvail)
1113 return;
1114
1115 g_fMouseActive = on;
1116 GetConsoleMode(g_hConIn, &cmodein);
1117
1118 if (g_fMouseActive)
1119 cmodein |= ENABLE_MOUSE_INPUT;
1120 else
1121 cmodein &= ~ENABLE_MOUSE_INPUT;
1122
1123 SetConsoleMode(g_hConIn, cmodein);
1124}
1125
1126
1127/*
1128 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1129 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1130 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1131 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1132 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1133 * and we return the mouse position in g_xMouse and g_yMouse.
1134 *
1135 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1136 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1137 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1138 *
1139 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1140 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1141 *
1142 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1143 * moves, even if it stays within the same character cell. We ignore
1144 * all MOUSE_MOVED messages if the position hasn't really changed, and
1145 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1146 * we're only interested in MOUSE_DRAG).
1147 *
1148 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1149 * 2-button mouses by pressing the left & right buttons simultaneously.
1150 * In practice, it's almost impossible to click both at the same time,
1151 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1152 * in such cases, if the user is clicking quickly.
1153 */
1154 static BOOL
1155decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001156 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157{
1158 static int s_nOldButton = -1;
1159 static int s_nOldMouseClick = -1;
1160 static int s_xOldMouse = -1;
1161 static int s_yOldMouse = -1;
1162 static linenr_T s_old_topline = 0;
1163#ifdef FEAT_DIFF
1164 static int s_old_topfill = 0;
1165#endif
1166 static int s_cClicks = 1;
1167 static BOOL s_fReleased = TRUE;
1168 static DWORD s_dwLastClickTime = 0;
1169 static BOOL s_fNextIsMiddle = FALSE;
1170
1171 static DWORD cButtons = 0; /* number of buttons supported */
1172
1173 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1174 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1175 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1176 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1177
1178 int nButton;
1179
1180 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1181 cButtons = 2;
1182
1183 if (!g_fMouseAvail || !g_fMouseActive)
1184 {
1185 g_nMouseClick = -1;
1186 return FALSE;
1187 }
1188
1189 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1190 if (g_fJustGotFocus)
1191 {
1192 g_fJustGotFocus = FALSE;
1193 return FALSE;
1194 }
1195
1196 /* unprocessed mouse click? */
1197 if (g_nMouseClick != -1)
1198 return TRUE;
1199
1200 nButton = -1;
1201 g_xMouse = pmer->dwMousePosition.X;
1202 g_yMouse = pmer->dwMousePosition.Y;
1203
1204 if (pmer->dwEventFlags == MOUSE_MOVED)
1205 {
1206 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1207 * events even when the mouse moves only within a char cell.) */
1208 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1209 return FALSE;
1210 }
1211
1212 /* If no buttons are pressed... */
1213 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1214 {
1215 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1216 if (s_fReleased)
1217 return FALSE;
1218
1219 nButton = MOUSE_RELEASE;
1220 s_fReleased = TRUE;
1221 }
1222 else /* one or more buttons pressed */
1223 {
1224 /* on a 2-button mouse, hold down left and right buttons
1225 * simultaneously to get MIDDLE. */
1226
1227 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1228 {
1229 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1230
1231 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001232 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233 if (dwLR == LEFT || dwLR == RIGHT)
1234 {
1235 for (;;)
1236 {
1237 /* wait a short time for next input event */
1238 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1239 != WAIT_OBJECT_0)
1240 break;
1241 else
1242 {
1243 DWORD cRecords = 0;
1244 INPUT_RECORD ir;
1245 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1246
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001247 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001248
1249 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1250 || !(pmer2->dwButtonState & LEFT_RIGHT))
1251 break;
1252 else
1253 {
1254 if (pmer2->dwEventFlags != MOUSE_MOVED)
1255 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001256 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001257
1258 return decode_mouse_event(pmer2);
1259 }
1260 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1261 s_yOldMouse == pmer2->dwMousePosition.Y)
1262 {
1263 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001264 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265
1266 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001267 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001268
1269 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1270 break;
1271 }
1272 else
1273 break;
1274 }
1275 }
1276 }
1277 }
1278 }
1279
1280 if (s_fNextIsMiddle)
1281 {
1282 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1283 ? MOUSE_DRAG : MOUSE_MIDDLE;
1284 s_fNextIsMiddle = FALSE;
1285 }
1286 else if (cButtons == 2 &&
1287 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1288 {
1289 nButton = MOUSE_MIDDLE;
1290
1291 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1292 {
1293 s_fNextIsMiddle = TRUE;
1294 nButton = MOUSE_RELEASE;
1295 }
1296 }
1297 else if ((pmer->dwButtonState & LEFT) == LEFT)
1298 nButton = MOUSE_LEFT;
1299 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1300 nButton = MOUSE_MIDDLE;
1301 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1302 nButton = MOUSE_RIGHT;
1303
1304 if (! s_fReleased && ! s_fNextIsMiddle
1305 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1306 return FALSE;
1307
1308 s_fReleased = s_fNextIsMiddle;
1309 }
1310
1311 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1312 {
1313 /* button pressed or released, without mouse moving */
1314 if (nButton != -1 && nButton != MOUSE_RELEASE)
1315 {
1316 DWORD dwCurrentTime = GetTickCount();
1317
1318 if (s_xOldMouse != g_xMouse
1319 || s_yOldMouse != g_yMouse
1320 || s_nOldButton != nButton
1321 || s_old_topline != curwin->w_topline
1322#ifdef FEAT_DIFF
1323 || s_old_topfill != curwin->w_topfill
1324#endif
1325 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1326 {
1327 s_cClicks = 1;
1328 }
1329 else if (++s_cClicks > 4)
1330 {
1331 s_cClicks = 1;
1332 }
1333
1334 s_dwLastClickTime = dwCurrentTime;
1335 }
1336 }
1337 else if (pmer->dwEventFlags == MOUSE_MOVED)
1338 {
1339 if (nButton != -1 && nButton != MOUSE_RELEASE)
1340 nButton = MOUSE_DRAG;
1341
1342 s_cClicks = 1;
1343 }
1344
1345 if (nButton == -1)
1346 return FALSE;
1347
1348 if (nButton != MOUSE_RELEASE)
1349 s_nOldButton = nButton;
1350
1351 g_nMouseClick = nButton;
1352
1353 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1354 g_nMouseClick |= MOUSE_SHIFT;
1355 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1356 g_nMouseClick |= MOUSE_CTRL;
1357 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1358 g_nMouseClick |= MOUSE_ALT;
1359
1360 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1361 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1362
1363 /* only pass on interesting (i.e., different) mouse events */
1364 if (s_xOldMouse == g_xMouse
1365 && s_yOldMouse == g_yMouse
1366 && s_nOldMouseClick == g_nMouseClick)
1367 {
1368 g_nMouseClick = -1;
1369 return FALSE;
1370 }
1371
1372 s_xOldMouse = g_xMouse;
1373 s_yOldMouse = g_yMouse;
1374 s_old_topline = curwin->w_topline;
1375#ifdef FEAT_DIFF
1376 s_old_topfill = curwin->w_topfill;
1377#endif
1378 s_nOldMouseClick = g_nMouseClick;
1379
1380 return TRUE;
1381}
1382
1383# endif /* FEAT_GUI_W32 */
1384#endif /* FEAT_MOUSE */
1385
1386
1387#ifdef MCH_CURSOR_SHAPE
1388/*
1389 * Set the shape of the cursor.
1390 * 'thickness' can be from 1 (thin) to 99 (block)
1391 */
1392 static void
1393mch_set_cursor_shape(int thickness)
1394{
1395 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1396 ConsoleCursorInfo.dwSize = thickness;
1397 ConsoleCursorInfo.bVisible = s_cursor_visible;
1398
1399 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1400 if (s_cursor_visible)
1401 SetConsoleCursorPosition(g_hConOut, g_coord);
1402}
1403
1404 void
1405mch_update_cursor(void)
1406{
1407 int idx;
1408 int thickness;
1409
1410 /*
1411 * How the cursor is drawn depends on the current mode.
1412 */
1413 idx = get_shape_idx(FALSE);
1414
1415 if (shape_table[idx].shape == SHAPE_BLOCK)
1416 thickness = 99; /* 100 doesn't work on W95 */
1417 else
1418 thickness = shape_table[idx].percentage;
1419 mch_set_cursor_shape(thickness);
1420}
1421#endif
1422
1423#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1424/*
1425 * Handle FOCUS_EVENT.
1426 */
1427 static void
1428handle_focus_event(INPUT_RECORD ir)
1429{
1430 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1431 ui_focus_change((int)g_fJustGotFocus);
1432}
1433
1434/*
1435 * Wait until console input from keyboard or mouse is available,
1436 * or the time is up.
1437 * Return TRUE if something is available FALSE if not.
1438 */
1439 static int
1440WaitForChar(long msec)
1441{
1442 DWORD dwNow = 0, dwEndTime = 0;
1443 INPUT_RECORD ir;
1444 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001445 WCHAR ch, ch2;
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001446#ifdef FEAT_CHANNEL
1447 int ret;
1448 fd_set rfds;
1449 int maxfd;
1450#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451
1452 if (msec > 0)
1453 /* Wait until the specified time has elapsed. */
1454 dwEndTime = GetTickCount() + msec;
1455 else if (msec < 0)
1456 /* Wait forever. */
1457 dwEndTime = INFINITE;
1458
1459 /* We need to loop until the end of the time period, because
1460 * we might get multiple unusable mouse events in that time.
1461 */
1462 for (;;)
1463 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001464#ifdef FEAT_MZSCHEME
1465 mzvim_check_threads();
1466#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001467
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468#ifdef FEAT_CLIENTSERVER
1469 serverProcessPendingMessages();
1470#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001471
1472#ifdef FEAT_CHANNEL
1473 FD_ZERO(&rfds);
1474 maxfd = channel_select_setup(-1, &rfds);
1475 if (maxfd >= 0)
1476 {
1477 ret = select(maxfd + 1, &rfds, NULL, NULL, NULL);
1478 if (ret > 0 && channel_select_check(ret, &rfds) > 0)
1479 return TRUE;
1480 }
1481#endif
1482
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483 if (0
1484#ifdef FEAT_MOUSE
1485 || g_nMouseClick != -1
1486#endif
1487#ifdef FEAT_CLIENTSERVER
1488 || input_available()
1489#endif
1490 )
1491 return TRUE;
1492
1493 if (msec > 0)
1494 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001495 /* If the specified wait time has passed, return. Beware that
1496 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001498 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499 break;
1500 }
1501 if (msec != 0)
1502 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001503 DWORD dwWaitTime = dwEndTime - dwNow;
1504
1505#ifdef FEAT_MZSCHEME
1506 if (mzthreads_allowed() && p_mzq > 0
1507 && (msec < 0 || (long)dwWaitTime > p_mzq))
1508 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1509#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510#ifdef FEAT_CLIENTSERVER
1511 /* Wait for either an event on the console input or a message in
1512 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001513 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001514 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001516 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001517#endif
1518 continue;
1519 }
1520
1521 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001522 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523
1524#ifdef FEAT_MBYTE_IME
1525 if (State & CMDLINE && msg_row == Rows - 1)
1526 {
1527 CONSOLE_SCREEN_BUFFER_INFO csbi;
1528
1529 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1530 {
1531 if (csbi.dwCursorPosition.Y != msg_row)
1532 {
1533 /* The screen is now messed up, must redraw the
1534 * command line and later all the windows. */
1535 redraw_all_later(CLEAR);
1536 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1537 redrawcmd();
1538 }
1539 }
1540 }
1541#endif
1542
1543 if (cRecords > 0)
1544 {
1545 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1546 {
1547#ifdef FEAT_MBYTE_IME
1548 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1549 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001550 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1552 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001553 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554 continue;
1555 }
1556#endif
1557 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1558 NULL, FALSE))
1559 return TRUE;
1560 }
1561
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001562 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563
1564 if (ir.EventType == FOCUS_EVENT)
1565 handle_focus_event(ir);
1566 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1567 shell_resized();
1568#ifdef FEAT_MOUSE
1569 else if (ir.EventType == MOUSE_EVENT
1570 && decode_mouse_event(&ir.Event.MouseEvent))
1571 return TRUE;
1572#endif
1573 }
1574 else if (msec == 0)
1575 break;
1576 }
1577
1578#ifdef FEAT_CLIENTSERVER
1579 /* Something might have been received while we were waiting. */
1580 if (input_available())
1581 return TRUE;
1582#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001583
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 return FALSE;
1585}
1586
1587#ifndef FEAT_GUI_MSWIN
1588/*
1589 * return non-zero if a character is available
1590 */
1591 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001592mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593{
1594 return WaitForChar(0L);
1595}
1596#endif
1597
1598/*
1599 * Create the console input. Used when reading stdin doesn't work.
1600 */
1601 static void
1602create_conin(void)
1603{
1604 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1605 FILE_SHARE_READ|FILE_SHARE_WRITE,
1606 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001607 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 did_create_conin = TRUE;
1609}
1610
1611/*
1612 * Get a keystroke or a mouse event
1613 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001614 static WCHAR
1615tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001617 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618
1619 for (;;)
1620 {
1621 INPUT_RECORD ir;
1622 DWORD cRecords = 0;
1623
1624#ifdef FEAT_CLIENTSERVER
1625 (void)WaitForChar(-1L);
1626 if (input_available())
1627 return 0;
1628# ifdef FEAT_MOUSE
1629 if (g_nMouseClick != -1)
1630 return 0;
1631# endif
1632#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001633 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001634 {
1635 if (did_create_conin)
1636 read_error_exit();
1637 create_conin();
1638 continue;
1639 }
1640
1641 if (ir.EventType == KEY_EVENT)
1642 {
1643 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1644 pmodifiers, TRUE))
1645 return ch;
1646 }
1647 else if (ir.EventType == FOCUS_EVENT)
1648 handle_focus_event(ir);
1649 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1650 shell_resized();
1651#ifdef FEAT_MOUSE
1652 else if (ir.EventType == MOUSE_EVENT)
1653 {
1654 if (decode_mouse_event(&ir.Event.MouseEvent))
1655 return 0;
1656 }
1657#endif
1658 }
1659}
1660#endif /* !FEAT_GUI_W32 */
1661
1662
1663/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001664 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665 * Get one or more characters from the keyboard or the mouse.
1666 * If time == 0, do not wait for characters.
1667 * If time == n, wait a short time for characters.
1668 * If time == -1, wait forever for characters.
1669 * Returns the number of characters read into buf.
1670 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001671/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 int
1673mch_inchar(
1674 char_u *buf,
1675 int maxlen,
1676 long time,
1677 int tb_change_cnt)
1678{
1679#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1680
1681 int len;
1682 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683#define TYPEAHEADLEN 20
1684 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1685 static int typeaheadlen = 0;
1686
1687 /* First use any typeahead that was kept because "buf" was too small. */
1688 if (typeaheadlen > 0)
1689 goto theend;
1690
1691#ifdef FEAT_SNIFF
1692 if (want_sniff_request)
1693 {
1694 if (sniff_request_waiting)
1695 {
1696 /* return K_SNIFF */
1697 typeahead[typeaheadlen++] = CSI;
1698 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1699 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1700 sniff_request_waiting = 0;
1701 want_sniff_request = 0;
1702 goto theend;
1703 }
1704 else if (time < 0 || time > 250)
1705 {
1706 /* don't wait too long, a request might be pending */
1707 time = 250;
1708 }
1709 }
1710#endif
1711
1712 if (time >= 0)
1713 {
1714 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716 }
1717 else /* time == -1, wait forever */
1718 {
1719 mch_set_winsize_now(); /* Allow winsize changes from now on */
1720
Bram Moolenaar3918c952005-03-15 22:34:55 +00001721 /*
1722 * If there is no character available within 2 seconds (default)
1723 * write the autoscript file to disk. Or cause the CursorHold event
1724 * to be triggered.
1725 */
1726 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727 {
1728#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001729 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001731 buf[0] = K_SPECIAL;
1732 buf[1] = KS_EXTRA;
1733 buf[2] = (int)KE_CURSORHOLD;
1734 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735 }
1736#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001737 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738 }
1739 }
1740
1741 /*
1742 * Try to read as many characters as there are, until the buffer is full.
1743 */
1744
1745 /* we will get at least one key. Get more if they are available. */
1746 g_fCBrkPressed = FALSE;
1747
1748#ifdef MCH_WRITE_DUMP
1749 if (fdDump)
1750 fputc('[', fdDump);
1751#endif
1752
1753 /* Keep looping until there is something in the typeahead buffer and more
1754 * to get and still room in the buffer (up to two bytes for a char and
1755 * three bytes for a modifier). */
1756 while ((typeaheadlen == 0 || WaitForChar(0L))
1757 && typeaheadlen + 5 <= TYPEAHEADLEN)
1758 {
1759 if (typebuf_changed(tb_change_cnt))
1760 {
1761 /* "buf" may be invalid now if a client put something in the
1762 * typeahead buffer and "buf" is in the typeahead buffer. */
1763 typeaheadlen = 0;
1764 break;
1765 }
1766#ifdef FEAT_MOUSE
1767 if (g_nMouseClick != -1)
1768 {
1769# ifdef MCH_WRITE_DUMP
1770 if (fdDump)
1771 fprintf(fdDump, "{%02x @ %d, %d}",
1772 g_nMouseClick, g_xMouse, g_yMouse);
1773# endif
1774 typeahead[typeaheadlen++] = ESC + 128;
1775 typeahead[typeaheadlen++] = 'M';
1776 typeahead[typeaheadlen++] = g_nMouseClick;
1777 typeahead[typeaheadlen++] = g_xMouse + '!';
1778 typeahead[typeaheadlen++] = g_yMouse + '!';
1779 g_nMouseClick = -1;
1780 }
1781 else
1782#endif
1783 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001784 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001785 int modifiers = 0;
1786
1787 c = tgetch(&modifiers, &ch2);
1788
1789 if (typebuf_changed(tb_change_cnt))
1790 {
1791 /* "buf" may be invalid now if a client put something in the
1792 * typeahead buffer and "buf" is in the typeahead buffer. */
1793 typeaheadlen = 0;
1794 break;
1795 }
1796
1797 if (c == Ctrl_C && ctrl_c_interrupts)
1798 {
1799#if defined(FEAT_CLIENTSERVER)
1800 trash_input_buf();
1801#endif
1802 got_int = TRUE;
1803 }
1804
1805#ifdef FEAT_MOUSE
1806 if (g_nMouseClick == -1)
1807#endif
1808 {
1809 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001810 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001812#ifdef FEAT_MBYTE
1813 if (ch2 == NUL)
1814 {
1815 int i;
1816 char_u *p;
1817 WCHAR ch[2];
1818
1819 ch[0] = c;
1820 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1821 {
1822 ch[1] = tgetch(&modifiers, &ch2);
1823 n++;
1824 }
1825 p = utf16_to_enc(ch, &n);
1826 if (p != NULL)
1827 {
1828 for (i = 0; i < n; i++)
1829 typeahead[typeaheadlen + i] = p[i];
1830 vim_free(p);
1831 }
1832 }
1833 else
1834#endif
1835 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 if (ch2 != NUL)
1837 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001838 typeahead[typeaheadlen + n] = 3;
1839 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001840 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001842
Bram Moolenaar45500912014-07-09 20:51:07 +02001843 if (conv)
1844 {
1845 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001846
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001847 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001848 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001849 char_u *e = typeahead + TYPEAHEADLEN;
1850
1851 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001852 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001853 if (*p == K_NUL)
1854 {
1855 ++p;
1856 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1857 *p = 3;
1858 ++n;
1859 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001860 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001861 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001862 }
1863 }
1864
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865 /* Use the ALT key to set the 8th bit of the character
1866 * when it's one byte, the 8th bit isn't set yet and not
1867 * using a double-byte encoding (would become a lead
1868 * byte). */
1869 if ((modifiers & MOD_MASK_ALT)
1870 && n == 1
1871 && (typeahead[typeaheadlen] & 0x80) == 0
1872#ifdef FEAT_MBYTE
1873 && !enc_dbcs
1874#endif
1875 )
1876 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001877#ifdef FEAT_MBYTE
1878 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1879 typeahead + typeaheadlen);
1880#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001882#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 modifiers &= ~MOD_MASK_ALT;
1884 }
1885
1886 if (modifiers != 0)
1887 {
1888 /* Prepend modifiers to the character. */
1889 mch_memmove(typeahead + typeaheadlen + 3,
1890 typeahead + typeaheadlen, n);
1891 typeahead[typeaheadlen++] = K_SPECIAL;
1892 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1893 typeahead[typeaheadlen++] = modifiers;
1894 }
1895
1896 typeaheadlen += n;
1897
1898#ifdef MCH_WRITE_DUMP
1899 if (fdDump)
1900 fputc(c, fdDump);
1901#endif
1902 }
1903 }
1904 }
1905
1906#ifdef MCH_WRITE_DUMP
1907 if (fdDump)
1908 {
1909 fputs("]\n", fdDump);
1910 fflush(fdDump);
1911 }
1912#endif
1913
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914theend:
1915 /* Move typeahead to "buf", as much as fits. */
1916 len = 0;
1917 while (len < maxlen && typeaheadlen > 0)
1918 {
1919 buf[len++] = typeahead[0];
1920 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1921 }
1922 return len;
1923
1924#else /* FEAT_GUI_W32 */
1925 return 0;
1926#endif /* FEAT_GUI_W32 */
1927}
1928
Bram Moolenaar82881492012-11-20 16:53:39 +01001929#ifndef PROTO
1930# ifndef __MINGW32__
1931# include <shellapi.h> /* required for FindExecutable() */
1932# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933#endif
1934
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001935/*
1936 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001937 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001938 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001940executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001942 char *dum;
1943 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001944 char *curpath, *newpath;
1945 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001946
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001947#ifdef FEAT_MBYTE
1948 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001950 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001951 WCHAR fnamew[_MAX_PATH];
1952 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001953 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001954
1955 if (p != NULL)
1956 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001957 wcurpath = _wgetenv(L"PATH");
1958 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1959 * sizeof(WCHAR));
1960 if (wnewpath == NULL)
1961 return FALSE;
1962 wcscpy(wnewpath, L".;");
1963 wcscat(wnewpath, wcurpath);
1964 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1965 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001966 vim_free(p);
1967 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1968 {
1969 if (n == 0)
1970 return FALSE;
1971 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1972 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001973 if (path != NULL)
1974 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001975 return TRUE;
1976 }
1977 /* Retry with non-wide function (for Windows 98). */
1978 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001980#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001981
1982 curpath = getenv("PATH");
1983 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1984 if (newpath == NULL)
1985 return FALSE;
1986 STRCPY(newpath, ".;");
1987 STRCAT(newpath, curpath);
1988 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1989 vim_free(newpath);
1990 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001991 return FALSE;
1992 if (mch_isdir(fname))
1993 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001994 if (path != NULL)
1995 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001996 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997}
1998
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001999#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002000 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002001/*
2002 * Bad parameter handler.
2003 *
2004 * Certain MS CRT functions will intentionally crash when passed invalid
2005 * parameters to highlight possible security holes. Setting this function as
2006 * the bad parameter handler will prevent the crash.
2007 *
2008 * In debug builds the parameters contain CRT information that might help track
2009 * down the source of a problem, but in non-debug builds the arguments are all
2010 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2011 * worth allowing these to make debugging of issues easier.
2012 */
2013 static void
2014bad_param_handler(const wchar_t *expression,
2015 const wchar_t *function,
2016 const wchar_t *file,
2017 unsigned int line,
2018 uintptr_t pReserved)
2019{
2020}
2021
2022# define SET_INVALID_PARAM_HANDLER \
2023 ((void)_set_invalid_parameter_handler(bad_param_handler))
2024#else
2025# define SET_INVALID_PARAM_HANDLER
2026#endif
2027
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028#ifdef FEAT_GUI_W32
2029
2030/*
2031 * GUI version of mch_init().
2032 */
2033 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002034mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035{
2036#ifndef __MINGW32__
2037 extern int _fmode;
2038#endif
2039
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002040 /* Silently handle invalid parameters to CRT functions */
2041 SET_INVALID_PARAM_HANDLER;
2042
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043 /* Let critical errors result in a failure, not in a dialog box. Required
2044 * for the timestamp test to work on removed floppies. */
2045 SetErrorMode(SEM_FAILCRITICALERRORS);
2046
2047 _fmode = O_BINARY; /* we do our own CR-LF translation */
2048
2049 /* Specify window size. Is there a place to get the default from? */
2050 Rows = 25;
2051 Columns = 80;
2052
2053 /* Look for 'vimrun' */
2054 if (!gui_is_win32s())
2055 {
2056 char_u vimrun_location[_MAX_PATH + 4];
2057
2058 /* First try in same directory as gvim.exe */
2059 STRCPY(vimrun_location, exe_name);
2060 STRCPY(gettail(vimrun_location), "vimrun.exe");
2061 if (mch_getperm(vimrun_location) >= 0)
2062 {
2063 if (*skiptowhite(vimrun_location) != NUL)
2064 {
2065 /* Enclose path with white space in double quotes. */
2066 mch_memmove(vimrun_location + 1, vimrun_location,
2067 STRLEN(vimrun_location) + 1);
2068 *vimrun_location = '"';
2069 STRCPY(gettail(vimrun_location), "vimrun\" ");
2070 }
2071 else
2072 STRCPY(gettail(vimrun_location), "vimrun ");
2073
2074 vimrun_path = (char *)vim_strsave(vimrun_location);
2075 s_dont_use_vimrun = FALSE;
2076 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002077 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078 s_dont_use_vimrun = FALSE;
2079
2080 /* Don't give the warning for a missing vimrun.exe right now, but only
2081 * when vimrun was supposed to be used. Don't bother people that do
2082 * not need vimrun.exe. */
2083 if (s_dont_use_vimrun)
2084 need_vimrun_warning = TRUE;
2085 }
2086
2087 /*
2088 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2089 * Otherwise the default "findstr /n" is used.
2090 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002091 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2093
2094#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002095 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096#endif
2097}
2098
2099
2100#else /* FEAT_GUI_W32 */
2101
2102#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2103#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2104
2105/*
2106 * ClearConsoleBuffer()
2107 * Description:
2108 * Clears the entire contents of the console screen buffer, using the
2109 * specified attribute.
2110 * Returns:
2111 * TRUE on success
2112 */
2113 static BOOL
2114ClearConsoleBuffer(WORD wAttribute)
2115{
2116 CONSOLE_SCREEN_BUFFER_INFO csbi;
2117 COORD coord;
2118 DWORD NumCells, dummy;
2119
2120 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2121 return FALSE;
2122
2123 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2124 coord.X = 0;
2125 coord.Y = 0;
2126 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2127 coord, &dummy))
2128 {
2129 return FALSE;
2130 }
2131 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2132 coord, &dummy))
2133 {
2134 return FALSE;
2135 }
2136
2137 return TRUE;
2138}
2139
2140/*
2141 * FitConsoleWindow()
2142 * Description:
2143 * Checks if the console window will fit within given buffer dimensions.
2144 * Also, if requested, will shrink the window to fit.
2145 * Returns:
2146 * TRUE on success
2147 */
2148 static BOOL
2149FitConsoleWindow(
2150 COORD dwBufferSize,
2151 BOOL WantAdjust)
2152{
2153 CONSOLE_SCREEN_BUFFER_INFO csbi;
2154 COORD dwWindowSize;
2155 BOOL NeedAdjust = FALSE;
2156
2157 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2158 {
2159 /*
2160 * A buffer resize will fail if the current console window does
2161 * not lie completely within that buffer. To avoid this, we might
2162 * have to move and possibly shrink the window.
2163 */
2164 if (csbi.srWindow.Right >= dwBufferSize.X)
2165 {
2166 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2167 if (dwWindowSize.X > dwBufferSize.X)
2168 dwWindowSize.X = dwBufferSize.X;
2169 csbi.srWindow.Right = dwBufferSize.X - 1;
2170 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2171 NeedAdjust = TRUE;
2172 }
2173 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2174 {
2175 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2176 if (dwWindowSize.Y > dwBufferSize.Y)
2177 dwWindowSize.Y = dwBufferSize.Y;
2178 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2179 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2180 NeedAdjust = TRUE;
2181 }
2182 if (NeedAdjust && WantAdjust)
2183 {
2184 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2185 return FALSE;
2186 }
2187 return TRUE;
2188 }
2189
2190 return FALSE;
2191}
2192
2193typedef struct ConsoleBufferStruct
2194{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002195 BOOL IsValid;
2196 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002197 PCHAR_INFO Buffer;
2198 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199} ConsoleBuffer;
2200
2201/*
2202 * SaveConsoleBuffer()
2203 * Description:
2204 * Saves important information about the console buffer, including the
2205 * actual buffer contents. The saved information is suitable for later
2206 * restoration by RestoreConsoleBuffer().
2207 * Returns:
2208 * TRUE if all information was saved; FALSE otherwise
2209 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2210 */
2211 static BOOL
2212SaveConsoleBuffer(
2213 ConsoleBuffer *cb)
2214{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002215 DWORD NumCells;
2216 COORD BufferCoord;
2217 SMALL_RECT ReadRegion;
2218 WORD Y, Y_incr;
2219
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220 if (cb == NULL)
2221 return FALSE;
2222
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002223 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224 {
2225 cb->IsValid = FALSE;
2226 return FALSE;
2227 }
2228 cb->IsValid = TRUE;
2229
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002230 /*
2231 * Allocate a buffer large enough to hold the entire console screen
2232 * buffer. If this ConsoleBuffer structure has already been initialized
2233 * with a buffer of the correct size, then just use that one.
2234 */
2235 if (!cb->IsValid || cb->Buffer == NULL ||
2236 cb->BufferSize.X != cb->Info.dwSize.X ||
2237 cb->BufferSize.Y != cb->Info.dwSize.Y)
2238 {
2239 cb->BufferSize.X = cb->Info.dwSize.X;
2240 cb->BufferSize.Y = cb->Info.dwSize.Y;
2241 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2242 vim_free(cb->Buffer);
2243 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2244 if (cb->Buffer == NULL)
2245 return FALSE;
2246 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247
2248 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002249 * We will now copy the console screen buffer into our buffer.
2250 * ReadConsoleOutput() seems to be limited as far as how much you
2251 * can read at a time. Empirically, this number seems to be about
2252 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2253 * in chunks until it is all copied. The chunks will all have the
2254 * same horizontal characteristics, so initialize them now. The
2255 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002257 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002258 ReadRegion.Left = 0;
2259 ReadRegion.Right = cb->Info.dwSize.X - 1;
2260 Y_incr = 12000 / cb->Info.dwSize.X;
2261 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002263 /*
2264 * Read into position (0, Y) in our buffer.
2265 */
2266 BufferCoord.Y = Y;
2267 /*
2268 * Read the region whose top left corner is (0, Y) and whose bottom
2269 * right corner is (width - 1, Y + Y_incr - 1). This should define
2270 * a region of size width by Y_incr. Don't worry if this region is
2271 * too large for the remaining buffer; it will be cropped.
2272 */
2273 ReadRegion.Top = Y;
2274 ReadRegion.Bottom = Y + Y_incr - 1;
2275 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2276 cb->Buffer, /* our buffer */
2277 cb->BufferSize, /* dimensions of our buffer */
2278 BufferCoord, /* offset in our buffer */
2279 &ReadRegion)) /* region to save */
2280 {
2281 vim_free(cb->Buffer);
2282 cb->Buffer = NULL;
2283 return FALSE;
2284 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 }
2286
2287 return TRUE;
2288}
2289
2290/*
2291 * RestoreConsoleBuffer()
2292 * Description:
2293 * Restores important information about the console buffer, including the
2294 * actual buffer contents, if desired. The information to restore is in
2295 * the same format used by SaveConsoleBuffer().
2296 * Returns:
2297 * TRUE on success
2298 */
2299 static BOOL
2300RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002301 ConsoleBuffer *cb,
2302 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002304 COORD BufferCoord;
2305 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306
2307 if (cb == NULL || !cb->IsValid)
2308 return FALSE;
2309
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002310 /*
2311 * Before restoring the buffer contents, clear the current buffer, and
2312 * restore the cursor position and window information. Doing this now
2313 * prevents old buffer contents from "flashing" onto the screen.
2314 */
2315 if (RestoreScreen)
2316 ClearConsoleBuffer(cb->Info.wAttributes);
2317
2318 FitConsoleWindow(cb->Info.dwSize, TRUE);
2319 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2320 return FALSE;
2321 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2322 return FALSE;
2323
2324 if (!RestoreScreen)
2325 {
2326 /*
2327 * No need to restore the screen buffer contents, so we're done.
2328 */
2329 return TRUE;
2330 }
2331
2332 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2333 return FALSE;
2334 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2335 return FALSE;
2336
2337 /*
2338 * Restore the screen buffer contents.
2339 */
2340 if (cb->Buffer != NULL)
2341 {
2342 BufferCoord.X = 0;
2343 BufferCoord.Y = 0;
2344 WriteRegion.Left = 0;
2345 WriteRegion.Top = 0;
2346 WriteRegion.Right = cb->Info.dwSize.X - 1;
2347 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2348 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2349 cb->Buffer, /* our buffer */
2350 cb->BufferSize, /* dimensions of our buffer */
2351 BufferCoord, /* offset in our buffer */
2352 &WriteRegion)) /* region to restore */
2353 {
2354 return FALSE;
2355 }
2356 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357
2358 return TRUE;
2359}
2360
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002361#define FEAT_RESTORE_ORIG_SCREEN
2362#ifdef FEAT_RESTORE_ORIG_SCREEN
2363static ConsoleBuffer g_cbOrig = { 0 };
2364#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365static ConsoleBuffer g_cbNonTermcap = { 0 };
2366static ConsoleBuffer g_cbTermcap = { 0 };
2367
2368#ifdef FEAT_TITLE
2369#ifdef __BORLANDC__
2370typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2371#else
2372typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2373#endif
2374char g_szOrigTitle[256] = { 0 };
2375HWND g_hWnd = NULL; /* also used in os_mswin.c */
2376static HICON g_hOrigIconSmall = NULL;
2377static HICON g_hOrigIcon = NULL;
2378static HICON g_hVimIcon = NULL;
2379static BOOL g_fCanChangeIcon = FALSE;
2380
2381/* ICON* are not defined in VC++ 4.0 */
2382#ifndef ICON_SMALL
2383#define ICON_SMALL 0
2384#endif
2385#ifndef ICON_BIG
2386#define ICON_BIG 1
2387#endif
2388/*
2389 * GetConsoleIcon()
2390 * Description:
2391 * Attempts to retrieve the small icon and/or the big icon currently in
2392 * use by a given window.
2393 * Returns:
2394 * TRUE on success
2395 */
2396 static BOOL
2397GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002398 HWND hWnd,
2399 HICON *phIconSmall,
2400 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401{
2402 if (hWnd == NULL)
2403 return FALSE;
2404
2405 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002406 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2407 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002409 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2410 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411 return TRUE;
2412}
2413
2414/*
2415 * SetConsoleIcon()
2416 * Description:
2417 * Attempts to change the small icon and/or the big icon currently in
2418 * use by a given window.
2419 * Returns:
2420 * TRUE on success
2421 */
2422 static BOOL
2423SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002424 HWND hWnd,
2425 HICON hIconSmall,
2426 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002428 HICON hPrevIconSmall;
2429 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430
2431 if (hWnd == NULL)
2432 return FALSE;
2433
2434 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002435 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2436 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002438 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2439 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440 return TRUE;
2441}
2442
2443/*
2444 * SaveConsoleTitleAndIcon()
2445 * Description:
2446 * Saves the current console window title in g_szOrigTitle, for later
2447 * restoration. Also, attempts to obtain a handle to the console window,
2448 * and use it to save the small and big icons currently in use by the
2449 * console window. This is not always possible on some versions of Windows;
2450 * nor is it possible when running Vim remotely using Telnet (since the
2451 * console window the user sees is owned by a remote process).
2452 */
2453 static void
2454SaveConsoleTitleAndIcon(void)
2455{
2456 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2457
2458 /* Save the original title. */
2459 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2460 return;
2461
2462 /*
2463 * Obtain a handle to the console window using GetConsoleWindow() from
2464 * KERNEL32.DLL; we need to handle in order to change the window icon.
2465 * This function only exists on NT-based Windows, starting with Windows
2466 * 2000. On older operating systems, we can't change the window icon
2467 * anyway.
2468 */
2469 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2470 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2471 "GetConsoleWindow")) != NULL)
2472 {
2473 g_hWnd = (*GetConsoleWindowProc)();
2474 }
2475 if (g_hWnd == NULL)
2476 return;
2477
2478 /* Save the original console window icon. */
2479 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2480 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2481 return;
2482
2483 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002484 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2485 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 if (g_hVimIcon != NULL)
2487 g_fCanChangeIcon = TRUE;
2488}
2489#endif
2490
2491static int g_fWindInitCalled = FALSE;
2492static int g_fTermcapMode = FALSE;
2493static CONSOLE_CURSOR_INFO g_cci;
2494static DWORD g_cmodein = 0;
2495static DWORD g_cmodeout = 0;
2496
2497/*
2498 * non-GUI version of mch_init().
2499 */
2500 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002501mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002503#ifndef FEAT_RESTORE_ORIG_SCREEN
2504 CONSOLE_SCREEN_BUFFER_INFO csbi;
2505#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506#ifndef __MINGW32__
2507 extern int _fmode;
2508#endif
2509
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002510 /* Silently handle invalid parameters to CRT functions */
2511 SET_INVALID_PARAM_HANDLER;
2512
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 /* Let critical errors result in a failure, not in a dialog box. Required
2514 * for the timestamp test to work on removed floppies. */
2515 SetErrorMode(SEM_FAILCRITICALERRORS);
2516
2517 _fmode = O_BINARY; /* we do our own CR-LF translation */
2518 out_flush();
2519
2520 /* Obtain handles for the standard Console I/O devices */
2521 if (read_cmd_fd == 0)
2522 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2523 else
2524 create_conin();
2525 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2526
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002527#ifdef FEAT_RESTORE_ORIG_SCREEN
2528 /* Save the initial console buffer for later restoration */
2529 SaveConsoleBuffer(&g_cbOrig);
2530 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2531#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002533 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2534 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2535#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 if (cterm_normal_fg_color == 0)
2537 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2538 if (cterm_normal_bg_color == 0)
2539 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2540
2541 /* set termcap codes to current text attributes */
2542 update_tcap(g_attrCurrent);
2543
2544 GetConsoleCursorInfo(g_hConOut, &g_cci);
2545 GetConsoleMode(g_hConIn, &g_cmodein);
2546 GetConsoleMode(g_hConOut, &g_cmodeout);
2547
2548#ifdef FEAT_TITLE
2549 SaveConsoleTitleAndIcon();
2550 /*
2551 * Set both the small and big icons of the console window to Vim's icon.
2552 * Note that Vim presently only has one size of icon (32x32), but it
2553 * automatically gets scaled down to 16x16 when setting the small icon.
2554 */
2555 if (g_fCanChangeIcon)
2556 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2557#endif
2558
2559 ui_get_shellsize();
2560
2561#ifdef MCH_WRITE_DUMP
2562 fdDump = fopen("dump", "wt");
2563
2564 if (fdDump)
2565 {
2566 time_t t;
2567
2568 time(&t);
2569 fputs(ctime(&t), fdDump);
2570 fflush(fdDump);
2571 }
2572#endif
2573
2574 g_fWindInitCalled = TRUE;
2575
2576#ifdef FEAT_MOUSE
2577 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2578#endif
2579
2580#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002581 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582#endif
2583
2584 /* This will be NULL on anything but NT 4.0 */
2585 s_pfnGetConsoleKeyboardLayoutName =
2586 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2587 "GetConsoleKeyboardLayoutNameA");
2588}
2589
2590/*
2591 * non-GUI version of mch_exit().
2592 * Shut down and exit with status `r'
2593 * Careful: mch_exit() may be called before mch_init()!
2594 */
2595 void
2596mch_exit(int r)
2597{
2598 stoptermcap();
2599
2600 if (g_fWindInitCalled)
2601 settmode(TMODE_COOK);
2602
2603 ml_close_all(TRUE); /* remove all memfiles */
2604
2605 if (g_fWindInitCalled)
2606 {
2607#ifdef FEAT_TITLE
2608 mch_restore_title(3);
2609 /*
2610 * Restore both the small and big icons of the console window to
2611 * what they were at startup. Don't do this when the window is
2612 * closed, Vim would hang here.
2613 */
2614 if (g_fCanChangeIcon && !g_fForceExit)
2615 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2616#endif
2617
2618#ifdef MCH_WRITE_DUMP
2619 if (fdDump)
2620 {
2621 time_t t;
2622
2623 time(&t);
2624 fputs(ctime(&t), fdDump);
2625 fclose(fdDump);
2626 }
2627 fdDump = NULL;
2628#endif
2629 }
2630
2631 SetConsoleCursorInfo(g_hConOut, &g_cci);
2632 SetConsoleMode(g_hConIn, g_cmodein);
2633 SetConsoleMode(g_hConOut, g_cmodeout);
2634
2635#ifdef DYNAMIC_GETTEXT
2636 dyn_libintl_end();
2637#endif
2638
2639 exit(r);
2640}
2641#endif /* !FEAT_GUI_W32 */
2642
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643/*
2644 * Do we have an interactive window?
2645 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002646/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647 int
2648mch_check_win(
2649 int argc,
2650 char **argv)
2651{
2652 get_exe_name();
2653
2654#ifdef FEAT_GUI_W32
2655 return OK; /* GUI always has a tty */
2656#else
2657 if (isatty(1))
2658 return OK;
2659 return FAIL;
2660#endif
2661}
2662
2663
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002664#ifdef FEAT_MBYTE
2665/*
2666 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2667 * if it already exists. When "len" is > 0, also expand short to long
2668 * filenames.
2669 * Return FAIL if wide functions are not available, OK otherwise.
2670 * NOTE: much of this is identical to fname_case(), keep in sync!
2671 */
2672 static int
2673fname_casew(
2674 WCHAR *name,
2675 int len)
2676{
2677 WCHAR szTrueName[_MAX_PATH + 2];
2678 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2679 WCHAR *ptrue, *ptruePrev;
2680 WCHAR *porig, *porigPrev;
2681 int flen;
2682 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002683 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002684 int c;
2685 int slen;
2686
2687 flen = (int)wcslen(name);
2688 if (flen > _MAX_PATH)
2689 return OK;
2690
2691 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2692
2693 /* Build the new name in szTrueName[] one component at a time. */
2694 porig = name;
2695 ptrue = szTrueName;
2696
2697 if (iswalpha(porig[0]) && porig[1] == L':')
2698 {
2699 /* copy leading drive letter */
2700 *ptrue++ = *porig++;
2701 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002702 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002703 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002704
2705 while (*porig != NUL)
2706 {
2707 /* copy \ characters */
2708 while (*porig == psepc)
2709 *ptrue++ = *porig++;
2710
2711 ptruePrev = ptrue;
2712 porigPrev = porig;
2713 while (*porig != NUL && *porig != psepc)
2714 {
2715 *ptrue++ = *porig++;
2716 }
2717 *ptrue = NUL;
2718
2719 /* To avoid a slow failure append "\*" when searching a directory,
2720 * server or network share. */
2721 wcscpy(szTrueNameTemp, szTrueName);
2722 slen = (int)wcslen(szTrueNameTemp);
2723 if (*porig == psepc && slen + 2 < _MAX_PATH)
2724 wcscpy(szTrueNameTemp + slen, L"\\*");
2725
2726 /* Skip "", "." and "..". */
2727 if (ptrue > ptruePrev
2728 && (ptruePrev[0] != L'.'
2729 || (ptruePrev[1] != NUL
2730 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2731 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2732 != INVALID_HANDLE_VALUE)
2733 {
2734 c = *porig;
2735 *porig = NUL;
2736
2737 /* Only use the match when it's the same name (ignoring case) or
2738 * expansion is allowed and there is a match with the short name
2739 * and there is enough room. */
2740 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2741 || (len > 0
2742 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2743 && (int)(ptruePrev - szTrueName)
2744 + (int)wcslen(fb.cFileName) < len)))
2745 {
2746 wcscpy(ptruePrev, fb.cFileName);
2747
2748 /* Look for exact match and prefer it if found. Must be a
2749 * long name, otherwise there would be only one match. */
2750 while (FindNextFileW(hFind, &fb))
2751 {
2752 if (*fb.cAlternateFileName != NUL
2753 && (wcscoll(porigPrev, fb.cFileName) == 0
2754 || (len > 0
2755 && (_wcsicoll(porigPrev,
2756 fb.cAlternateFileName) == 0
2757 && (int)(ptruePrev - szTrueName)
2758 + (int)wcslen(fb.cFileName) < len))))
2759 {
2760 wcscpy(ptruePrev, fb.cFileName);
2761 break;
2762 }
2763 }
2764 }
2765 FindClose(hFind);
2766 *porig = c;
2767 ptrue = ptruePrev + wcslen(ptruePrev);
2768 }
2769 else if (hFind == INVALID_HANDLE_VALUE
2770 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2771 return FAIL;
2772 }
2773
2774 wcscpy(name, szTrueName);
2775 return OK;
2776}
2777#endif
2778
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779/*
2780 * fname_case(): Set the case of the file name, if it already exists.
2781 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002782 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783 */
2784 void
2785fname_case(
2786 char_u *name,
2787 int len)
2788{
2789 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002790 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791 char *ptrue, *ptruePrev;
2792 char *porig, *porigPrev;
2793 int flen;
2794 WIN32_FIND_DATA fb;
2795 HANDLE hFind;
2796 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002797 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002798
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002799 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002800 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 return;
2802
2803 slash_adjust(name);
2804
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002805#ifdef FEAT_MBYTE
2806 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2807 {
2808 WCHAR *p = enc_to_utf16(name, NULL);
2809
2810 if (p != NULL)
2811 {
2812 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002813 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002814
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002815 wcsncpy(buf, p, _MAX_PATH);
2816 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002817 vim_free(p);
2818
2819 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2820 {
2821 q = utf16_to_enc(buf, NULL);
2822 if (q != NULL)
2823 {
2824 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2825 vim_free(q);
2826 return;
2827 }
2828 }
2829 }
2830 /* Retry with non-wide function (for Windows 98). */
2831 }
2832#endif
2833
2834 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2835 * So we should check this after calling wide function. */
2836 if (flen > _MAX_PATH)
2837 return;
2838
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839 /* Build the new name in szTrueName[] one component at a time. */
2840 porig = name;
2841 ptrue = szTrueName;
2842
2843 if (isalpha(porig[0]) && porig[1] == ':')
2844 {
2845 /* copy leading drive letter */
2846 *ptrue++ = *porig++;
2847 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002849 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850
2851 while (*porig != NUL)
2852 {
2853 /* copy \ characters */
2854 while (*porig == psepc)
2855 *ptrue++ = *porig++;
2856
2857 ptruePrev = ptrue;
2858 porigPrev = porig;
2859 while (*porig != NUL && *porig != psepc)
2860 {
2861#ifdef FEAT_MBYTE
2862 int l;
2863
2864 if (enc_dbcs)
2865 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002866 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867 while (--l >= 0)
2868 *ptrue++ = *porig++;
2869 }
2870 else
2871#endif
2872 *ptrue++ = *porig++;
2873 }
2874 *ptrue = NUL;
2875
Bram Moolenaar464c9252010-10-13 20:37:41 +02002876 /* To avoid a slow failure append "\*" when searching a directory,
2877 * server or network share. */
2878 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002879 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002880 if (*porig == psepc && slen + 2 < _MAX_PATH)
2881 STRCPY(szTrueNameTemp + slen, "\\*");
2882
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883 /* Skip "", "." and "..". */
2884 if (ptrue > ptruePrev
2885 && (ptruePrev[0] != '.'
2886 || (ptruePrev[1] != NUL
2887 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002888 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889 != INVALID_HANDLE_VALUE)
2890 {
2891 c = *porig;
2892 *porig = NUL;
2893
2894 /* Only use the match when it's the same name (ignoring case) or
2895 * expansion is allowed and there is a match with the short name
2896 * and there is enough room. */
2897 if (_stricoll(porigPrev, fb.cFileName) == 0
2898 || (len > 0
2899 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2900 && (int)(ptruePrev - szTrueName)
2901 + (int)strlen(fb.cFileName) < len)))
2902 {
2903 STRCPY(ptruePrev, fb.cFileName);
2904
2905 /* Look for exact match and prefer it if found. Must be a
2906 * long name, otherwise there would be only one match. */
2907 while (FindNextFile(hFind, &fb))
2908 {
2909 if (*fb.cAlternateFileName != NUL
2910 && (strcoll(porigPrev, fb.cFileName) == 0
2911 || (len > 0
2912 && (_stricoll(porigPrev,
2913 fb.cAlternateFileName) == 0
2914 && (int)(ptruePrev - szTrueName)
2915 + (int)strlen(fb.cFileName) < len))))
2916 {
2917 STRCPY(ptruePrev, fb.cFileName);
2918 break;
2919 }
2920 }
2921 }
2922 FindClose(hFind);
2923 *porig = c;
2924 ptrue = ptruePrev + strlen(ptruePrev);
2925 }
2926 }
2927
2928 STRCPY(name, szTrueName);
2929}
2930
2931
2932/*
2933 * Insert user name in s[len].
2934 */
2935 int
2936mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002937 char_u *s,
2938 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002940 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941 DWORD cch = sizeof szUserName;
2942
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002943#ifdef FEAT_MBYTE
2944 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2945 {
2946 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2947 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2948
2949 if (GetUserNameW(wszUserName, &wcch))
2950 {
2951 char_u *p = utf16_to_enc(wszUserName, NULL);
2952
2953 if (p != NULL)
2954 {
2955 vim_strncpy(s, p, len - 1);
2956 vim_free(p);
2957 return OK;
2958 }
2959 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002960 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2961 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002962 /* Retry with non-wide function (for Windows 98). */
2963 }
2964#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965 if (GetUserName(szUserName, &cch))
2966 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002967 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 return OK;
2969 }
2970 s[0] = NUL;
2971 return FAIL;
2972}
2973
2974
2975/*
2976 * Insert host name in s[len].
2977 */
2978 void
2979mch_get_host_name(
2980 char_u *s,
2981 int len)
2982{
2983 DWORD cch = len;
2984
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002985#ifdef FEAT_MBYTE
2986 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2987 {
2988 WCHAR wszHostName[256 + 1];
2989 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2990
2991 if (GetComputerNameW(wszHostName, &wcch))
2992 {
2993 char_u *p = utf16_to_enc(wszHostName, NULL);
2994
2995 if (p != NULL)
2996 {
2997 vim_strncpy(s, p, len - 1);
2998 vim_free(p);
2999 return;
3000 }
3001 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003002 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3003 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003004 /* Retry with non-wide function (for Windows 98). */
3005 }
3006#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003008 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009}
3010
3011
3012/*
3013 * return process ID
3014 */
3015 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003016mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017{
3018 return (long)GetCurrentProcessId();
3019}
3020
3021
3022/*
3023 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3024 * Return OK for success, FAIL for failure.
3025 */
3026 int
3027mch_dirname(
3028 char_u *buf,
3029 int len)
3030{
3031 /*
3032 * Originally this was:
3033 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3034 * But the Win32s known bug list says that getcwd() doesn't work
3035 * so use the Win32 system call instead. <Negri>
3036 */
3037#ifdef FEAT_MBYTE
3038 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3039 {
3040 WCHAR wbuf[_MAX_PATH + 1];
3041
3042 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3043 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003044 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045
3046 if (p != NULL)
3047 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003048 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049 vim_free(p);
3050 return OK;
3051 }
3052 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003053 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3054 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 /* Retry with non-wide function (for Windows 98). */
3056 }
3057#endif
3058 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3059}
3060
3061/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003062 * Get file permissions for "name".
3063 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 */
3065 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003066mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003068 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003069 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003071 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003072 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073}
3074
3075
3076/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003077 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003078 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003079 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080 */
3081 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003082mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003084 long n = -1;
3085
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086#ifdef FEAT_MBYTE
3087 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3088 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003089 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090
3091 if (p != NULL)
3092 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003093 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003095 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003096 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097 /* Retry with non-wide function (for Windows 98). */
3098 }
3099 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003100 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003102 n = _chmod(name, perm);
3103 if (n == -1)
3104 return FAIL;
3105
3106 win32_set_archive(name);
3107
3108 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003109}
3110
3111/*
3112 * Set hidden flag for "name".
3113 */
3114 void
3115mch_hide(char_u *name)
3116{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003117 int attrs = win32_getattrs(name);
3118 if (attrs == -1)
3119 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003121 attrs |= FILE_ATTRIBUTE_HIDDEN;
3122 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123}
3124
3125/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003126 * Return TRUE if file "name" exists and is hidden.
3127 */
3128 int
3129mch_ishidden(char_u *name)
3130{
3131 int f = win32_getattrs(name);
3132
3133 if (f == -1)
3134 return FALSE; /* file does not exist at all */
3135
3136 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3137}
3138
3139/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 * return TRUE if "name" is a directory
3141 * return FALSE if "name" is not a directory or upon error
3142 */
3143 int
3144mch_isdir(char_u *name)
3145{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003146 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147
3148 if (f == -1)
3149 return FALSE; /* file does not exist at all */
3150
3151 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3152}
3153
3154/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003155 * return TRUE if "name" is a directory, NOT a symlink to a directory
3156 * return FALSE if "name" is not a directory
3157 * return FALSE for error
3158 */
3159 int
3160mch_isrealdir(char_u *name)
3161{
3162 return mch_isdir(name) && !mch_is_symbolic_link(name);
3163}
3164
3165/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003166 * Create directory "name".
3167 * Return 0 on success, -1 on error.
3168 */
3169 int
3170mch_mkdir(char_u *name)
3171{
3172#ifdef FEAT_MBYTE
3173 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3174 {
3175 WCHAR *p;
3176 int retval;
3177
3178 p = enc_to_utf16(name, NULL);
3179 if (p == NULL)
3180 return -1;
3181 retval = _wmkdir(p);
3182 vim_free(p);
3183 return retval;
3184 }
3185#endif
3186 return _mkdir(name);
3187}
3188
3189/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003190 * Delete directory "name".
3191 * Return 0 on success, -1 on error.
3192 */
3193 int
3194mch_rmdir(char_u *name)
3195{
3196#ifdef FEAT_MBYTE
3197 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3198 {
3199 WCHAR *p;
3200 int retval;
3201
3202 p = enc_to_utf16(name, NULL);
3203 if (p == NULL)
3204 return -1;
3205 retval = _wrmdir(p);
3206 vim_free(p);
3207 return retval;
3208 }
3209#endif
3210 return _rmdir(name);
3211}
3212
3213/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003214 * Return TRUE if file "fname" has more than one link.
3215 */
3216 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003217mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003218{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003219 BY_HANDLE_FILE_INFORMATION info;
3220
3221 return win32_fileinfo(fname, &info) == FILEINFO_OK
3222 && info.nNumberOfLinks > 1;
3223}
3224
3225/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003226 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003227 */
3228 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003229mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003230{
3231 HANDLE hFind;
3232 int res = FALSE;
3233 WIN32_FIND_DATAA findDataA;
3234 DWORD fileFlags = 0, reparseTag = 0;
3235#ifdef FEAT_MBYTE
3236 WCHAR *wn = NULL;
3237 WIN32_FIND_DATAW findDataW;
3238
3239 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003240 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241 if (wn != NULL)
3242 {
3243 hFind = FindFirstFileW(wn, &findDataW);
3244 vim_free(wn);
3245 if (hFind == INVALID_HANDLE_VALUE
3246 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3247 {
3248 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar203258c2016-01-17 22:15:16 +01003249 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003250 if (hFind != INVALID_HANDLE_VALUE)
3251 {
3252 fileFlags = findDataA.dwFileAttributes;
3253 reparseTag = findDataA.dwReserved0;
3254 }
3255 }
3256 else
3257 {
3258 fileFlags = findDataW.dwFileAttributes;
3259 reparseTag = findDataW.dwReserved0;
3260 }
3261 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003262 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003263#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003264 {
Bram Moolenaar203258c2016-01-17 22:15:16 +01003265 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003266 if (hFind != INVALID_HANDLE_VALUE)
3267 {
3268 fileFlags = findDataA.dwFileAttributes;
3269 reparseTag = findDataA.dwReserved0;
3270 }
3271 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003272
3273 if (hFind != INVALID_HANDLE_VALUE)
3274 FindClose(hFind);
3275
3276 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003277 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3278 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003279 res = TRUE;
3280
3281 return res;
3282}
3283
3284/*
3285 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3286 * link.
3287 */
3288 int
3289mch_is_linked(char_u *fname)
3290{
3291 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3292 return TRUE;
3293 return FALSE;
3294}
3295
3296/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003297 * Get the by-handle-file-information for "fname".
3298 * Returns FILEINFO_OK when OK.
3299 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3300 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3301 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3302 */
3303 int
3304win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3305{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003306 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003307 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003308#ifdef FEAT_MBYTE
3309 WCHAR *wn = NULL;
3310
3311 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003312 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003313 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003314 if (wn == NULL)
3315 res = FILEINFO_ENC_FAIL;
3316 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003317 if (wn != NULL)
3318 {
3319 hFile = CreateFileW(wn, /* file name */
3320 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003321 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003322 NULL, /* security descriptor */
3323 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003324 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003325 NULL); /* handle to template file */
3326 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003327 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003328 {
3329 /* Retry with non-wide function (for Windows 98). */
3330 vim_free(wn);
3331 wn = NULL;
3332 }
3333 }
3334 if (wn == NULL)
3335#endif
3336 hFile = CreateFile(fname, /* file name */
3337 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003338 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003339 NULL, /* security descriptor */
3340 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003341 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003342 NULL); /* handle to template file */
3343
3344 if (hFile != INVALID_HANDLE_VALUE)
3345 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003346 if (GetFileInformationByHandle(hFile, info) != 0)
3347 res = FILEINFO_OK;
3348 else
3349 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003350 CloseHandle(hFile);
3351 }
3352
3353#ifdef FEAT_MBYTE
3354 vim_free(wn);
3355#endif
3356 return res;
3357}
3358
3359/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003360 * get file attributes for `name'
3361 * -1 : error
3362 * else FILE_ATTRIBUTE_* defined in winnt.h
3363 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003364 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003365win32_getattrs(char_u *name)
3366{
3367 int attr;
3368#ifdef FEAT_MBYTE
3369 WCHAR *p = NULL;
3370
3371 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3372 p = enc_to_utf16(name, NULL);
3373
3374 if (p != NULL)
3375 {
3376 attr = GetFileAttributesW(p);
3377 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3378 {
3379 /* Retry with non-wide function (for Windows 98). */
3380 vim_free(p);
3381 p = NULL;
3382 }
3383 }
3384 if (p == NULL)
3385#endif
3386 attr = GetFileAttributes((char *)name);
3387#ifdef FEAT_MBYTE
3388 vim_free(p);
3389#endif
3390 return attr;
3391}
3392
3393/*
3394 * set file attributes for `name' to `attrs'
3395 *
3396 * return -1 for failure, 0 otherwise
3397 */
3398 static
3399 int
3400win32_setattrs(char_u *name, int attrs)
3401{
3402 int res;
3403#ifdef FEAT_MBYTE
3404 WCHAR *p = NULL;
3405
3406 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3407 p = enc_to_utf16(name, NULL);
3408
3409 if (p != NULL)
3410 {
3411 res = SetFileAttributesW(p, attrs);
3412 if (res == FALSE
3413 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3414 {
3415 /* Retry with non-wide function (for Windows 98). */
3416 vim_free(p);
3417 p = NULL;
3418 }
3419 }
3420 if (p == NULL)
3421#endif
3422 res = SetFileAttributes((char *)name, attrs);
3423#ifdef FEAT_MBYTE
3424 vim_free(p);
3425#endif
3426 return res ? 0 : -1;
3427}
3428
3429/*
3430 * Set archive flag for "name".
3431 */
3432 static
3433 int
3434win32_set_archive(char_u *name)
3435{
3436 int attrs = win32_getattrs(name);
3437 if (attrs == -1)
3438 return -1;
3439
3440 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3441 return win32_setattrs(name, attrs);
3442}
3443
3444/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445 * Return TRUE if file or directory "name" is writable (not readonly).
3446 * Strange semantics of Win32: a readonly directory is writable, but you can't
3447 * delete a file. Let's say this means it is writable.
3448 */
3449 int
3450mch_writable(char_u *name)
3451{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003452 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003453
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003454 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3455 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003456}
3457
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458/*
3459 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003460 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461 * Return -1 if unknown.
3462 */
3463 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003464mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003466 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003467 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003468 char_u *p;
3469
3470 if (len >= _MAX_PATH) /* safety check */
3471 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003472 if (!use_path)
3473 {
3474 /* TODO: check if file is really executable. */
3475 return mch_getperm(name) != -1 && !mch_isdir(name);
3476 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003477
3478 /* If there already is an extension try using the name directly. Also do
3479 * this with a Unix-shell like 'shell'. */
3480 if (vim_strchr(gettail(name), '.') != NULL
3481 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003482 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003483 return TRUE;
3484
3485 /*
3486 * Loop over all extensions in $PATHEXT.
3487 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003488 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003489 p = mch_getenv("PATHEXT");
3490 if (p == NULL)
3491 p = (char_u *)".com;.exe;.bat;.cmd";
3492 while (*p)
3493 {
3494 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3495 {
3496 /* A single "." means no extension is added. */
3497 buf[len] = NUL;
3498 ++p;
3499 if (*p)
3500 ++p;
3501 }
3502 else
3503 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003504 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003505 return TRUE;
3506 }
3507 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509
3510/*
3511 * Check what "name" is:
3512 * NODE_NORMAL: file or directory (or doesn't exist)
3513 * NODE_WRITABLE: writable device, socket, fifo, etc.
3514 * NODE_OTHER: non-writable things
3515 */
3516 int
3517mch_nodetype(char_u *name)
3518{
3519 HANDLE hFile;
3520 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003521#ifdef FEAT_MBYTE
3522 WCHAR *wn = NULL;
3523#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003524
Bram Moolenaar043545e2006-10-10 16:44:07 +00003525 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3526 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3527 * here. */
3528 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3529 return NODE_WRITABLE;
3530
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003531#ifdef FEAT_MBYTE
3532 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3533 {
3534 wn = enc_to_utf16(name, NULL);
3535 if (wn != NULL)
3536 {
3537 hFile = CreateFileW(wn, /* 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 */
3544 if (hFile == INVALID_HANDLE_VALUE
3545 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3546 {
3547 /* Retry with non-wide function (for Windows 98). */
3548 vim_free(wn);
3549 wn = NULL;
3550 }
3551 }
3552 }
3553 if (wn == NULL)
3554#endif
3555 hFile = CreateFile(name, /* file name */
3556 GENERIC_WRITE, /* access mode */
3557 0, /* share mode */
3558 NULL, /* security descriptor */
3559 OPEN_EXISTING, /* creation disposition */
3560 0, /* file attributes */
3561 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003562
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003563#ifdef FEAT_MBYTE
3564 vim_free(wn);
3565#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566 if (hFile == INVALID_HANDLE_VALUE)
3567 return NODE_NORMAL;
3568
3569 type = GetFileType(hFile);
3570 CloseHandle(hFile);
3571 if (type == FILE_TYPE_CHAR)
3572 return NODE_WRITABLE;
3573 if (type == FILE_TYPE_DISK)
3574 return NODE_NORMAL;
3575 return NODE_OTHER;
3576}
3577
3578#ifdef HAVE_ACL
3579struct my_acl
3580{
3581 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3582 PSID pSidOwner;
3583 PSID pSidGroup;
3584 PACL pDacl;
3585 PACL pSacl;
3586};
3587#endif
3588
3589/*
3590 * Return a pointer to the ACL of file "fname" in allocated memory.
3591 * Return NULL if the ACL is not available for whatever reason.
3592 */
3593 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003594mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595{
3596#ifndef HAVE_ACL
3597 return (vim_acl_T)NULL;
3598#else
3599 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003600 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601
3602 /* This only works on Windows NT and 2000. */
3603 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3604 {
3605 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3606 if (p != NULL)
3607 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003608# ifdef FEAT_MBYTE
3609 WCHAR *wn = NULL;
3610
3611 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3612 wn = enc_to_utf16(fname, NULL);
3613 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003615 /* Try to retrieve the entire security descriptor. */
3616 err = pGetNamedSecurityInfoW(
3617 wn, // Abstract filename
3618 SE_FILE_OBJECT, // File Object
3619 OWNER_SECURITY_INFORMATION |
3620 GROUP_SECURITY_INFORMATION |
3621 DACL_SECURITY_INFORMATION |
3622 SACL_SECURITY_INFORMATION,
3623 &p->pSidOwner, // Ownership information.
3624 &p->pSidGroup, // Group membership.
3625 &p->pDacl, // Discretionary information.
3626 &p->pSacl, // For auditing purposes.
3627 &p->pSecurityDescriptor);
3628 if (err == ERROR_ACCESS_DENIED ||
3629 err == ERROR_PRIVILEGE_NOT_HELD)
3630 {
3631 /* Retrieve only DACL. */
3632 (void)pGetNamedSecurityInfoW(
3633 wn,
3634 SE_FILE_OBJECT,
3635 DACL_SECURITY_INFORMATION,
3636 NULL,
3637 NULL,
3638 &p->pDacl,
3639 NULL,
3640 &p->pSecurityDescriptor);
3641 }
3642 if (p->pSecurityDescriptor == NULL)
3643 {
3644 mch_free_acl((vim_acl_T)p);
3645 p = NULL;
3646 }
3647 vim_free(wn);
3648 }
3649 else
3650# endif
3651 {
3652 /* Try to retrieve the entire security descriptor. */
3653 err = pGetNamedSecurityInfo(
3654 (LPSTR)fname, // Abstract filename
3655 SE_FILE_OBJECT, // File Object
3656 OWNER_SECURITY_INFORMATION |
3657 GROUP_SECURITY_INFORMATION |
3658 DACL_SECURITY_INFORMATION |
3659 SACL_SECURITY_INFORMATION,
3660 &p->pSidOwner, // Ownership information.
3661 &p->pSidGroup, // Group membership.
3662 &p->pDacl, // Discretionary information.
3663 &p->pSacl, // For auditing purposes.
3664 &p->pSecurityDescriptor);
3665 if (err == ERROR_ACCESS_DENIED ||
3666 err == ERROR_PRIVILEGE_NOT_HELD)
3667 {
3668 /* Retrieve only DACL. */
3669 (void)pGetNamedSecurityInfo(
3670 (LPSTR)fname,
3671 SE_FILE_OBJECT,
3672 DACL_SECURITY_INFORMATION,
3673 NULL,
3674 NULL,
3675 &p->pDacl,
3676 NULL,
3677 &p->pSecurityDescriptor);
3678 }
3679 if (p->pSecurityDescriptor == NULL)
3680 {
3681 mch_free_acl((vim_acl_T)p);
3682 p = NULL;
3683 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684 }
3685 }
3686 }
3687
3688 return (vim_acl_T)p;
3689#endif
3690}
3691
Bram Moolenaar27515922013-06-29 15:36:26 +02003692#ifdef HAVE_ACL
3693/*
3694 * Check if "acl" contains inherited ACE.
3695 */
3696 static BOOL
3697is_acl_inherited(PACL acl)
3698{
3699 DWORD i;
3700 ACL_SIZE_INFORMATION acl_info;
3701 PACCESS_ALLOWED_ACE ace;
3702
3703 acl_info.AceCount = 0;
3704 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3705 for (i = 0; i < acl_info.AceCount; i++)
3706 {
3707 GetAce(acl, i, (LPVOID *)&ace);
3708 if (ace->Header.AceFlags & INHERITED_ACE)
3709 return TRUE;
3710 }
3711 return FALSE;
3712}
3713#endif
3714
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715/*
3716 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3717 * Errors are ignored.
3718 * This must only be called with "acl" equal to what mch_get_acl() returned.
3719 */
3720 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003721mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722{
3723#ifdef HAVE_ACL
3724 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003725 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726
3727 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003728 {
3729# ifdef FEAT_MBYTE
3730 WCHAR *wn = NULL;
3731# endif
3732
3733 /* Set security flags */
3734 if (p->pSidOwner)
3735 sec_info |= OWNER_SECURITY_INFORMATION;
3736 if (p->pSidGroup)
3737 sec_info |= GROUP_SECURITY_INFORMATION;
3738 if (p->pDacl)
3739 {
3740 sec_info |= DACL_SECURITY_INFORMATION;
3741 /* Do not inherit its parent's DACL.
3742 * If the DACL is inherited, Cygwin permissions would be changed.
3743 */
3744 if (!is_acl_inherited(p->pDacl))
3745 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3746 }
3747 if (p->pSacl)
3748 sec_info |= SACL_SECURITY_INFORMATION;
3749
3750# ifdef FEAT_MBYTE
3751 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3752 wn = enc_to_utf16(fname, NULL);
3753 if (wn != NULL)
3754 {
3755 (void)pSetNamedSecurityInfoW(
3756 wn, // Abstract filename
3757 SE_FILE_OBJECT, // File Object
3758 sec_info,
3759 p->pSidOwner, // Ownership information.
3760 p->pSidGroup, // Group membership.
3761 p->pDacl, // Discretionary information.
3762 p->pSacl // For auditing purposes.
3763 );
3764 vim_free(wn);
3765 }
3766 else
3767# endif
3768 {
3769 (void)pSetNamedSecurityInfo(
3770 (LPSTR)fname, // Abstract filename
3771 SE_FILE_OBJECT, // File Object
3772 sec_info,
3773 p->pSidOwner, // Ownership information.
3774 p->pSidGroup, // Group membership.
3775 p->pDacl, // Discretionary information.
3776 p->pSacl // For auditing purposes.
3777 );
3778 }
3779 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780#endif
3781}
3782
3783 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003784mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785{
3786#ifdef HAVE_ACL
3787 struct my_acl *p = (struct my_acl *)acl;
3788
3789 if (p != NULL)
3790 {
3791 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3792 vim_free(p);
3793 }
3794#endif
3795}
3796
3797#ifndef FEAT_GUI_W32
3798
3799/*
3800 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3801 */
3802 static BOOL WINAPI
3803handler_routine(
3804 DWORD dwCtrlType)
3805{
3806 switch (dwCtrlType)
3807 {
3808 case CTRL_C_EVENT:
3809 if (ctrl_c_interrupts)
3810 g_fCtrlCPressed = TRUE;
3811 return TRUE;
3812
3813 case CTRL_BREAK_EVENT:
3814 g_fCBrkPressed = TRUE;
3815 return TRUE;
3816
3817 /* fatal events: shut down gracefully */
3818 case CTRL_CLOSE_EVENT:
3819 case CTRL_LOGOFF_EVENT:
3820 case CTRL_SHUTDOWN_EVENT:
3821 windgoto((int)Rows - 1, 0);
3822 g_fForceExit = TRUE;
3823
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003824 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825 (dwCtrlType == CTRL_CLOSE_EVENT
3826 ? _("close")
3827 : dwCtrlType == CTRL_LOGOFF_EVENT
3828 ? _("logoff")
3829 : _("shutdown")));
3830#ifdef DEBUG
3831 OutputDebugString(IObuff);
3832#endif
3833
3834 preserve_exit(); /* output IObuff, preserve files and exit */
3835
3836 return TRUE; /* not reached */
3837
3838 default:
3839 return FALSE;
3840 }
3841}
3842
3843
3844/*
3845 * set the tty in (raw) ? "raw" : "cooked" mode
3846 */
3847 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003848mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849{
3850 DWORD cmodein;
3851 DWORD cmodeout;
3852 BOOL bEnableHandler;
3853
3854 GetConsoleMode(g_hConIn, &cmodein);
3855 GetConsoleMode(g_hConOut, &cmodeout);
3856 if (tmode == TMODE_RAW)
3857 {
3858 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3859 ENABLE_ECHO_INPUT);
3860#ifdef FEAT_MOUSE
3861 if (g_fMouseActive)
3862 cmodein |= ENABLE_MOUSE_INPUT;
3863#endif
3864 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3865 bEnableHandler = TRUE;
3866 }
3867 else /* cooked */
3868 {
3869 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3870 ENABLE_ECHO_INPUT);
3871 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3872 bEnableHandler = FALSE;
3873 }
3874 SetConsoleMode(g_hConIn, cmodein);
3875 SetConsoleMode(g_hConOut, cmodeout);
3876 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3877
3878#ifdef MCH_WRITE_DUMP
3879 if (fdDump)
3880 {
3881 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3882 tmode == TMODE_RAW ? "raw" :
3883 tmode == TMODE_COOK ? "cooked" : "normal",
3884 cmodein, cmodeout);
3885 fflush(fdDump);
3886 }
3887#endif
3888}
3889
3890
3891/*
3892 * Get the size of the current window in `Rows' and `Columns'
3893 * Return OK when size could be determined, FAIL otherwise.
3894 */
3895 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003896mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003897{
3898 CONSOLE_SCREEN_BUFFER_INFO csbi;
3899
3900 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3901 {
3902 /*
3903 * For some reason, we are trying to get the screen dimensions
3904 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3905 * variables are really intended to mean the size of Vim screen
3906 * while in termcap mode.
3907 */
3908 Rows = g_cbTermcap.Info.dwSize.Y;
3909 Columns = g_cbTermcap.Info.dwSize.X;
3910 }
3911 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3912 {
3913 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3914 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3915 }
3916 else
3917 {
3918 Rows = 25;
3919 Columns = 80;
3920 }
3921 return OK;
3922}
3923
3924/*
3925 * Set a console window to `xSize' * `ySize'
3926 */
3927 static void
3928ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003929 HANDLE hConsole,
3930 int xSize,
3931 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932{
3933 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3934 SMALL_RECT srWindowRect; /* hold the new console size */
3935 COORD coordScreen;
3936
3937#ifdef MCH_WRITE_DUMP
3938 if (fdDump)
3939 {
3940 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3941 fflush(fdDump);
3942 }
3943#endif
3944
3945 /* get the largest size we can size the console window to */
3946 coordScreen = GetLargestConsoleWindowSize(hConsole);
3947
3948 /* define the new console window size and scroll position */
3949 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3950 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3951 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3952
3953 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3954 {
3955 int sx, sy;
3956
3957 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3958 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3959 if (sy < ySize || sx < xSize)
3960 {
3961 /*
3962 * Increasing number of lines/columns, do buffer first.
3963 * Use the maximal size in x and y direction.
3964 */
3965 if (sy < ySize)
3966 coordScreen.Y = ySize;
3967 else
3968 coordScreen.Y = sy;
3969 if (sx < xSize)
3970 coordScreen.X = xSize;
3971 else
3972 coordScreen.X = sx;
3973 SetConsoleScreenBufferSize(hConsole, coordScreen);
3974 }
3975 }
3976
3977 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3978 {
3979#ifdef MCH_WRITE_DUMP
3980 if (fdDump)
3981 {
3982 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3983 GetLastError());
3984 fflush(fdDump);
3985 }
3986#endif
3987 }
3988
3989 /* define the new console buffer size */
3990 coordScreen.X = xSize;
3991 coordScreen.Y = ySize;
3992
3993 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3994 {
3995#ifdef MCH_WRITE_DUMP
3996 if (fdDump)
3997 {
3998 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3999 GetLastError());
4000 fflush(fdDump);
4001 }
4002#endif
4003 }
4004}
4005
4006
4007/*
4008 * Set the console window to `Rows' * `Columns'
4009 */
4010 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004011mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012{
4013 COORD coordScreen;
4014
4015 /* Don't change window size while still starting up */
4016 if (suppress_winsize != 0)
4017 {
4018 suppress_winsize = 2;
4019 return;
4020 }
4021
4022 if (term_console)
4023 {
4024 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4025
4026 /* Clamp Rows and Columns to reasonable values */
4027 if (Rows > coordScreen.Y)
4028 Rows = coordScreen.Y;
4029 if (Columns > coordScreen.X)
4030 Columns = coordScreen.X;
4031
4032 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4033 }
4034}
4035
4036/*
4037 * Rows and/or Columns has changed.
4038 */
4039 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004040mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041{
4042 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4043}
4044
4045
4046/*
4047 * Called when started up, to set the winsize that was delayed.
4048 */
4049 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004050mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051{
4052 if (suppress_winsize == 2)
4053 {
4054 suppress_winsize = 0;
4055 mch_set_shellsize();
4056 shell_resized();
4057 }
4058 suppress_winsize = 0;
4059}
4060#endif /* FEAT_GUI_W32 */
4061
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004062 static BOOL
4063vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004064 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004065 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004066 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004067 STARTUPINFO *si,
4068 PROCESS_INFORMATION *pi)
4069{
4070# ifdef FEAT_MBYTE
4071 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4072 {
4073 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4074
4075 if (wcmd != NULL)
4076 {
4077 BOOL ret;
4078 ret = CreateProcessW(
4079 NULL, /* Executable name */
4080 wcmd, /* Command to execute */
4081 NULL, /* Process security attributes */
4082 NULL, /* Thread security attributes */
4083 inherit_handles, /* Inherit handles */
4084 flags, /* Creation flags */
4085 NULL, /* Environment */
4086 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004087 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004088 pi); /* Process information */
4089 vim_free(wcmd);
4090 return ret;
4091 }
4092 }
4093#endif
4094 return CreateProcess(
4095 NULL, /* Executable name */
4096 cmd, /* Command to execute */
4097 NULL, /* Process security attributes */
4098 NULL, /* Thread security attributes */
4099 inherit_handles, /* Inherit handles */
4100 flags, /* Creation flags */
4101 NULL, /* Environment */
4102 NULL, /* Current directory */
4103 si, /* Startup information */
4104 pi); /* Process information */
4105}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106
4107
4108#if defined(FEAT_GUI_W32) || defined(PROTO)
4109
4110/*
4111 * Specialised version of system() for Win32 GUI mode.
4112 * This version proceeds as follows:
4113 * 1. Create a console window for use by the subprocess
4114 * 2. Run the subprocess (it gets the allocated console by default)
4115 * 3. Wait for the subprocess to terminate and get its exit code
4116 * 4. Prompt the user to press a key to close the console window
4117 */
4118 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004119mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120{
4121 STARTUPINFO si;
4122 PROCESS_INFORMATION pi;
4123 DWORD ret = 0;
4124 HWND hwnd = GetFocus();
4125
4126 si.cb = sizeof(si);
4127 si.lpReserved = NULL;
4128 si.lpDesktop = NULL;
4129 si.lpTitle = NULL;
4130 si.dwFlags = STARTF_USESHOWWINDOW;
4131 /*
4132 * It's nicer to run a filter command in a minimized window, but in
4133 * Windows 95 this makes the command MUCH slower. We can't do it under
4134 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004135 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 */
4137 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004138 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139 else
4140 si.wShowWindow = SW_SHOWNORMAL;
4141 si.cbReserved2 = 0;
4142 si.lpReserved2 = NULL;
4143
4144 /* There is a strange error on Windows 95 when using "c:\\command.com".
4145 * When the "c:\\" is left out it works OK...? */
4146 if (mch_windows95()
4147 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4148 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4149 cmd += 3;
4150
4151 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004152 vim_create_process(cmd, FALSE,
4153 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154
4155 /* Wait for the command to terminate before continuing */
4156 if (g_PlatformId != VER_PLATFORM_WIN32s)
4157 {
4158#ifdef FEAT_GUI
4159 int delay = 1;
4160
4161 /* Keep updating the window while waiting for the shell to finish. */
4162 for (;;)
4163 {
4164 MSG msg;
4165
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004166 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004167 {
4168 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004169 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004170 delay = 1;
4171 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 }
4173 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4174 break;
4175
4176 /* We start waiting for a very short time and then increase it, so
4177 * that we respond quickly when the process is quick, and don't
4178 * consume too much overhead when it's slow. */
4179 if (delay < 50)
4180 delay += 10;
4181 }
4182#else
4183 WaitForSingleObject(pi.hProcess, INFINITE);
4184#endif
4185
4186 /* Get the command exit code */
4187 GetExitCodeProcess(pi.hProcess, &ret);
4188 }
4189 else
4190 {
4191 /*
4192 * This ugly code is the only quick way of performing
4193 * a synchronous spawn under Win32s. Yuk.
4194 */
4195 num_windows = 0;
4196 EnumWindows(win32ssynch_cb, 0);
4197 old_num_windows = num_windows;
4198 do
4199 {
4200 Sleep(1000);
4201 num_windows = 0;
4202 EnumWindows(win32ssynch_cb, 0);
4203 } while (num_windows == old_num_windows);
4204 ret = 0;
4205 }
4206
4207 /* Close the handles to the subprocess, so that it goes away */
4208 CloseHandle(pi.hThread);
4209 CloseHandle(pi.hProcess);
4210
4211 /* Try to get input focus back. Doesn't always work though. */
4212 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4213
4214 return ret;
4215}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004216
4217/*
4218 * Thread launched by the gui to send the current buffer data to the
4219 * process. This way avoid to hang up vim totally if the children
4220 * process take a long time to process the lines.
4221 */
4222 static DWORD WINAPI
4223sub_process_writer(LPVOID param)
4224{
4225 HANDLE g_hChildStd_IN_Wr = param;
4226 linenr_T lnum = curbuf->b_op_start.lnum;
4227 DWORD len = 0;
4228 DWORD l;
4229 char_u *lp = ml_get(lnum);
4230 char_u *s;
4231 int written = 0;
4232
4233 for (;;)
4234 {
4235 l = (DWORD)STRLEN(lp + written);
4236 if (l == 0)
4237 len = 0;
4238 else if (lp[written] == NL)
4239 {
4240 /* NL -> NUL translation */
4241 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4242 }
4243 else
4244 {
4245 s = vim_strchr(lp + written, NL);
4246 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4247 s == NULL ? l : (DWORD)(s - (lp + written)),
4248 &len, NULL);
4249 }
4250 if (len == (int)l)
4251 {
4252 /* Finished a line, add a NL, unless this line should not have
4253 * one. */
4254 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004255 || (!curbuf->b_p_bin
4256 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004257 || (lnum != curbuf->b_no_eol_lnum
4258 && (lnum != curbuf->b_ml.ml_line_count
4259 || curbuf->b_p_eol)))
4260 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004261 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004262 }
4263
4264 ++lnum;
4265 if (lnum > curbuf->b_op_end.lnum)
4266 break;
4267
4268 lp = ml_get(lnum);
4269 written = 0;
4270 }
4271 else if (len > 0)
4272 written += len;
4273 }
4274
4275 /* finished all the lines, close pipe */
4276 CloseHandle(g_hChildStd_IN_Wr);
4277 ExitThread(0);
4278}
4279
4280
4281# define BUFLEN 100 /* length for buffer, stolen from unix version */
4282
4283/*
4284 * This function read from the children's stdout and write the
4285 * data on screen or in the buffer accordingly.
4286 */
4287 static void
4288dump_pipe(int options,
4289 HANDLE g_hChildStd_OUT_Rd,
4290 garray_T *ga,
4291 char_u buffer[],
4292 DWORD *buffer_off)
4293{
4294 DWORD availableBytes = 0;
4295 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004296 int ret;
4297 DWORD len;
4298 DWORD toRead;
4299 int repeatCount;
4300
4301 /* we query the pipe to see if there is any data to read
4302 * to avoid to perform a blocking read */
4303 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4304 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004305 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004306 NULL, /* number of read bytes */
4307 &availableBytes, /* available bytes total */
4308 NULL); /* byteLeft */
4309
4310 repeatCount = 0;
4311 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004312 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004313 {
4314 repeatCount++;
4315 toRead =
4316# ifdef FEAT_MBYTE
4317 (DWORD)(BUFLEN - *buffer_off);
4318# else
4319 (DWORD)BUFLEN;
4320# endif
4321 toRead = availableBytes < toRead ? availableBytes : toRead;
4322 ReadFile(g_hChildStd_OUT_Rd, buffer
4323# ifdef FEAT_MBYTE
4324 + *buffer_off, toRead
4325# else
4326 , toRead
4327# endif
4328 , &len, NULL);
4329
4330 /* If we haven't read anything, there is a problem */
4331 if (len == 0)
4332 break;
4333
4334 availableBytes -= len;
4335
4336 if (options & SHELL_READ)
4337 {
4338 /* Do NUL -> NL translation, append NL separated
4339 * lines to the current buffer. */
4340 for (i = 0; i < len; ++i)
4341 {
4342 if (buffer[i] == NL)
4343 append_ga_line(ga);
4344 else if (buffer[i] == NUL)
4345 ga_append(ga, NL);
4346 else
4347 ga_append(ga, buffer[i]);
4348 }
4349 }
4350# ifdef FEAT_MBYTE
4351 else if (has_mbyte)
4352 {
4353 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004354 int c;
4355 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004356
4357 len += *buffer_off;
4358 buffer[len] = NUL;
4359
4360 /* Check if the last character in buffer[] is
4361 * incomplete, keep these bytes for the next
4362 * round. */
4363 for (p = buffer; p < buffer + len; p += l)
4364 {
4365 l = mb_cptr2len(p);
4366 if (l == 0)
4367 l = 1; /* NUL byte? */
4368 else if (MB_BYTE2LEN(*p) != l)
4369 break;
4370 }
4371 if (p == buffer) /* no complete character */
4372 {
4373 /* avoid getting stuck at an illegal byte */
4374 if (len >= 12)
4375 ++p;
4376 else
4377 {
4378 *buffer_off = len;
4379 return;
4380 }
4381 }
4382 c = *p;
4383 *p = NUL;
4384 msg_puts(buffer);
4385 if (p < buffer + len)
4386 {
4387 *p = c;
4388 *buffer_off = (DWORD)((buffer + len) - p);
4389 mch_memmove(buffer, p, *buffer_off);
4390 return;
4391 }
4392 *buffer_off = 0;
4393 }
4394# endif /* FEAT_MBYTE */
4395 else
4396 {
4397 buffer[len] = NUL;
4398 msg_puts(buffer);
4399 }
4400
4401 windgoto(msg_row, msg_col);
4402 cursor_on();
4403 out_flush();
4404 }
4405}
4406
4407/*
4408 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4409 * for communication and doesn't open any new window.
4410 */
4411 static int
4412mch_system_piped(char *cmd, int options)
4413{
4414 STARTUPINFO si;
4415 PROCESS_INFORMATION pi;
4416 DWORD ret = 0;
4417
4418 HANDLE g_hChildStd_IN_Rd = NULL;
4419 HANDLE g_hChildStd_IN_Wr = NULL;
4420 HANDLE g_hChildStd_OUT_Rd = NULL;
4421 HANDLE g_hChildStd_OUT_Wr = NULL;
4422
4423 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4424 DWORD len;
4425
4426 /* buffer used to receive keys */
4427 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4428 int ta_len = 0; /* valid bytes in ta_buf[] */
4429
4430 DWORD i;
4431 int c;
4432 int noread_cnt = 0;
4433 garray_T ga;
4434 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004435 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004436 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004437
4438 SECURITY_ATTRIBUTES saAttr;
4439
4440 /* Set the bInheritHandle flag so pipe handles are inherited. */
4441 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4442 saAttr.bInheritHandle = TRUE;
4443 saAttr.lpSecurityDescriptor = NULL;
4444
4445 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4446 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4447 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4448 /* Create a pipe for the child process's STDIN. */
4449 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4450 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4451 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4452 {
4453 CloseHandle(g_hChildStd_IN_Rd);
4454 CloseHandle(g_hChildStd_IN_Wr);
4455 CloseHandle(g_hChildStd_OUT_Rd);
4456 CloseHandle(g_hChildStd_OUT_Wr);
4457 MSG_PUTS(_("\nCannot create pipes\n"));
4458 }
4459
4460 si.cb = sizeof(si);
4461 si.lpReserved = NULL;
4462 si.lpDesktop = NULL;
4463 si.lpTitle = NULL;
4464 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4465
4466 /* set-up our file redirection */
4467 si.hStdError = g_hChildStd_OUT_Wr;
4468 si.hStdOutput = g_hChildStd_OUT_Wr;
4469 si.hStdInput = g_hChildStd_IN_Rd;
4470 si.wShowWindow = SW_HIDE;
4471 si.cbReserved2 = 0;
4472 si.lpReserved2 = NULL;
4473
4474 if (options & SHELL_READ)
4475 ga_init2(&ga, 1, BUFLEN);
4476
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004477 if (cmd != NULL)
4478 {
4479 p = (char *)vim_strsave((char_u *)cmd);
4480 if (p != NULL)
4481 unescape_shellxquote((char_u *)p, p_sxe);
4482 else
4483 p = cmd;
4484 }
4485
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004486 /* Now, run the command.
4487 * About "Inherit handles" being TRUE: this command can be litigious,
4488 * handle inheritance was deactivated for pending temp file, but, if we
4489 * deactivate it, the pipes don't work for some reason. */
4490 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004491
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004492 if (p != cmd)
4493 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004494
4495 /* Close our unused side of the pipes */
4496 CloseHandle(g_hChildStd_IN_Rd);
4497 CloseHandle(g_hChildStd_OUT_Wr);
4498
4499 if (options & SHELL_WRITE)
4500 {
4501 HANDLE thread =
4502 CreateThread(NULL, /* security attributes */
4503 0, /* default stack size */
4504 sub_process_writer, /* function to be executed */
4505 g_hChildStd_IN_Wr, /* parameter */
4506 0, /* creation flag, start immediately */
4507 NULL); /* we don't care about thread id */
4508 CloseHandle(thread);
4509 g_hChildStd_IN_Wr = NULL;
4510 }
4511
4512 /* Keep updating the window while waiting for the shell to finish. */
4513 for (;;)
4514 {
4515 MSG msg;
4516
Bram Moolenaar175d0702013-12-11 18:36:33 +01004517 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004518 {
4519 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004520 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004521 }
4522
4523 /* write pipe information in the window */
4524 if ((options & (SHELL_READ|SHELL_WRITE))
4525# ifdef FEAT_GUI
4526 || gui.in_use
4527# endif
4528 )
4529 {
4530 len = 0;
4531 if (!(options & SHELL_EXPAND)
4532 && ((options &
4533 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4534 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4535# ifdef FEAT_GUI
4536 || gui.in_use
4537# endif
4538 )
4539 && (ta_len > 0 || noread_cnt > 4))
4540 {
4541 if (ta_len == 0)
4542 {
4543 /* Get extra characters when we don't have any. Reset the
4544 * counter and timer. */
4545 noread_cnt = 0;
4546# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4547 gettimeofday(&start_tv, NULL);
4548# endif
4549 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4550 }
4551 if (ta_len > 0 || len > 0)
4552 {
4553 /*
4554 * For pipes: Check for CTRL-C: send interrupt signal to
4555 * child. Check for CTRL-D: EOF, close pipe to child.
4556 */
4557 if (len == 1 && cmd != NULL)
4558 {
4559 if (ta_buf[ta_len] == Ctrl_C)
4560 {
4561 /* Learn what exit code is expected, for
4562 * now put 9 as SIGKILL */
4563 TerminateProcess(pi.hProcess, 9);
4564 }
4565 if (ta_buf[ta_len] == Ctrl_D)
4566 {
4567 CloseHandle(g_hChildStd_IN_Wr);
4568 g_hChildStd_IN_Wr = NULL;
4569 }
4570 }
4571
4572 /* replace K_BS by <BS> and K_DEL by <DEL> */
4573 for (i = ta_len; i < ta_len + len; ++i)
4574 {
4575 if (ta_buf[i] == CSI && len - i > 2)
4576 {
4577 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4578 if (c == K_DEL || c == K_KDEL || c == K_BS)
4579 {
4580 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4581 (size_t)(len - i - 2));
4582 if (c == K_DEL || c == K_KDEL)
4583 ta_buf[i] = DEL;
4584 else
4585 ta_buf[i] = Ctrl_H;
4586 len -= 2;
4587 }
4588 }
4589 else if (ta_buf[i] == '\r')
4590 ta_buf[i] = '\n';
4591# ifdef FEAT_MBYTE
4592 if (has_mbyte)
4593 i += (*mb_ptr2len_len)(ta_buf + i,
4594 ta_len + len - i) - 1;
4595# endif
4596 }
4597
4598 /*
4599 * For pipes: echo the typed characters. For a pty this
4600 * does not seem to work.
4601 */
4602 for (i = ta_len; i < ta_len + len; ++i)
4603 {
4604 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4605 msg_putchar(ta_buf[i]);
4606# ifdef FEAT_MBYTE
4607 else if (has_mbyte)
4608 {
4609 int l = (*mb_ptr2len)(ta_buf + i);
4610
4611 msg_outtrans_len(ta_buf + i, l);
4612 i += l - 1;
4613 }
4614# endif
4615 else
4616 msg_outtrans_len(ta_buf + i, 1);
4617 }
4618 windgoto(msg_row, msg_col);
4619 out_flush();
4620
4621 ta_len += len;
4622
4623 /*
4624 * Write the characters to the child, unless EOF has been
4625 * typed for pipes. Write one character at a time, to
4626 * avoid losing too much typeahead. When writing buffer
4627 * lines, drop the typed characters (only check for
4628 * CTRL-C).
4629 */
4630 if (options & SHELL_WRITE)
4631 ta_len = 0;
4632 else if (g_hChildStd_IN_Wr != NULL)
4633 {
4634 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4635 1, &len, NULL);
4636 // if we are typing in, we want to keep things reactive
4637 delay = 1;
4638 if (len > 0)
4639 {
4640 ta_len -= len;
4641 mch_memmove(ta_buf, ta_buf + len, ta_len);
4642 }
4643 }
4644 }
4645 }
4646 }
4647
4648 if (ta_len)
4649 ui_inchar_undo(ta_buf, ta_len);
4650
4651 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4652 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004653 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004654 break;
4655 }
4656
4657 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004658 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004659
4660 /* We start waiting for a very short time and then increase it, so
4661 * that we respond quickly when the process is quick, and don't
4662 * consume too much overhead when it's slow. */
4663 if (delay < 50)
4664 delay += 10;
4665 }
4666
4667 /* Close the pipe */
4668 CloseHandle(g_hChildStd_OUT_Rd);
4669 if (g_hChildStd_IN_Wr != NULL)
4670 CloseHandle(g_hChildStd_IN_Wr);
4671
4672 WaitForSingleObject(pi.hProcess, INFINITE);
4673
4674 /* Get the command exit code */
4675 GetExitCodeProcess(pi.hProcess, &ret);
4676
4677 if (options & SHELL_READ)
4678 {
4679 if (ga.ga_len > 0)
4680 {
4681 append_ga_line(&ga);
4682 /* remember that the NL was missing */
4683 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4684 }
4685 else
4686 curbuf->b_no_eol_lnum = 0;
4687 ga_clear(&ga);
4688 }
4689
4690 /* Close the handles to the subprocess, so that it goes away */
4691 CloseHandle(pi.hThread);
4692 CloseHandle(pi.hProcess);
4693
4694 return ret;
4695}
4696
4697 static int
4698mch_system(char *cmd, int options)
4699{
4700 /* if we can pipe and the shelltemp option is off */
4701 if (allowPiping && !p_stmp)
4702 return mch_system_piped(cmd, options);
4703 else
4704 return mch_system_classic(cmd, options);
4705}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706#else
4707
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004708# ifdef FEAT_MBYTE
4709 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004710mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004711{
4712 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4713 {
4714 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4715 if (wcmd != NULL)
4716 {
4717 int ret = _wsystem(wcmd);
4718 vim_free(wcmd);
4719 return ret;
4720 }
4721 }
4722 return system(cmd);
4723}
4724# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004725# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004726# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004727
4728#endif
4729
4730/*
4731 * Either execute a command by calling the shell or start a new shell
4732 */
4733 int
4734mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004735 char_u *cmd,
4736 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737{
4738 int x = 0;
4739 int tmode = cur_tmode;
4740#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004741 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004742# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004743 int did_set_title = FALSE;
4744
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004745 /* Change the title to reflect that we are in a subshell. */
4746 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4747 {
4748 WCHAR szShellTitle[512];
4749
4750 if (GetConsoleTitleW(szShellTitle,
4751 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4752 {
4753 if (cmd == NULL)
4754 wcscat(szShellTitle, L" :sh");
4755 else
4756 {
4757 WCHAR *wn = enc_to_utf16(cmd, NULL);
4758
4759 if (wn != NULL)
4760 {
4761 wcscat(szShellTitle, L" - !");
4762 if ((wcslen(szShellTitle) + wcslen(wn) <
4763 sizeof(szShellTitle)/sizeof(WCHAR)))
4764 wcscat(szShellTitle, wn);
4765 SetConsoleTitleW(szShellTitle);
4766 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004767 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004768 }
4769 }
4770 }
4771 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004772 if (!did_set_title)
4773# endif
4774 /* Change the title to reflect that we are in a subshell. */
4775 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004777 if (cmd == NULL)
4778 strcat(szShellTitle, " :sh");
4779 else
4780 {
4781 strcat(szShellTitle, " - !");
4782 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4783 strcat(szShellTitle, cmd);
4784 }
4785 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004786 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787#endif
4788
4789 out_flush();
4790
4791#ifdef MCH_WRITE_DUMP
4792 if (fdDump)
4793 {
4794 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4795 fflush(fdDump);
4796 }
4797#endif
4798
4799 /*
4800 * Catch all deadly signals while running the external command, because a
4801 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4802 */
4803 signal(SIGINT, SIG_IGN);
4804#if defined(__GNUC__) && !defined(__MINGW32__)
4805 signal(SIGKILL, SIG_IGN);
4806#else
4807 signal(SIGBREAK, SIG_IGN);
4808#endif
4809 signal(SIGILL, SIG_IGN);
4810 signal(SIGFPE, SIG_IGN);
4811 signal(SIGSEGV, SIG_IGN);
4812 signal(SIGTERM, SIG_IGN);
4813 signal(SIGABRT, SIG_IGN);
4814
4815 if (options & SHELL_COOKED)
4816 settmode(TMODE_COOK); /* set to normal mode */
4817
4818 if (cmd == NULL)
4819 {
4820 x = mch_system(p_sh, options);
4821 }
4822 else
4823 {
4824 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004825 char_u *newcmd = NULL;
4826 char_u *cmdbase = cmd;
4827 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004828
4829 /* Skip a leading ", ( and "(. */
4830 if (*cmdbase == '"' )
4831 ++cmdbase;
4832 if (*cmdbase == '(')
4833 ++cmdbase;
4834
4835 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4836 {
4837 STARTUPINFO si;
4838 PROCESS_INFORMATION pi;
4839 DWORD flags = CREATE_NEW_CONSOLE;
4840 char_u *p;
4841
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004842 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004843 si.cb = sizeof(si);
4844 si.lpReserved = NULL;
4845 si.lpDesktop = NULL;
4846 si.lpTitle = NULL;
4847 si.dwFlags = 0;
4848 si.cbReserved2 = 0;
4849 si.lpReserved2 = NULL;
4850
4851 cmdbase = skipwhite(cmdbase + 5);
4852 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4853 && vim_iswhite(cmdbase[4]))
4854 {
4855 cmdbase = skipwhite(cmdbase + 4);
4856 si.dwFlags = STARTF_USESHOWWINDOW;
4857 si.wShowWindow = SW_SHOWMINNOACTIVE;
4858 }
4859 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4860 && vim_iswhite(cmdbase[2]))
4861 {
4862 cmdbase = skipwhite(cmdbase + 2);
4863 flags = CREATE_NO_WINDOW;
4864 si.dwFlags = STARTF_USESTDHANDLES;
4865 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004866 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004867 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004868 NULL, // Security att.
4869 OPEN_EXISTING, // Open flags
4870 FILE_ATTRIBUTE_NORMAL, // File att.
4871 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004872 si.hStdOutput = si.hStdInput;
4873 si.hStdError = si.hStdInput;
4874 }
4875
4876 /* Remove a trailing ", ) and )" if they have a match
4877 * at the start of the command. */
4878 if (cmdbase > cmd)
4879 {
4880 p = cmdbase + STRLEN(cmdbase);
4881 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4882 *--p = NUL;
4883 if (p > cmdbase && p[-1] == ')'
4884 && (*cmd =='(' || cmd[1] == '('))
4885 *--p = NUL;
4886 }
4887
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004888 newcmd = cmdbase;
4889 unescape_shellxquote(cmdbase, p_sxe);
4890
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004891 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004892 * If creating new console, arguments are passed to the
4893 * 'cmd.exe' as-is. If it's not, arguments are not treated
4894 * correctly for current 'cmd.exe'. So unescape characters in
4895 * shellxescape except '|' for avoiding to be treated as
4896 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004897 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004898 if (flags != CREATE_NEW_CONSOLE)
4899 {
4900 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004901 char_u *cmd_shell = mch_getenv("COMSPEC");
4902
4903 if (cmd_shell == NULL || *cmd_shell == NUL)
4904 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004905
4906 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4907 if (subcmd != NULL)
4908 {
4909 /* make "cmd.exe /c arguments" */
4910 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004911 newcmd = lalloc(cmdlen, TRUE);
4912 if (newcmd != NULL)
4913 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004914 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004915 else
4916 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004917 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004918 }
4919 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004920
4921 /*
4922 * Now, start the command as a process, so that it doesn't
4923 * inherit our handles which causes unpleasant dangling swap
4924 * files if we exit before the spawned process
4925 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004926 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004927 x = 0;
4928 else
4929 {
4930 x = -1;
4931#ifdef FEAT_GUI_W32
4932 EMSG(_("E371: Command not found"));
4933#endif
4934 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004935
4936 if (newcmd != cmdbase)
4937 vim_free(newcmd);
4938
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004939 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004940 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004941 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004942 CloseHandle(si.hStdInput);
4943 }
4944 /* Close the handles to the subprocess, so that it goes away */
4945 CloseHandle(pi.hThread);
4946 CloseHandle(pi.hProcess);
4947 }
4948 else
4949 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004950 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004951#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004952 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004954 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4955
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004956 newcmd = lalloc(cmdlen, TRUE);
4957 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004958 {
4959#if defined(FEAT_GUI_W32)
4960 if (need_vimrun_warning)
4961 {
4962 MessageBox(NULL,
4963 _("VIMRUN.EXE not found in your $PATH.\n"
4964 "External commands will not pause after completion.\n"
4965 "See :help win32-vimrun for more information."),
4966 _("Vim Warning"),
4967 MB_ICONWARNING);
4968 need_vimrun_warning = FALSE;
4969 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004970 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 /* Use vimrun to execute the command. It opens a console
4972 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004973 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974 vimrun_path,
4975 (msg_silent != 0 || (options & SHELL_DOOUT))
4976 ? "-s " : "",
4977 p_sh, p_shcf, cmd);
4978 else
4979#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004980 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004981 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004983 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004984 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985 }
4986 }
4987
4988 if (tmode == TMODE_RAW)
4989 settmode(TMODE_RAW); /* set to raw mode */
4990
4991 /* Print the return value, unless "vimrun" was used. */
4992 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4993#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004994 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4995 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004996#endif
4997 )
4998 {
4999 smsg(_("shell returned %d"), x);
5000 msg_putchar('\n');
5001 }
5002#ifdef FEAT_TITLE
5003 resettitle();
5004#endif
5005
5006 signal(SIGINT, SIG_DFL);
5007#if defined(__GNUC__) && !defined(__MINGW32__)
5008 signal(SIGKILL, SIG_DFL);
5009#else
5010 signal(SIGBREAK, SIG_DFL);
5011#endif
5012 signal(SIGILL, SIG_DFL);
5013 signal(SIGFPE, SIG_DFL);
5014 signal(SIGSEGV, SIG_DFL);
5015 signal(SIGTERM, SIG_DFL);
5016 signal(SIGABRT, SIG_DFL);
5017
5018 return x;
5019}
5020
5021
5022#ifndef FEAT_GUI_W32
5023
5024/*
5025 * Start termcap mode
5026 */
5027 static void
5028termcap_mode_start(void)
5029{
5030 DWORD cmodein;
5031
5032 if (g_fTermcapMode)
5033 return;
5034
5035 SaveConsoleBuffer(&g_cbNonTermcap);
5036
5037 if (g_cbTermcap.IsValid)
5038 {
5039 /*
5040 * We've been in termcap mode before. Restore certain screen
5041 * characteristics, including the buffer size and the window
5042 * size. Since we will be redrawing the screen, we don't need
5043 * to restore the actual contents of the buffer.
5044 */
5045 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5046 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5047 Rows = g_cbTermcap.Info.dwSize.Y;
5048 Columns = g_cbTermcap.Info.dwSize.X;
5049 }
5050 else
5051 {
5052 /*
5053 * This is our first time entering termcap mode. Clear the console
5054 * screen buffer, and resize the buffer to match the current window
5055 * size. We will use this as the size of our editing environment.
5056 */
5057 ClearConsoleBuffer(g_attrCurrent);
5058 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5059 }
5060
5061#ifdef FEAT_TITLE
5062 resettitle();
5063#endif
5064
5065 GetConsoleMode(g_hConIn, &cmodein);
5066#ifdef FEAT_MOUSE
5067 if (g_fMouseActive)
5068 cmodein |= ENABLE_MOUSE_INPUT;
5069 else
5070 cmodein &= ~ENABLE_MOUSE_INPUT;
5071#endif
5072 cmodein |= ENABLE_WINDOW_INPUT;
5073 SetConsoleMode(g_hConIn, cmodein);
5074
5075 redraw_later_clear();
5076 g_fTermcapMode = TRUE;
5077}
5078
5079
5080/*
5081 * End termcap mode
5082 */
5083 static void
5084termcap_mode_end(void)
5085{
5086 DWORD cmodein;
5087 ConsoleBuffer *cb;
5088 COORD coord;
5089 DWORD dwDummy;
5090
5091 if (!g_fTermcapMode)
5092 return;
5093
5094 SaveConsoleBuffer(&g_cbTermcap);
5095
5096 GetConsoleMode(g_hConIn, &cmodein);
5097 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5098 SetConsoleMode(g_hConIn, cmodein);
5099
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005100#ifdef FEAT_RESTORE_ORIG_SCREEN
5101 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5102#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005103 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005104#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005105 RestoreConsoleBuffer(cb, p_rs);
5106 SetConsoleCursorInfo(g_hConOut, &g_cci);
5107
5108 if (p_rs || exiting)
5109 {
5110 /*
5111 * Clear anything that happens to be on the current line.
5112 */
5113 coord.X = 0;
5114 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5115 FillConsoleOutputCharacter(g_hConOut, ' ',
5116 cb->Info.dwSize.X, coord, &dwDummy);
5117 /*
5118 * The following is just for aesthetics. If we are exiting without
5119 * restoring the screen, then we want to have a prompt string
5120 * appear at the bottom line. However, the command interpreter
5121 * seems to always advance the cursor one line before displaying
5122 * the prompt string, which causes the screen to scroll. To
5123 * counter this, move the cursor up one line before exiting.
5124 */
5125 if (exiting && !p_rs)
5126 coord.Y--;
5127 /*
5128 * Position the cursor at the leftmost column of the desired row.
5129 */
5130 SetConsoleCursorPosition(g_hConOut, coord);
5131 }
5132
5133 g_fTermcapMode = FALSE;
5134}
5135#endif /* FEAT_GUI_W32 */
5136
5137
5138#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005139/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005140 void
5141mch_write(
5142 char_u *s,
5143 int len)
5144{
5145 /* never used */
5146}
5147
5148#else
5149
5150/*
5151 * clear `n' chars, starting from `coord'
5152 */
5153 static void
5154clear_chars(
5155 COORD coord,
5156 DWORD n)
5157{
5158 DWORD dwDummy;
5159
5160 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5161 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5162}
5163
5164
5165/*
5166 * Clear the screen
5167 */
5168 static void
5169clear_screen(void)
5170{
5171 g_coord.X = g_coord.Y = 0;
5172 clear_chars(g_coord, Rows * Columns);
5173}
5174
5175
5176/*
5177 * Clear to end of display
5178 */
5179 static void
5180clear_to_end_of_display(void)
5181{
5182 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5183 * Columns + (Columns - g_coord.X));
5184}
5185
5186
5187/*
5188 * Clear to end of line
5189 */
5190 static void
5191clear_to_end_of_line(void)
5192{
5193 clear_chars(g_coord, Columns - g_coord.X);
5194}
5195
5196
5197/*
5198 * Scroll the scroll region up by `cLines' lines
5199 */
5200 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005201scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005202{
5203 COORD oldcoord = g_coord;
5204
5205 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5206 delete_lines(cLines);
5207
5208 g_coord = oldcoord;
5209}
5210
5211
5212/*
5213 * Set the scroll region
5214 */
5215 static void
5216set_scroll_region(
5217 unsigned left,
5218 unsigned top,
5219 unsigned right,
5220 unsigned bottom)
5221{
5222 if (left >= right
5223 || top >= bottom
5224 || right > (unsigned) Columns - 1
5225 || bottom > (unsigned) Rows - 1)
5226 return;
5227
5228 g_srScrollRegion.Left = left;
5229 g_srScrollRegion.Top = top;
5230 g_srScrollRegion.Right = right;
5231 g_srScrollRegion.Bottom = bottom;
5232}
5233
5234
5235/*
5236 * Insert `cLines' lines at the current cursor position
5237 */
5238 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005239insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005240{
5241 SMALL_RECT source;
5242 COORD dest;
5243 CHAR_INFO fill;
5244
5245 dest.X = 0;
5246 dest.Y = g_coord.Y + cLines;
5247
5248 source.Left = 0;
5249 source.Top = g_coord.Y;
5250 source.Right = g_srScrollRegion.Right;
5251 source.Bottom = g_srScrollRegion.Bottom - cLines;
5252
5253 fill.Char.AsciiChar = ' ';
5254 fill.Attributes = g_attrCurrent;
5255
5256 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5257
5258 /* Here we have to deal with a win32 console flake: If the scroll
5259 * region looks like abc and we scroll c to a and fill with d we get
5260 * cbd... if we scroll block c one line at a time to a, we get cdd...
5261 * vim expects cdd consistently... So we have to deal with that
5262 * here... (this also occurs scrolling the same way in the other
5263 * direction). */
5264
5265 if (source.Bottom < dest.Y)
5266 {
5267 COORD coord;
5268
5269 coord.X = 0;
5270 coord.Y = source.Bottom;
5271 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5272 }
5273}
5274
5275
5276/*
5277 * Delete `cLines' lines at the current cursor position
5278 */
5279 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005280delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005281{
5282 SMALL_RECT source;
5283 COORD dest;
5284 CHAR_INFO fill;
5285 int nb;
5286
5287 dest.X = 0;
5288 dest.Y = g_coord.Y;
5289
5290 source.Left = 0;
5291 source.Top = g_coord.Y + cLines;
5292 source.Right = g_srScrollRegion.Right;
5293 source.Bottom = g_srScrollRegion.Bottom;
5294
5295 fill.Char.AsciiChar = ' ';
5296 fill.Attributes = g_attrCurrent;
5297
5298 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5299
5300 /* Here we have to deal with a win32 console flake: If the scroll
5301 * region looks like abc and we scroll c to a and fill with d we get
5302 * cbd... if we scroll block c one line at a time to a, we get cdd...
5303 * vim expects cdd consistently... So we have to deal with that
5304 * here... (this also occurs scrolling the same way in the other
5305 * direction). */
5306
5307 nb = dest.Y + (source.Bottom - source.Top) + 1;
5308
5309 if (nb < source.Top)
5310 {
5311 COORD coord;
5312
5313 coord.X = 0;
5314 coord.Y = nb;
5315 clear_chars(coord, Columns * (source.Top - nb));
5316 }
5317}
5318
5319
5320/*
5321 * Set the cursor position
5322 */
5323 static void
5324gotoxy(
5325 unsigned x,
5326 unsigned y)
5327{
5328 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5329 return;
5330
5331 /* external cursor coords are 1-based; internal are 0-based */
5332 g_coord.X = x - 1;
5333 g_coord.Y = y - 1;
5334 SetConsoleCursorPosition(g_hConOut, g_coord);
5335}
5336
5337
5338/*
5339 * Set the current text attribute = (foreground | background)
5340 * See ../doc/os_win32.txt for the numbers.
5341 */
5342 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005343textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005344{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005345 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005346
5347 SetConsoleTextAttribute(g_hConOut, wAttr);
5348}
5349
5350
5351 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005352textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005354 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005355
5356 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5357}
5358
5359
5360 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005361textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005362{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005363 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364
5365 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5366}
5367
5368
5369/*
5370 * restore the default text attribute (whatever we started with)
5371 */
5372 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005373normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005374{
5375 textattr(g_attrDefault);
5376}
5377
5378
5379static WORD g_attrPreStandout = 0;
5380
5381/*
5382 * Make the text standout, by brightening it
5383 */
5384 static void
5385standout(void)
5386{
5387 g_attrPreStandout = g_attrCurrent;
5388 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5389}
5390
5391
5392/*
5393 * Turn off standout mode
5394 */
5395 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005396standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005397{
5398 if (g_attrPreStandout)
5399 {
5400 textattr(g_attrPreStandout);
5401 g_attrPreStandout = 0;
5402 }
5403}
5404
5405
5406/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005407 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005408 */
5409 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005410mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005411{
5412 char_u *p;
5413 int n;
5414
5415 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5416 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5417 if (T_ME[0] == ESC && T_ME[1] == '|')
5418 {
5419 p = T_ME + 2;
5420 n = getdigits(&p);
5421 if (*p == 'm' && n > 0)
5422 {
5423 cterm_normal_fg_color = (n & 0xf) + 1;
5424 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5425 }
5426 }
5427}
5428
5429
5430/*
5431 * visual bell: flash the screen
5432 */
5433 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005434visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435{
5436 COORD coordOrigin = {0, 0};
5437 WORD attrFlash = ~g_attrCurrent & 0xff;
5438
5439 DWORD dwDummy;
5440 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5441
5442 if (oldattrs == NULL)
5443 return;
5444 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5445 coordOrigin, &dwDummy);
5446 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5447 coordOrigin, &dwDummy);
5448
5449 Sleep(15); /* wait for 15 msec */
5450 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5451 coordOrigin, &dwDummy);
5452 vim_free(oldattrs);
5453}
5454
5455
5456/*
5457 * Make the cursor visible or invisible
5458 */
5459 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005460cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005461{
5462 s_cursor_visible = fVisible;
5463#ifdef MCH_CURSOR_SHAPE
5464 mch_update_cursor();
5465#endif
5466}
5467
5468
5469/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005470 * write `cbToWrite' bytes in `pchBuf' to the screen
5471 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005472 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005473 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005475 char_u *pchBuf,
5476 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005477{
5478 COORD coord = g_coord;
5479 DWORD written;
5480
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005481#ifdef FEAT_MBYTE
5482 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5483 {
5484 static WCHAR *unicodebuf = NULL;
5485 static int unibuflen = 0;
5486 int length;
5487 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005489 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5490 if (unicodebuf == NULL || length > unibuflen)
5491 {
5492 vim_free(unicodebuf);
5493 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5494 unibuflen = length;
5495 }
5496 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5497 unicodebuf, unibuflen);
5498
5499 cells = mb_string2cells(pchBuf, cbToWrite);
5500 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5501 coord, &written);
5502 /* When writing fails or didn't write a single character, pretend one
5503 * character was written, otherwise we get stuck. */
5504 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5505 coord, &cchwritten) == 0
5506 || cchwritten == 0)
5507 cchwritten = 1;
5508
5509 if (cchwritten == length)
5510 {
5511 written = cbToWrite;
5512 g_coord.X += (SHORT)cells;
5513 }
5514 else
5515 {
5516 char_u *p = pchBuf;
5517 for (n = 0; n < cchwritten; n++)
5518 mb_cptr_adv(p);
5519 written = p - pchBuf;
5520 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5521 }
5522 }
5523 else
5524#endif
5525 {
5526 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5527 coord, &written);
5528 /* When writing fails or didn't write a single character, pretend one
5529 * character was written, otherwise we get stuck. */
5530 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5531 coord, &written) == 0
5532 || written == 0)
5533 written = 1;
5534
5535 g_coord.X += (SHORT) written;
5536 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537
5538 while (g_coord.X > g_srScrollRegion.Right)
5539 {
5540 g_coord.X -= (SHORT) Columns;
5541 if (g_coord.Y < g_srScrollRegion.Bottom)
5542 g_coord.Y++;
5543 }
5544
5545 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5546
5547 return written;
5548}
5549
5550
5551/*
5552 * mch_write(): write the output buffer to the screen, translating ESC
5553 * sequences into calls to console output routines.
5554 */
5555 void
5556mch_write(
5557 char_u *s,
5558 int len)
5559{
5560 s[len] = NUL;
5561
5562 if (!term_console)
5563 {
5564 write(1, s, (unsigned)len);
5565 return;
5566 }
5567
5568 /* translate ESC | sequences into faked bios calls */
5569 while (len--)
5570 {
5571 /* optimization: use one single write_chars for runs of text,
5572 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005573 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574
5575 if (p_wd)
5576 {
5577 WaitForChar(p_wd);
5578 if (prefix != 0)
5579 prefix = 1;
5580 }
5581
5582 if (prefix != 0)
5583 {
5584 DWORD nWritten;
5585
5586 nWritten = write_chars(s, prefix);
5587#ifdef MCH_WRITE_DUMP
5588 if (fdDump)
5589 {
5590 fputc('>', fdDump);
5591 fwrite(s, sizeof(char_u), nWritten, fdDump);
5592 fputs("<\n", fdDump);
5593 }
5594#endif
5595 len -= (nWritten - 1);
5596 s += nWritten;
5597 }
5598 else if (s[0] == '\n')
5599 {
5600 /* \n, newline: go to the beginning of the next line or scroll */
5601 if (g_coord.Y == g_srScrollRegion.Bottom)
5602 {
5603 scroll(1);
5604 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5605 }
5606 else
5607 {
5608 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5609 }
5610#ifdef MCH_WRITE_DUMP
5611 if (fdDump)
5612 fputs("\\n\n", fdDump);
5613#endif
5614 s++;
5615 }
5616 else if (s[0] == '\r')
5617 {
5618 /* \r, carriage return: go to beginning of line */
5619 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5620#ifdef MCH_WRITE_DUMP
5621 if (fdDump)
5622 fputs("\\r\n", fdDump);
5623#endif
5624 s++;
5625 }
5626 else if (s[0] == '\b')
5627 {
5628 /* \b, backspace: move cursor one position left */
5629 if (g_coord.X > g_srScrollRegion.Left)
5630 g_coord.X--;
5631 else if (g_coord.Y > g_srScrollRegion.Top)
5632 {
5633 g_coord.X = g_srScrollRegion.Right;
5634 g_coord.Y--;
5635 }
5636 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5637#ifdef MCH_WRITE_DUMP
5638 if (fdDump)
5639 fputs("\\b\n", fdDump);
5640#endif
5641 s++;
5642 }
5643 else if (s[0] == '\a')
5644 {
5645 /* \a, bell */
5646 MessageBeep(0xFFFFFFFF);
5647#ifdef MCH_WRITE_DUMP
5648 if (fdDump)
5649 fputs("\\a\n", fdDump);
5650#endif
5651 s++;
5652 }
5653 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5654 {
5655#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005656 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005658 char_u *p;
5659 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660
5661 switch (s[2])
5662 {
5663 /* one or two numeric arguments, separated by ';' */
5664
5665 case '0': case '1': case '2': case '3': case '4':
5666 case '5': case '6': case '7': case '8': case '9':
5667 p = s + 2;
5668 arg1 = getdigits(&p); /* no check for length! */
5669 if (p > s + len)
5670 break;
5671
5672 if (*p == ';')
5673 {
5674 ++p;
5675 arg2 = getdigits(&p); /* no check for length! */
5676 if (p > s + len)
5677 break;
5678
5679 if (*p == 'H')
5680 gotoxy(arg2, arg1);
5681 else if (*p == 'r')
5682 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5683 }
5684 else if (*p == 'A')
5685 {
5686 /* move cursor up arg1 lines in same column */
5687 gotoxy(g_coord.X + 1,
5688 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5689 }
5690 else if (*p == 'C')
5691 {
5692 /* move cursor right arg1 columns in same line */
5693 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5694 g_coord.Y + 1);
5695 }
5696 else if (*p == 'H')
5697 {
5698 gotoxy(1, arg1);
5699 }
5700 else if (*p == 'L')
5701 {
5702 insert_lines(arg1);
5703 }
5704 else if (*p == 'm')
5705 {
5706 if (arg1 == 0)
5707 normvideo();
5708 else
5709 textattr((WORD) arg1);
5710 }
5711 else if (*p == 'f')
5712 {
5713 textcolor((WORD) arg1);
5714 }
5715 else if (*p == 'b')
5716 {
5717 textbackground((WORD) arg1);
5718 }
5719 else if (*p == 'M')
5720 {
5721 delete_lines(arg1);
5722 }
5723
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005724 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 s = p + 1;
5726 break;
5727
5728
5729 /* Three-character escape sequences */
5730
5731 case 'A':
5732 /* move cursor up one line in same column */
5733 gotoxy(g_coord.X + 1,
5734 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5735 goto got3;
5736
5737 case 'B':
5738 visual_bell();
5739 goto got3;
5740
5741 case 'C':
5742 /* move cursor right one column in same line */
5743 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5744 g_coord.Y + 1);
5745 goto got3;
5746
5747 case 'E':
5748 termcap_mode_end();
5749 goto got3;
5750
5751 case 'F':
5752 standout();
5753 goto got3;
5754
5755 case 'f':
5756 standend();
5757 goto got3;
5758
5759 case 'H':
5760 gotoxy(1, 1);
5761 goto got3;
5762
5763 case 'j':
5764 clear_to_end_of_display();
5765 goto got3;
5766
5767 case 'J':
5768 clear_screen();
5769 goto got3;
5770
5771 case 'K':
5772 clear_to_end_of_line();
5773 goto got3;
5774
5775 case 'L':
5776 insert_lines(1);
5777 goto got3;
5778
5779 case 'M':
5780 delete_lines(1);
5781 goto got3;
5782
5783 case 'S':
5784 termcap_mode_start();
5785 goto got3;
5786
5787 case 'V':
5788 cursor_visible(TRUE);
5789 goto got3;
5790
5791 case 'v':
5792 cursor_visible(FALSE);
5793 goto got3;
5794
5795 got3:
5796 s += 3;
5797 len -= 2;
5798 }
5799
5800#ifdef MCH_WRITE_DUMP
5801 if (fdDump)
5802 {
5803 fputs("ESC | ", fdDump);
5804 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5805 fputc('\n', fdDump);
5806 }
5807#endif
5808 }
5809 else
5810 {
5811 /* Write a single character */
5812 DWORD nWritten;
5813
5814 nWritten = write_chars(s, 1);
5815#ifdef MCH_WRITE_DUMP
5816 if (fdDump)
5817 {
5818 fputc('>', fdDump);
5819 fwrite(s, sizeof(char_u), nWritten, fdDump);
5820 fputs("<\n", fdDump);
5821 }
5822#endif
5823
5824 len -= (nWritten - 1);
5825 s += nWritten;
5826 }
5827 }
5828
5829#ifdef MCH_WRITE_DUMP
5830 if (fdDump)
5831 fflush(fdDump);
5832#endif
5833}
5834
5835#endif /* FEAT_GUI_W32 */
5836
5837
5838/*
5839 * Delay for half a second.
5840 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005841/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842 void
5843mch_delay(
5844 long msec,
5845 int ignoreinput)
5846{
5847#ifdef FEAT_GUI_W32
5848 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005849#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005851# ifdef FEAT_MZSCHEME
5852 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5853 {
5854 int towait = p_mzq;
5855
5856 /* if msec is large enough, wait by portions in p_mzq */
5857 while (msec > 0)
5858 {
5859 mzvim_check_threads();
5860 if (msec < towait)
5861 towait = msec;
5862 Sleep(towait);
5863 msec -= towait;
5864 }
5865 }
5866 else
5867# endif
5868 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869 else
5870 WaitForChar(msec);
5871#endif
5872}
5873
5874
5875/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01005876 * This version of remove is not scared by a readonly (backup) file.
5877 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878 * Return 0 for success, -1 for failure.
5879 */
5880 int
5881mch_remove(char_u *name)
5882{
5883#ifdef FEAT_MBYTE
5884 WCHAR *wn = NULL;
5885 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005886#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887
Bram Moolenaar203258c2016-01-17 22:15:16 +01005888 /*
5889 * On Windows, deleting a directory's symbolic link is done by
5890 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
5891 */
5892 if (mch_isdir(name) && mch_is_symbolic_link(name))
5893 return mch_rmdir(name);
5894
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005895 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5896
5897#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5899 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005900 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005901 if (wn != NULL)
5902 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903 n = DeleteFileW(wn) ? 0 : -1;
5904 vim_free(wn);
5905 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5906 return n;
5907 /* Retry with non-wide function (for Windows 98). */
5908 }
5909 }
5910#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005911 return DeleteFile(name) ? 0 : -1;
5912}
5913
5914
5915/*
5916 * check for an "interrupt signal": CTRL-break or CTRL-C
5917 */
5918 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005919mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920{
5921#ifndef FEAT_GUI_W32 /* never used */
5922 if (g_fCtrlCPressed || g_fCBrkPressed)
5923 {
5924 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5925 got_int = TRUE;
5926 }
5927#endif
5928}
5929
Bram Moolenaaree273972016-01-02 21:11:51 +01005930/* physical RAM to leave for the OS */
5931#define WINNT_RESERVE_BYTES (256*1024*1024)
5932#define WIN95_RESERVE_BYTES (8*1024*1024)
5933
5934/*
5935 * How much main memory in KiB that can be used by VIM.
5936 */
5937/*ARGSUSED*/
5938 long_u
5939mch_total_mem(int special)
5940{
5941 PlatformId();
5942#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
5943 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5944 {
5945 MEMORYSTATUSEX ms;
5946
5947 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5948 * what fits in 32 bits. But it's not always available. */
5949 ms.dwLength = sizeof(MEMORYSTATUSEX);
5950 GlobalMemoryStatusEx(&ms);
5951 if (ms.ullAvailVirtual < ms.ullTotalPhys)
5952 {
5953 /* Process address space fits in physical RAM, use all of it. */
5954 return (long_u)(ms.ullAvailVirtual / 1024);
5955 }
5956 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
5957 {
5958 /* Catch old NT box or perverse hardware setup. */
5959 return (long_u)((ms.ullTotalPhys / 2) / 1024);
5960 }
5961 /* Use physical RAM less reserve for OS + data. */
5962 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
5963 }
5964 else
5965#endif
5966 {
5967 /* Pre-XP or 95 OS handling. */
5968 MEMORYSTATUS ms;
5969 long_u os_reserve_bytes;
5970
5971 ms.dwLength = sizeof(MEMORYSTATUS);
5972 GlobalMemoryStatus(&ms);
5973 if (ms.dwAvailVirtual < ms.dwTotalPhys)
5974 {
5975 /* Process address space fits in physical RAM, use all of it. */
5976 return (long_u)(ms.dwAvailVirtual / 1024);
5977 }
5978 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
5979 ? WINNT_RESERVE_BYTES
5980 : WIN95_RESERVE_BYTES;
5981 if (ms.dwTotalPhys <= os_reserve_bytes)
5982 {
5983 /* Catch old boxes or perverse hardware setup. */
5984 return (long_u)((ms.dwTotalPhys / 2) / 1024);
5985 }
5986 /* Use physical RAM less reserve for OS + data. */
5987 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
5988 }
5989}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005990
Bram Moolenaar071d4272004-06-13 20:20:40 +00005991#ifdef FEAT_MBYTE
5992/*
5993 * Same code as below, but with wide functions and no comments.
5994 * Return 0 for success, non-zero for failure.
5995 */
5996 int
5997mch_wrename(WCHAR *wold, WCHAR *wnew)
5998{
5999 WCHAR *p;
6000 int i;
6001 WCHAR szTempFile[_MAX_PATH + 1];
6002 WCHAR szNewPath[_MAX_PATH + 1];
6003 HANDLE hf;
6004
6005 if (!mch_windows95())
6006 {
6007 p = wold;
6008 for (i = 0; wold[i] != NUL; ++i)
6009 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6010 && wold[i + 1] != 0)
6011 p = wold + i + 1;
6012 if ((int)(wold + i - p) < 8 || p[6] != '~')
6013 return (MoveFileW(wold, wnew) == 0);
6014 }
6015
6016 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6017 return -1;
6018 *p = NUL;
6019
6020 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6021 return -2;
6022
6023 if (!DeleteFileW(szTempFile))
6024 return -3;
6025
6026 if (!MoveFileW(wold, szTempFile))
6027 return -4;
6028
6029 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6030 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6031 return -5;
6032 if (!CloseHandle(hf))
6033 return -6;
6034
6035 if (!MoveFileW(szTempFile, wnew))
6036 {
6037 (void)MoveFileW(szTempFile, wold);
6038 return -7;
6039 }
6040
6041 DeleteFileW(szTempFile);
6042
6043 if (!DeleteFileW(wold))
6044 return -8;
6045
6046 return 0;
6047}
6048#endif
6049
6050
6051/*
6052 * mch_rename() works around a bug in rename (aka MoveFile) in
6053 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6054 * file whose short file name is "FOO.BAR" (its long file name will
6055 * be correct: "foo.bar~"). Because a file can be accessed by
6056 * either its SFN or its LFN, "foo.bar" has effectively been
6057 * renamed to "foo.bar", which is not at all what was wanted. This
6058 * seems to happen only when renaming files with three-character
6059 * extensions by appending a suffix that does not include ".".
6060 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6061 *
6062 * There is another problem, which isn't really a bug but isn't right either:
6063 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6064 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6065 * service pack 6. Doesn't seem to happen on Windows 98.
6066 *
6067 * Like rename(), returns 0 upon success, non-zero upon failure.
6068 * Should probably set errno appropriately when errors occur.
6069 */
6070 int
6071mch_rename(
6072 const char *pszOldFile,
6073 const char *pszNewFile)
6074{
6075 char szTempFile[_MAX_PATH+1];
6076 char szNewPath[_MAX_PATH+1];
6077 char *pszFilePart;
6078 HANDLE hf;
6079#ifdef FEAT_MBYTE
6080 WCHAR *wold = NULL;
6081 WCHAR *wnew = NULL;
6082 int retval = -1;
6083
6084 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6085 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006086 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6087 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006088 if (wold != NULL && wnew != NULL)
6089 retval = mch_wrename(wold, wnew);
6090 vim_free(wold);
6091 vim_free(wnew);
6092 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6093 return retval;
6094 /* Retry with non-wide function (for Windows 98). */
6095 }
6096#endif
6097
6098 /*
6099 * No need to play tricks if not running Windows 95, unless the file name
6100 * contains a "~" as the seventh character.
6101 */
6102 if (!mch_windows95())
6103 {
6104 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6105 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6106 return rename(pszOldFile, pszNewFile);
6107 }
6108
6109 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6110 * a directory, no error is returned and pszFilePart will be NULL. */
6111 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6112 || pszFilePart == NULL)
6113 return -1;
6114 *pszFilePart = NUL;
6115
6116 /* Get (and create) a unique temporary file name in directory of new file */
6117 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6118 return -2;
6119
6120 /* blow the temp file away */
6121 if (!DeleteFile(szTempFile))
6122 return -3;
6123
6124 /* rename old file to the temp file */
6125 if (!MoveFile(pszOldFile, szTempFile))
6126 return -4;
6127
6128 /* now create an empty file called pszOldFile; this prevents the operating
6129 * system using pszOldFile as an alias (SFN) if we're renaming within the
6130 * same directory. For example, we're editing a file called
6131 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6132 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6133 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006134 * cause all sorts of problems later in buf_write(). So, we create an
6135 * empty file called filena~1.txt and the system will have to find some
6136 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137 */
6138 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6139 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6140 return -5;
6141 if (!CloseHandle(hf))
6142 return -6;
6143
6144 /* rename the temp file to the new file */
6145 if (!MoveFile(szTempFile, pszNewFile))
6146 {
6147 /* Renaming failed. Rename the file back to its old name, so that it
6148 * looks like nothing happened. */
6149 (void)MoveFile(szTempFile, pszOldFile);
6150
6151 return -7;
6152 }
6153
6154 /* Seems to be left around on Novell filesystems */
6155 DeleteFile(szTempFile);
6156
6157 /* finally, remove the empty old file */
6158 if (!DeleteFile(pszOldFile))
6159 return -8;
6160
6161 return 0; /* success */
6162}
6163
6164/*
6165 * Get the default shell for the current hardware platform
6166 */
6167 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006168default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169{
6170 char* psz = NULL;
6171
6172 PlatformId();
6173
6174 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6175 psz = "cmd.exe";
6176 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6177 psz = "command.com";
6178
6179 return psz;
6180}
6181
6182/*
6183 * mch_access() extends access() to do more detailed check on network drives.
6184 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6185 */
6186 int
6187mch_access(char *n, int p)
6188{
6189 HANDLE hFile;
6190 DWORD am;
6191 int retval = -1; /* default: fail */
6192#ifdef FEAT_MBYTE
6193 WCHAR *wn = NULL;
6194
6195 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006196 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197#endif
6198
6199 if (mch_isdir(n))
6200 {
6201 char TempName[_MAX_PATH + 16] = "";
6202#ifdef FEAT_MBYTE
6203 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6204#endif
6205
6206 if (p & R_OK)
6207 {
6208 /* Read check is performed by seeing if we can do a find file on
6209 * the directory for any file. */
6210#ifdef FEAT_MBYTE
6211 if (wn != NULL)
6212 {
6213 int i;
6214 WIN32_FIND_DATAW d;
6215
6216 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6217 TempNameW[i] = wn[i];
6218 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6219 TempNameW[i++] = '\\';
6220 TempNameW[i++] = '*';
6221 TempNameW[i++] = 0;
6222
6223 hFile = FindFirstFileW(TempNameW, &d);
6224 if (hFile == INVALID_HANDLE_VALUE)
6225 {
6226 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6227 goto getout;
6228
6229 /* Retry with non-wide function (for Windows 98). */
6230 vim_free(wn);
6231 wn = NULL;
6232 }
6233 else
6234 (void)FindClose(hFile);
6235 }
6236 if (wn == NULL)
6237#endif
6238 {
6239 char *pch;
6240 WIN32_FIND_DATA d;
6241
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006242 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243 pch = TempName + STRLEN(TempName) - 1;
6244 if (*pch != '\\' && *pch != '/')
6245 *++pch = '\\';
6246 *++pch = '*';
6247 *++pch = NUL;
6248
6249 hFile = FindFirstFile(TempName, &d);
6250 if (hFile == INVALID_HANDLE_VALUE)
6251 goto getout;
6252 (void)FindClose(hFile);
6253 }
6254 }
6255
6256 if (p & W_OK)
6257 {
6258 /* Trying to create a temporary file in the directory should catch
6259 * directories on read-only network shares. However, in
6260 * directories whose ACL allows writes but denies deletes will end
6261 * up keeping the temporary file :-(. */
6262#ifdef FEAT_MBYTE
6263 if (wn != NULL)
6264 {
6265 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6266 {
6267 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6268 goto getout;
6269
6270 /* Retry with non-wide function (for Windows 98). */
6271 vim_free(wn);
6272 wn = NULL;
6273 }
6274 else
6275 DeleteFileW(TempNameW);
6276 }
6277 if (wn == NULL)
6278#endif
6279 {
6280 if (!GetTempFileName(n, "VIM", 0, TempName))
6281 goto getout;
6282 mch_remove((char_u *)TempName);
6283 }
6284 }
6285 }
6286 else
6287 {
6288 /* Trying to open the file for the required access does ACL, read-only
6289 * network share, and file attribute checks. */
6290 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6291 | ((p & R_OK) ? GENERIC_READ : 0);
6292#ifdef FEAT_MBYTE
6293 if (wn != NULL)
6294 {
6295 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6296 if (hFile == INVALID_HANDLE_VALUE
6297 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6298 {
6299 /* Retry with non-wide function (for Windows 98). */
6300 vim_free(wn);
6301 wn = NULL;
6302 }
6303 }
6304 if (wn == NULL)
6305#endif
6306 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6307 if (hFile == INVALID_HANDLE_VALUE)
6308 goto getout;
6309 CloseHandle(hFile);
6310 }
6311
6312 retval = 0; /* success */
6313getout:
6314#ifdef FEAT_MBYTE
6315 vim_free(wn);
6316#endif
6317 return retval;
6318}
6319
6320#if defined(FEAT_MBYTE) || defined(PROTO)
6321/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006322 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323 */
6324 int
6325mch_open(char *name, int flags, int mode)
6326{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006327 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6328# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 WCHAR *wn;
6330 int f;
6331
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006332 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006334 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335 if (wn != NULL)
6336 {
6337 f = _wopen(wn, flags, mode);
6338 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006339 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340 return f;
6341 /* Retry with non-wide function (for Windows 98). Can't use
6342 * GetLastError() here and it's unclear what errno gets set to if
6343 * the _wopen() fails for missing wide functions. */
6344 }
6345 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006346# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006348 /* open() can open a file which name is longer than _MAX_PATH bytes
6349 * and shorter than _MAX_PATH characters successfully, but sometimes it
6350 * causes unexpected error in another part. We make it an error explicitly
6351 * here. */
6352 if (strlen(name) >= _MAX_PATH)
6353 return -1;
6354
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 return open(name, flags, mode);
6356}
6357
6358/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006359 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360 */
6361 FILE *
6362mch_fopen(char *name, char *mode)
6363{
6364 WCHAR *wn, *wm;
6365 FILE *f = NULL;
6366
6367 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6368# ifdef __BORLANDC__
6369 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6370 && g_PlatformId == VER_PLATFORM_WIN32_NT
6371# endif
6372 )
6373 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006374# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006375 /* Work around an annoying assertion in the Microsoft debug CRT
6376 * when mode's text/binary setting doesn't match _get_fmode(). */
6377 char newMode = mode[strlen(mode) - 1];
6378 int oldMode = 0;
6379
6380 _get_fmode(&oldMode);
6381 if (newMode == 't')
6382 _set_fmode(_O_TEXT);
6383 else if (newMode == 'b')
6384 _set_fmode(_O_BINARY);
6385# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006386 wn = enc_to_utf16(name, NULL);
6387 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388 if (wn != NULL && wm != NULL)
6389 f = _wfopen(wn, wm);
6390 vim_free(wn);
6391 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006392
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006393# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006394 _set_fmode(oldMode);
6395# endif
6396
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006397 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006398 return f;
6399 /* Retry with non-wide function (for Windows 98). Can't use
6400 * GetLastError() here and it's unclear what errno gets set to if
6401 * the _wfopen() fails for missing wide functions. */
6402 }
6403
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006404 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6405 * and shorter than _MAX_PATH characters successfully, but sometimes it
6406 * causes unexpected error in another part. We make it an error explicitly
6407 * here. */
6408 if (strlen(name) >= _MAX_PATH)
6409 return NULL;
6410
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 return fopen(name, mode);
6412}
6413#endif
6414
6415#ifdef FEAT_MBYTE
6416/*
6417 * SUB STREAM (aka info stream) handling:
6418 *
6419 * NTFS can have sub streams for each file. Normal contents of file is
6420 * stored in the main stream, and extra contents (author information and
6421 * title and so on) can be stored in sub stream. After Windows 2000, user
6422 * can access and store those informations in sub streams via explorer's
6423 * property menuitem in right click menu. Those informations in sub streams
6424 * were lost when copying only the main stream. So we have to copy sub
6425 * streams.
6426 *
6427 * Incomplete explanation:
6428 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6429 * More useful info and an example:
6430 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6431 */
6432
6433/*
6434 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6435 * and write to stream "substream" of file "to".
6436 * Errors are ignored.
6437 */
6438 static void
6439copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6440{
6441 HANDLE hTo;
6442 WCHAR *to_name;
6443
6444 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6445 wcscpy(to_name, to);
6446 wcscat(to_name, substream);
6447
6448 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6449 FILE_ATTRIBUTE_NORMAL, NULL);
6450 if (hTo != INVALID_HANDLE_VALUE)
6451 {
6452 long done;
6453 DWORD todo;
6454 DWORD readcnt, written;
6455 char buf[4096];
6456
6457 /* Copy block of bytes at a time. Abort when something goes wrong. */
6458 for (done = 0; done < len; done += written)
6459 {
6460 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006461 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6462 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006463 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6464 FALSE, FALSE, context)
6465 || readcnt != todo
6466 || !WriteFile(hTo, buf, todo, &written, NULL)
6467 || written != todo)
6468 break;
6469 }
6470 CloseHandle(hTo);
6471 }
6472
6473 free(to_name);
6474}
6475
6476/*
6477 * Copy info streams from file "from" to file "to".
6478 */
6479 static void
6480copy_infostreams(char_u *from, char_u *to)
6481{
6482 WCHAR *fromw;
6483 WCHAR *tow;
6484 HANDLE sh;
6485 WIN32_STREAM_ID sid;
6486 int headersize;
6487 WCHAR streamname[_MAX_PATH];
6488 DWORD readcount;
6489 void *context = NULL;
6490 DWORD lo, hi;
6491 int len;
6492
6493 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006494 fromw = enc_to_utf16(from, NULL);
6495 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496 if (fromw != NULL && tow != NULL)
6497 {
6498 /* Open the file for reading. */
6499 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6500 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6501 if (sh != INVALID_HANDLE_VALUE)
6502 {
6503 /* Use BackupRead() to find the info streams. Repeat until we
6504 * have done them all.*/
6505 for (;;)
6506 {
6507 /* Get the header to find the length of the stream name. If
6508 * the "readcount" is zero we have done all info streams. */
6509 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006510 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6512 &readcount, FALSE, FALSE, &context)
6513 || readcount == 0)
6514 break;
6515
6516 /* We only deal with streams that have a name. The normal
6517 * file data appears to be without a name, even though docs
6518 * suggest it is called "::$DATA". */
6519 if (sid.dwStreamNameSize > 0)
6520 {
6521 /* Read the stream name. */
6522 if (!BackupRead(sh, (LPBYTE)streamname,
6523 sid.dwStreamNameSize,
6524 &readcount, FALSE, FALSE, &context))
6525 break;
6526
6527 /* Copy an info stream with a name ":anything:$DATA".
6528 * Skip "::$DATA", it has no stream name (examples suggest
6529 * it might be used for the normal file contents).
6530 * Note that BackupRead() counts bytes, but the name is in
6531 * wide characters. */
6532 len = readcount / sizeof(WCHAR);
6533 streamname[len] = 0;
6534 if (len > 7 && wcsicmp(streamname + len - 6,
6535 L":$DATA") == 0)
6536 {
6537 streamname[len - 6] = 0;
6538 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006539 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 }
6541 }
6542
6543 /* Advance to the next stream. We might try seeking too far,
6544 * but BackupSeek() doesn't skip over stream borders, thus
6545 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006546 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547 &lo, &hi, &context);
6548 }
6549
6550 /* Clear the context. */
6551 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6552
6553 CloseHandle(sh);
6554 }
6555 }
6556 vim_free(fromw);
6557 vim_free(tow);
6558}
6559#endif
6560
6561/*
6562 * Copy file attributes from file "from" to file "to".
6563 * For Windows NT and later we copy info streams.
6564 * Always returns zero, errors are ignored.
6565 */
6566 int
6567mch_copy_file_attribute(char_u *from, char_u *to)
6568{
6569#ifdef FEAT_MBYTE
6570 /* File streams only work on Windows NT and later. */
6571 PlatformId();
6572 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6573 copy_infostreams(from, to);
6574#endif
6575 return 0;
6576}
6577
6578#if defined(MYRESETSTKOFLW) || defined(PROTO)
6579/*
6580 * Recreate a destroyed stack guard page in win32.
6581 * Written by Benjamin Peterson.
6582 */
6583
6584/* These magic numbers are from the MS header files */
6585#define MIN_STACK_WIN9X 17
6586#define MIN_STACK_WINNT 2
6587
6588/*
6589 * This function does the same thing as _resetstkoflw(), which is only
6590 * available in DevStudio .net and later.
6591 * Returns 0 for failure, 1 for success.
6592 */
6593 int
6594myresetstkoflw(void)
6595{
6596 BYTE *pStackPtr;
6597 BYTE *pGuardPage;
6598 BYTE *pStackBase;
6599 BYTE *pLowestPossiblePage;
6600 MEMORY_BASIC_INFORMATION mbi;
6601 SYSTEM_INFO si;
6602 DWORD nPageSize;
6603 DWORD dummy;
6604
6605 /* This code will not work on win32s. */
6606 PlatformId();
6607 if (g_PlatformId == VER_PLATFORM_WIN32s)
6608 return 0;
6609
6610 /* We need to know the system page size. */
6611 GetSystemInfo(&si);
6612 nPageSize = si.dwPageSize;
6613
6614 /* ...and the current stack pointer */
6615 pStackPtr = (BYTE*)_alloca(1);
6616
6617 /* ...and the base of the stack. */
6618 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6619 return 0;
6620 pStackBase = (BYTE*)mbi.AllocationBase;
6621
6622 /* ...and the page thats min_stack_req pages away from stack base; this is
6623 * the lowest page we could use. */
6624 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6625 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6626
6627 /* On Win95, we want the next page down from the end of the stack. */
6628 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6629 {
6630 /* Find the page that's only 1 page down from the page that the stack
6631 * ptr is in. */
6632 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6633 / (DWORD)nPageSize) - 1));
6634 if (pGuardPage < pLowestPossiblePage)
6635 return 0;
6636
6637 /* Apply the noaccess attribute to the page -- there's no guard
6638 * attribute in win95-type OSes. */
6639 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6640 return 0;
6641 }
6642 else
6643 {
6644 /* On NT, however, we want the first committed page in the stack Start
6645 * at the stack base and move forward through memory until we find a
6646 * committed block. */
6647 BYTE *pBlock = pStackBase;
6648
Bram Moolenaara466c992005-07-09 21:03:22 +00006649 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650 {
6651 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6652 return 0;
6653
6654 pBlock += mbi.RegionSize;
6655
6656 if (mbi.State & MEM_COMMIT)
6657 break;
6658 }
6659
6660 /* mbi now describes the first committed block in the stack. */
6661 if (mbi.Protect & PAGE_GUARD)
6662 return 1;
6663
6664 /* decide where the guard page should start */
6665 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6666 pGuardPage = pLowestPossiblePage;
6667 else
6668 pGuardPage = (BYTE*)mbi.BaseAddress;
6669
6670 /* allocate the guard page */
6671 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6672 return 0;
6673
6674 /* apply the guard attribute to the page */
6675 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6676 &dummy))
6677 return 0;
6678 }
6679
6680 return 1;
6681}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006682#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006683
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006684
6685#if defined(FEAT_MBYTE) || defined(PROTO)
6686/*
6687 * The command line arguments in UCS2
6688 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006689static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006690static LPWSTR *ArglistW = NULL;
6691static int global_argc = 0;
6692static char **global_argv;
6693
6694static int used_file_argc = 0; /* last argument in global_argv[] used
6695 for the argument list. */
6696static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6697 command line arguments added to
6698 the argument list */
6699static int used_file_count = 0; /* nr of entries in used_file_indexes */
6700static int used_file_literal = FALSE; /* take file names literally */
6701static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006702static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006703static int used_alist_count = 0;
6704
6705
6706/*
6707 * Get the command line arguments. Unicode version.
6708 * Returns argc. Zero when something fails.
6709 */
6710 int
6711get_cmd_argsW(char ***argvp)
6712{
6713 char **argv = NULL;
6714 int argc = 0;
6715 int i;
6716
Bram Moolenaar14993322014-09-09 12:25:33 +02006717 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006718 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6719 if (ArglistW != NULL)
6720 {
6721 argv = malloc((nArgsW + 1) * sizeof(char *));
6722 if (argv != NULL)
6723 {
6724 argc = nArgsW;
6725 argv[argc] = NULL;
6726 for (i = 0; i < argc; ++i)
6727 {
6728 int len;
6729
6730 /* Convert each Unicode argument to the current codepage. */
6731 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006732 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006733 (LPSTR *)&argv[i], &len, 0, 0);
6734 if (argv[i] == NULL)
6735 {
6736 /* Out of memory, clear everything. */
6737 while (i > 0)
6738 free(argv[--i]);
6739 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006740 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006741 argc = 0;
6742 }
6743 }
6744 }
6745 }
6746
6747 global_argc = argc;
6748 global_argv = argv;
6749 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006750 {
6751 if (used_file_indexes != NULL)
6752 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006753 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006754 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006755
6756 if (argvp != NULL)
6757 *argvp = argv;
6758 return argc;
6759}
6760
6761 void
6762free_cmd_argsW(void)
6763{
6764 if (ArglistW != NULL)
6765 {
6766 GlobalFree(ArglistW);
6767 ArglistW = NULL;
6768 }
6769}
6770
6771/*
6772 * Remember "name" is an argument that was added to the argument list.
6773 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6774 * is called.
6775 */
6776 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006777used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006778{
6779 int i;
6780
6781 if (used_file_indexes == NULL)
6782 return;
6783 for (i = used_file_argc + 1; i < global_argc; ++i)
6784 if (STRCMP(global_argv[i], name) == 0)
6785 {
6786 used_file_argc = i;
6787 used_file_indexes[used_file_count++] = i;
6788 break;
6789 }
6790 used_file_literal = literal;
6791 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006792 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006793}
6794
6795/*
6796 * Remember the length of the argument list as it was. If it changes then we
6797 * leave it alone when 'encoding' is set.
6798 */
6799 void
6800set_alist_count(void)
6801{
6802 used_alist_count = GARGCOUNT;
6803}
6804
6805/*
6806 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6807 * has been changed while starting up. Use the UCS-2 command line arguments
6808 * and convert them to 'encoding'.
6809 */
6810 void
6811fix_arg_enc(void)
6812{
6813 int i;
6814 int idx;
6815 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006816 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006817
6818 /* Safety checks:
6819 * - if argument count differs between the wide and non-wide argument
6820 * list, something must be wrong.
6821 * - the file name arguments must have been located.
6822 * - the length of the argument list wasn't changed by the user.
6823 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006824 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006825 || ArglistW == NULL
6826 || used_file_indexes == NULL
6827 || used_file_count == 0
6828 || used_alist_count != GARGCOUNT)
6829 return;
6830
Bram Moolenaar86b68352004-12-27 21:59:20 +00006831 /* Remember the buffer numbers for the arguments. */
6832 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6833 if (fnum_list == NULL)
6834 return; /* out of memory */
6835 for (i = 0; i < GARGCOUNT; ++i)
6836 fnum_list[i] = GARGLIST[i].ae_fnum;
6837
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006838 /* Clear the argument list. Make room for the new arguments. */
6839 alist_clear(&global_alist);
6840 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006841 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006842
6843 for (i = 0; i < used_file_count; ++i)
6844 {
6845 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006846 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006847 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006848 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006849#ifdef FEAT_DIFF
6850 /* When using diff mode may need to concatenate file name to
6851 * directory name. Just like it's done in main(). */
6852 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6853 && !mch_isdir(alist_name(&GARGLIST[0])))
6854 {
6855 char_u *r;
6856
6857 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6858 if (r != NULL)
6859 {
6860 vim_free(str);
6861 str = r;
6862 }
6863 }
6864#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006865 /* Re-use the old buffer by renaming it. When not using literal
6866 * names it's done by alist_expand() below. */
6867 if (used_file_literal)
6868 buf_set_name(fnum_list[i], str);
6869
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006870 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006871 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006872 }
6873
6874 if (!used_file_literal)
6875 {
6876 /* Now expand wildcards in the arguments. */
6877 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6878 * filename characters but are excluded from 'isfname' to make
6879 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6880 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006881 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006882 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6883 }
6884
6885 /* If wildcard expansion failed, we are editing the first file of the
6886 * arglist and there is no file name: Edit the first argument now. */
6887 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6888 {
6889 do_cmdline_cmd((char_u *)":rewind");
6890 if (GARGCOUNT == 1 && used_file_full_path)
6891 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6892 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006893
6894 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006895}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896#endif