blob: fb136718842f65a8568ae385110760bd13dd6720 [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 Moolenaarca568ae2016-02-01 21:32:58 +01001464#ifdef MESSAGE_QUEUE
1465 parse_queued_messages();
1466#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001467#ifdef FEAT_MZSCHEME
1468 mzvim_check_threads();
1469#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470#ifdef FEAT_CLIENTSERVER
1471 serverProcessPendingMessages();
1472#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001473
1474#ifdef FEAT_CHANNEL
1475 FD_ZERO(&rfds);
1476 maxfd = channel_select_setup(-1, &rfds);
1477 if (maxfd >= 0)
1478 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001479 struct timeval tv;
1480
1481 tv.tv_sec = 0;
1482 tv.tv_usec = 0;
1483 ret = select(maxfd + 1, &rfds, NULL, NULL, &tv);
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001484 if (ret > 0 && channel_select_check(ret, &rfds) > 0)
1485 return TRUE;
1486 }
1487#endif
1488
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 if (0
1490#ifdef FEAT_MOUSE
1491 || g_nMouseClick != -1
1492#endif
1493#ifdef FEAT_CLIENTSERVER
1494 || input_available()
1495#endif
1496 )
1497 return TRUE;
1498
1499 if (msec > 0)
1500 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001501 /* If the specified wait time has passed, return. Beware that
1502 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001504 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505 break;
1506 }
1507 if (msec != 0)
1508 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001509 DWORD dwWaitTime = dwEndTime - dwNow;
1510
1511#ifdef FEAT_MZSCHEME
1512 if (mzthreads_allowed() && p_mzq > 0
1513 && (msec < 0 || (long)dwWaitTime > p_mzq))
1514 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1515#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516#ifdef FEAT_CLIENTSERVER
1517 /* Wait for either an event on the console input or a message in
1518 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001519 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001520 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001522 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523#endif
1524 continue;
1525 }
1526
1527 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001528 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529
1530#ifdef FEAT_MBYTE_IME
1531 if (State & CMDLINE && msg_row == Rows - 1)
1532 {
1533 CONSOLE_SCREEN_BUFFER_INFO csbi;
1534
1535 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1536 {
1537 if (csbi.dwCursorPosition.Y != msg_row)
1538 {
1539 /* The screen is now messed up, must redraw the
1540 * command line and later all the windows. */
1541 redraw_all_later(CLEAR);
1542 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1543 redrawcmd();
1544 }
1545 }
1546 }
1547#endif
1548
1549 if (cRecords > 0)
1550 {
1551 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1552 {
1553#ifdef FEAT_MBYTE_IME
1554 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1555 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001556 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1558 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001559 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 continue;
1561 }
1562#endif
1563 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1564 NULL, FALSE))
1565 return TRUE;
1566 }
1567
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001568 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569
1570 if (ir.EventType == FOCUS_EVENT)
1571 handle_focus_event(ir);
1572 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1573 shell_resized();
1574#ifdef FEAT_MOUSE
1575 else if (ir.EventType == MOUSE_EVENT
1576 && decode_mouse_event(&ir.Event.MouseEvent))
1577 return TRUE;
1578#endif
1579 }
1580 else if (msec == 0)
1581 break;
1582 }
1583
1584#ifdef FEAT_CLIENTSERVER
1585 /* Something might have been received while we were waiting. */
1586 if (input_available())
1587 return TRUE;
1588#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001589
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 return FALSE;
1591}
1592
1593#ifndef FEAT_GUI_MSWIN
1594/*
1595 * return non-zero if a character is available
1596 */
1597 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001598mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599{
1600 return WaitForChar(0L);
1601}
1602#endif
1603
1604/*
1605 * Create the console input. Used when reading stdin doesn't work.
1606 */
1607 static void
1608create_conin(void)
1609{
1610 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1611 FILE_SHARE_READ|FILE_SHARE_WRITE,
1612 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001613 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614 did_create_conin = TRUE;
1615}
1616
1617/*
1618 * Get a keystroke or a mouse event
1619 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001620 static WCHAR
1621tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001623 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624
1625 for (;;)
1626 {
1627 INPUT_RECORD ir;
1628 DWORD cRecords = 0;
1629
1630#ifdef FEAT_CLIENTSERVER
1631 (void)WaitForChar(-1L);
1632 if (input_available())
1633 return 0;
1634# ifdef FEAT_MOUSE
1635 if (g_nMouseClick != -1)
1636 return 0;
1637# endif
1638#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001639 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 {
1641 if (did_create_conin)
1642 read_error_exit();
1643 create_conin();
1644 continue;
1645 }
1646
1647 if (ir.EventType == KEY_EVENT)
1648 {
1649 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1650 pmodifiers, TRUE))
1651 return ch;
1652 }
1653 else if (ir.EventType == FOCUS_EVENT)
1654 handle_focus_event(ir);
1655 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1656 shell_resized();
1657#ifdef FEAT_MOUSE
1658 else if (ir.EventType == MOUSE_EVENT)
1659 {
1660 if (decode_mouse_event(&ir.Event.MouseEvent))
1661 return 0;
1662 }
1663#endif
1664 }
1665}
1666#endif /* !FEAT_GUI_W32 */
1667
1668
1669/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001670 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 * Get one or more characters from the keyboard or the mouse.
1672 * If time == 0, do not wait for characters.
1673 * If time == n, wait a short time for characters.
1674 * If time == -1, wait forever for characters.
1675 * Returns the number of characters read into buf.
1676 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001677/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678 int
1679mch_inchar(
1680 char_u *buf,
1681 int maxlen,
1682 long time,
1683 int tb_change_cnt)
1684{
1685#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1686
1687 int len;
1688 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689#define TYPEAHEADLEN 20
1690 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1691 static int typeaheadlen = 0;
1692
1693 /* First use any typeahead that was kept because "buf" was too small. */
1694 if (typeaheadlen > 0)
1695 goto theend;
1696
1697#ifdef FEAT_SNIFF
1698 if (want_sniff_request)
1699 {
1700 if (sniff_request_waiting)
1701 {
1702 /* return K_SNIFF */
1703 typeahead[typeaheadlen++] = CSI;
1704 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1705 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1706 sniff_request_waiting = 0;
1707 want_sniff_request = 0;
1708 goto theend;
1709 }
1710 else if (time < 0 || time > 250)
1711 {
1712 /* don't wait too long, a request might be pending */
1713 time = 250;
1714 }
1715 }
1716#endif
1717
1718 if (time >= 0)
1719 {
1720 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722 }
1723 else /* time == -1, wait forever */
1724 {
1725 mch_set_winsize_now(); /* Allow winsize changes from now on */
1726
Bram Moolenaar3918c952005-03-15 22:34:55 +00001727 /*
1728 * If there is no character available within 2 seconds (default)
1729 * write the autoscript file to disk. Or cause the CursorHold event
1730 * to be triggered.
1731 */
1732 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733 {
1734#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001735 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001736 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001737 buf[0] = K_SPECIAL;
1738 buf[1] = KS_EXTRA;
1739 buf[2] = (int)KE_CURSORHOLD;
1740 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001741 }
1742#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001743 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 }
1745 }
1746
1747 /*
1748 * Try to read as many characters as there are, until the buffer is full.
1749 */
1750
1751 /* we will get at least one key. Get more if they are available. */
1752 g_fCBrkPressed = FALSE;
1753
1754#ifdef MCH_WRITE_DUMP
1755 if (fdDump)
1756 fputc('[', fdDump);
1757#endif
1758
1759 /* Keep looping until there is something in the typeahead buffer and more
1760 * to get and still room in the buffer (up to two bytes for a char and
1761 * three bytes for a modifier). */
1762 while ((typeaheadlen == 0 || WaitForChar(0L))
1763 && typeaheadlen + 5 <= TYPEAHEADLEN)
1764 {
1765 if (typebuf_changed(tb_change_cnt))
1766 {
1767 /* "buf" may be invalid now if a client put something in the
1768 * typeahead buffer and "buf" is in the typeahead buffer. */
1769 typeaheadlen = 0;
1770 break;
1771 }
1772#ifdef FEAT_MOUSE
1773 if (g_nMouseClick != -1)
1774 {
1775# ifdef MCH_WRITE_DUMP
1776 if (fdDump)
1777 fprintf(fdDump, "{%02x @ %d, %d}",
1778 g_nMouseClick, g_xMouse, g_yMouse);
1779# endif
1780 typeahead[typeaheadlen++] = ESC + 128;
1781 typeahead[typeaheadlen++] = 'M';
1782 typeahead[typeaheadlen++] = g_nMouseClick;
1783 typeahead[typeaheadlen++] = g_xMouse + '!';
1784 typeahead[typeaheadlen++] = g_yMouse + '!';
1785 g_nMouseClick = -1;
1786 }
1787 else
1788#endif
1789 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001790 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 int modifiers = 0;
1792
1793 c = tgetch(&modifiers, &ch2);
1794
1795 if (typebuf_changed(tb_change_cnt))
1796 {
1797 /* "buf" may be invalid now if a client put something in the
1798 * typeahead buffer and "buf" is in the typeahead buffer. */
1799 typeaheadlen = 0;
1800 break;
1801 }
1802
1803 if (c == Ctrl_C && ctrl_c_interrupts)
1804 {
1805#if defined(FEAT_CLIENTSERVER)
1806 trash_input_buf();
1807#endif
1808 got_int = TRUE;
1809 }
1810
1811#ifdef FEAT_MOUSE
1812 if (g_nMouseClick == -1)
1813#endif
1814 {
1815 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001816 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001818#ifdef FEAT_MBYTE
1819 if (ch2 == NUL)
1820 {
1821 int i;
1822 char_u *p;
1823 WCHAR ch[2];
1824
1825 ch[0] = c;
1826 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1827 {
1828 ch[1] = tgetch(&modifiers, &ch2);
1829 n++;
1830 }
1831 p = utf16_to_enc(ch, &n);
1832 if (p != NULL)
1833 {
1834 for (i = 0; i < n; i++)
1835 typeahead[typeaheadlen + i] = p[i];
1836 vim_free(p);
1837 }
1838 }
1839 else
1840#endif
1841 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001842 if (ch2 != NUL)
1843 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001844 typeahead[typeaheadlen + n] = 3;
1845 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001846 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001848
Bram Moolenaar45500912014-07-09 20:51:07 +02001849 if (conv)
1850 {
1851 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001852
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001853 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001854 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001855 char_u *e = typeahead + TYPEAHEADLEN;
1856
1857 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001858 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001859 if (*p == K_NUL)
1860 {
1861 ++p;
1862 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1863 *p = 3;
1864 ++n;
1865 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001866 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001867 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001868 }
1869 }
1870
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871 /* Use the ALT key to set the 8th bit of the character
1872 * when it's one byte, the 8th bit isn't set yet and not
1873 * using a double-byte encoding (would become a lead
1874 * byte). */
1875 if ((modifiers & MOD_MASK_ALT)
1876 && n == 1
1877 && (typeahead[typeaheadlen] & 0x80) == 0
1878#ifdef FEAT_MBYTE
1879 && !enc_dbcs
1880#endif
1881 )
1882 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001883#ifdef FEAT_MBYTE
1884 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1885 typeahead + typeaheadlen);
1886#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001888#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 modifiers &= ~MOD_MASK_ALT;
1890 }
1891
1892 if (modifiers != 0)
1893 {
1894 /* Prepend modifiers to the character. */
1895 mch_memmove(typeahead + typeaheadlen + 3,
1896 typeahead + typeaheadlen, n);
1897 typeahead[typeaheadlen++] = K_SPECIAL;
1898 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1899 typeahead[typeaheadlen++] = modifiers;
1900 }
1901
1902 typeaheadlen += n;
1903
1904#ifdef MCH_WRITE_DUMP
1905 if (fdDump)
1906 fputc(c, fdDump);
1907#endif
1908 }
1909 }
1910 }
1911
1912#ifdef MCH_WRITE_DUMP
1913 if (fdDump)
1914 {
1915 fputs("]\n", fdDump);
1916 fflush(fdDump);
1917 }
1918#endif
1919
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920theend:
1921 /* Move typeahead to "buf", as much as fits. */
1922 len = 0;
1923 while (len < maxlen && typeaheadlen > 0)
1924 {
1925 buf[len++] = typeahead[0];
1926 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1927 }
1928 return len;
1929
1930#else /* FEAT_GUI_W32 */
1931 return 0;
1932#endif /* FEAT_GUI_W32 */
1933}
1934
Bram Moolenaar82881492012-11-20 16:53:39 +01001935#ifndef PROTO
1936# ifndef __MINGW32__
1937# include <shellapi.h> /* required for FindExecutable() */
1938# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939#endif
1940
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001941/*
1942 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001943 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001944 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001946executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001948 char *dum;
1949 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001950 char *curpath, *newpath;
1951 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001953#ifdef FEAT_MBYTE
1954 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001956 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001957 WCHAR fnamew[_MAX_PATH];
1958 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001959 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001960
1961 if (p != NULL)
1962 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001963 wcurpath = _wgetenv(L"PATH");
1964 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1965 * sizeof(WCHAR));
1966 if (wnewpath == NULL)
1967 return FALSE;
1968 wcscpy(wnewpath, L".;");
1969 wcscat(wnewpath, wcurpath);
1970 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1971 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001972 vim_free(p);
1973 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1974 {
1975 if (n == 0)
1976 return FALSE;
1977 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1978 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001979 if (path != NULL)
1980 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001981 return TRUE;
1982 }
1983 /* Retry with non-wide function (for Windows 98). */
1984 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001986#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001987
1988 curpath = getenv("PATH");
1989 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1990 if (newpath == NULL)
1991 return FALSE;
1992 STRCPY(newpath, ".;");
1993 STRCAT(newpath, curpath);
1994 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1995 vim_free(newpath);
1996 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001997 return FALSE;
1998 if (mch_isdir(fname))
1999 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002000 if (path != NULL)
2001 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002002 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003}
2004
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002005#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002006 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002007/*
2008 * Bad parameter handler.
2009 *
2010 * Certain MS CRT functions will intentionally crash when passed invalid
2011 * parameters to highlight possible security holes. Setting this function as
2012 * the bad parameter handler will prevent the crash.
2013 *
2014 * In debug builds the parameters contain CRT information that might help track
2015 * down the source of a problem, but in non-debug builds the arguments are all
2016 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2017 * worth allowing these to make debugging of issues easier.
2018 */
2019 static void
2020bad_param_handler(const wchar_t *expression,
2021 const wchar_t *function,
2022 const wchar_t *file,
2023 unsigned int line,
2024 uintptr_t pReserved)
2025{
2026}
2027
2028# define SET_INVALID_PARAM_HANDLER \
2029 ((void)_set_invalid_parameter_handler(bad_param_handler))
2030#else
2031# define SET_INVALID_PARAM_HANDLER
2032#endif
2033
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034#ifdef FEAT_GUI_W32
2035
2036/*
2037 * GUI version of mch_init().
2038 */
2039 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002040mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041{
2042#ifndef __MINGW32__
2043 extern int _fmode;
2044#endif
2045
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002046 /* Silently handle invalid parameters to CRT functions */
2047 SET_INVALID_PARAM_HANDLER;
2048
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 /* Let critical errors result in a failure, not in a dialog box. Required
2050 * for the timestamp test to work on removed floppies. */
2051 SetErrorMode(SEM_FAILCRITICALERRORS);
2052
2053 _fmode = O_BINARY; /* we do our own CR-LF translation */
2054
2055 /* Specify window size. Is there a place to get the default from? */
2056 Rows = 25;
2057 Columns = 80;
2058
2059 /* Look for 'vimrun' */
2060 if (!gui_is_win32s())
2061 {
2062 char_u vimrun_location[_MAX_PATH + 4];
2063
2064 /* First try in same directory as gvim.exe */
2065 STRCPY(vimrun_location, exe_name);
2066 STRCPY(gettail(vimrun_location), "vimrun.exe");
2067 if (mch_getperm(vimrun_location) >= 0)
2068 {
2069 if (*skiptowhite(vimrun_location) != NUL)
2070 {
2071 /* Enclose path with white space in double quotes. */
2072 mch_memmove(vimrun_location + 1, vimrun_location,
2073 STRLEN(vimrun_location) + 1);
2074 *vimrun_location = '"';
2075 STRCPY(gettail(vimrun_location), "vimrun\" ");
2076 }
2077 else
2078 STRCPY(gettail(vimrun_location), "vimrun ");
2079
2080 vimrun_path = (char *)vim_strsave(vimrun_location);
2081 s_dont_use_vimrun = FALSE;
2082 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002083 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002084 s_dont_use_vimrun = FALSE;
2085
2086 /* Don't give the warning for a missing vimrun.exe right now, but only
2087 * when vimrun was supposed to be used. Don't bother people that do
2088 * not need vimrun.exe. */
2089 if (s_dont_use_vimrun)
2090 need_vimrun_warning = TRUE;
2091 }
2092
2093 /*
2094 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2095 * Otherwise the default "findstr /n" is used.
2096 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002097 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002098 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2099
2100#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002101 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002102#endif
2103}
2104
2105
2106#else /* FEAT_GUI_W32 */
2107
2108#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2109#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2110
2111/*
2112 * ClearConsoleBuffer()
2113 * Description:
2114 * Clears the entire contents of the console screen buffer, using the
2115 * specified attribute.
2116 * Returns:
2117 * TRUE on success
2118 */
2119 static BOOL
2120ClearConsoleBuffer(WORD wAttribute)
2121{
2122 CONSOLE_SCREEN_BUFFER_INFO csbi;
2123 COORD coord;
2124 DWORD NumCells, dummy;
2125
2126 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2127 return FALSE;
2128
2129 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2130 coord.X = 0;
2131 coord.Y = 0;
2132 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2133 coord, &dummy))
2134 {
2135 return FALSE;
2136 }
2137 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2138 coord, &dummy))
2139 {
2140 return FALSE;
2141 }
2142
2143 return TRUE;
2144}
2145
2146/*
2147 * FitConsoleWindow()
2148 * Description:
2149 * Checks if the console window will fit within given buffer dimensions.
2150 * Also, if requested, will shrink the window to fit.
2151 * Returns:
2152 * TRUE on success
2153 */
2154 static BOOL
2155FitConsoleWindow(
2156 COORD dwBufferSize,
2157 BOOL WantAdjust)
2158{
2159 CONSOLE_SCREEN_BUFFER_INFO csbi;
2160 COORD dwWindowSize;
2161 BOOL NeedAdjust = FALSE;
2162
2163 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2164 {
2165 /*
2166 * A buffer resize will fail if the current console window does
2167 * not lie completely within that buffer. To avoid this, we might
2168 * have to move and possibly shrink the window.
2169 */
2170 if (csbi.srWindow.Right >= dwBufferSize.X)
2171 {
2172 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2173 if (dwWindowSize.X > dwBufferSize.X)
2174 dwWindowSize.X = dwBufferSize.X;
2175 csbi.srWindow.Right = dwBufferSize.X - 1;
2176 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2177 NeedAdjust = TRUE;
2178 }
2179 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2180 {
2181 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2182 if (dwWindowSize.Y > dwBufferSize.Y)
2183 dwWindowSize.Y = dwBufferSize.Y;
2184 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2185 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2186 NeedAdjust = TRUE;
2187 }
2188 if (NeedAdjust && WantAdjust)
2189 {
2190 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2191 return FALSE;
2192 }
2193 return TRUE;
2194 }
2195
2196 return FALSE;
2197}
2198
2199typedef struct ConsoleBufferStruct
2200{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002201 BOOL IsValid;
2202 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002203 PCHAR_INFO Buffer;
2204 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205} ConsoleBuffer;
2206
2207/*
2208 * SaveConsoleBuffer()
2209 * Description:
2210 * Saves important information about the console buffer, including the
2211 * actual buffer contents. The saved information is suitable for later
2212 * restoration by RestoreConsoleBuffer().
2213 * Returns:
2214 * TRUE if all information was saved; FALSE otherwise
2215 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2216 */
2217 static BOOL
2218SaveConsoleBuffer(
2219 ConsoleBuffer *cb)
2220{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002221 DWORD NumCells;
2222 COORD BufferCoord;
2223 SMALL_RECT ReadRegion;
2224 WORD Y, Y_incr;
2225
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226 if (cb == NULL)
2227 return FALSE;
2228
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002229 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 {
2231 cb->IsValid = FALSE;
2232 return FALSE;
2233 }
2234 cb->IsValid = TRUE;
2235
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002236 /*
2237 * Allocate a buffer large enough to hold the entire console screen
2238 * buffer. If this ConsoleBuffer structure has already been initialized
2239 * with a buffer of the correct size, then just use that one.
2240 */
2241 if (!cb->IsValid || cb->Buffer == NULL ||
2242 cb->BufferSize.X != cb->Info.dwSize.X ||
2243 cb->BufferSize.Y != cb->Info.dwSize.Y)
2244 {
2245 cb->BufferSize.X = cb->Info.dwSize.X;
2246 cb->BufferSize.Y = cb->Info.dwSize.Y;
2247 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2248 vim_free(cb->Buffer);
2249 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2250 if (cb->Buffer == NULL)
2251 return FALSE;
2252 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002253
2254 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002255 * We will now copy the console screen buffer into our buffer.
2256 * ReadConsoleOutput() seems to be limited as far as how much you
2257 * can read at a time. Empirically, this number seems to be about
2258 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2259 * in chunks until it is all copied. The chunks will all have the
2260 * same horizontal characteristics, so initialize them now. The
2261 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002263 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002264 ReadRegion.Left = 0;
2265 ReadRegion.Right = cb->Info.dwSize.X - 1;
2266 Y_incr = 12000 / cb->Info.dwSize.X;
2267 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002269 /*
2270 * Read into position (0, Y) in our buffer.
2271 */
2272 BufferCoord.Y = Y;
2273 /*
2274 * Read the region whose top left corner is (0, Y) and whose bottom
2275 * right corner is (width - 1, Y + Y_incr - 1). This should define
2276 * a region of size width by Y_incr. Don't worry if this region is
2277 * too large for the remaining buffer; it will be cropped.
2278 */
2279 ReadRegion.Top = Y;
2280 ReadRegion.Bottom = Y + Y_incr - 1;
2281 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2282 cb->Buffer, /* our buffer */
2283 cb->BufferSize, /* dimensions of our buffer */
2284 BufferCoord, /* offset in our buffer */
2285 &ReadRegion)) /* region to save */
2286 {
2287 vim_free(cb->Buffer);
2288 cb->Buffer = NULL;
2289 return FALSE;
2290 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002291 }
2292
2293 return TRUE;
2294}
2295
2296/*
2297 * RestoreConsoleBuffer()
2298 * Description:
2299 * Restores important information about the console buffer, including the
2300 * actual buffer contents, if desired. The information to restore is in
2301 * the same format used by SaveConsoleBuffer().
2302 * Returns:
2303 * TRUE on success
2304 */
2305 static BOOL
2306RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002307 ConsoleBuffer *cb,
2308 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002309{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002310 COORD BufferCoord;
2311 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312
2313 if (cb == NULL || !cb->IsValid)
2314 return FALSE;
2315
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002316 /*
2317 * Before restoring the buffer contents, clear the current buffer, and
2318 * restore the cursor position and window information. Doing this now
2319 * prevents old buffer contents from "flashing" onto the screen.
2320 */
2321 if (RestoreScreen)
2322 ClearConsoleBuffer(cb->Info.wAttributes);
2323
2324 FitConsoleWindow(cb->Info.dwSize, TRUE);
2325 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2326 return FALSE;
2327 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2328 return FALSE;
2329
2330 if (!RestoreScreen)
2331 {
2332 /*
2333 * No need to restore the screen buffer contents, so we're done.
2334 */
2335 return TRUE;
2336 }
2337
2338 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2339 return FALSE;
2340 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2341 return FALSE;
2342
2343 /*
2344 * Restore the screen buffer contents.
2345 */
2346 if (cb->Buffer != NULL)
2347 {
2348 BufferCoord.X = 0;
2349 BufferCoord.Y = 0;
2350 WriteRegion.Left = 0;
2351 WriteRegion.Top = 0;
2352 WriteRegion.Right = cb->Info.dwSize.X - 1;
2353 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2354 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2355 cb->Buffer, /* our buffer */
2356 cb->BufferSize, /* dimensions of our buffer */
2357 BufferCoord, /* offset in our buffer */
2358 &WriteRegion)) /* region to restore */
2359 {
2360 return FALSE;
2361 }
2362 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363
2364 return TRUE;
2365}
2366
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002367#define FEAT_RESTORE_ORIG_SCREEN
2368#ifdef FEAT_RESTORE_ORIG_SCREEN
2369static ConsoleBuffer g_cbOrig = { 0 };
2370#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371static ConsoleBuffer g_cbNonTermcap = { 0 };
2372static ConsoleBuffer g_cbTermcap = { 0 };
2373
2374#ifdef FEAT_TITLE
2375#ifdef __BORLANDC__
2376typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2377#else
2378typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2379#endif
2380char g_szOrigTitle[256] = { 0 };
2381HWND g_hWnd = NULL; /* also used in os_mswin.c */
2382static HICON g_hOrigIconSmall = NULL;
2383static HICON g_hOrigIcon = NULL;
2384static HICON g_hVimIcon = NULL;
2385static BOOL g_fCanChangeIcon = FALSE;
2386
2387/* ICON* are not defined in VC++ 4.0 */
2388#ifndef ICON_SMALL
2389#define ICON_SMALL 0
2390#endif
2391#ifndef ICON_BIG
2392#define ICON_BIG 1
2393#endif
2394/*
2395 * GetConsoleIcon()
2396 * Description:
2397 * Attempts to retrieve the small icon and/or the big icon currently in
2398 * use by a given window.
2399 * Returns:
2400 * TRUE on success
2401 */
2402 static BOOL
2403GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002404 HWND hWnd,
2405 HICON *phIconSmall,
2406 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407{
2408 if (hWnd == NULL)
2409 return FALSE;
2410
2411 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002412 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2413 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002415 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2416 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417 return TRUE;
2418}
2419
2420/*
2421 * SetConsoleIcon()
2422 * Description:
2423 * Attempts to change the small icon and/or the big icon currently in
2424 * use by a given window.
2425 * Returns:
2426 * TRUE on success
2427 */
2428 static BOOL
2429SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002430 HWND hWnd,
2431 HICON hIconSmall,
2432 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002434 HICON hPrevIconSmall;
2435 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436
2437 if (hWnd == NULL)
2438 return FALSE;
2439
2440 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002441 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2442 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002444 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2445 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 return TRUE;
2447}
2448
2449/*
2450 * SaveConsoleTitleAndIcon()
2451 * Description:
2452 * Saves the current console window title in g_szOrigTitle, for later
2453 * restoration. Also, attempts to obtain a handle to the console window,
2454 * and use it to save the small and big icons currently in use by the
2455 * console window. This is not always possible on some versions of Windows;
2456 * nor is it possible when running Vim remotely using Telnet (since the
2457 * console window the user sees is owned by a remote process).
2458 */
2459 static void
2460SaveConsoleTitleAndIcon(void)
2461{
2462 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2463
2464 /* Save the original title. */
2465 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2466 return;
2467
2468 /*
2469 * Obtain a handle to the console window using GetConsoleWindow() from
2470 * KERNEL32.DLL; we need to handle in order to change the window icon.
2471 * This function only exists on NT-based Windows, starting with Windows
2472 * 2000. On older operating systems, we can't change the window icon
2473 * anyway.
2474 */
2475 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2476 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2477 "GetConsoleWindow")) != NULL)
2478 {
2479 g_hWnd = (*GetConsoleWindowProc)();
2480 }
2481 if (g_hWnd == NULL)
2482 return;
2483
2484 /* Save the original console window icon. */
2485 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2486 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2487 return;
2488
2489 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002490 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2491 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 if (g_hVimIcon != NULL)
2493 g_fCanChangeIcon = TRUE;
2494}
2495#endif
2496
2497static int g_fWindInitCalled = FALSE;
2498static int g_fTermcapMode = FALSE;
2499static CONSOLE_CURSOR_INFO g_cci;
2500static DWORD g_cmodein = 0;
2501static DWORD g_cmodeout = 0;
2502
2503/*
2504 * non-GUI version of mch_init().
2505 */
2506 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002507mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002509#ifndef FEAT_RESTORE_ORIG_SCREEN
2510 CONSOLE_SCREEN_BUFFER_INFO csbi;
2511#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512#ifndef __MINGW32__
2513 extern int _fmode;
2514#endif
2515
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002516 /* Silently handle invalid parameters to CRT functions */
2517 SET_INVALID_PARAM_HANDLER;
2518
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 /* Let critical errors result in a failure, not in a dialog box. Required
2520 * for the timestamp test to work on removed floppies. */
2521 SetErrorMode(SEM_FAILCRITICALERRORS);
2522
2523 _fmode = O_BINARY; /* we do our own CR-LF translation */
2524 out_flush();
2525
2526 /* Obtain handles for the standard Console I/O devices */
2527 if (read_cmd_fd == 0)
2528 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2529 else
2530 create_conin();
2531 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2532
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002533#ifdef FEAT_RESTORE_ORIG_SCREEN
2534 /* Save the initial console buffer for later restoration */
2535 SaveConsoleBuffer(&g_cbOrig);
2536 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2537#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002538 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002539 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2540 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2541#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 if (cterm_normal_fg_color == 0)
2543 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2544 if (cterm_normal_bg_color == 0)
2545 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2546
2547 /* set termcap codes to current text attributes */
2548 update_tcap(g_attrCurrent);
2549
2550 GetConsoleCursorInfo(g_hConOut, &g_cci);
2551 GetConsoleMode(g_hConIn, &g_cmodein);
2552 GetConsoleMode(g_hConOut, &g_cmodeout);
2553
2554#ifdef FEAT_TITLE
2555 SaveConsoleTitleAndIcon();
2556 /*
2557 * Set both the small and big icons of the console window to Vim's icon.
2558 * Note that Vim presently only has one size of icon (32x32), but it
2559 * automatically gets scaled down to 16x16 when setting the small icon.
2560 */
2561 if (g_fCanChangeIcon)
2562 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2563#endif
2564
2565 ui_get_shellsize();
2566
2567#ifdef MCH_WRITE_DUMP
2568 fdDump = fopen("dump", "wt");
2569
2570 if (fdDump)
2571 {
2572 time_t t;
2573
2574 time(&t);
2575 fputs(ctime(&t), fdDump);
2576 fflush(fdDump);
2577 }
2578#endif
2579
2580 g_fWindInitCalled = TRUE;
2581
2582#ifdef FEAT_MOUSE
2583 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2584#endif
2585
2586#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002587 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588#endif
2589
2590 /* This will be NULL on anything but NT 4.0 */
2591 s_pfnGetConsoleKeyboardLayoutName =
2592 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2593 "GetConsoleKeyboardLayoutNameA");
2594}
2595
2596/*
2597 * non-GUI version of mch_exit().
2598 * Shut down and exit with status `r'
2599 * Careful: mch_exit() may be called before mch_init()!
2600 */
2601 void
2602mch_exit(int r)
2603{
2604 stoptermcap();
2605
2606 if (g_fWindInitCalled)
2607 settmode(TMODE_COOK);
2608
2609 ml_close_all(TRUE); /* remove all memfiles */
2610
2611 if (g_fWindInitCalled)
2612 {
2613#ifdef FEAT_TITLE
2614 mch_restore_title(3);
2615 /*
2616 * Restore both the small and big icons of the console window to
2617 * what they were at startup. Don't do this when the window is
2618 * closed, Vim would hang here.
2619 */
2620 if (g_fCanChangeIcon && !g_fForceExit)
2621 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2622#endif
2623
2624#ifdef MCH_WRITE_DUMP
2625 if (fdDump)
2626 {
2627 time_t t;
2628
2629 time(&t);
2630 fputs(ctime(&t), fdDump);
2631 fclose(fdDump);
2632 }
2633 fdDump = NULL;
2634#endif
2635 }
2636
2637 SetConsoleCursorInfo(g_hConOut, &g_cci);
2638 SetConsoleMode(g_hConIn, g_cmodein);
2639 SetConsoleMode(g_hConOut, g_cmodeout);
2640
2641#ifdef DYNAMIC_GETTEXT
2642 dyn_libintl_end();
2643#endif
2644
2645 exit(r);
2646}
2647#endif /* !FEAT_GUI_W32 */
2648
Bram Moolenaar071d4272004-06-13 20:20:40 +00002649/*
2650 * Do we have an interactive window?
2651 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002652/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653 int
2654mch_check_win(
2655 int argc,
2656 char **argv)
2657{
2658 get_exe_name();
2659
2660#ifdef FEAT_GUI_W32
2661 return OK; /* GUI always has a tty */
2662#else
2663 if (isatty(1))
2664 return OK;
2665 return FAIL;
2666#endif
2667}
2668
2669
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002670#ifdef FEAT_MBYTE
2671/*
2672 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2673 * if it already exists. When "len" is > 0, also expand short to long
2674 * filenames.
2675 * Return FAIL if wide functions are not available, OK otherwise.
2676 * NOTE: much of this is identical to fname_case(), keep in sync!
2677 */
2678 static int
2679fname_casew(
2680 WCHAR *name,
2681 int len)
2682{
2683 WCHAR szTrueName[_MAX_PATH + 2];
2684 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2685 WCHAR *ptrue, *ptruePrev;
2686 WCHAR *porig, *porigPrev;
2687 int flen;
2688 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002689 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002690 int c;
2691 int slen;
2692
2693 flen = (int)wcslen(name);
2694 if (flen > _MAX_PATH)
2695 return OK;
2696
2697 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2698
2699 /* Build the new name in szTrueName[] one component at a time. */
2700 porig = name;
2701 ptrue = szTrueName;
2702
2703 if (iswalpha(porig[0]) && porig[1] == L':')
2704 {
2705 /* copy leading drive letter */
2706 *ptrue++ = *porig++;
2707 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002708 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002709 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002710
2711 while (*porig != NUL)
2712 {
2713 /* copy \ characters */
2714 while (*porig == psepc)
2715 *ptrue++ = *porig++;
2716
2717 ptruePrev = ptrue;
2718 porigPrev = porig;
2719 while (*porig != NUL && *porig != psepc)
2720 {
2721 *ptrue++ = *porig++;
2722 }
2723 *ptrue = NUL;
2724
2725 /* To avoid a slow failure append "\*" when searching a directory,
2726 * server or network share. */
2727 wcscpy(szTrueNameTemp, szTrueName);
2728 slen = (int)wcslen(szTrueNameTemp);
2729 if (*porig == psepc && slen + 2 < _MAX_PATH)
2730 wcscpy(szTrueNameTemp + slen, L"\\*");
2731
2732 /* Skip "", "." and "..". */
2733 if (ptrue > ptruePrev
2734 && (ptruePrev[0] != L'.'
2735 || (ptruePrev[1] != NUL
2736 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2737 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2738 != INVALID_HANDLE_VALUE)
2739 {
2740 c = *porig;
2741 *porig = NUL;
2742
2743 /* Only use the match when it's the same name (ignoring case) or
2744 * expansion is allowed and there is a match with the short name
2745 * and there is enough room. */
2746 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2747 || (len > 0
2748 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2749 && (int)(ptruePrev - szTrueName)
2750 + (int)wcslen(fb.cFileName) < len)))
2751 {
2752 wcscpy(ptruePrev, fb.cFileName);
2753
2754 /* Look for exact match and prefer it if found. Must be a
2755 * long name, otherwise there would be only one match. */
2756 while (FindNextFileW(hFind, &fb))
2757 {
2758 if (*fb.cAlternateFileName != NUL
2759 && (wcscoll(porigPrev, fb.cFileName) == 0
2760 || (len > 0
2761 && (_wcsicoll(porigPrev,
2762 fb.cAlternateFileName) == 0
2763 && (int)(ptruePrev - szTrueName)
2764 + (int)wcslen(fb.cFileName) < len))))
2765 {
2766 wcscpy(ptruePrev, fb.cFileName);
2767 break;
2768 }
2769 }
2770 }
2771 FindClose(hFind);
2772 *porig = c;
2773 ptrue = ptruePrev + wcslen(ptruePrev);
2774 }
2775 else if (hFind == INVALID_HANDLE_VALUE
2776 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2777 return FAIL;
2778 }
2779
2780 wcscpy(name, szTrueName);
2781 return OK;
2782}
2783#endif
2784
Bram Moolenaar071d4272004-06-13 20:20:40 +00002785/*
2786 * fname_case(): Set the case of the file name, if it already exists.
2787 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002788 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789 */
2790 void
2791fname_case(
2792 char_u *name,
2793 int len)
2794{
2795 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002796 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797 char *ptrue, *ptruePrev;
2798 char *porig, *porigPrev;
2799 int flen;
2800 WIN32_FIND_DATA fb;
2801 HANDLE hFind;
2802 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002803 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002804
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002805 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002806 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807 return;
2808
2809 slash_adjust(name);
2810
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002811#ifdef FEAT_MBYTE
2812 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2813 {
2814 WCHAR *p = enc_to_utf16(name, NULL);
2815
2816 if (p != NULL)
2817 {
2818 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002819 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002820
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002821 wcsncpy(buf, p, _MAX_PATH);
2822 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002823 vim_free(p);
2824
2825 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2826 {
2827 q = utf16_to_enc(buf, NULL);
2828 if (q != NULL)
2829 {
2830 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2831 vim_free(q);
2832 return;
2833 }
2834 }
2835 }
2836 /* Retry with non-wide function (for Windows 98). */
2837 }
2838#endif
2839
2840 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2841 * So we should check this after calling wide function. */
2842 if (flen > _MAX_PATH)
2843 return;
2844
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845 /* Build the new name in szTrueName[] one component at a time. */
2846 porig = name;
2847 ptrue = szTrueName;
2848
2849 if (isalpha(porig[0]) && porig[1] == ':')
2850 {
2851 /* copy leading drive letter */
2852 *ptrue++ = *porig++;
2853 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002855 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856
2857 while (*porig != NUL)
2858 {
2859 /* copy \ characters */
2860 while (*porig == psepc)
2861 *ptrue++ = *porig++;
2862
2863 ptruePrev = ptrue;
2864 porigPrev = porig;
2865 while (*porig != NUL && *porig != psepc)
2866 {
2867#ifdef FEAT_MBYTE
2868 int l;
2869
2870 if (enc_dbcs)
2871 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002872 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 while (--l >= 0)
2874 *ptrue++ = *porig++;
2875 }
2876 else
2877#endif
2878 *ptrue++ = *porig++;
2879 }
2880 *ptrue = NUL;
2881
Bram Moolenaar464c9252010-10-13 20:37:41 +02002882 /* To avoid a slow failure append "\*" when searching a directory,
2883 * server or network share. */
2884 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002885 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002886 if (*porig == psepc && slen + 2 < _MAX_PATH)
2887 STRCPY(szTrueNameTemp + slen, "\\*");
2888
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889 /* Skip "", "." and "..". */
2890 if (ptrue > ptruePrev
2891 && (ptruePrev[0] != '.'
2892 || (ptruePrev[1] != NUL
2893 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002894 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895 != INVALID_HANDLE_VALUE)
2896 {
2897 c = *porig;
2898 *porig = NUL;
2899
2900 /* Only use the match when it's the same name (ignoring case) or
2901 * expansion is allowed and there is a match with the short name
2902 * and there is enough room. */
2903 if (_stricoll(porigPrev, fb.cFileName) == 0
2904 || (len > 0
2905 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2906 && (int)(ptruePrev - szTrueName)
2907 + (int)strlen(fb.cFileName) < len)))
2908 {
2909 STRCPY(ptruePrev, fb.cFileName);
2910
2911 /* Look for exact match and prefer it if found. Must be a
2912 * long name, otherwise there would be only one match. */
2913 while (FindNextFile(hFind, &fb))
2914 {
2915 if (*fb.cAlternateFileName != NUL
2916 && (strcoll(porigPrev, fb.cFileName) == 0
2917 || (len > 0
2918 && (_stricoll(porigPrev,
2919 fb.cAlternateFileName) == 0
2920 && (int)(ptruePrev - szTrueName)
2921 + (int)strlen(fb.cFileName) < len))))
2922 {
2923 STRCPY(ptruePrev, fb.cFileName);
2924 break;
2925 }
2926 }
2927 }
2928 FindClose(hFind);
2929 *porig = c;
2930 ptrue = ptruePrev + strlen(ptruePrev);
2931 }
2932 }
2933
2934 STRCPY(name, szTrueName);
2935}
2936
2937
2938/*
2939 * Insert user name in s[len].
2940 */
2941 int
2942mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002943 char_u *s,
2944 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002946 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 DWORD cch = sizeof szUserName;
2948
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002949#ifdef FEAT_MBYTE
2950 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2951 {
2952 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2953 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2954
2955 if (GetUserNameW(wszUserName, &wcch))
2956 {
2957 char_u *p = utf16_to_enc(wszUserName, NULL);
2958
2959 if (p != NULL)
2960 {
2961 vim_strncpy(s, p, len - 1);
2962 vim_free(p);
2963 return OK;
2964 }
2965 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002966 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2967 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002968 /* Retry with non-wide function (for Windows 98). */
2969 }
2970#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 if (GetUserName(szUserName, &cch))
2972 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002973 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 return OK;
2975 }
2976 s[0] = NUL;
2977 return FAIL;
2978}
2979
2980
2981/*
2982 * Insert host name in s[len].
2983 */
2984 void
2985mch_get_host_name(
2986 char_u *s,
2987 int len)
2988{
2989 DWORD cch = len;
2990
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002991#ifdef FEAT_MBYTE
2992 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2993 {
2994 WCHAR wszHostName[256 + 1];
2995 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2996
2997 if (GetComputerNameW(wszHostName, &wcch))
2998 {
2999 char_u *p = utf16_to_enc(wszHostName, NULL);
3000
3001 if (p != NULL)
3002 {
3003 vim_strncpy(s, p, len - 1);
3004 vim_free(p);
3005 return;
3006 }
3007 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003008 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3009 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003010 /* Retry with non-wide function (for Windows 98). */
3011 }
3012#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003014 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015}
3016
3017
3018/*
3019 * return process ID
3020 */
3021 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003022mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023{
3024 return (long)GetCurrentProcessId();
3025}
3026
3027
3028/*
3029 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3030 * Return OK for success, FAIL for failure.
3031 */
3032 int
3033mch_dirname(
3034 char_u *buf,
3035 int len)
3036{
3037 /*
3038 * Originally this was:
3039 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3040 * But the Win32s known bug list says that getcwd() doesn't work
3041 * so use the Win32 system call instead. <Negri>
3042 */
3043#ifdef FEAT_MBYTE
3044 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3045 {
3046 WCHAR wbuf[_MAX_PATH + 1];
3047
3048 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3049 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003050 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051
3052 if (p != NULL)
3053 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003054 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 vim_free(p);
3056 return OK;
3057 }
3058 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003059 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3060 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061 /* Retry with non-wide function (for Windows 98). */
3062 }
3063#endif
3064 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3065}
3066
3067/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003068 * Get file permissions for "name".
3069 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070 */
3071 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003072mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003074 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003075 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003077 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003078 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079}
3080
3081
3082/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003083 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003084 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003085 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086 */
3087 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003088mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003090 long n = -1;
3091
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092#ifdef FEAT_MBYTE
3093 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3094 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003095 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096
3097 if (p != NULL)
3098 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003099 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003101 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003102 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003103 /* Retry with non-wide function (for Windows 98). */
3104 }
3105 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003106 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003108 n = _chmod(name, perm);
3109 if (n == -1)
3110 return FAIL;
3111
3112 win32_set_archive(name);
3113
3114 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115}
3116
3117/*
3118 * Set hidden flag for "name".
3119 */
3120 void
3121mch_hide(char_u *name)
3122{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003123 int attrs = win32_getattrs(name);
3124 if (attrs == -1)
3125 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003127 attrs |= FILE_ATTRIBUTE_HIDDEN;
3128 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129}
3130
3131/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003132 * Return TRUE if file "name" exists and is hidden.
3133 */
3134 int
3135mch_ishidden(char_u *name)
3136{
3137 int f = win32_getattrs(name);
3138
3139 if (f == -1)
3140 return FALSE; /* file does not exist at all */
3141
3142 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3143}
3144
3145/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146 * return TRUE if "name" is a directory
3147 * return FALSE if "name" is not a directory or upon error
3148 */
3149 int
3150mch_isdir(char_u *name)
3151{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003152 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153
3154 if (f == -1)
3155 return FALSE; /* file does not exist at all */
3156
3157 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3158}
3159
3160/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003161 * return TRUE if "name" is a directory, NOT a symlink to a directory
3162 * return FALSE if "name" is not a directory
3163 * return FALSE for error
3164 */
3165 int
3166mch_isrealdir(char_u *name)
3167{
3168 return mch_isdir(name) && !mch_is_symbolic_link(name);
3169}
3170
3171/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003172 * Create directory "name".
3173 * Return 0 on success, -1 on error.
3174 */
3175 int
3176mch_mkdir(char_u *name)
3177{
3178#ifdef FEAT_MBYTE
3179 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3180 {
3181 WCHAR *p;
3182 int retval;
3183
3184 p = enc_to_utf16(name, NULL);
3185 if (p == NULL)
3186 return -1;
3187 retval = _wmkdir(p);
3188 vim_free(p);
3189 return retval;
3190 }
3191#endif
3192 return _mkdir(name);
3193}
3194
3195/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003196 * Delete directory "name".
3197 * Return 0 on success, -1 on error.
3198 */
3199 int
3200mch_rmdir(char_u *name)
3201{
3202#ifdef FEAT_MBYTE
3203 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3204 {
3205 WCHAR *p;
3206 int retval;
3207
3208 p = enc_to_utf16(name, NULL);
3209 if (p == NULL)
3210 return -1;
3211 retval = _wrmdir(p);
3212 vim_free(p);
3213 return retval;
3214 }
3215#endif
3216 return _rmdir(name);
3217}
3218
3219/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003220 * Return TRUE if file "fname" has more than one link.
3221 */
3222 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003223mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003224{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003225 BY_HANDLE_FILE_INFORMATION info;
3226
3227 return win32_fileinfo(fname, &info) == FILEINFO_OK
3228 && info.nNumberOfLinks > 1;
3229}
3230
3231/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003232 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003233 */
3234 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003235mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003236{
3237 HANDLE hFind;
3238 int res = FALSE;
3239 WIN32_FIND_DATAA findDataA;
3240 DWORD fileFlags = 0, reparseTag = 0;
3241#ifdef FEAT_MBYTE
3242 WCHAR *wn = NULL;
3243 WIN32_FIND_DATAW findDataW;
3244
3245 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003246 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003247 if (wn != NULL)
3248 {
3249 hFind = FindFirstFileW(wn, &findDataW);
3250 vim_free(wn);
3251 if (hFind == INVALID_HANDLE_VALUE
3252 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3253 {
3254 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar203258c2016-01-17 22:15:16 +01003255 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003256 if (hFind != INVALID_HANDLE_VALUE)
3257 {
3258 fileFlags = findDataA.dwFileAttributes;
3259 reparseTag = findDataA.dwReserved0;
3260 }
3261 }
3262 else
3263 {
3264 fileFlags = findDataW.dwFileAttributes;
3265 reparseTag = findDataW.dwReserved0;
3266 }
3267 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003268 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003269#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003270 {
Bram Moolenaar203258c2016-01-17 22:15:16 +01003271 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003272 if (hFind != INVALID_HANDLE_VALUE)
3273 {
3274 fileFlags = findDataA.dwFileAttributes;
3275 reparseTag = findDataA.dwReserved0;
3276 }
3277 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003278
3279 if (hFind != INVALID_HANDLE_VALUE)
3280 FindClose(hFind);
3281
3282 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003283 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3284 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003285 res = TRUE;
3286
3287 return res;
3288}
3289
3290/*
3291 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3292 * link.
3293 */
3294 int
3295mch_is_linked(char_u *fname)
3296{
3297 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3298 return TRUE;
3299 return FALSE;
3300}
3301
3302/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003303 * Get the by-handle-file-information for "fname".
3304 * Returns FILEINFO_OK when OK.
3305 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3306 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3307 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3308 */
3309 int
3310win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3311{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003312 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003313 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003314#ifdef FEAT_MBYTE
3315 WCHAR *wn = NULL;
3316
3317 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003318 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003319 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003320 if (wn == NULL)
3321 res = FILEINFO_ENC_FAIL;
3322 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003323 if (wn != NULL)
3324 {
3325 hFile = CreateFileW(wn, /* file name */
3326 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003327 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003328 NULL, /* security descriptor */
3329 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003330 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003331 NULL); /* handle to template file */
3332 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003333 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003334 {
3335 /* Retry with non-wide function (for Windows 98). */
3336 vim_free(wn);
3337 wn = NULL;
3338 }
3339 }
3340 if (wn == NULL)
3341#endif
3342 hFile = CreateFile(fname, /* file name */
3343 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003344 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003345 NULL, /* security descriptor */
3346 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003347 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003348 NULL); /* handle to template file */
3349
3350 if (hFile != INVALID_HANDLE_VALUE)
3351 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003352 if (GetFileInformationByHandle(hFile, info) != 0)
3353 res = FILEINFO_OK;
3354 else
3355 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003356 CloseHandle(hFile);
3357 }
3358
3359#ifdef FEAT_MBYTE
3360 vim_free(wn);
3361#endif
3362 return res;
3363}
3364
3365/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003366 * get file attributes for `name'
3367 * -1 : error
3368 * else FILE_ATTRIBUTE_* defined in winnt.h
3369 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003370 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003371win32_getattrs(char_u *name)
3372{
3373 int attr;
3374#ifdef FEAT_MBYTE
3375 WCHAR *p = NULL;
3376
3377 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3378 p = enc_to_utf16(name, NULL);
3379
3380 if (p != NULL)
3381 {
3382 attr = GetFileAttributesW(p);
3383 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3384 {
3385 /* Retry with non-wide function (for Windows 98). */
3386 vim_free(p);
3387 p = NULL;
3388 }
3389 }
3390 if (p == NULL)
3391#endif
3392 attr = GetFileAttributes((char *)name);
3393#ifdef FEAT_MBYTE
3394 vim_free(p);
3395#endif
3396 return attr;
3397}
3398
3399/*
3400 * set file attributes for `name' to `attrs'
3401 *
3402 * return -1 for failure, 0 otherwise
3403 */
3404 static
3405 int
3406win32_setattrs(char_u *name, int attrs)
3407{
3408 int res;
3409#ifdef FEAT_MBYTE
3410 WCHAR *p = NULL;
3411
3412 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3413 p = enc_to_utf16(name, NULL);
3414
3415 if (p != NULL)
3416 {
3417 res = SetFileAttributesW(p, attrs);
3418 if (res == FALSE
3419 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3420 {
3421 /* Retry with non-wide function (for Windows 98). */
3422 vim_free(p);
3423 p = NULL;
3424 }
3425 }
3426 if (p == NULL)
3427#endif
3428 res = SetFileAttributes((char *)name, attrs);
3429#ifdef FEAT_MBYTE
3430 vim_free(p);
3431#endif
3432 return res ? 0 : -1;
3433}
3434
3435/*
3436 * Set archive flag for "name".
3437 */
3438 static
3439 int
3440win32_set_archive(char_u *name)
3441{
3442 int attrs = win32_getattrs(name);
3443 if (attrs == -1)
3444 return -1;
3445
3446 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3447 return win32_setattrs(name, attrs);
3448}
3449
3450/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451 * Return TRUE if file or directory "name" is writable (not readonly).
3452 * Strange semantics of Win32: a readonly directory is writable, but you can't
3453 * delete a file. Let's say this means it is writable.
3454 */
3455 int
3456mch_writable(char_u *name)
3457{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003458 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003459
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003460 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3461 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462}
3463
Bram Moolenaar071d4272004-06-13 20:20:40 +00003464/*
3465 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003466 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467 * Return -1 if unknown.
3468 */
3469 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003470mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003472 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003473 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003474 char_u *p;
3475
3476 if (len >= _MAX_PATH) /* safety check */
3477 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003478 if (!use_path)
3479 {
3480 /* TODO: check if file is really executable. */
3481 return mch_getperm(name) != -1 && !mch_isdir(name);
3482 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003483
3484 /* If there already is an extension try using the name directly. Also do
3485 * this with a Unix-shell like 'shell'. */
3486 if (vim_strchr(gettail(name), '.') != NULL
3487 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003488 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003489 return TRUE;
3490
3491 /*
3492 * Loop over all extensions in $PATHEXT.
3493 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003494 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003495 p = mch_getenv("PATHEXT");
3496 if (p == NULL)
3497 p = (char_u *)".com;.exe;.bat;.cmd";
3498 while (*p)
3499 {
3500 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3501 {
3502 /* A single "." means no extension is added. */
3503 buf[len] = NUL;
3504 ++p;
3505 if (*p)
3506 ++p;
3507 }
3508 else
3509 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003510 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003511 return TRUE;
3512 }
3513 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515
3516/*
3517 * Check what "name" is:
3518 * NODE_NORMAL: file or directory (or doesn't exist)
3519 * NODE_WRITABLE: writable device, socket, fifo, etc.
3520 * NODE_OTHER: non-writable things
3521 */
3522 int
3523mch_nodetype(char_u *name)
3524{
3525 HANDLE hFile;
3526 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003527#ifdef FEAT_MBYTE
3528 WCHAR *wn = NULL;
3529#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003530
Bram Moolenaar043545e2006-10-10 16:44:07 +00003531 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3532 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3533 * here. */
3534 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3535 return NODE_WRITABLE;
3536
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003537#ifdef FEAT_MBYTE
3538 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3539 {
3540 wn = enc_to_utf16(name, NULL);
3541 if (wn != NULL)
3542 {
3543 hFile = CreateFileW(wn, /* file name */
3544 GENERIC_WRITE, /* access mode */
3545 0, /* share mode */
3546 NULL, /* security descriptor */
3547 OPEN_EXISTING, /* creation disposition */
3548 0, /* file attributes */
3549 NULL); /* handle to template file */
3550 if (hFile == INVALID_HANDLE_VALUE
3551 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3552 {
3553 /* Retry with non-wide function (for Windows 98). */
3554 vim_free(wn);
3555 wn = NULL;
3556 }
3557 }
3558 }
3559 if (wn == NULL)
3560#endif
3561 hFile = CreateFile(name, /* file name */
3562 GENERIC_WRITE, /* access mode */
3563 0, /* share mode */
3564 NULL, /* security descriptor */
3565 OPEN_EXISTING, /* creation disposition */
3566 0, /* file attributes */
3567 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003568
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003569#ifdef FEAT_MBYTE
3570 vim_free(wn);
3571#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 if (hFile == INVALID_HANDLE_VALUE)
3573 return NODE_NORMAL;
3574
3575 type = GetFileType(hFile);
3576 CloseHandle(hFile);
3577 if (type == FILE_TYPE_CHAR)
3578 return NODE_WRITABLE;
3579 if (type == FILE_TYPE_DISK)
3580 return NODE_NORMAL;
3581 return NODE_OTHER;
3582}
3583
3584#ifdef HAVE_ACL
3585struct my_acl
3586{
3587 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3588 PSID pSidOwner;
3589 PSID pSidGroup;
3590 PACL pDacl;
3591 PACL pSacl;
3592};
3593#endif
3594
3595/*
3596 * Return a pointer to the ACL of file "fname" in allocated memory.
3597 * Return NULL if the ACL is not available for whatever reason.
3598 */
3599 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003600mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601{
3602#ifndef HAVE_ACL
3603 return (vim_acl_T)NULL;
3604#else
3605 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003606 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607
3608 /* This only works on Windows NT and 2000. */
3609 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3610 {
3611 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3612 if (p != NULL)
3613 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003614# ifdef FEAT_MBYTE
3615 WCHAR *wn = NULL;
3616
3617 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3618 wn = enc_to_utf16(fname, NULL);
3619 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003620 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003621 /* Try to retrieve the entire security descriptor. */
3622 err = pGetNamedSecurityInfoW(
3623 wn, // Abstract filename
3624 SE_FILE_OBJECT, // File Object
3625 OWNER_SECURITY_INFORMATION |
3626 GROUP_SECURITY_INFORMATION |
3627 DACL_SECURITY_INFORMATION |
3628 SACL_SECURITY_INFORMATION,
3629 &p->pSidOwner, // Ownership information.
3630 &p->pSidGroup, // Group membership.
3631 &p->pDacl, // Discretionary information.
3632 &p->pSacl, // For auditing purposes.
3633 &p->pSecurityDescriptor);
3634 if (err == ERROR_ACCESS_DENIED ||
3635 err == ERROR_PRIVILEGE_NOT_HELD)
3636 {
3637 /* Retrieve only DACL. */
3638 (void)pGetNamedSecurityInfoW(
3639 wn,
3640 SE_FILE_OBJECT,
3641 DACL_SECURITY_INFORMATION,
3642 NULL,
3643 NULL,
3644 &p->pDacl,
3645 NULL,
3646 &p->pSecurityDescriptor);
3647 }
3648 if (p->pSecurityDescriptor == NULL)
3649 {
3650 mch_free_acl((vim_acl_T)p);
3651 p = NULL;
3652 }
3653 vim_free(wn);
3654 }
3655 else
3656# endif
3657 {
3658 /* Try to retrieve the entire security descriptor. */
3659 err = pGetNamedSecurityInfo(
3660 (LPSTR)fname, // Abstract filename
3661 SE_FILE_OBJECT, // File Object
3662 OWNER_SECURITY_INFORMATION |
3663 GROUP_SECURITY_INFORMATION |
3664 DACL_SECURITY_INFORMATION |
3665 SACL_SECURITY_INFORMATION,
3666 &p->pSidOwner, // Ownership information.
3667 &p->pSidGroup, // Group membership.
3668 &p->pDacl, // Discretionary information.
3669 &p->pSacl, // For auditing purposes.
3670 &p->pSecurityDescriptor);
3671 if (err == ERROR_ACCESS_DENIED ||
3672 err == ERROR_PRIVILEGE_NOT_HELD)
3673 {
3674 /* Retrieve only DACL. */
3675 (void)pGetNamedSecurityInfo(
3676 (LPSTR)fname,
3677 SE_FILE_OBJECT,
3678 DACL_SECURITY_INFORMATION,
3679 NULL,
3680 NULL,
3681 &p->pDacl,
3682 NULL,
3683 &p->pSecurityDescriptor);
3684 }
3685 if (p->pSecurityDescriptor == NULL)
3686 {
3687 mch_free_acl((vim_acl_T)p);
3688 p = NULL;
3689 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690 }
3691 }
3692 }
3693
3694 return (vim_acl_T)p;
3695#endif
3696}
3697
Bram Moolenaar27515922013-06-29 15:36:26 +02003698#ifdef HAVE_ACL
3699/*
3700 * Check if "acl" contains inherited ACE.
3701 */
3702 static BOOL
3703is_acl_inherited(PACL acl)
3704{
3705 DWORD i;
3706 ACL_SIZE_INFORMATION acl_info;
3707 PACCESS_ALLOWED_ACE ace;
3708
3709 acl_info.AceCount = 0;
3710 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3711 for (i = 0; i < acl_info.AceCount; i++)
3712 {
3713 GetAce(acl, i, (LPVOID *)&ace);
3714 if (ace->Header.AceFlags & INHERITED_ACE)
3715 return TRUE;
3716 }
3717 return FALSE;
3718}
3719#endif
3720
Bram Moolenaar071d4272004-06-13 20:20:40 +00003721/*
3722 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3723 * Errors are ignored.
3724 * This must only be called with "acl" equal to what mch_get_acl() returned.
3725 */
3726 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003727mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728{
3729#ifdef HAVE_ACL
3730 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003731 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732
3733 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003734 {
3735# ifdef FEAT_MBYTE
3736 WCHAR *wn = NULL;
3737# endif
3738
3739 /* Set security flags */
3740 if (p->pSidOwner)
3741 sec_info |= OWNER_SECURITY_INFORMATION;
3742 if (p->pSidGroup)
3743 sec_info |= GROUP_SECURITY_INFORMATION;
3744 if (p->pDacl)
3745 {
3746 sec_info |= DACL_SECURITY_INFORMATION;
3747 /* Do not inherit its parent's DACL.
3748 * If the DACL is inherited, Cygwin permissions would be changed.
3749 */
3750 if (!is_acl_inherited(p->pDacl))
3751 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3752 }
3753 if (p->pSacl)
3754 sec_info |= SACL_SECURITY_INFORMATION;
3755
3756# ifdef FEAT_MBYTE
3757 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3758 wn = enc_to_utf16(fname, NULL);
3759 if (wn != NULL)
3760 {
3761 (void)pSetNamedSecurityInfoW(
3762 wn, // Abstract filename
3763 SE_FILE_OBJECT, // File Object
3764 sec_info,
3765 p->pSidOwner, // Ownership information.
3766 p->pSidGroup, // Group membership.
3767 p->pDacl, // Discretionary information.
3768 p->pSacl // For auditing purposes.
3769 );
3770 vim_free(wn);
3771 }
3772 else
3773# endif
3774 {
3775 (void)pSetNamedSecurityInfo(
3776 (LPSTR)fname, // Abstract filename
3777 SE_FILE_OBJECT, // File Object
3778 sec_info,
3779 p->pSidOwner, // Ownership information.
3780 p->pSidGroup, // Group membership.
3781 p->pDacl, // Discretionary information.
3782 p->pSacl // For auditing purposes.
3783 );
3784 }
3785 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786#endif
3787}
3788
3789 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003790mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791{
3792#ifdef HAVE_ACL
3793 struct my_acl *p = (struct my_acl *)acl;
3794
3795 if (p != NULL)
3796 {
3797 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3798 vim_free(p);
3799 }
3800#endif
3801}
3802
3803#ifndef FEAT_GUI_W32
3804
3805/*
3806 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3807 */
3808 static BOOL WINAPI
3809handler_routine(
3810 DWORD dwCtrlType)
3811{
3812 switch (dwCtrlType)
3813 {
3814 case CTRL_C_EVENT:
3815 if (ctrl_c_interrupts)
3816 g_fCtrlCPressed = TRUE;
3817 return TRUE;
3818
3819 case CTRL_BREAK_EVENT:
3820 g_fCBrkPressed = TRUE;
3821 return TRUE;
3822
3823 /* fatal events: shut down gracefully */
3824 case CTRL_CLOSE_EVENT:
3825 case CTRL_LOGOFF_EVENT:
3826 case CTRL_SHUTDOWN_EVENT:
3827 windgoto((int)Rows - 1, 0);
3828 g_fForceExit = TRUE;
3829
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003830 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831 (dwCtrlType == CTRL_CLOSE_EVENT
3832 ? _("close")
3833 : dwCtrlType == CTRL_LOGOFF_EVENT
3834 ? _("logoff")
3835 : _("shutdown")));
3836#ifdef DEBUG
3837 OutputDebugString(IObuff);
3838#endif
3839
3840 preserve_exit(); /* output IObuff, preserve files and exit */
3841
3842 return TRUE; /* not reached */
3843
3844 default:
3845 return FALSE;
3846 }
3847}
3848
3849
3850/*
3851 * set the tty in (raw) ? "raw" : "cooked" mode
3852 */
3853 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003854mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855{
3856 DWORD cmodein;
3857 DWORD cmodeout;
3858 BOOL bEnableHandler;
3859
3860 GetConsoleMode(g_hConIn, &cmodein);
3861 GetConsoleMode(g_hConOut, &cmodeout);
3862 if (tmode == TMODE_RAW)
3863 {
3864 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3865 ENABLE_ECHO_INPUT);
3866#ifdef FEAT_MOUSE
3867 if (g_fMouseActive)
3868 cmodein |= ENABLE_MOUSE_INPUT;
3869#endif
3870 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3871 bEnableHandler = TRUE;
3872 }
3873 else /* cooked */
3874 {
3875 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3876 ENABLE_ECHO_INPUT);
3877 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3878 bEnableHandler = FALSE;
3879 }
3880 SetConsoleMode(g_hConIn, cmodein);
3881 SetConsoleMode(g_hConOut, cmodeout);
3882 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3883
3884#ifdef MCH_WRITE_DUMP
3885 if (fdDump)
3886 {
3887 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3888 tmode == TMODE_RAW ? "raw" :
3889 tmode == TMODE_COOK ? "cooked" : "normal",
3890 cmodein, cmodeout);
3891 fflush(fdDump);
3892 }
3893#endif
3894}
3895
3896
3897/*
3898 * Get the size of the current window in `Rows' and `Columns'
3899 * Return OK when size could be determined, FAIL otherwise.
3900 */
3901 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003902mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903{
3904 CONSOLE_SCREEN_BUFFER_INFO csbi;
3905
3906 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3907 {
3908 /*
3909 * For some reason, we are trying to get the screen dimensions
3910 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3911 * variables are really intended to mean the size of Vim screen
3912 * while in termcap mode.
3913 */
3914 Rows = g_cbTermcap.Info.dwSize.Y;
3915 Columns = g_cbTermcap.Info.dwSize.X;
3916 }
3917 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3918 {
3919 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3920 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3921 }
3922 else
3923 {
3924 Rows = 25;
3925 Columns = 80;
3926 }
3927 return OK;
3928}
3929
3930/*
3931 * Set a console window to `xSize' * `ySize'
3932 */
3933 static void
3934ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003935 HANDLE hConsole,
3936 int xSize,
3937 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938{
3939 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3940 SMALL_RECT srWindowRect; /* hold the new console size */
3941 COORD coordScreen;
3942
3943#ifdef MCH_WRITE_DUMP
3944 if (fdDump)
3945 {
3946 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3947 fflush(fdDump);
3948 }
3949#endif
3950
3951 /* get the largest size we can size the console window to */
3952 coordScreen = GetLargestConsoleWindowSize(hConsole);
3953
3954 /* define the new console window size and scroll position */
3955 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3956 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3957 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3958
3959 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3960 {
3961 int sx, sy;
3962
3963 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3964 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3965 if (sy < ySize || sx < xSize)
3966 {
3967 /*
3968 * Increasing number of lines/columns, do buffer first.
3969 * Use the maximal size in x and y direction.
3970 */
3971 if (sy < ySize)
3972 coordScreen.Y = ySize;
3973 else
3974 coordScreen.Y = sy;
3975 if (sx < xSize)
3976 coordScreen.X = xSize;
3977 else
3978 coordScreen.X = sx;
3979 SetConsoleScreenBufferSize(hConsole, coordScreen);
3980 }
3981 }
3982
3983 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3984 {
3985#ifdef MCH_WRITE_DUMP
3986 if (fdDump)
3987 {
3988 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3989 GetLastError());
3990 fflush(fdDump);
3991 }
3992#endif
3993 }
3994
3995 /* define the new console buffer size */
3996 coordScreen.X = xSize;
3997 coordScreen.Y = ySize;
3998
3999 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4000 {
4001#ifdef MCH_WRITE_DUMP
4002 if (fdDump)
4003 {
4004 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4005 GetLastError());
4006 fflush(fdDump);
4007 }
4008#endif
4009 }
4010}
4011
4012
4013/*
4014 * Set the console window to `Rows' * `Columns'
4015 */
4016 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004017mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004018{
4019 COORD coordScreen;
4020
4021 /* Don't change window size while still starting up */
4022 if (suppress_winsize != 0)
4023 {
4024 suppress_winsize = 2;
4025 return;
4026 }
4027
4028 if (term_console)
4029 {
4030 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4031
4032 /* Clamp Rows and Columns to reasonable values */
4033 if (Rows > coordScreen.Y)
4034 Rows = coordScreen.Y;
4035 if (Columns > coordScreen.X)
4036 Columns = coordScreen.X;
4037
4038 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4039 }
4040}
4041
4042/*
4043 * Rows and/or Columns has changed.
4044 */
4045 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004046mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004047{
4048 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4049}
4050
4051
4052/*
4053 * Called when started up, to set the winsize that was delayed.
4054 */
4055 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004056mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057{
4058 if (suppress_winsize == 2)
4059 {
4060 suppress_winsize = 0;
4061 mch_set_shellsize();
4062 shell_resized();
4063 }
4064 suppress_winsize = 0;
4065}
4066#endif /* FEAT_GUI_W32 */
4067
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004068 static BOOL
4069vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004070 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004071 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004072 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004073 STARTUPINFO *si,
4074 PROCESS_INFORMATION *pi)
4075{
4076# ifdef FEAT_MBYTE
4077 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4078 {
4079 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4080
4081 if (wcmd != NULL)
4082 {
4083 BOOL ret;
4084 ret = CreateProcessW(
4085 NULL, /* Executable name */
4086 wcmd, /* Command to execute */
4087 NULL, /* Process security attributes */
4088 NULL, /* Thread security attributes */
4089 inherit_handles, /* Inherit handles */
4090 flags, /* Creation flags */
4091 NULL, /* Environment */
4092 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004093 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004094 pi); /* Process information */
4095 vim_free(wcmd);
4096 return ret;
4097 }
4098 }
4099#endif
4100 return CreateProcess(
4101 NULL, /* Executable name */
4102 cmd, /* Command to execute */
4103 NULL, /* Process security attributes */
4104 NULL, /* Thread security attributes */
4105 inherit_handles, /* Inherit handles */
4106 flags, /* Creation flags */
4107 NULL, /* Environment */
4108 NULL, /* Current directory */
4109 si, /* Startup information */
4110 pi); /* Process information */
4111}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004112
4113
4114#if defined(FEAT_GUI_W32) || defined(PROTO)
4115
4116/*
4117 * Specialised version of system() for Win32 GUI mode.
4118 * This version proceeds as follows:
4119 * 1. Create a console window for use by the subprocess
4120 * 2. Run the subprocess (it gets the allocated console by default)
4121 * 3. Wait for the subprocess to terminate and get its exit code
4122 * 4. Prompt the user to press a key to close the console window
4123 */
4124 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004125mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126{
4127 STARTUPINFO si;
4128 PROCESS_INFORMATION pi;
4129 DWORD ret = 0;
4130 HWND hwnd = GetFocus();
4131
4132 si.cb = sizeof(si);
4133 si.lpReserved = NULL;
4134 si.lpDesktop = NULL;
4135 si.lpTitle = NULL;
4136 si.dwFlags = STARTF_USESHOWWINDOW;
4137 /*
4138 * It's nicer to run a filter command in a minimized window, but in
4139 * Windows 95 this makes the command MUCH slower. We can't do it under
4140 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004141 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 */
4143 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004144 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145 else
4146 si.wShowWindow = SW_SHOWNORMAL;
4147 si.cbReserved2 = 0;
4148 si.lpReserved2 = NULL;
4149
4150 /* There is a strange error on Windows 95 when using "c:\\command.com".
4151 * When the "c:\\" is left out it works OK...? */
4152 if (mch_windows95()
4153 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4154 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4155 cmd += 3;
4156
4157 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004158 vim_create_process(cmd, FALSE,
4159 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160
4161 /* Wait for the command to terminate before continuing */
4162 if (g_PlatformId != VER_PLATFORM_WIN32s)
4163 {
4164#ifdef FEAT_GUI
4165 int delay = 1;
4166
4167 /* Keep updating the window while waiting for the shell to finish. */
4168 for (;;)
4169 {
4170 MSG msg;
4171
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004172 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 {
4174 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004175 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004176 delay = 1;
4177 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178 }
4179 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4180 break;
4181
4182 /* We start waiting for a very short time and then increase it, so
4183 * that we respond quickly when the process is quick, and don't
4184 * consume too much overhead when it's slow. */
4185 if (delay < 50)
4186 delay += 10;
4187 }
4188#else
4189 WaitForSingleObject(pi.hProcess, INFINITE);
4190#endif
4191
4192 /* Get the command exit code */
4193 GetExitCodeProcess(pi.hProcess, &ret);
4194 }
4195 else
4196 {
4197 /*
4198 * This ugly code is the only quick way of performing
4199 * a synchronous spawn under Win32s. Yuk.
4200 */
4201 num_windows = 0;
4202 EnumWindows(win32ssynch_cb, 0);
4203 old_num_windows = num_windows;
4204 do
4205 {
4206 Sleep(1000);
4207 num_windows = 0;
4208 EnumWindows(win32ssynch_cb, 0);
4209 } while (num_windows == old_num_windows);
4210 ret = 0;
4211 }
4212
4213 /* Close the handles to the subprocess, so that it goes away */
4214 CloseHandle(pi.hThread);
4215 CloseHandle(pi.hProcess);
4216
4217 /* Try to get input focus back. Doesn't always work though. */
4218 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4219
4220 return ret;
4221}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004222
4223/*
4224 * Thread launched by the gui to send the current buffer data to the
4225 * process. This way avoid to hang up vim totally if the children
4226 * process take a long time to process the lines.
4227 */
4228 static DWORD WINAPI
4229sub_process_writer(LPVOID param)
4230{
4231 HANDLE g_hChildStd_IN_Wr = param;
4232 linenr_T lnum = curbuf->b_op_start.lnum;
4233 DWORD len = 0;
4234 DWORD l;
4235 char_u *lp = ml_get(lnum);
4236 char_u *s;
4237 int written = 0;
4238
4239 for (;;)
4240 {
4241 l = (DWORD)STRLEN(lp + written);
4242 if (l == 0)
4243 len = 0;
4244 else if (lp[written] == NL)
4245 {
4246 /* NL -> NUL translation */
4247 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4248 }
4249 else
4250 {
4251 s = vim_strchr(lp + written, NL);
4252 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4253 s == NULL ? l : (DWORD)(s - (lp + written)),
4254 &len, NULL);
4255 }
4256 if (len == (int)l)
4257 {
4258 /* Finished a line, add a NL, unless this line should not have
4259 * one. */
4260 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004261 || (!curbuf->b_p_bin
4262 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004263 || (lnum != curbuf->b_no_eol_lnum
4264 && (lnum != curbuf->b_ml.ml_line_count
4265 || curbuf->b_p_eol)))
4266 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004267 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004268 }
4269
4270 ++lnum;
4271 if (lnum > curbuf->b_op_end.lnum)
4272 break;
4273
4274 lp = ml_get(lnum);
4275 written = 0;
4276 }
4277 else if (len > 0)
4278 written += len;
4279 }
4280
4281 /* finished all the lines, close pipe */
4282 CloseHandle(g_hChildStd_IN_Wr);
4283 ExitThread(0);
4284}
4285
4286
4287# define BUFLEN 100 /* length for buffer, stolen from unix version */
4288
4289/*
4290 * This function read from the children's stdout and write the
4291 * data on screen or in the buffer accordingly.
4292 */
4293 static void
4294dump_pipe(int options,
4295 HANDLE g_hChildStd_OUT_Rd,
4296 garray_T *ga,
4297 char_u buffer[],
4298 DWORD *buffer_off)
4299{
4300 DWORD availableBytes = 0;
4301 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004302 int ret;
4303 DWORD len;
4304 DWORD toRead;
4305 int repeatCount;
4306
4307 /* we query the pipe to see if there is any data to read
4308 * to avoid to perform a blocking read */
4309 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4310 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004311 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004312 NULL, /* number of read bytes */
4313 &availableBytes, /* available bytes total */
4314 NULL); /* byteLeft */
4315
4316 repeatCount = 0;
4317 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004318 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004319 {
4320 repeatCount++;
4321 toRead =
4322# ifdef FEAT_MBYTE
4323 (DWORD)(BUFLEN - *buffer_off);
4324# else
4325 (DWORD)BUFLEN;
4326# endif
4327 toRead = availableBytes < toRead ? availableBytes : toRead;
4328 ReadFile(g_hChildStd_OUT_Rd, buffer
4329# ifdef FEAT_MBYTE
4330 + *buffer_off, toRead
4331# else
4332 , toRead
4333# endif
4334 , &len, NULL);
4335
4336 /* If we haven't read anything, there is a problem */
4337 if (len == 0)
4338 break;
4339
4340 availableBytes -= len;
4341
4342 if (options & SHELL_READ)
4343 {
4344 /* Do NUL -> NL translation, append NL separated
4345 * lines to the current buffer. */
4346 for (i = 0; i < len; ++i)
4347 {
4348 if (buffer[i] == NL)
4349 append_ga_line(ga);
4350 else if (buffer[i] == NUL)
4351 ga_append(ga, NL);
4352 else
4353 ga_append(ga, buffer[i]);
4354 }
4355 }
4356# ifdef FEAT_MBYTE
4357 else if (has_mbyte)
4358 {
4359 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004360 int c;
4361 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004362
4363 len += *buffer_off;
4364 buffer[len] = NUL;
4365
4366 /* Check if the last character in buffer[] is
4367 * incomplete, keep these bytes for the next
4368 * round. */
4369 for (p = buffer; p < buffer + len; p += l)
4370 {
4371 l = mb_cptr2len(p);
4372 if (l == 0)
4373 l = 1; /* NUL byte? */
4374 else if (MB_BYTE2LEN(*p) != l)
4375 break;
4376 }
4377 if (p == buffer) /* no complete character */
4378 {
4379 /* avoid getting stuck at an illegal byte */
4380 if (len >= 12)
4381 ++p;
4382 else
4383 {
4384 *buffer_off = len;
4385 return;
4386 }
4387 }
4388 c = *p;
4389 *p = NUL;
4390 msg_puts(buffer);
4391 if (p < buffer + len)
4392 {
4393 *p = c;
4394 *buffer_off = (DWORD)((buffer + len) - p);
4395 mch_memmove(buffer, p, *buffer_off);
4396 return;
4397 }
4398 *buffer_off = 0;
4399 }
4400# endif /* FEAT_MBYTE */
4401 else
4402 {
4403 buffer[len] = NUL;
4404 msg_puts(buffer);
4405 }
4406
4407 windgoto(msg_row, msg_col);
4408 cursor_on();
4409 out_flush();
4410 }
4411}
4412
4413/*
4414 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4415 * for communication and doesn't open any new window.
4416 */
4417 static int
4418mch_system_piped(char *cmd, int options)
4419{
4420 STARTUPINFO si;
4421 PROCESS_INFORMATION pi;
4422 DWORD ret = 0;
4423
4424 HANDLE g_hChildStd_IN_Rd = NULL;
4425 HANDLE g_hChildStd_IN_Wr = NULL;
4426 HANDLE g_hChildStd_OUT_Rd = NULL;
4427 HANDLE g_hChildStd_OUT_Wr = NULL;
4428
4429 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4430 DWORD len;
4431
4432 /* buffer used to receive keys */
4433 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4434 int ta_len = 0; /* valid bytes in ta_buf[] */
4435
4436 DWORD i;
4437 int c;
4438 int noread_cnt = 0;
4439 garray_T ga;
4440 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004441 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004442 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004443
4444 SECURITY_ATTRIBUTES saAttr;
4445
4446 /* Set the bInheritHandle flag so pipe handles are inherited. */
4447 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4448 saAttr.bInheritHandle = TRUE;
4449 saAttr.lpSecurityDescriptor = NULL;
4450
4451 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4452 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4453 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4454 /* Create a pipe for the child process's STDIN. */
4455 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4456 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4457 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4458 {
4459 CloseHandle(g_hChildStd_IN_Rd);
4460 CloseHandle(g_hChildStd_IN_Wr);
4461 CloseHandle(g_hChildStd_OUT_Rd);
4462 CloseHandle(g_hChildStd_OUT_Wr);
4463 MSG_PUTS(_("\nCannot create pipes\n"));
4464 }
4465
4466 si.cb = sizeof(si);
4467 si.lpReserved = NULL;
4468 si.lpDesktop = NULL;
4469 si.lpTitle = NULL;
4470 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4471
4472 /* set-up our file redirection */
4473 si.hStdError = g_hChildStd_OUT_Wr;
4474 si.hStdOutput = g_hChildStd_OUT_Wr;
4475 si.hStdInput = g_hChildStd_IN_Rd;
4476 si.wShowWindow = SW_HIDE;
4477 si.cbReserved2 = 0;
4478 si.lpReserved2 = NULL;
4479
4480 if (options & SHELL_READ)
4481 ga_init2(&ga, 1, BUFLEN);
4482
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004483 if (cmd != NULL)
4484 {
4485 p = (char *)vim_strsave((char_u *)cmd);
4486 if (p != NULL)
4487 unescape_shellxquote((char_u *)p, p_sxe);
4488 else
4489 p = cmd;
4490 }
4491
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004492 /* Now, run the command.
4493 * About "Inherit handles" being TRUE: this command can be litigious,
4494 * handle inheritance was deactivated for pending temp file, but, if we
4495 * deactivate it, the pipes don't work for some reason. */
4496 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004497
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004498 if (p != cmd)
4499 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004500
4501 /* Close our unused side of the pipes */
4502 CloseHandle(g_hChildStd_IN_Rd);
4503 CloseHandle(g_hChildStd_OUT_Wr);
4504
4505 if (options & SHELL_WRITE)
4506 {
4507 HANDLE thread =
4508 CreateThread(NULL, /* security attributes */
4509 0, /* default stack size */
4510 sub_process_writer, /* function to be executed */
4511 g_hChildStd_IN_Wr, /* parameter */
4512 0, /* creation flag, start immediately */
4513 NULL); /* we don't care about thread id */
4514 CloseHandle(thread);
4515 g_hChildStd_IN_Wr = NULL;
4516 }
4517
4518 /* Keep updating the window while waiting for the shell to finish. */
4519 for (;;)
4520 {
4521 MSG msg;
4522
Bram Moolenaar175d0702013-12-11 18:36:33 +01004523 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004524 {
4525 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004526 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004527 }
4528
4529 /* write pipe information in the window */
4530 if ((options & (SHELL_READ|SHELL_WRITE))
4531# ifdef FEAT_GUI
4532 || gui.in_use
4533# endif
4534 )
4535 {
4536 len = 0;
4537 if (!(options & SHELL_EXPAND)
4538 && ((options &
4539 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4540 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4541# ifdef FEAT_GUI
4542 || gui.in_use
4543# endif
4544 )
4545 && (ta_len > 0 || noread_cnt > 4))
4546 {
4547 if (ta_len == 0)
4548 {
4549 /* Get extra characters when we don't have any. Reset the
4550 * counter and timer. */
4551 noread_cnt = 0;
4552# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4553 gettimeofday(&start_tv, NULL);
4554# endif
4555 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4556 }
4557 if (ta_len > 0 || len > 0)
4558 {
4559 /*
4560 * For pipes: Check for CTRL-C: send interrupt signal to
4561 * child. Check for CTRL-D: EOF, close pipe to child.
4562 */
4563 if (len == 1 && cmd != NULL)
4564 {
4565 if (ta_buf[ta_len] == Ctrl_C)
4566 {
4567 /* Learn what exit code is expected, for
4568 * now put 9 as SIGKILL */
4569 TerminateProcess(pi.hProcess, 9);
4570 }
4571 if (ta_buf[ta_len] == Ctrl_D)
4572 {
4573 CloseHandle(g_hChildStd_IN_Wr);
4574 g_hChildStd_IN_Wr = NULL;
4575 }
4576 }
4577
4578 /* replace K_BS by <BS> and K_DEL by <DEL> */
4579 for (i = ta_len; i < ta_len + len; ++i)
4580 {
4581 if (ta_buf[i] == CSI && len - i > 2)
4582 {
4583 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4584 if (c == K_DEL || c == K_KDEL || c == K_BS)
4585 {
4586 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4587 (size_t)(len - i - 2));
4588 if (c == K_DEL || c == K_KDEL)
4589 ta_buf[i] = DEL;
4590 else
4591 ta_buf[i] = Ctrl_H;
4592 len -= 2;
4593 }
4594 }
4595 else if (ta_buf[i] == '\r')
4596 ta_buf[i] = '\n';
4597# ifdef FEAT_MBYTE
4598 if (has_mbyte)
4599 i += (*mb_ptr2len_len)(ta_buf + i,
4600 ta_len + len - i) - 1;
4601# endif
4602 }
4603
4604 /*
4605 * For pipes: echo the typed characters. For a pty this
4606 * does not seem to work.
4607 */
4608 for (i = ta_len; i < ta_len + len; ++i)
4609 {
4610 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4611 msg_putchar(ta_buf[i]);
4612# ifdef FEAT_MBYTE
4613 else if (has_mbyte)
4614 {
4615 int l = (*mb_ptr2len)(ta_buf + i);
4616
4617 msg_outtrans_len(ta_buf + i, l);
4618 i += l - 1;
4619 }
4620# endif
4621 else
4622 msg_outtrans_len(ta_buf + i, 1);
4623 }
4624 windgoto(msg_row, msg_col);
4625 out_flush();
4626
4627 ta_len += len;
4628
4629 /*
4630 * Write the characters to the child, unless EOF has been
4631 * typed for pipes. Write one character at a time, to
4632 * avoid losing too much typeahead. When writing buffer
4633 * lines, drop the typed characters (only check for
4634 * CTRL-C).
4635 */
4636 if (options & SHELL_WRITE)
4637 ta_len = 0;
4638 else if (g_hChildStd_IN_Wr != NULL)
4639 {
4640 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4641 1, &len, NULL);
4642 // if we are typing in, we want to keep things reactive
4643 delay = 1;
4644 if (len > 0)
4645 {
4646 ta_len -= len;
4647 mch_memmove(ta_buf, ta_buf + len, ta_len);
4648 }
4649 }
4650 }
4651 }
4652 }
4653
4654 if (ta_len)
4655 ui_inchar_undo(ta_buf, ta_len);
4656
4657 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4658 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004659 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004660 break;
4661 }
4662
4663 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004664 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004665
4666 /* We start waiting for a very short time and then increase it, so
4667 * that we respond quickly when the process is quick, and don't
4668 * consume too much overhead when it's slow. */
4669 if (delay < 50)
4670 delay += 10;
4671 }
4672
4673 /* Close the pipe */
4674 CloseHandle(g_hChildStd_OUT_Rd);
4675 if (g_hChildStd_IN_Wr != NULL)
4676 CloseHandle(g_hChildStd_IN_Wr);
4677
4678 WaitForSingleObject(pi.hProcess, INFINITE);
4679
4680 /* Get the command exit code */
4681 GetExitCodeProcess(pi.hProcess, &ret);
4682
4683 if (options & SHELL_READ)
4684 {
4685 if (ga.ga_len > 0)
4686 {
4687 append_ga_line(&ga);
4688 /* remember that the NL was missing */
4689 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4690 }
4691 else
4692 curbuf->b_no_eol_lnum = 0;
4693 ga_clear(&ga);
4694 }
4695
4696 /* Close the handles to the subprocess, so that it goes away */
4697 CloseHandle(pi.hThread);
4698 CloseHandle(pi.hProcess);
4699
4700 return ret;
4701}
4702
4703 static int
4704mch_system(char *cmd, int options)
4705{
4706 /* if we can pipe and the shelltemp option is off */
4707 if (allowPiping && !p_stmp)
4708 return mch_system_piped(cmd, options);
4709 else
4710 return mch_system_classic(cmd, options);
4711}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004712#else
4713
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004714# ifdef FEAT_MBYTE
4715 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004716mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004717{
4718 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4719 {
4720 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4721 if (wcmd != NULL)
4722 {
4723 int ret = _wsystem(wcmd);
4724 vim_free(wcmd);
4725 return ret;
4726 }
4727 }
4728 return system(cmd);
4729}
4730# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004731# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004732# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733
4734#endif
4735
4736/*
4737 * Either execute a command by calling the shell or start a new shell
4738 */
4739 int
4740mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004741 char_u *cmd,
4742 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004743{
4744 int x = 0;
4745 int tmode = cur_tmode;
4746#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004747 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004748# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004749 int did_set_title = FALSE;
4750
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004751 /* Change the title to reflect that we are in a subshell. */
4752 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4753 {
4754 WCHAR szShellTitle[512];
4755
4756 if (GetConsoleTitleW(szShellTitle,
4757 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4758 {
4759 if (cmd == NULL)
4760 wcscat(szShellTitle, L" :sh");
4761 else
4762 {
4763 WCHAR *wn = enc_to_utf16(cmd, NULL);
4764
4765 if (wn != NULL)
4766 {
4767 wcscat(szShellTitle, L" - !");
4768 if ((wcslen(szShellTitle) + wcslen(wn) <
4769 sizeof(szShellTitle)/sizeof(WCHAR)))
4770 wcscat(szShellTitle, wn);
4771 SetConsoleTitleW(szShellTitle);
4772 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004773 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004774 }
4775 }
4776 }
4777 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004778 if (!did_set_title)
4779# endif
4780 /* Change the title to reflect that we are in a subshell. */
4781 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004783 if (cmd == NULL)
4784 strcat(szShellTitle, " :sh");
4785 else
4786 {
4787 strcat(szShellTitle, " - !");
4788 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4789 strcat(szShellTitle, cmd);
4790 }
4791 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004793#endif
4794
4795 out_flush();
4796
4797#ifdef MCH_WRITE_DUMP
4798 if (fdDump)
4799 {
4800 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4801 fflush(fdDump);
4802 }
4803#endif
4804
4805 /*
4806 * Catch all deadly signals while running the external command, because a
4807 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4808 */
4809 signal(SIGINT, SIG_IGN);
4810#if defined(__GNUC__) && !defined(__MINGW32__)
4811 signal(SIGKILL, SIG_IGN);
4812#else
4813 signal(SIGBREAK, SIG_IGN);
4814#endif
4815 signal(SIGILL, SIG_IGN);
4816 signal(SIGFPE, SIG_IGN);
4817 signal(SIGSEGV, SIG_IGN);
4818 signal(SIGTERM, SIG_IGN);
4819 signal(SIGABRT, SIG_IGN);
4820
4821 if (options & SHELL_COOKED)
4822 settmode(TMODE_COOK); /* set to normal mode */
4823
4824 if (cmd == NULL)
4825 {
4826 x = mch_system(p_sh, options);
4827 }
4828 else
4829 {
4830 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004831 char_u *newcmd = NULL;
4832 char_u *cmdbase = cmd;
4833 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004834
4835 /* Skip a leading ", ( and "(. */
4836 if (*cmdbase == '"' )
4837 ++cmdbase;
4838 if (*cmdbase == '(')
4839 ++cmdbase;
4840
4841 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4842 {
4843 STARTUPINFO si;
4844 PROCESS_INFORMATION pi;
4845 DWORD flags = CREATE_NEW_CONSOLE;
4846 char_u *p;
4847
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004848 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004849 si.cb = sizeof(si);
4850 si.lpReserved = NULL;
4851 si.lpDesktop = NULL;
4852 si.lpTitle = NULL;
4853 si.dwFlags = 0;
4854 si.cbReserved2 = 0;
4855 si.lpReserved2 = NULL;
4856
4857 cmdbase = skipwhite(cmdbase + 5);
4858 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4859 && vim_iswhite(cmdbase[4]))
4860 {
4861 cmdbase = skipwhite(cmdbase + 4);
4862 si.dwFlags = STARTF_USESHOWWINDOW;
4863 si.wShowWindow = SW_SHOWMINNOACTIVE;
4864 }
4865 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4866 && vim_iswhite(cmdbase[2]))
4867 {
4868 cmdbase = skipwhite(cmdbase + 2);
4869 flags = CREATE_NO_WINDOW;
4870 si.dwFlags = STARTF_USESTDHANDLES;
4871 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004872 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004873 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004874 NULL, // Security att.
4875 OPEN_EXISTING, // Open flags
4876 FILE_ATTRIBUTE_NORMAL, // File att.
4877 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004878 si.hStdOutput = si.hStdInput;
4879 si.hStdError = si.hStdInput;
4880 }
4881
4882 /* Remove a trailing ", ) and )" if they have a match
4883 * at the start of the command. */
4884 if (cmdbase > cmd)
4885 {
4886 p = cmdbase + STRLEN(cmdbase);
4887 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4888 *--p = NUL;
4889 if (p > cmdbase && p[-1] == ')'
4890 && (*cmd =='(' || cmd[1] == '('))
4891 *--p = NUL;
4892 }
4893
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004894 newcmd = cmdbase;
4895 unescape_shellxquote(cmdbase, p_sxe);
4896
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004897 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004898 * If creating new console, arguments are passed to the
4899 * 'cmd.exe' as-is. If it's not, arguments are not treated
4900 * correctly for current 'cmd.exe'. So unescape characters in
4901 * shellxescape except '|' for avoiding to be treated as
4902 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004903 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004904 if (flags != CREATE_NEW_CONSOLE)
4905 {
4906 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004907 char_u *cmd_shell = mch_getenv("COMSPEC");
4908
4909 if (cmd_shell == NULL || *cmd_shell == NUL)
4910 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004911
4912 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4913 if (subcmd != NULL)
4914 {
4915 /* make "cmd.exe /c arguments" */
4916 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004917 newcmd = lalloc(cmdlen, TRUE);
4918 if (newcmd != NULL)
4919 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004920 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004921 else
4922 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004923 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004924 }
4925 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004926
4927 /*
4928 * Now, start the command as a process, so that it doesn't
4929 * inherit our handles which causes unpleasant dangling swap
4930 * files if we exit before the spawned process
4931 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004932 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004933 x = 0;
4934 else
4935 {
4936 x = -1;
4937#ifdef FEAT_GUI_W32
4938 EMSG(_("E371: Command not found"));
4939#endif
4940 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004941
4942 if (newcmd != cmdbase)
4943 vim_free(newcmd);
4944
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004945 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004946 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004947 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004948 CloseHandle(si.hStdInput);
4949 }
4950 /* Close the handles to the subprocess, so that it goes away */
4951 CloseHandle(pi.hThread);
4952 CloseHandle(pi.hProcess);
4953 }
4954 else
4955 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004956 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004957#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004958 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004959#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004960 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4961
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004962 newcmd = lalloc(cmdlen, TRUE);
4963 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964 {
4965#if defined(FEAT_GUI_W32)
4966 if (need_vimrun_warning)
4967 {
4968 MessageBox(NULL,
4969 _("VIMRUN.EXE not found in your $PATH.\n"
4970 "External commands will not pause after completion.\n"
4971 "See :help win32-vimrun for more information."),
4972 _("Vim Warning"),
4973 MB_ICONWARNING);
4974 need_vimrun_warning = FALSE;
4975 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004976 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977 /* Use vimrun to execute the command. It opens a console
4978 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004979 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004980 vimrun_path,
4981 (msg_silent != 0 || (options & SHELL_DOOUT))
4982 ? "-s " : "",
4983 p_sh, p_shcf, cmd);
4984 else
4985#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004986 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004987 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004988 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004989 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004990 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004991 }
4992 }
4993
4994 if (tmode == TMODE_RAW)
4995 settmode(TMODE_RAW); /* set to raw mode */
4996
4997 /* Print the return value, unless "vimrun" was used. */
4998 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4999#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005000 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
5001 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002#endif
5003 )
5004 {
5005 smsg(_("shell returned %d"), x);
5006 msg_putchar('\n');
5007 }
5008#ifdef FEAT_TITLE
5009 resettitle();
5010#endif
5011
5012 signal(SIGINT, SIG_DFL);
5013#if defined(__GNUC__) && !defined(__MINGW32__)
5014 signal(SIGKILL, SIG_DFL);
5015#else
5016 signal(SIGBREAK, SIG_DFL);
5017#endif
5018 signal(SIGILL, SIG_DFL);
5019 signal(SIGFPE, SIG_DFL);
5020 signal(SIGSEGV, SIG_DFL);
5021 signal(SIGTERM, SIG_DFL);
5022 signal(SIGABRT, SIG_DFL);
5023
5024 return x;
5025}
5026
5027
5028#ifndef FEAT_GUI_W32
5029
5030/*
5031 * Start termcap mode
5032 */
5033 static void
5034termcap_mode_start(void)
5035{
5036 DWORD cmodein;
5037
5038 if (g_fTermcapMode)
5039 return;
5040
5041 SaveConsoleBuffer(&g_cbNonTermcap);
5042
5043 if (g_cbTermcap.IsValid)
5044 {
5045 /*
5046 * We've been in termcap mode before. Restore certain screen
5047 * characteristics, including the buffer size and the window
5048 * size. Since we will be redrawing the screen, we don't need
5049 * to restore the actual contents of the buffer.
5050 */
5051 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5052 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5053 Rows = g_cbTermcap.Info.dwSize.Y;
5054 Columns = g_cbTermcap.Info.dwSize.X;
5055 }
5056 else
5057 {
5058 /*
5059 * This is our first time entering termcap mode. Clear the console
5060 * screen buffer, and resize the buffer to match the current window
5061 * size. We will use this as the size of our editing environment.
5062 */
5063 ClearConsoleBuffer(g_attrCurrent);
5064 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5065 }
5066
5067#ifdef FEAT_TITLE
5068 resettitle();
5069#endif
5070
5071 GetConsoleMode(g_hConIn, &cmodein);
5072#ifdef FEAT_MOUSE
5073 if (g_fMouseActive)
5074 cmodein |= ENABLE_MOUSE_INPUT;
5075 else
5076 cmodein &= ~ENABLE_MOUSE_INPUT;
5077#endif
5078 cmodein |= ENABLE_WINDOW_INPUT;
5079 SetConsoleMode(g_hConIn, cmodein);
5080
5081 redraw_later_clear();
5082 g_fTermcapMode = TRUE;
5083}
5084
5085
5086/*
5087 * End termcap mode
5088 */
5089 static void
5090termcap_mode_end(void)
5091{
5092 DWORD cmodein;
5093 ConsoleBuffer *cb;
5094 COORD coord;
5095 DWORD dwDummy;
5096
5097 if (!g_fTermcapMode)
5098 return;
5099
5100 SaveConsoleBuffer(&g_cbTermcap);
5101
5102 GetConsoleMode(g_hConIn, &cmodein);
5103 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5104 SetConsoleMode(g_hConIn, cmodein);
5105
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005106#ifdef FEAT_RESTORE_ORIG_SCREEN
5107 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5108#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005109 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005110#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005111 RestoreConsoleBuffer(cb, p_rs);
5112 SetConsoleCursorInfo(g_hConOut, &g_cci);
5113
5114 if (p_rs || exiting)
5115 {
5116 /*
5117 * Clear anything that happens to be on the current line.
5118 */
5119 coord.X = 0;
5120 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5121 FillConsoleOutputCharacter(g_hConOut, ' ',
5122 cb->Info.dwSize.X, coord, &dwDummy);
5123 /*
5124 * The following is just for aesthetics. If we are exiting without
5125 * restoring the screen, then we want to have a prompt string
5126 * appear at the bottom line. However, the command interpreter
5127 * seems to always advance the cursor one line before displaying
5128 * the prompt string, which causes the screen to scroll. To
5129 * counter this, move the cursor up one line before exiting.
5130 */
5131 if (exiting && !p_rs)
5132 coord.Y--;
5133 /*
5134 * Position the cursor at the leftmost column of the desired row.
5135 */
5136 SetConsoleCursorPosition(g_hConOut, coord);
5137 }
5138
5139 g_fTermcapMode = FALSE;
5140}
5141#endif /* FEAT_GUI_W32 */
5142
5143
5144#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005145/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005146 void
5147mch_write(
5148 char_u *s,
5149 int len)
5150{
5151 /* never used */
5152}
5153
5154#else
5155
5156/*
5157 * clear `n' chars, starting from `coord'
5158 */
5159 static void
5160clear_chars(
5161 COORD coord,
5162 DWORD n)
5163{
5164 DWORD dwDummy;
5165
5166 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5167 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5168}
5169
5170
5171/*
5172 * Clear the screen
5173 */
5174 static void
5175clear_screen(void)
5176{
5177 g_coord.X = g_coord.Y = 0;
5178 clear_chars(g_coord, Rows * Columns);
5179}
5180
5181
5182/*
5183 * Clear to end of display
5184 */
5185 static void
5186clear_to_end_of_display(void)
5187{
5188 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5189 * Columns + (Columns - g_coord.X));
5190}
5191
5192
5193/*
5194 * Clear to end of line
5195 */
5196 static void
5197clear_to_end_of_line(void)
5198{
5199 clear_chars(g_coord, Columns - g_coord.X);
5200}
5201
5202
5203/*
5204 * Scroll the scroll region up by `cLines' lines
5205 */
5206 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005207scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208{
5209 COORD oldcoord = g_coord;
5210
5211 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5212 delete_lines(cLines);
5213
5214 g_coord = oldcoord;
5215}
5216
5217
5218/*
5219 * Set the scroll region
5220 */
5221 static void
5222set_scroll_region(
5223 unsigned left,
5224 unsigned top,
5225 unsigned right,
5226 unsigned bottom)
5227{
5228 if (left >= right
5229 || top >= bottom
5230 || right > (unsigned) Columns - 1
5231 || bottom > (unsigned) Rows - 1)
5232 return;
5233
5234 g_srScrollRegion.Left = left;
5235 g_srScrollRegion.Top = top;
5236 g_srScrollRegion.Right = right;
5237 g_srScrollRegion.Bottom = bottom;
5238}
5239
5240
5241/*
5242 * Insert `cLines' lines at the current cursor position
5243 */
5244 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005245insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246{
5247 SMALL_RECT source;
5248 COORD dest;
5249 CHAR_INFO fill;
5250
5251 dest.X = 0;
5252 dest.Y = g_coord.Y + cLines;
5253
5254 source.Left = 0;
5255 source.Top = g_coord.Y;
5256 source.Right = g_srScrollRegion.Right;
5257 source.Bottom = g_srScrollRegion.Bottom - cLines;
5258
5259 fill.Char.AsciiChar = ' ';
5260 fill.Attributes = g_attrCurrent;
5261
5262 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5263
5264 /* Here we have to deal with a win32 console flake: If the scroll
5265 * region looks like abc and we scroll c to a and fill with d we get
5266 * cbd... if we scroll block c one line at a time to a, we get cdd...
5267 * vim expects cdd consistently... So we have to deal with that
5268 * here... (this also occurs scrolling the same way in the other
5269 * direction). */
5270
5271 if (source.Bottom < dest.Y)
5272 {
5273 COORD coord;
5274
5275 coord.X = 0;
5276 coord.Y = source.Bottom;
5277 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5278 }
5279}
5280
5281
5282/*
5283 * Delete `cLines' lines at the current cursor position
5284 */
5285 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005286delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005287{
5288 SMALL_RECT source;
5289 COORD dest;
5290 CHAR_INFO fill;
5291 int nb;
5292
5293 dest.X = 0;
5294 dest.Y = g_coord.Y;
5295
5296 source.Left = 0;
5297 source.Top = g_coord.Y + cLines;
5298 source.Right = g_srScrollRegion.Right;
5299 source.Bottom = g_srScrollRegion.Bottom;
5300
5301 fill.Char.AsciiChar = ' ';
5302 fill.Attributes = g_attrCurrent;
5303
5304 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5305
5306 /* Here we have to deal with a win32 console flake: If the scroll
5307 * region looks like abc and we scroll c to a and fill with d we get
5308 * cbd... if we scroll block c one line at a time to a, we get cdd...
5309 * vim expects cdd consistently... So we have to deal with that
5310 * here... (this also occurs scrolling the same way in the other
5311 * direction). */
5312
5313 nb = dest.Y + (source.Bottom - source.Top) + 1;
5314
5315 if (nb < source.Top)
5316 {
5317 COORD coord;
5318
5319 coord.X = 0;
5320 coord.Y = nb;
5321 clear_chars(coord, Columns * (source.Top - nb));
5322 }
5323}
5324
5325
5326/*
5327 * Set the cursor position
5328 */
5329 static void
5330gotoxy(
5331 unsigned x,
5332 unsigned y)
5333{
5334 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5335 return;
5336
5337 /* external cursor coords are 1-based; internal are 0-based */
5338 g_coord.X = x - 1;
5339 g_coord.Y = y - 1;
5340 SetConsoleCursorPosition(g_hConOut, g_coord);
5341}
5342
5343
5344/*
5345 * Set the current text attribute = (foreground | background)
5346 * See ../doc/os_win32.txt for the numbers.
5347 */
5348 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005349textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005350{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005351 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005352
5353 SetConsoleTextAttribute(g_hConOut, wAttr);
5354}
5355
5356
5357 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005358textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005359{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005360 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005361
5362 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5363}
5364
5365
5366 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005367textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005368{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005369 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005370
5371 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5372}
5373
5374
5375/*
5376 * restore the default text attribute (whatever we started with)
5377 */
5378 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005379normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005380{
5381 textattr(g_attrDefault);
5382}
5383
5384
5385static WORD g_attrPreStandout = 0;
5386
5387/*
5388 * Make the text standout, by brightening it
5389 */
5390 static void
5391standout(void)
5392{
5393 g_attrPreStandout = g_attrCurrent;
5394 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5395}
5396
5397
5398/*
5399 * Turn off standout mode
5400 */
5401 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005402standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005403{
5404 if (g_attrPreStandout)
5405 {
5406 textattr(g_attrPreStandout);
5407 g_attrPreStandout = 0;
5408 }
5409}
5410
5411
5412/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005413 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414 */
5415 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005416mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005417{
5418 char_u *p;
5419 int n;
5420
5421 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5422 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5423 if (T_ME[0] == ESC && T_ME[1] == '|')
5424 {
5425 p = T_ME + 2;
5426 n = getdigits(&p);
5427 if (*p == 'm' && n > 0)
5428 {
5429 cterm_normal_fg_color = (n & 0xf) + 1;
5430 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5431 }
5432 }
5433}
5434
5435
5436/*
5437 * visual bell: flash the screen
5438 */
5439 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005440visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005441{
5442 COORD coordOrigin = {0, 0};
5443 WORD attrFlash = ~g_attrCurrent & 0xff;
5444
5445 DWORD dwDummy;
5446 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5447
5448 if (oldattrs == NULL)
5449 return;
5450 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5451 coordOrigin, &dwDummy);
5452 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5453 coordOrigin, &dwDummy);
5454
5455 Sleep(15); /* wait for 15 msec */
5456 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5457 coordOrigin, &dwDummy);
5458 vim_free(oldattrs);
5459}
5460
5461
5462/*
5463 * Make the cursor visible or invisible
5464 */
5465 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005466cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005467{
5468 s_cursor_visible = fVisible;
5469#ifdef MCH_CURSOR_SHAPE
5470 mch_update_cursor();
5471#endif
5472}
5473
5474
5475/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005476 * write `cbToWrite' bytes in `pchBuf' to the screen
5477 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005478 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005479 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005480write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005481 char_u *pchBuf,
5482 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005483{
5484 COORD coord = g_coord;
5485 DWORD written;
5486
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005487#ifdef FEAT_MBYTE
5488 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5489 {
5490 static WCHAR *unicodebuf = NULL;
5491 static int unibuflen = 0;
5492 int length;
5493 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005494
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005495 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5496 if (unicodebuf == NULL || length > unibuflen)
5497 {
5498 vim_free(unicodebuf);
5499 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5500 unibuflen = length;
5501 }
5502 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5503 unicodebuf, unibuflen);
5504
5505 cells = mb_string2cells(pchBuf, cbToWrite);
5506 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5507 coord, &written);
5508 /* When writing fails or didn't write a single character, pretend one
5509 * character was written, otherwise we get stuck. */
5510 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5511 coord, &cchwritten) == 0
5512 || cchwritten == 0)
5513 cchwritten = 1;
5514
5515 if (cchwritten == length)
5516 {
5517 written = cbToWrite;
5518 g_coord.X += (SHORT)cells;
5519 }
5520 else
5521 {
5522 char_u *p = pchBuf;
5523 for (n = 0; n < cchwritten; n++)
5524 mb_cptr_adv(p);
5525 written = p - pchBuf;
5526 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5527 }
5528 }
5529 else
5530#endif
5531 {
5532 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5533 coord, &written);
5534 /* When writing fails or didn't write a single character, pretend one
5535 * character was written, otherwise we get stuck. */
5536 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5537 coord, &written) == 0
5538 || written == 0)
5539 written = 1;
5540
5541 g_coord.X += (SHORT) written;
5542 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005543
5544 while (g_coord.X > g_srScrollRegion.Right)
5545 {
5546 g_coord.X -= (SHORT) Columns;
5547 if (g_coord.Y < g_srScrollRegion.Bottom)
5548 g_coord.Y++;
5549 }
5550
5551 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5552
5553 return written;
5554}
5555
5556
5557/*
5558 * mch_write(): write the output buffer to the screen, translating ESC
5559 * sequences into calls to console output routines.
5560 */
5561 void
5562mch_write(
5563 char_u *s,
5564 int len)
5565{
5566 s[len] = NUL;
5567
5568 if (!term_console)
5569 {
5570 write(1, s, (unsigned)len);
5571 return;
5572 }
5573
5574 /* translate ESC | sequences into faked bios calls */
5575 while (len--)
5576 {
5577 /* optimization: use one single write_chars for runs of text,
5578 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005579 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005580
5581 if (p_wd)
5582 {
5583 WaitForChar(p_wd);
5584 if (prefix != 0)
5585 prefix = 1;
5586 }
5587
5588 if (prefix != 0)
5589 {
5590 DWORD nWritten;
5591
5592 nWritten = write_chars(s, prefix);
5593#ifdef MCH_WRITE_DUMP
5594 if (fdDump)
5595 {
5596 fputc('>', fdDump);
5597 fwrite(s, sizeof(char_u), nWritten, fdDump);
5598 fputs("<\n", fdDump);
5599 }
5600#endif
5601 len -= (nWritten - 1);
5602 s += nWritten;
5603 }
5604 else if (s[0] == '\n')
5605 {
5606 /* \n, newline: go to the beginning of the next line or scroll */
5607 if (g_coord.Y == g_srScrollRegion.Bottom)
5608 {
5609 scroll(1);
5610 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5611 }
5612 else
5613 {
5614 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5615 }
5616#ifdef MCH_WRITE_DUMP
5617 if (fdDump)
5618 fputs("\\n\n", fdDump);
5619#endif
5620 s++;
5621 }
5622 else if (s[0] == '\r')
5623 {
5624 /* \r, carriage return: go to beginning of line */
5625 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5626#ifdef MCH_WRITE_DUMP
5627 if (fdDump)
5628 fputs("\\r\n", fdDump);
5629#endif
5630 s++;
5631 }
5632 else if (s[0] == '\b')
5633 {
5634 /* \b, backspace: move cursor one position left */
5635 if (g_coord.X > g_srScrollRegion.Left)
5636 g_coord.X--;
5637 else if (g_coord.Y > g_srScrollRegion.Top)
5638 {
5639 g_coord.X = g_srScrollRegion.Right;
5640 g_coord.Y--;
5641 }
5642 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5643#ifdef MCH_WRITE_DUMP
5644 if (fdDump)
5645 fputs("\\b\n", fdDump);
5646#endif
5647 s++;
5648 }
5649 else if (s[0] == '\a')
5650 {
5651 /* \a, bell */
5652 MessageBeep(0xFFFFFFFF);
5653#ifdef MCH_WRITE_DUMP
5654 if (fdDump)
5655 fputs("\\a\n", fdDump);
5656#endif
5657 s++;
5658 }
5659 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5660 {
5661#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005662 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005664 char_u *p;
5665 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666
5667 switch (s[2])
5668 {
5669 /* one or two numeric arguments, separated by ';' */
5670
5671 case '0': case '1': case '2': case '3': case '4':
5672 case '5': case '6': case '7': case '8': case '9':
5673 p = s + 2;
5674 arg1 = getdigits(&p); /* no check for length! */
5675 if (p > s + len)
5676 break;
5677
5678 if (*p == ';')
5679 {
5680 ++p;
5681 arg2 = getdigits(&p); /* no check for length! */
5682 if (p > s + len)
5683 break;
5684
5685 if (*p == 'H')
5686 gotoxy(arg2, arg1);
5687 else if (*p == 'r')
5688 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5689 }
5690 else if (*p == 'A')
5691 {
5692 /* move cursor up arg1 lines in same column */
5693 gotoxy(g_coord.X + 1,
5694 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5695 }
5696 else if (*p == 'C')
5697 {
5698 /* move cursor right arg1 columns in same line */
5699 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5700 g_coord.Y + 1);
5701 }
5702 else if (*p == 'H')
5703 {
5704 gotoxy(1, arg1);
5705 }
5706 else if (*p == 'L')
5707 {
5708 insert_lines(arg1);
5709 }
5710 else if (*p == 'm')
5711 {
5712 if (arg1 == 0)
5713 normvideo();
5714 else
5715 textattr((WORD) arg1);
5716 }
5717 else if (*p == 'f')
5718 {
5719 textcolor((WORD) arg1);
5720 }
5721 else if (*p == 'b')
5722 {
5723 textbackground((WORD) arg1);
5724 }
5725 else if (*p == 'M')
5726 {
5727 delete_lines(arg1);
5728 }
5729
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005730 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731 s = p + 1;
5732 break;
5733
5734
5735 /* Three-character escape sequences */
5736
5737 case 'A':
5738 /* move cursor up one line in same column */
5739 gotoxy(g_coord.X + 1,
5740 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5741 goto got3;
5742
5743 case 'B':
5744 visual_bell();
5745 goto got3;
5746
5747 case 'C':
5748 /* move cursor right one column in same line */
5749 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5750 g_coord.Y + 1);
5751 goto got3;
5752
5753 case 'E':
5754 termcap_mode_end();
5755 goto got3;
5756
5757 case 'F':
5758 standout();
5759 goto got3;
5760
5761 case 'f':
5762 standend();
5763 goto got3;
5764
5765 case 'H':
5766 gotoxy(1, 1);
5767 goto got3;
5768
5769 case 'j':
5770 clear_to_end_of_display();
5771 goto got3;
5772
5773 case 'J':
5774 clear_screen();
5775 goto got3;
5776
5777 case 'K':
5778 clear_to_end_of_line();
5779 goto got3;
5780
5781 case 'L':
5782 insert_lines(1);
5783 goto got3;
5784
5785 case 'M':
5786 delete_lines(1);
5787 goto got3;
5788
5789 case 'S':
5790 termcap_mode_start();
5791 goto got3;
5792
5793 case 'V':
5794 cursor_visible(TRUE);
5795 goto got3;
5796
5797 case 'v':
5798 cursor_visible(FALSE);
5799 goto got3;
5800
5801 got3:
5802 s += 3;
5803 len -= 2;
5804 }
5805
5806#ifdef MCH_WRITE_DUMP
5807 if (fdDump)
5808 {
5809 fputs("ESC | ", fdDump);
5810 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5811 fputc('\n', fdDump);
5812 }
5813#endif
5814 }
5815 else
5816 {
5817 /* Write a single character */
5818 DWORD nWritten;
5819
5820 nWritten = write_chars(s, 1);
5821#ifdef MCH_WRITE_DUMP
5822 if (fdDump)
5823 {
5824 fputc('>', fdDump);
5825 fwrite(s, sizeof(char_u), nWritten, fdDump);
5826 fputs("<\n", fdDump);
5827 }
5828#endif
5829
5830 len -= (nWritten - 1);
5831 s += nWritten;
5832 }
5833 }
5834
5835#ifdef MCH_WRITE_DUMP
5836 if (fdDump)
5837 fflush(fdDump);
5838#endif
5839}
5840
5841#endif /* FEAT_GUI_W32 */
5842
5843
5844/*
5845 * Delay for half a second.
5846 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005847/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848 void
5849mch_delay(
5850 long msec,
5851 int ignoreinput)
5852{
5853#ifdef FEAT_GUI_W32
5854 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005855#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005857# ifdef FEAT_MZSCHEME
5858 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5859 {
5860 int towait = p_mzq;
5861
5862 /* if msec is large enough, wait by portions in p_mzq */
5863 while (msec > 0)
5864 {
5865 mzvim_check_threads();
5866 if (msec < towait)
5867 towait = msec;
5868 Sleep(towait);
5869 msec -= towait;
5870 }
5871 }
5872 else
5873# endif
5874 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875 else
5876 WaitForChar(msec);
5877#endif
5878}
5879
5880
5881/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01005882 * This version of remove is not scared by a readonly (backup) file.
5883 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884 * Return 0 for success, -1 for failure.
5885 */
5886 int
5887mch_remove(char_u *name)
5888{
5889#ifdef FEAT_MBYTE
5890 WCHAR *wn = NULL;
5891 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005892#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893
Bram Moolenaar203258c2016-01-17 22:15:16 +01005894 /*
5895 * On Windows, deleting a directory's symbolic link is done by
5896 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
5897 */
5898 if (mch_isdir(name) && mch_is_symbolic_link(name))
5899 return mch_rmdir(name);
5900
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005901 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5902
5903#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005904 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5905 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005906 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907 if (wn != NULL)
5908 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909 n = DeleteFileW(wn) ? 0 : -1;
5910 vim_free(wn);
5911 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5912 return n;
5913 /* Retry with non-wide function (for Windows 98). */
5914 }
5915 }
5916#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917 return DeleteFile(name) ? 0 : -1;
5918}
5919
5920
5921/*
5922 * check for an "interrupt signal": CTRL-break or CTRL-C
5923 */
5924 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005925mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005926{
5927#ifndef FEAT_GUI_W32 /* never used */
5928 if (g_fCtrlCPressed || g_fCBrkPressed)
5929 {
5930 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5931 got_int = TRUE;
5932 }
5933#endif
5934}
5935
Bram Moolenaaree273972016-01-02 21:11:51 +01005936/* physical RAM to leave for the OS */
5937#define WINNT_RESERVE_BYTES (256*1024*1024)
5938#define WIN95_RESERVE_BYTES (8*1024*1024)
5939
5940/*
5941 * How much main memory in KiB that can be used by VIM.
5942 */
5943/*ARGSUSED*/
5944 long_u
5945mch_total_mem(int special)
5946{
5947 PlatformId();
5948#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
5949 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5950 {
5951 MEMORYSTATUSEX ms;
5952
5953 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5954 * what fits in 32 bits. But it's not always available. */
5955 ms.dwLength = sizeof(MEMORYSTATUSEX);
5956 GlobalMemoryStatusEx(&ms);
5957 if (ms.ullAvailVirtual < ms.ullTotalPhys)
5958 {
5959 /* Process address space fits in physical RAM, use all of it. */
5960 return (long_u)(ms.ullAvailVirtual / 1024);
5961 }
5962 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
5963 {
5964 /* Catch old NT box or perverse hardware setup. */
5965 return (long_u)((ms.ullTotalPhys / 2) / 1024);
5966 }
5967 /* Use physical RAM less reserve for OS + data. */
5968 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
5969 }
5970 else
5971#endif
5972 {
5973 /* Pre-XP or 95 OS handling. */
5974 MEMORYSTATUS ms;
5975 long_u os_reserve_bytes;
5976
5977 ms.dwLength = sizeof(MEMORYSTATUS);
5978 GlobalMemoryStatus(&ms);
5979 if (ms.dwAvailVirtual < ms.dwTotalPhys)
5980 {
5981 /* Process address space fits in physical RAM, use all of it. */
5982 return (long_u)(ms.dwAvailVirtual / 1024);
5983 }
5984 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
5985 ? WINNT_RESERVE_BYTES
5986 : WIN95_RESERVE_BYTES;
5987 if (ms.dwTotalPhys <= os_reserve_bytes)
5988 {
5989 /* Catch old boxes or perverse hardware setup. */
5990 return (long_u)((ms.dwTotalPhys / 2) / 1024);
5991 }
5992 /* Use physical RAM less reserve for OS + data. */
5993 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
5994 }
5995}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005996
Bram Moolenaar071d4272004-06-13 20:20:40 +00005997#ifdef FEAT_MBYTE
5998/*
5999 * Same code as below, but with wide functions and no comments.
6000 * Return 0 for success, non-zero for failure.
6001 */
6002 int
6003mch_wrename(WCHAR *wold, WCHAR *wnew)
6004{
6005 WCHAR *p;
6006 int i;
6007 WCHAR szTempFile[_MAX_PATH + 1];
6008 WCHAR szNewPath[_MAX_PATH + 1];
6009 HANDLE hf;
6010
6011 if (!mch_windows95())
6012 {
6013 p = wold;
6014 for (i = 0; wold[i] != NUL; ++i)
6015 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6016 && wold[i + 1] != 0)
6017 p = wold + i + 1;
6018 if ((int)(wold + i - p) < 8 || p[6] != '~')
6019 return (MoveFileW(wold, wnew) == 0);
6020 }
6021
6022 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6023 return -1;
6024 *p = NUL;
6025
6026 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6027 return -2;
6028
6029 if (!DeleteFileW(szTempFile))
6030 return -3;
6031
6032 if (!MoveFileW(wold, szTempFile))
6033 return -4;
6034
6035 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6036 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6037 return -5;
6038 if (!CloseHandle(hf))
6039 return -6;
6040
6041 if (!MoveFileW(szTempFile, wnew))
6042 {
6043 (void)MoveFileW(szTempFile, wold);
6044 return -7;
6045 }
6046
6047 DeleteFileW(szTempFile);
6048
6049 if (!DeleteFileW(wold))
6050 return -8;
6051
6052 return 0;
6053}
6054#endif
6055
6056
6057/*
6058 * mch_rename() works around a bug in rename (aka MoveFile) in
6059 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6060 * file whose short file name is "FOO.BAR" (its long file name will
6061 * be correct: "foo.bar~"). Because a file can be accessed by
6062 * either its SFN or its LFN, "foo.bar" has effectively been
6063 * renamed to "foo.bar", which is not at all what was wanted. This
6064 * seems to happen only when renaming files with three-character
6065 * extensions by appending a suffix that does not include ".".
6066 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6067 *
6068 * There is another problem, which isn't really a bug but isn't right either:
6069 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6070 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6071 * service pack 6. Doesn't seem to happen on Windows 98.
6072 *
6073 * Like rename(), returns 0 upon success, non-zero upon failure.
6074 * Should probably set errno appropriately when errors occur.
6075 */
6076 int
6077mch_rename(
6078 const char *pszOldFile,
6079 const char *pszNewFile)
6080{
6081 char szTempFile[_MAX_PATH+1];
6082 char szNewPath[_MAX_PATH+1];
6083 char *pszFilePart;
6084 HANDLE hf;
6085#ifdef FEAT_MBYTE
6086 WCHAR *wold = NULL;
6087 WCHAR *wnew = NULL;
6088 int retval = -1;
6089
6090 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6091 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006092 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6093 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094 if (wold != NULL && wnew != NULL)
6095 retval = mch_wrename(wold, wnew);
6096 vim_free(wold);
6097 vim_free(wnew);
6098 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6099 return retval;
6100 /* Retry with non-wide function (for Windows 98). */
6101 }
6102#endif
6103
6104 /*
6105 * No need to play tricks if not running Windows 95, unless the file name
6106 * contains a "~" as the seventh character.
6107 */
6108 if (!mch_windows95())
6109 {
6110 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6111 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6112 return rename(pszOldFile, pszNewFile);
6113 }
6114
6115 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6116 * a directory, no error is returned and pszFilePart will be NULL. */
6117 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6118 || pszFilePart == NULL)
6119 return -1;
6120 *pszFilePart = NUL;
6121
6122 /* Get (and create) a unique temporary file name in directory of new file */
6123 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6124 return -2;
6125
6126 /* blow the temp file away */
6127 if (!DeleteFile(szTempFile))
6128 return -3;
6129
6130 /* rename old file to the temp file */
6131 if (!MoveFile(pszOldFile, szTempFile))
6132 return -4;
6133
6134 /* now create an empty file called pszOldFile; this prevents the operating
6135 * system using pszOldFile as an alias (SFN) if we're renaming within the
6136 * same directory. For example, we're editing a file called
6137 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6138 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6139 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006140 * cause all sorts of problems later in buf_write(). So, we create an
6141 * empty file called filena~1.txt and the system will have to find some
6142 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143 */
6144 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6145 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6146 return -5;
6147 if (!CloseHandle(hf))
6148 return -6;
6149
6150 /* rename the temp file to the new file */
6151 if (!MoveFile(szTempFile, pszNewFile))
6152 {
6153 /* Renaming failed. Rename the file back to its old name, so that it
6154 * looks like nothing happened. */
6155 (void)MoveFile(szTempFile, pszOldFile);
6156
6157 return -7;
6158 }
6159
6160 /* Seems to be left around on Novell filesystems */
6161 DeleteFile(szTempFile);
6162
6163 /* finally, remove the empty old file */
6164 if (!DeleteFile(pszOldFile))
6165 return -8;
6166
6167 return 0; /* success */
6168}
6169
6170/*
6171 * Get the default shell for the current hardware platform
6172 */
6173 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006174default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175{
6176 char* psz = NULL;
6177
6178 PlatformId();
6179
6180 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6181 psz = "cmd.exe";
6182 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6183 psz = "command.com";
6184
6185 return psz;
6186}
6187
6188/*
6189 * mch_access() extends access() to do more detailed check on network drives.
6190 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6191 */
6192 int
6193mch_access(char *n, int p)
6194{
6195 HANDLE hFile;
6196 DWORD am;
6197 int retval = -1; /* default: fail */
6198#ifdef FEAT_MBYTE
6199 WCHAR *wn = NULL;
6200
6201 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006202 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203#endif
6204
6205 if (mch_isdir(n))
6206 {
6207 char TempName[_MAX_PATH + 16] = "";
6208#ifdef FEAT_MBYTE
6209 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6210#endif
6211
6212 if (p & R_OK)
6213 {
6214 /* Read check is performed by seeing if we can do a find file on
6215 * the directory for any file. */
6216#ifdef FEAT_MBYTE
6217 if (wn != NULL)
6218 {
6219 int i;
6220 WIN32_FIND_DATAW d;
6221
6222 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6223 TempNameW[i] = wn[i];
6224 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6225 TempNameW[i++] = '\\';
6226 TempNameW[i++] = '*';
6227 TempNameW[i++] = 0;
6228
6229 hFile = FindFirstFileW(TempNameW, &d);
6230 if (hFile == INVALID_HANDLE_VALUE)
6231 {
6232 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6233 goto getout;
6234
6235 /* Retry with non-wide function (for Windows 98). */
6236 vim_free(wn);
6237 wn = NULL;
6238 }
6239 else
6240 (void)FindClose(hFile);
6241 }
6242 if (wn == NULL)
6243#endif
6244 {
6245 char *pch;
6246 WIN32_FIND_DATA d;
6247
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006248 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 pch = TempName + STRLEN(TempName) - 1;
6250 if (*pch != '\\' && *pch != '/')
6251 *++pch = '\\';
6252 *++pch = '*';
6253 *++pch = NUL;
6254
6255 hFile = FindFirstFile(TempName, &d);
6256 if (hFile == INVALID_HANDLE_VALUE)
6257 goto getout;
6258 (void)FindClose(hFile);
6259 }
6260 }
6261
6262 if (p & W_OK)
6263 {
6264 /* Trying to create a temporary file in the directory should catch
6265 * directories on read-only network shares. However, in
6266 * directories whose ACL allows writes but denies deletes will end
6267 * up keeping the temporary file :-(. */
6268#ifdef FEAT_MBYTE
6269 if (wn != NULL)
6270 {
6271 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6272 {
6273 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6274 goto getout;
6275
6276 /* Retry with non-wide function (for Windows 98). */
6277 vim_free(wn);
6278 wn = NULL;
6279 }
6280 else
6281 DeleteFileW(TempNameW);
6282 }
6283 if (wn == NULL)
6284#endif
6285 {
6286 if (!GetTempFileName(n, "VIM", 0, TempName))
6287 goto getout;
6288 mch_remove((char_u *)TempName);
6289 }
6290 }
6291 }
6292 else
6293 {
6294 /* Trying to open the file for the required access does ACL, read-only
6295 * network share, and file attribute checks. */
6296 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6297 | ((p & R_OK) ? GENERIC_READ : 0);
6298#ifdef FEAT_MBYTE
6299 if (wn != NULL)
6300 {
6301 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6302 if (hFile == INVALID_HANDLE_VALUE
6303 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6304 {
6305 /* Retry with non-wide function (for Windows 98). */
6306 vim_free(wn);
6307 wn = NULL;
6308 }
6309 }
6310 if (wn == NULL)
6311#endif
6312 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6313 if (hFile == INVALID_HANDLE_VALUE)
6314 goto getout;
6315 CloseHandle(hFile);
6316 }
6317
6318 retval = 0; /* success */
6319getout:
6320#ifdef FEAT_MBYTE
6321 vim_free(wn);
6322#endif
6323 return retval;
6324}
6325
6326#if defined(FEAT_MBYTE) || defined(PROTO)
6327/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006328 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 */
6330 int
6331mch_open(char *name, int flags, int mode)
6332{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006333 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6334# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335 WCHAR *wn;
6336 int f;
6337
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006338 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006340 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341 if (wn != NULL)
6342 {
6343 f = _wopen(wn, flags, mode);
6344 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006345 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 return f;
6347 /* Retry with non-wide function (for Windows 98). Can't use
6348 * GetLastError() here and it's unclear what errno gets set to if
6349 * the _wopen() fails for missing wide functions. */
6350 }
6351 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006352# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006353
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006354 /* open() can open a file which name is longer than _MAX_PATH bytes
6355 * and shorter than _MAX_PATH characters successfully, but sometimes it
6356 * causes unexpected error in another part. We make it an error explicitly
6357 * here. */
6358 if (strlen(name) >= _MAX_PATH)
6359 return -1;
6360
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361 return open(name, flags, mode);
6362}
6363
6364/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006365 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 */
6367 FILE *
6368mch_fopen(char *name, char *mode)
6369{
6370 WCHAR *wn, *wm;
6371 FILE *f = NULL;
6372
6373 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6374# ifdef __BORLANDC__
6375 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6376 && g_PlatformId == VER_PLATFORM_WIN32_NT
6377# endif
6378 )
6379 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006380# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006381 /* Work around an annoying assertion in the Microsoft debug CRT
6382 * when mode's text/binary setting doesn't match _get_fmode(). */
6383 char newMode = mode[strlen(mode) - 1];
6384 int oldMode = 0;
6385
6386 _get_fmode(&oldMode);
6387 if (newMode == 't')
6388 _set_fmode(_O_TEXT);
6389 else if (newMode == 'b')
6390 _set_fmode(_O_BINARY);
6391# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006392 wn = enc_to_utf16(name, NULL);
6393 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006394 if (wn != NULL && wm != NULL)
6395 f = _wfopen(wn, wm);
6396 vim_free(wn);
6397 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006398
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006399# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006400 _set_fmode(oldMode);
6401# endif
6402
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006403 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404 return f;
6405 /* Retry with non-wide function (for Windows 98). Can't use
6406 * GetLastError() here and it's unclear what errno gets set to if
6407 * the _wfopen() fails for missing wide functions. */
6408 }
6409
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006410 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6411 * and shorter than _MAX_PATH characters successfully, but sometimes it
6412 * causes unexpected error in another part. We make it an error explicitly
6413 * here. */
6414 if (strlen(name) >= _MAX_PATH)
6415 return NULL;
6416
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417 return fopen(name, mode);
6418}
6419#endif
6420
6421#ifdef FEAT_MBYTE
6422/*
6423 * SUB STREAM (aka info stream) handling:
6424 *
6425 * NTFS can have sub streams for each file. Normal contents of file is
6426 * stored in the main stream, and extra contents (author information and
6427 * title and so on) can be stored in sub stream. After Windows 2000, user
6428 * can access and store those informations in sub streams via explorer's
6429 * property menuitem in right click menu. Those informations in sub streams
6430 * were lost when copying only the main stream. So we have to copy sub
6431 * streams.
6432 *
6433 * Incomplete explanation:
6434 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6435 * More useful info and an example:
6436 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6437 */
6438
6439/*
6440 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6441 * and write to stream "substream" of file "to".
6442 * Errors are ignored.
6443 */
6444 static void
6445copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6446{
6447 HANDLE hTo;
6448 WCHAR *to_name;
6449
6450 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6451 wcscpy(to_name, to);
6452 wcscat(to_name, substream);
6453
6454 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6455 FILE_ATTRIBUTE_NORMAL, NULL);
6456 if (hTo != INVALID_HANDLE_VALUE)
6457 {
6458 long done;
6459 DWORD todo;
6460 DWORD readcnt, written;
6461 char buf[4096];
6462
6463 /* Copy block of bytes at a time. Abort when something goes wrong. */
6464 for (done = 0; done < len; done += written)
6465 {
6466 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006467 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6468 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6470 FALSE, FALSE, context)
6471 || readcnt != todo
6472 || !WriteFile(hTo, buf, todo, &written, NULL)
6473 || written != todo)
6474 break;
6475 }
6476 CloseHandle(hTo);
6477 }
6478
6479 free(to_name);
6480}
6481
6482/*
6483 * Copy info streams from file "from" to file "to".
6484 */
6485 static void
6486copy_infostreams(char_u *from, char_u *to)
6487{
6488 WCHAR *fromw;
6489 WCHAR *tow;
6490 HANDLE sh;
6491 WIN32_STREAM_ID sid;
6492 int headersize;
6493 WCHAR streamname[_MAX_PATH];
6494 DWORD readcount;
6495 void *context = NULL;
6496 DWORD lo, hi;
6497 int len;
6498
6499 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006500 fromw = enc_to_utf16(from, NULL);
6501 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502 if (fromw != NULL && tow != NULL)
6503 {
6504 /* Open the file for reading. */
6505 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6506 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6507 if (sh != INVALID_HANDLE_VALUE)
6508 {
6509 /* Use BackupRead() to find the info streams. Repeat until we
6510 * have done them all.*/
6511 for (;;)
6512 {
6513 /* Get the header to find the length of the stream name. If
6514 * the "readcount" is zero we have done all info streams. */
6515 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006516 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6518 &readcount, FALSE, FALSE, &context)
6519 || readcount == 0)
6520 break;
6521
6522 /* We only deal with streams that have a name. The normal
6523 * file data appears to be without a name, even though docs
6524 * suggest it is called "::$DATA". */
6525 if (sid.dwStreamNameSize > 0)
6526 {
6527 /* Read the stream name. */
6528 if (!BackupRead(sh, (LPBYTE)streamname,
6529 sid.dwStreamNameSize,
6530 &readcount, FALSE, FALSE, &context))
6531 break;
6532
6533 /* Copy an info stream with a name ":anything:$DATA".
6534 * Skip "::$DATA", it has no stream name (examples suggest
6535 * it might be used for the normal file contents).
6536 * Note that BackupRead() counts bytes, but the name is in
6537 * wide characters. */
6538 len = readcount / sizeof(WCHAR);
6539 streamname[len] = 0;
6540 if (len > 7 && wcsicmp(streamname + len - 6,
6541 L":$DATA") == 0)
6542 {
6543 streamname[len - 6] = 0;
6544 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006545 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546 }
6547 }
6548
6549 /* Advance to the next stream. We might try seeking too far,
6550 * but BackupSeek() doesn't skip over stream borders, thus
6551 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006552 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553 &lo, &hi, &context);
6554 }
6555
6556 /* Clear the context. */
6557 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6558
6559 CloseHandle(sh);
6560 }
6561 }
6562 vim_free(fromw);
6563 vim_free(tow);
6564}
6565#endif
6566
6567/*
6568 * Copy file attributes from file "from" to file "to".
6569 * For Windows NT and later we copy info streams.
6570 * Always returns zero, errors are ignored.
6571 */
6572 int
6573mch_copy_file_attribute(char_u *from, char_u *to)
6574{
6575#ifdef FEAT_MBYTE
6576 /* File streams only work on Windows NT and later. */
6577 PlatformId();
6578 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6579 copy_infostreams(from, to);
6580#endif
6581 return 0;
6582}
6583
6584#if defined(MYRESETSTKOFLW) || defined(PROTO)
6585/*
6586 * Recreate a destroyed stack guard page in win32.
6587 * Written by Benjamin Peterson.
6588 */
6589
6590/* These magic numbers are from the MS header files */
6591#define MIN_STACK_WIN9X 17
6592#define MIN_STACK_WINNT 2
6593
6594/*
6595 * This function does the same thing as _resetstkoflw(), which is only
6596 * available in DevStudio .net and later.
6597 * Returns 0 for failure, 1 for success.
6598 */
6599 int
6600myresetstkoflw(void)
6601{
6602 BYTE *pStackPtr;
6603 BYTE *pGuardPage;
6604 BYTE *pStackBase;
6605 BYTE *pLowestPossiblePage;
6606 MEMORY_BASIC_INFORMATION mbi;
6607 SYSTEM_INFO si;
6608 DWORD nPageSize;
6609 DWORD dummy;
6610
6611 /* This code will not work on win32s. */
6612 PlatformId();
6613 if (g_PlatformId == VER_PLATFORM_WIN32s)
6614 return 0;
6615
6616 /* We need to know the system page size. */
6617 GetSystemInfo(&si);
6618 nPageSize = si.dwPageSize;
6619
6620 /* ...and the current stack pointer */
6621 pStackPtr = (BYTE*)_alloca(1);
6622
6623 /* ...and the base of the stack. */
6624 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6625 return 0;
6626 pStackBase = (BYTE*)mbi.AllocationBase;
6627
6628 /* ...and the page thats min_stack_req pages away from stack base; this is
6629 * the lowest page we could use. */
6630 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6631 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6632
6633 /* On Win95, we want the next page down from the end of the stack. */
6634 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6635 {
6636 /* Find the page that's only 1 page down from the page that the stack
6637 * ptr is in. */
6638 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6639 / (DWORD)nPageSize) - 1));
6640 if (pGuardPage < pLowestPossiblePage)
6641 return 0;
6642
6643 /* Apply the noaccess attribute to the page -- there's no guard
6644 * attribute in win95-type OSes. */
6645 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6646 return 0;
6647 }
6648 else
6649 {
6650 /* On NT, however, we want the first committed page in the stack Start
6651 * at the stack base and move forward through memory until we find a
6652 * committed block. */
6653 BYTE *pBlock = pStackBase;
6654
Bram Moolenaara466c992005-07-09 21:03:22 +00006655 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 {
6657 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6658 return 0;
6659
6660 pBlock += mbi.RegionSize;
6661
6662 if (mbi.State & MEM_COMMIT)
6663 break;
6664 }
6665
6666 /* mbi now describes the first committed block in the stack. */
6667 if (mbi.Protect & PAGE_GUARD)
6668 return 1;
6669
6670 /* decide where the guard page should start */
6671 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6672 pGuardPage = pLowestPossiblePage;
6673 else
6674 pGuardPage = (BYTE*)mbi.BaseAddress;
6675
6676 /* allocate the guard page */
6677 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6678 return 0;
6679
6680 /* apply the guard attribute to the page */
6681 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6682 &dummy))
6683 return 0;
6684 }
6685
6686 return 1;
6687}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006688#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006690
6691#if defined(FEAT_MBYTE) || defined(PROTO)
6692/*
6693 * The command line arguments in UCS2
6694 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006695static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006696static LPWSTR *ArglistW = NULL;
6697static int global_argc = 0;
6698static char **global_argv;
6699
6700static int used_file_argc = 0; /* last argument in global_argv[] used
6701 for the argument list. */
6702static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6703 command line arguments added to
6704 the argument list */
6705static int used_file_count = 0; /* nr of entries in used_file_indexes */
6706static int used_file_literal = FALSE; /* take file names literally */
6707static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006708static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006709static int used_alist_count = 0;
6710
6711
6712/*
6713 * Get the command line arguments. Unicode version.
6714 * Returns argc. Zero when something fails.
6715 */
6716 int
6717get_cmd_argsW(char ***argvp)
6718{
6719 char **argv = NULL;
6720 int argc = 0;
6721 int i;
6722
Bram Moolenaar14993322014-09-09 12:25:33 +02006723 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006724 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6725 if (ArglistW != NULL)
6726 {
6727 argv = malloc((nArgsW + 1) * sizeof(char *));
6728 if (argv != NULL)
6729 {
6730 argc = nArgsW;
6731 argv[argc] = NULL;
6732 for (i = 0; i < argc; ++i)
6733 {
6734 int len;
6735
6736 /* Convert each Unicode argument to the current codepage. */
6737 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006738 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006739 (LPSTR *)&argv[i], &len, 0, 0);
6740 if (argv[i] == NULL)
6741 {
6742 /* Out of memory, clear everything. */
6743 while (i > 0)
6744 free(argv[--i]);
6745 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006746 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006747 argc = 0;
6748 }
6749 }
6750 }
6751 }
6752
6753 global_argc = argc;
6754 global_argv = argv;
6755 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006756 {
6757 if (used_file_indexes != NULL)
6758 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006759 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006760 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006761
6762 if (argvp != NULL)
6763 *argvp = argv;
6764 return argc;
6765}
6766
6767 void
6768free_cmd_argsW(void)
6769{
6770 if (ArglistW != NULL)
6771 {
6772 GlobalFree(ArglistW);
6773 ArglistW = NULL;
6774 }
6775}
6776
6777/*
6778 * Remember "name" is an argument that was added to the argument list.
6779 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6780 * is called.
6781 */
6782 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006783used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006784{
6785 int i;
6786
6787 if (used_file_indexes == NULL)
6788 return;
6789 for (i = used_file_argc + 1; i < global_argc; ++i)
6790 if (STRCMP(global_argv[i], name) == 0)
6791 {
6792 used_file_argc = i;
6793 used_file_indexes[used_file_count++] = i;
6794 break;
6795 }
6796 used_file_literal = literal;
6797 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006798 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006799}
6800
6801/*
6802 * Remember the length of the argument list as it was. If it changes then we
6803 * leave it alone when 'encoding' is set.
6804 */
6805 void
6806set_alist_count(void)
6807{
6808 used_alist_count = GARGCOUNT;
6809}
6810
6811/*
6812 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6813 * has been changed while starting up. Use the UCS-2 command line arguments
6814 * and convert them to 'encoding'.
6815 */
6816 void
6817fix_arg_enc(void)
6818{
6819 int i;
6820 int idx;
6821 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006822 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006823
6824 /* Safety checks:
6825 * - if argument count differs between the wide and non-wide argument
6826 * list, something must be wrong.
6827 * - the file name arguments must have been located.
6828 * - the length of the argument list wasn't changed by the user.
6829 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006830 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006831 || ArglistW == NULL
6832 || used_file_indexes == NULL
6833 || used_file_count == 0
6834 || used_alist_count != GARGCOUNT)
6835 return;
6836
Bram Moolenaar86b68352004-12-27 21:59:20 +00006837 /* Remember the buffer numbers for the arguments. */
6838 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6839 if (fnum_list == NULL)
6840 return; /* out of memory */
6841 for (i = 0; i < GARGCOUNT; ++i)
6842 fnum_list[i] = GARGLIST[i].ae_fnum;
6843
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006844 /* Clear the argument list. Make room for the new arguments. */
6845 alist_clear(&global_alist);
6846 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006847 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006848
6849 for (i = 0; i < used_file_count; ++i)
6850 {
6851 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006852 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006853 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006854 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006855#ifdef FEAT_DIFF
6856 /* When using diff mode may need to concatenate file name to
6857 * directory name. Just like it's done in main(). */
6858 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6859 && !mch_isdir(alist_name(&GARGLIST[0])))
6860 {
6861 char_u *r;
6862
6863 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6864 if (r != NULL)
6865 {
6866 vim_free(str);
6867 str = r;
6868 }
6869 }
6870#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006871 /* Re-use the old buffer by renaming it. When not using literal
6872 * names it's done by alist_expand() below. */
6873 if (used_file_literal)
6874 buf_set_name(fnum_list[i], str);
6875
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006876 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006877 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006878 }
6879
6880 if (!used_file_literal)
6881 {
6882 /* Now expand wildcards in the arguments. */
6883 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6884 * filename characters but are excluded from 'isfname' to make
6885 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6886 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006887 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006888 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6889 }
6890
6891 /* If wildcard expansion failed, we are editing the first file of the
6892 * arglist and there is no file name: Edit the first argument now. */
6893 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6894 {
6895 do_cmdline_cmd((char_u *)":rewind");
6896 if (GARGCOUNT == 1 && used_file_full_path)
6897 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6898 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006899
6900 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006901}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902#endif