blob: d7b563459d8851a43b4c624a0a7104cf1fa4f9ac [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
Bram Moolenaar071d4272004-06-13 20:20:40 +000094typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000095typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000096typedef int ACCESS_MASK;
97typedef int BOOL;
98typedef int COLORREF;
99typedef int CONSOLE_CURSOR_INFO;
100typedef int COORD;
101typedef int DWORD;
102typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100103typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000104typedef int HDC;
105typedef int HFONT;
106typedef int HICON;
107typedef int HINSTANCE;
108typedef int HWND;
109typedef int INPUT_RECORD;
110typedef int KEY_EVENT_RECORD;
111typedef int LOGFONT;
112typedef int LPBOOL;
113typedef int LPCTSTR;
114typedef int LPDWORD;
115typedef int LPSTR;
116typedef int LPTSTR;
117typedef int LPVOID;
118typedef int MOUSE_EVENT_RECORD;
119typedef int PACL;
120typedef int PDWORD;
121typedef int PHANDLE;
122typedef int PRINTDLG;
123typedef int PSECURITY_DESCRIPTOR;
124typedef int PSID;
125typedef int SECURITY_INFORMATION;
126typedef int SHORT;
127typedef int SMALL_RECT;
128typedef int TEXTMETRIC;
129typedef int TOKEN_INFORMATION_CLASS;
130typedef int TRUSTEE;
131typedef int WORD;
132typedef int WCHAR;
133typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100134typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200135typedef int SE_OBJECT_TYPE;
136typedef int PSNSECINFO;
137typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100138typedef int STARTUPINFO;
139typedef int PROCESS_INFORMATION;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140#endif
141
142#ifndef FEAT_GUI_W32
143/* Undocumented API in kernel32.dll needed to work around dead key bug in
144 * console-mode applications in NT 4.0. If you switch keyboard layouts
145 * in a console app to a layout that includes dead keys and then hit a
146 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
147 * and Michael Dietrich for helping me figure out this workaround.
148 */
149
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100150/* WINAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
151#ifndef WINAPI
152# define WINAPI __stdcall
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153#endif
154#if defined(__BORLANDC__)
155typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
156#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100157typedef BOOL (WINAPI *PFNGCKLN)(LPSTR);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000159static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160#endif
161
162#if defined(__BORLANDC__)
163/* Strangely Borland uses a non-standard name. */
164# define wcsicmp(a, b) wcscmpi((a), (b))
165#endif
166
Bram Moolenaar82881492012-11-20 16:53:39 +0100167#ifndef PROTO
168
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200169/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200170#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100171LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200172BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
173BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
174BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
175#endif
176
Bram Moolenaar82881492012-11-20 16:53:39 +0100177#endif /* PROTO */
178
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179#ifndef FEAT_GUI_W32
180/* Win32 Console handles for input and output */
181static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
182static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
183
184/* Win32 Screen buffer,coordinate,console I/O information */
185static SMALL_RECT g_srScrollRegion;
186static COORD g_coord; /* 0-based, but external coords are 1-based */
187
188/* The attribute of the screen when the editor was started */
189static WORD g_attrDefault = 7; /* lightgray text on black background */
190static WORD g_attrCurrent;
191
192static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
193static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
194static int g_fForceExit = FALSE; /* set when forcefully exiting */
195
196static void termcap_mode_start(void);
197static void termcap_mode_end(void);
198static void clear_chars(COORD coord, DWORD n);
199static void clear_screen(void);
200static void clear_to_end_of_display(void);
201static void clear_to_end_of_line(void);
202static void scroll(unsigned cLines);
203static void set_scroll_region(unsigned left, unsigned top,
204 unsigned right, unsigned bottom);
205static void insert_lines(unsigned cLines);
206static void delete_lines(unsigned cLines);
207static void gotoxy(unsigned x, unsigned y);
208static void normvideo(void);
209static void textattr(WORD wAttr);
210static void textcolor(WORD wAttr);
211static void textbackground(WORD wAttr);
212static void standout(void);
213static void standend(void);
214static void visual_bell(void);
215static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200216static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
217static WCHAR tgetch(int *pmodifiers, WCHAR *pch2);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218static void create_conin(void);
219static int s_cursor_visible = TRUE;
220static int did_create_conin = FALSE;
221#else
222static int s_dont_use_vimrun = TRUE;
223static int need_vimrun_warning = FALSE;
224static char *vimrun_path = "vimrun ";
225#endif
226
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200227static int win32_getattrs(char_u *name);
228static int win32_setattrs(char_u *name, int attrs);
229static int win32_set_archive(char_u *name);
230
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231#ifndef FEAT_GUI_W32
232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100239#ifndef FEAT_GUI_W32
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 Moolenaar418f81b2016-02-16 20:12:02 +0100329# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200330 static DWORD
331msg_wait_for_multiple_objects(
332 DWORD nCount,
333 LPHANDLE pHandles,
334 BOOL fWaitAll,
335 DWORD dwMilliseconds,
336 DWORD dwWakeMask)
337{
338 if (read_console_input(NULL, NULL, -2, NULL))
339 return WAIT_OBJECT_0;
340 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
341 dwMilliseconds, dwWakeMask);
342}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100343# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200344
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100345# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200346 static DWORD
347wait_for_single_object(
348 HANDLE hHandle,
349 DWORD dwMilliseconds)
350{
351 if (read_console_input(NULL, NULL, -2, NULL))
352 return WAIT_OBJECT_0;
353 return WaitForSingleObject(hHandle, dwMilliseconds);
354}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100355# endif
356#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200357
Bram Moolenaar071d4272004-06-13 20:20:40 +0000358 static void
359get_exe_name(void)
360{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100361 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
362 * as the maximum length that works (plus a NUL byte). */
363#define MAX_ENV_PATH_LEN 8192
364 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200365 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366
367 if (exe_name == NULL)
368 {
369 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100370 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371 if (*temp != NUL)
372 exe_name = FullName_save((char_u *)temp, FALSE);
373 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000374
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200375 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000376 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200377 exe_path = vim_strnsave(exe_name,
378 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200379 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000380 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200381 /* Append our starting directory to $PATH, so that when doing
382 * "!xxd" it's found in our starting directory. Needed because
383 * SearchPath() also looks there. */
384 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100385 if (p == NULL
386 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200387 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100388 if (p == NULL || *p == NUL)
389 temp[0] = NUL;
390 else
391 {
392 STRCPY(temp, p);
393 STRCAT(temp, ";");
394 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200395 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100396 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200397 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000398 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000399 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400}
401
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200402/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100403 * Unescape characters in "p" that appear in "escaped".
404 */
405 static void
406unescape_shellxquote(char_u *p, char_u *escaped)
407{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100408 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100409 int n;
410
411 while (*p != NUL)
412 {
413 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
414 mch_memmove(p, p + 1, l--);
415#ifdef FEAT_MBYTE
416 n = (*mb_ptr2len)(p);
417#else
418 n = 1;
419#endif
420 p += n;
421 l -= n;
422 }
423}
424
425/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200426 * Load library "name".
427 */
428 HINSTANCE
429vimLoadLib(char *name)
430{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200431 HINSTANCE dll = NULL;
432 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200433
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200434 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
435 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200436 if (exe_path == NULL)
437 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200438 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200439 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200440#ifdef FEAT_MBYTE
441 WCHAR old_dirw[MAXPATHL];
442
443 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
444 {
445 /* Change directory to where the executable is, both to make
446 * sure we find a .dll there and to avoid looking for a .dll
447 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100448 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200449 dll = LoadLibrary(name);
450 SetCurrentDirectoryW(old_dirw);
451 return dll;
452 }
453 /* Retry with non-wide function (for Windows 98). */
454 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
455#endif
456 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
457 {
458 /* Change directory to where the executable is, both to make
459 * sure we find a .dll there and to avoid looking for a .dll
460 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100461 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200462 dll = LoadLibrary(name);
463 SetCurrentDirectory(old_dir);
464 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200465 }
466 return dll;
467}
468
Bram Moolenaar071d4272004-06-13 20:20:40 +0000469#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
470# ifndef GETTEXT_DLL
471# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100472# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200474/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000475static char *null_libintl_gettext(const char *);
476static char *null_libintl_textdomain(const char *);
477static char *null_libintl_bindtextdomain(const char *, const char *);
478static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000481char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
482char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
483char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000485char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
486 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000487
488 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100489dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000490{
491 int i;
492 static struct
493 {
494 char *name;
495 FARPROC *ptr;
496 } libintl_entry[] =
497 {
498 {"gettext", (FARPROC*)&dyn_libintl_gettext},
499 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
500 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
501 {NULL, NULL}
502 };
503
504 /* No need to initialize twice. */
505 if (hLibintlDLL)
506 return 1;
507 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100508 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100509#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100510 if (!hLibintlDLL)
511 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100512#endif
513 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200515 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000516 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200517 verbose_enter();
518 EMSG2(_(e_loadlib), GETTEXT_DLL);
519 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200521 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522 }
523 for (i = 0; libintl_entry[i].name != NULL
524 && libintl_entry[i].ptr != NULL; ++i)
525 {
526 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
527 libintl_entry[i].name)) == NULL)
528 {
529 dyn_libintl_end();
530 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000531 {
532 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000534 verbose_leave();
535 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 return 0;
537 }
538 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000539
540 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000541 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000542 "bind_textdomain_codeset");
543 if (dyn_libintl_bind_textdomain_codeset == NULL)
544 dyn_libintl_bind_textdomain_codeset =
545 null_libintl_bind_textdomain_codeset;
546
Bram Moolenaar071d4272004-06-13 20:20:40 +0000547 return 1;
548}
549
550 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100551dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552{
553 if (hLibintlDLL)
554 FreeLibrary(hLibintlDLL);
555 hLibintlDLL = NULL;
556 dyn_libintl_gettext = null_libintl_gettext;
557 dyn_libintl_textdomain = null_libintl_textdomain;
558 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000559 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560}
561
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000562/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000563 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000564null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565{
566 return (char*)msgid;
567}
568
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000569/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000571null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572{
573 return NULL;
574}
575
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000576/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000578null_libintl_bind_textdomain_codeset(const char *domainname,
579 const char *codeset)
580{
581 return NULL;
582}
583
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000584/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000585 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000586null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587{
588 return NULL;
589}
590
591#endif /* DYNAMIC_GETTEXT */
592
593/* This symbol is not defined in older versions of the SDK or Visual C++ */
594
595#ifndef VER_PLATFORM_WIN32_WINDOWS
596# define VER_PLATFORM_WIN32_WINDOWS 1
597#endif
598
599DWORD g_PlatformId;
600
601#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100602# ifndef PROTO
603# include <aclapi.h>
604# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200605# ifndef PROTECTED_DACL_SECURITY_INFORMATION
606# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
607# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100608
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609/*
610 * These are needed to dynamically load the ADVAPI DLL, which is not
611 * implemented under Windows 95 (and causes VIM to crash)
612 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200613typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200615typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
617 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200618# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200619typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200620 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200621typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200622 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
623 PSECURITY_DESCRIPTOR *);
624# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000625
626static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
627static PSNSECINFO pSetNamedSecurityInfo;
628static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200629# ifdef FEAT_MBYTE
630static PSNSECINFOW pSetNamedSecurityInfoW;
631static PGNSECINFOW pGetNamedSecurityInfoW;
632# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633#endif
634
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200635typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
636
637static BOOL allowPiping = FALSE;
638static PSETHANDLEINFORMATION pSetHandleInformation;
639
Bram Moolenaar27515922013-06-29 15:36:26 +0200640#ifdef HAVE_ACL
641/*
642 * Enables or disables the specified privilege.
643 */
644 static BOOL
645win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
646{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100647 BOOL bResult;
648 LUID luid;
649 HANDLE hToken;
650 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200651
652 if (!OpenProcessToken(GetCurrentProcess(),
653 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
654 return FALSE;
655
656 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
657 {
658 CloseHandle(hToken);
659 return FALSE;
660 }
661
Bram Moolenaar45500912014-07-09 20:51:07 +0200662 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200663 tokenPrivileges.Privileges[0].Luid = luid;
664 tokenPrivileges.Privileges[0].Attributes = bEnable ?
665 SE_PRIVILEGE_ENABLED : 0;
666
667 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
668 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
669
670 CloseHandle(hToken);
671
672 return bResult && GetLastError() == ERROR_SUCCESS;
673}
674#endif
675
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676/*
677 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
678 * VER_PLATFORM_WIN32_WINDOWS (Win95).
679 */
680 void
681PlatformId(void)
682{
683 static int done = FALSE;
684
685 if (!done)
686 {
687 OSVERSIONINFO ovi;
688
689 ovi.dwOSVersionInfoSize = sizeof(ovi);
690 GetVersionEx(&ovi);
691
692 g_PlatformId = ovi.dwPlatformId;
693
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100694 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
695 || ovi.dwMajorVersion > 6)
696 win8_or_later = TRUE;
697
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698#ifdef HAVE_ACL
699 /*
700 * Load the ADVAPI runtime if we are on anything
701 * other than Windows 95
702 */
703 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
704 {
705 /*
706 * do this load. Problems: Doesn't unload at end of run (this is
707 * theoretically okay, since Windows should unload it when VIM
708 * terminates). Should we be using the 'mch_libcall' routines?
709 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
710 * time we verify security...
711 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200712 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713 if (advapi_lib != NULL)
714 {
715 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
716 "SetNamedSecurityInfoA");
717 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
718 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200719# ifdef FEAT_MBYTE
720 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
721 "SetNamedSecurityInfoW");
722 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
723 "GetNamedSecurityInfoW");
724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200726 || pGetNamedSecurityInfo == NULL
727# ifdef FEAT_MBYTE
728 || pSetNamedSecurityInfoW == NULL
729 || pGetNamedSecurityInfoW == NULL
730# endif
731 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732 {
733 /* If we can't get the function addresses, set advapi_lib
734 * to NULL so that we don't use them. */
735 FreeLibrary(advapi_lib);
736 advapi_lib = NULL;
737 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200738 /* Enable privilege for getting or setting SACLs. */
739 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 }
741 }
742#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200743 /*
744 * If we are on windows NT, try to load the pipe functions, only
745 * available from Win2K.
746 */
747 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
748 {
749 HANDLE kernel32 = GetModuleHandle("kernel32");
750 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
751 kernel32, "SetHandleInformation");
752
753 allowPiping = pSetHandleInformation != NULL;
754 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 done = TRUE;
756 }
757}
758
759/*
760 * Return TRUE when running on Windows 95 (or 98 or ME).
761 * Only to be used after mch_init().
762 */
763 int
764mch_windows95(void)
765{
766 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
767}
768
769#ifdef FEAT_GUI_W32
770/*
771 * Used to work around the "can't do synchronous spawn"
772 * problem on Win32s, without resorting to Universal Thunk.
773 */
774static int old_num_windows;
775static int num_windows;
776
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000777/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 static BOOL CALLBACK
779win32ssynch_cb(HWND hwnd, LPARAM lparam)
780{
781 num_windows++;
782 return TRUE;
783}
784#endif
785
786#ifndef FEAT_GUI_W32
787
788#define SHIFT (SHIFT_PRESSED)
789#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
790#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
791#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
792
793
794/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
795 * We map function keys to their ANSI terminal equivalents, as produced
796 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
797 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
798 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
799 * combinations of function/arrow/etc keys.
800 */
801
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000802static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803{
804 WORD wVirtKey;
805 BOOL fAnsiKey;
806 int chAlone;
807 int chShift;
808 int chCtrl;
809 int chAlt;
810} VirtKeyMap[] =
811{
812
813/* Key ANSI alone shift ctrl alt */
814 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
815
816 { VK_F1, TRUE, ';', 'T', '^', 'h', },
817 { VK_F2, TRUE, '<', 'U', '_', 'i', },
818 { VK_F3, TRUE, '=', 'V', '`', 'j', },
819 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
820 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
821 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
822 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
823 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
824 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
825 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
826 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
827 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
828
829 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
830 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
831 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
832 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
833 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
834 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
835 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
836 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
837 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
838 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
839
840 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
841
842#if 0
843 /* Most people don't have F13-F20, but what the hell... */
844 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
845 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
846 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
847 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
848 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
849 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
850 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
851 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
852#endif
853 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
854 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
855 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
856 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
857
858 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
859 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
860 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
861 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
862 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
863 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
864 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
865 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
866 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
867 /* Sorry, out of number space! <negri>*/
868 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
869
870};
871
872
873#ifdef _MSC_VER
874// The ToAscii bug destroys several registers. Need to turn off optimization
875// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000876# pragma warning(push)
877# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878# pragma optimize("", off)
879#endif
880
881#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200882# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200884# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885#endif
886
887/* The return code indicates key code size. */
888 static int
889#ifdef __BORLANDC__
890 __stdcall
891#endif
892win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000893 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894{
895 UINT uMods = pker->dwControlKeyState;
896 static int s_iIsDead = 0;
897 static WORD awAnsiCode[2];
898 static BYTE abKeystate[256];
899
900
901 if (s_iIsDead == 2)
902 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200903 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904 s_iIsDead = 0;
905 return 1;
906 }
907
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200908 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909 return 1;
910
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200911 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912
913 // Should only be non-NULL on NT 4.0
914 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
915 {
916 CHAR szKLID[KL_NAMELENGTH];
917
918 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
919 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
920 }
921
922 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200923 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924
925 if (uMods & SHIFT_PRESSED)
926 abKeystate[VK_SHIFT] = 0x80;
927 if (uMods & CAPSLOCK_ON)
928 abKeystate[VK_CAPITAL] = 1;
929
930 if ((uMods & ALT_GR) == ALT_GR)
931 {
932 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
933 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
934 }
935
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200936 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
937 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938
939 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200940 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941
942 return s_iIsDead;
943}
944
945#ifdef _MSC_VER
946/* MUST switch optimization on again here, otherwise a call to
947 * decode_key_event() may crash (e.g. when hitting caps-lock) */
948# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000949# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950
951# if (_MSC_VER < 1100)
952/* MUST turn off global optimisation for this next function, or
953 * pressing ctrl-minus in insert mode crashes Vim when built with
954 * VC4.1. -- negri. */
955# pragma optimize("g", off)
956# endif
957#endif
958
959static BOOL g_fJustGotFocus = FALSE;
960
961/*
962 * Decode a KEY_EVENT into one or two keystrokes
963 */
964 static BOOL
965decode_key_event(
966 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200967 WCHAR *pch,
968 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969 int *pmodifiers,
970 BOOL fDoPost)
971{
972 int i;
973 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
974
975 *pch = *pch2 = NUL;
976 g_fJustGotFocus = FALSE;
977
978 /* ignore key up events */
979 if (!pker->bKeyDown)
980 return FALSE;
981
982 /* ignore some keystrokes */
983 switch (pker->wVirtualKeyCode)
984 {
985 /* modifiers */
986 case VK_SHIFT:
987 case VK_CONTROL:
988 case VK_MENU: /* Alt key */
989 return FALSE;
990
991 default:
992 break;
993 }
994
995 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200996 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997 {
998 /* Ctrl-6 is Ctrl-^ */
999 if (pker->wVirtualKeyCode == '6')
1000 {
1001 *pch = Ctrl_HAT;
1002 return TRUE;
1003 }
1004 /* Ctrl-2 is Ctrl-@ */
1005 else if (pker->wVirtualKeyCode == '2')
1006 {
1007 *pch = NUL;
1008 return TRUE;
1009 }
1010 /* Ctrl-- is Ctrl-_ */
1011 else if (pker->wVirtualKeyCode == 0xBD)
1012 {
1013 *pch = Ctrl__;
1014 return TRUE;
1015 }
1016 }
1017
1018 /* Shift-TAB */
1019 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1020 {
1021 *pch = K_NUL;
1022 *pch2 = '\017';
1023 return TRUE;
1024 }
1025
1026 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1027 {
1028 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1029 {
1030 if (nModifs == 0)
1031 *pch = VirtKeyMap[i].chAlone;
1032 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1033 *pch = VirtKeyMap[i].chShift;
1034 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1035 *pch = VirtKeyMap[i].chCtrl;
1036 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1037 *pch = VirtKeyMap[i].chAlt;
1038
1039 if (*pch != 0)
1040 {
1041 if (VirtKeyMap[i].fAnsiKey)
1042 {
1043 *pch2 = *pch;
1044 *pch = K_NUL;
1045 }
1046
1047 return TRUE;
1048 }
1049 }
1050 }
1051
1052 i = win32_kbd_patch_key(pker);
1053
1054 if (i < 0)
1055 *pch = NUL;
1056 else
1057 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001058 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059
1060 if (pmodifiers != NULL)
1061 {
1062 /* Pass on the ALT key as a modifier, but only when not combined
1063 * with CTRL (which is ALTGR). */
1064 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1065 *pmodifiers |= MOD_MASK_ALT;
1066
1067 /* Pass on SHIFT only for special keys, because we don't know when
1068 * it's already included with the character. */
1069 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1070 *pmodifiers |= MOD_MASK_SHIFT;
1071
1072 /* Pass on CTRL only for non-special keys, because we don't know
1073 * when it's already included with the character. And not when
1074 * combined with ALT (which is ALTGR). */
1075 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1076 && *pch >= 0x20 && *pch < 0x80)
1077 *pmodifiers |= MOD_MASK_CTRL;
1078 }
1079 }
1080
1081 return (*pch != NUL);
1082}
1083
1084#ifdef _MSC_VER
1085# pragma optimize("", on)
1086#endif
1087
1088#endif /* FEAT_GUI_W32 */
1089
1090
1091#ifdef FEAT_MOUSE
1092
1093/*
1094 * For the GUI the mouse handling is in gui_w32.c.
1095 */
1096# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001097/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001099mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100{
1101}
1102# else
1103static int g_fMouseAvail = FALSE; /* mouse present */
1104static int g_fMouseActive = FALSE; /* mouse enabled */
1105static int g_nMouseClick = -1; /* mouse status */
1106static int g_xMouse; /* mouse x coordinate */
1107static int g_yMouse; /* mouse y coordinate */
1108
1109/*
1110 * Enable or disable mouse input
1111 */
1112 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001113mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114{
1115 DWORD cmodein;
1116
1117 if (!g_fMouseAvail)
1118 return;
1119
1120 g_fMouseActive = on;
1121 GetConsoleMode(g_hConIn, &cmodein);
1122
1123 if (g_fMouseActive)
1124 cmodein |= ENABLE_MOUSE_INPUT;
1125 else
1126 cmodein &= ~ENABLE_MOUSE_INPUT;
1127
1128 SetConsoleMode(g_hConIn, cmodein);
1129}
1130
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131/*
1132 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1133 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1134 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1135 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1136 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1137 * and we return the mouse position in g_xMouse and g_yMouse.
1138 *
1139 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1140 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1141 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1142 *
1143 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1144 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1145 *
1146 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1147 * moves, even if it stays within the same character cell. We ignore
1148 * all MOUSE_MOVED messages if the position hasn't really changed, and
1149 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1150 * we're only interested in MOUSE_DRAG).
1151 *
1152 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1153 * 2-button mouses by pressing the left & right buttons simultaneously.
1154 * In practice, it's almost impossible to click both at the same time,
1155 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1156 * in such cases, if the user is clicking quickly.
1157 */
1158 static BOOL
1159decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001160 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161{
1162 static int s_nOldButton = -1;
1163 static int s_nOldMouseClick = -1;
1164 static int s_xOldMouse = -1;
1165 static int s_yOldMouse = -1;
1166 static linenr_T s_old_topline = 0;
1167#ifdef FEAT_DIFF
1168 static int s_old_topfill = 0;
1169#endif
1170 static int s_cClicks = 1;
1171 static BOOL s_fReleased = TRUE;
1172 static DWORD s_dwLastClickTime = 0;
1173 static BOOL s_fNextIsMiddle = FALSE;
1174
1175 static DWORD cButtons = 0; /* number of buttons supported */
1176
1177 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1178 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1179 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1180 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1181
1182 int nButton;
1183
1184 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1185 cButtons = 2;
1186
1187 if (!g_fMouseAvail || !g_fMouseActive)
1188 {
1189 g_nMouseClick = -1;
1190 return FALSE;
1191 }
1192
1193 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1194 if (g_fJustGotFocus)
1195 {
1196 g_fJustGotFocus = FALSE;
1197 return FALSE;
1198 }
1199
1200 /* unprocessed mouse click? */
1201 if (g_nMouseClick != -1)
1202 return TRUE;
1203
1204 nButton = -1;
1205 g_xMouse = pmer->dwMousePosition.X;
1206 g_yMouse = pmer->dwMousePosition.Y;
1207
1208 if (pmer->dwEventFlags == MOUSE_MOVED)
1209 {
1210 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1211 * events even when the mouse moves only within a char cell.) */
1212 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1213 return FALSE;
1214 }
1215
1216 /* If no buttons are pressed... */
1217 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1218 {
1219 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1220 if (s_fReleased)
1221 return FALSE;
1222
1223 nButton = MOUSE_RELEASE;
1224 s_fReleased = TRUE;
1225 }
1226 else /* one or more buttons pressed */
1227 {
1228 /* on a 2-button mouse, hold down left and right buttons
1229 * simultaneously to get MIDDLE. */
1230
1231 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1232 {
1233 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1234
1235 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001236 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001237 if (dwLR == LEFT || dwLR == RIGHT)
1238 {
1239 for (;;)
1240 {
1241 /* wait a short time for next input event */
1242 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1243 != WAIT_OBJECT_0)
1244 break;
1245 else
1246 {
1247 DWORD cRecords = 0;
1248 INPUT_RECORD ir;
1249 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1250
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001251 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252
1253 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1254 || !(pmer2->dwButtonState & LEFT_RIGHT))
1255 break;
1256 else
1257 {
1258 if (pmer2->dwEventFlags != MOUSE_MOVED)
1259 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001260 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261
1262 return decode_mouse_event(pmer2);
1263 }
1264 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1265 s_yOldMouse == pmer2->dwMousePosition.Y)
1266 {
1267 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001268 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269
1270 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001271 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001272
1273 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1274 break;
1275 }
1276 else
1277 break;
1278 }
1279 }
1280 }
1281 }
1282 }
1283
1284 if (s_fNextIsMiddle)
1285 {
1286 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1287 ? MOUSE_DRAG : MOUSE_MIDDLE;
1288 s_fNextIsMiddle = FALSE;
1289 }
1290 else if (cButtons == 2 &&
1291 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1292 {
1293 nButton = MOUSE_MIDDLE;
1294
1295 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1296 {
1297 s_fNextIsMiddle = TRUE;
1298 nButton = MOUSE_RELEASE;
1299 }
1300 }
1301 else if ((pmer->dwButtonState & LEFT) == LEFT)
1302 nButton = MOUSE_LEFT;
1303 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1304 nButton = MOUSE_MIDDLE;
1305 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1306 nButton = MOUSE_RIGHT;
1307
1308 if (! s_fReleased && ! s_fNextIsMiddle
1309 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1310 return FALSE;
1311
1312 s_fReleased = s_fNextIsMiddle;
1313 }
1314
1315 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1316 {
1317 /* button pressed or released, without mouse moving */
1318 if (nButton != -1 && nButton != MOUSE_RELEASE)
1319 {
1320 DWORD dwCurrentTime = GetTickCount();
1321
1322 if (s_xOldMouse != g_xMouse
1323 || s_yOldMouse != g_yMouse
1324 || s_nOldButton != nButton
1325 || s_old_topline != curwin->w_topline
1326#ifdef FEAT_DIFF
1327 || s_old_topfill != curwin->w_topfill
1328#endif
1329 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1330 {
1331 s_cClicks = 1;
1332 }
1333 else if (++s_cClicks > 4)
1334 {
1335 s_cClicks = 1;
1336 }
1337
1338 s_dwLastClickTime = dwCurrentTime;
1339 }
1340 }
1341 else if (pmer->dwEventFlags == MOUSE_MOVED)
1342 {
1343 if (nButton != -1 && nButton != MOUSE_RELEASE)
1344 nButton = MOUSE_DRAG;
1345
1346 s_cClicks = 1;
1347 }
1348
1349 if (nButton == -1)
1350 return FALSE;
1351
1352 if (nButton != MOUSE_RELEASE)
1353 s_nOldButton = nButton;
1354
1355 g_nMouseClick = nButton;
1356
1357 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1358 g_nMouseClick |= MOUSE_SHIFT;
1359 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1360 g_nMouseClick |= MOUSE_CTRL;
1361 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1362 g_nMouseClick |= MOUSE_ALT;
1363
1364 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1365 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1366
1367 /* only pass on interesting (i.e., different) mouse events */
1368 if (s_xOldMouse == g_xMouse
1369 && s_yOldMouse == g_yMouse
1370 && s_nOldMouseClick == g_nMouseClick)
1371 {
1372 g_nMouseClick = -1;
1373 return FALSE;
1374 }
1375
1376 s_xOldMouse = g_xMouse;
1377 s_yOldMouse = g_yMouse;
1378 s_old_topline = curwin->w_topline;
1379#ifdef FEAT_DIFF
1380 s_old_topfill = curwin->w_topfill;
1381#endif
1382 s_nOldMouseClick = g_nMouseClick;
1383
1384 return TRUE;
1385}
1386
1387# endif /* FEAT_GUI_W32 */
1388#endif /* FEAT_MOUSE */
1389
1390
1391#ifdef MCH_CURSOR_SHAPE
1392/*
1393 * Set the shape of the cursor.
1394 * 'thickness' can be from 1 (thin) to 99 (block)
1395 */
1396 static void
1397mch_set_cursor_shape(int thickness)
1398{
1399 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1400 ConsoleCursorInfo.dwSize = thickness;
1401 ConsoleCursorInfo.bVisible = s_cursor_visible;
1402
1403 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1404 if (s_cursor_visible)
1405 SetConsoleCursorPosition(g_hConOut, g_coord);
1406}
1407
1408 void
1409mch_update_cursor(void)
1410{
1411 int idx;
1412 int thickness;
1413
1414 /*
1415 * How the cursor is drawn depends on the current mode.
1416 */
1417 idx = get_shape_idx(FALSE);
1418
1419 if (shape_table[idx].shape == SHAPE_BLOCK)
1420 thickness = 99; /* 100 doesn't work on W95 */
1421 else
1422 thickness = shape_table[idx].percentage;
1423 mch_set_cursor_shape(thickness);
1424}
1425#endif
1426
1427#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1428/*
1429 * Handle FOCUS_EVENT.
1430 */
1431 static void
1432handle_focus_event(INPUT_RECORD ir)
1433{
1434 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1435 ui_focus_change((int)g_fJustGotFocus);
1436}
1437
1438/*
1439 * Wait until console input from keyboard or mouse is available,
1440 * or the time is up.
1441 * Return TRUE if something is available FALSE if not.
1442 */
1443 static int
1444WaitForChar(long msec)
1445{
1446 DWORD dwNow = 0, dwEndTime = 0;
1447 INPUT_RECORD ir;
1448 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001449 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450
1451 if (msec > 0)
1452 /* Wait until the specified time has elapsed. */
1453 dwEndTime = GetTickCount() + msec;
1454 else if (msec < 0)
1455 /* Wait forever. */
1456 dwEndTime = INFINITE;
1457
1458 /* We need to loop until the end of the time period, because
1459 * we might get multiple unusable mouse events in that time.
1460 */
1461 for (;;)
1462 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001463#ifdef MESSAGE_QUEUE
1464 parse_queued_messages();
1465#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001466#ifdef FEAT_MZSCHEME
1467 mzvim_check_threads();
1468#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469#ifdef FEAT_CLIENTSERVER
1470 serverProcessPendingMessages();
1471#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001472
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473 if (0
1474#ifdef FEAT_MOUSE
1475 || g_nMouseClick != -1
1476#endif
1477#ifdef FEAT_CLIENTSERVER
1478 || input_available()
1479#endif
1480 )
1481 return TRUE;
1482
1483 if (msec > 0)
1484 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001485 /* If the specified wait time has passed, return. Beware that
1486 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001487 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001488 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 break;
1490 }
1491 if (msec != 0)
1492 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001493 DWORD dwWaitTime = dwEndTime - dwNow;
1494
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001495#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar9186a272016-02-23 19:34:01 +01001496 /* Check channel while waiting input. */
1497 if (dwWaitTime > 100)
1498 dwWaitTime = 100;
1499#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001500#ifdef FEAT_MZSCHEME
1501 if (mzthreads_allowed() && p_mzq > 0
1502 && (msec < 0 || (long)dwWaitTime > p_mzq))
1503 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1504#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505#ifdef FEAT_CLIENTSERVER
1506 /* Wait for either an event on the console input or a message in
1507 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001508 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001509 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001511 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512#endif
1513 continue;
1514 }
1515
1516 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001517 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518
1519#ifdef FEAT_MBYTE_IME
1520 if (State & CMDLINE && msg_row == Rows - 1)
1521 {
1522 CONSOLE_SCREEN_BUFFER_INFO csbi;
1523
1524 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1525 {
1526 if (csbi.dwCursorPosition.Y != msg_row)
1527 {
1528 /* The screen is now messed up, must redraw the
1529 * command line and later all the windows. */
1530 redraw_all_later(CLEAR);
1531 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1532 redrawcmd();
1533 }
1534 }
1535 }
1536#endif
1537
1538 if (cRecords > 0)
1539 {
1540 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1541 {
1542#ifdef FEAT_MBYTE_IME
1543 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1544 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001545 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1547 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001548 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549 continue;
1550 }
1551#endif
1552 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1553 NULL, FALSE))
1554 return TRUE;
1555 }
1556
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001557 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558
1559 if (ir.EventType == FOCUS_EVENT)
1560 handle_focus_event(ir);
1561 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1562 shell_resized();
1563#ifdef FEAT_MOUSE
1564 else if (ir.EventType == MOUSE_EVENT
1565 && decode_mouse_event(&ir.Event.MouseEvent))
1566 return TRUE;
1567#endif
1568 }
1569 else if (msec == 0)
1570 break;
1571 }
1572
1573#ifdef FEAT_CLIENTSERVER
1574 /* Something might have been received while we were waiting. */
1575 if (input_available())
1576 return TRUE;
1577#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001578
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579 return FALSE;
1580}
1581
1582#ifndef FEAT_GUI_MSWIN
1583/*
1584 * return non-zero if a character is available
1585 */
1586 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001587mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588{
1589 return WaitForChar(0L);
1590}
1591#endif
1592
1593/*
1594 * Create the console input. Used when reading stdin doesn't work.
1595 */
1596 static void
1597create_conin(void)
1598{
1599 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1600 FILE_SHARE_READ|FILE_SHARE_WRITE,
1601 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001602 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 did_create_conin = TRUE;
1604}
1605
1606/*
1607 * Get a keystroke or a mouse event
1608 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001609 static WCHAR
1610tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001612 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613
1614 for (;;)
1615 {
1616 INPUT_RECORD ir;
1617 DWORD cRecords = 0;
1618
1619#ifdef FEAT_CLIENTSERVER
1620 (void)WaitForChar(-1L);
1621 if (input_available())
1622 return 0;
1623# ifdef FEAT_MOUSE
1624 if (g_nMouseClick != -1)
1625 return 0;
1626# endif
1627#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001628 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629 {
1630 if (did_create_conin)
1631 read_error_exit();
1632 create_conin();
1633 continue;
1634 }
1635
1636 if (ir.EventType == KEY_EVENT)
1637 {
1638 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1639 pmodifiers, TRUE))
1640 return ch;
1641 }
1642 else if (ir.EventType == FOCUS_EVENT)
1643 handle_focus_event(ir);
1644 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1645 shell_resized();
1646#ifdef FEAT_MOUSE
1647 else if (ir.EventType == MOUSE_EVENT)
1648 {
1649 if (decode_mouse_event(&ir.Event.MouseEvent))
1650 return 0;
1651 }
1652#endif
1653 }
1654}
1655#endif /* !FEAT_GUI_W32 */
1656
1657
1658/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001659 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660 * Get one or more characters from the keyboard or the mouse.
1661 * If time == 0, do not wait for characters.
1662 * If time == n, wait a short time for characters.
1663 * If time == -1, wait forever for characters.
1664 * Returns the number of characters read into buf.
1665 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001666/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667 int
1668mch_inchar(
1669 char_u *buf,
1670 int maxlen,
1671 long time,
1672 int tb_change_cnt)
1673{
1674#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1675
1676 int len;
1677 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678#define TYPEAHEADLEN 20
1679 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1680 static int typeaheadlen = 0;
1681
1682 /* First use any typeahead that was kept because "buf" was too small. */
1683 if (typeaheadlen > 0)
1684 goto theend;
1685
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 if (time >= 0)
1687 {
1688 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 }
1691 else /* time == -1, wait forever */
1692 {
1693 mch_set_winsize_now(); /* Allow winsize changes from now on */
1694
Bram Moolenaar3918c952005-03-15 22:34:55 +00001695 /*
1696 * If there is no character available within 2 seconds (default)
1697 * write the autoscript file to disk. Or cause the CursorHold event
1698 * to be triggered.
1699 */
1700 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701 {
1702#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001703 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001705 buf[0] = K_SPECIAL;
1706 buf[1] = KS_EXTRA;
1707 buf[2] = (int)KE_CURSORHOLD;
1708 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 }
1710#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001711 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 }
1713 }
1714
1715 /*
1716 * Try to read as many characters as there are, until the buffer is full.
1717 */
1718
1719 /* we will get at least one key. Get more if they are available. */
1720 g_fCBrkPressed = FALSE;
1721
1722#ifdef MCH_WRITE_DUMP
1723 if (fdDump)
1724 fputc('[', fdDump);
1725#endif
1726
1727 /* Keep looping until there is something in the typeahead buffer and more
1728 * to get and still room in the buffer (up to two bytes for a char and
1729 * three bytes for a modifier). */
1730 while ((typeaheadlen == 0 || WaitForChar(0L))
1731 && typeaheadlen + 5 <= TYPEAHEADLEN)
1732 {
1733 if (typebuf_changed(tb_change_cnt))
1734 {
1735 /* "buf" may be invalid now if a client put something in the
1736 * typeahead buffer and "buf" is in the typeahead buffer. */
1737 typeaheadlen = 0;
1738 break;
1739 }
1740#ifdef FEAT_MOUSE
1741 if (g_nMouseClick != -1)
1742 {
1743# ifdef MCH_WRITE_DUMP
1744 if (fdDump)
1745 fprintf(fdDump, "{%02x @ %d, %d}",
1746 g_nMouseClick, g_xMouse, g_yMouse);
1747# endif
1748 typeahead[typeaheadlen++] = ESC + 128;
1749 typeahead[typeaheadlen++] = 'M';
1750 typeahead[typeaheadlen++] = g_nMouseClick;
1751 typeahead[typeaheadlen++] = g_xMouse + '!';
1752 typeahead[typeaheadlen++] = g_yMouse + '!';
1753 g_nMouseClick = -1;
1754 }
1755 else
1756#endif
1757 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001758 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001759 int modifiers = 0;
1760
1761 c = tgetch(&modifiers, &ch2);
1762
1763 if (typebuf_changed(tb_change_cnt))
1764 {
1765 /* "buf" may be invalid now if a client put something in the
1766 * typeahead buffer and "buf" is in the typeahead buffer. */
1767 typeaheadlen = 0;
1768 break;
1769 }
1770
1771 if (c == Ctrl_C && ctrl_c_interrupts)
1772 {
1773#if defined(FEAT_CLIENTSERVER)
1774 trash_input_buf();
1775#endif
1776 got_int = TRUE;
1777 }
1778
1779#ifdef FEAT_MOUSE
1780 if (g_nMouseClick == -1)
1781#endif
1782 {
1783 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001784 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001785
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001786#ifdef FEAT_MBYTE
1787 if (ch2 == NUL)
1788 {
1789 int i;
1790 char_u *p;
1791 WCHAR ch[2];
1792
1793 ch[0] = c;
1794 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1795 {
1796 ch[1] = tgetch(&modifiers, &ch2);
1797 n++;
1798 }
1799 p = utf16_to_enc(ch, &n);
1800 if (p != NULL)
1801 {
1802 for (i = 0; i < n; i++)
1803 typeahead[typeaheadlen + i] = p[i];
1804 vim_free(p);
1805 }
1806 }
1807 else
1808#endif
1809 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 if (ch2 != NUL)
1811 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001812 typeahead[typeaheadlen + n] = 3;
1813 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001814 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816
Bram Moolenaar45500912014-07-09 20:51:07 +02001817 if (conv)
1818 {
1819 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001820
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001821 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001822 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001823 char_u *e = typeahead + TYPEAHEADLEN;
1824
1825 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001826 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001827 if (*p == K_NUL)
1828 {
1829 ++p;
1830 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1831 *p = 3;
1832 ++n;
1833 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001834 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001835 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001836 }
1837 }
1838
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839 /* Use the ALT key to set the 8th bit of the character
1840 * when it's one byte, the 8th bit isn't set yet and not
1841 * using a double-byte encoding (would become a lead
1842 * byte). */
1843 if ((modifiers & MOD_MASK_ALT)
1844 && n == 1
1845 && (typeahead[typeaheadlen] & 0x80) == 0
1846#ifdef FEAT_MBYTE
1847 && !enc_dbcs
1848#endif
1849 )
1850 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001851#ifdef FEAT_MBYTE
1852 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1853 typeahead + typeaheadlen);
1854#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001856#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001857 modifiers &= ~MOD_MASK_ALT;
1858 }
1859
1860 if (modifiers != 0)
1861 {
1862 /* Prepend modifiers to the character. */
1863 mch_memmove(typeahead + typeaheadlen + 3,
1864 typeahead + typeaheadlen, n);
1865 typeahead[typeaheadlen++] = K_SPECIAL;
1866 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1867 typeahead[typeaheadlen++] = modifiers;
1868 }
1869
1870 typeaheadlen += n;
1871
1872#ifdef MCH_WRITE_DUMP
1873 if (fdDump)
1874 fputc(c, fdDump);
1875#endif
1876 }
1877 }
1878 }
1879
1880#ifdef MCH_WRITE_DUMP
1881 if (fdDump)
1882 {
1883 fputs("]\n", fdDump);
1884 fflush(fdDump);
1885 }
1886#endif
1887
Bram Moolenaar071d4272004-06-13 20:20:40 +00001888theend:
1889 /* Move typeahead to "buf", as much as fits. */
1890 len = 0;
1891 while (len < maxlen && typeaheadlen > 0)
1892 {
1893 buf[len++] = typeahead[0];
1894 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1895 }
1896 return len;
1897
1898#else /* FEAT_GUI_W32 */
1899 return 0;
1900#endif /* FEAT_GUI_W32 */
1901}
1902
Bram Moolenaar82881492012-11-20 16:53:39 +01001903#ifndef PROTO
1904# ifndef __MINGW32__
1905# include <shellapi.h> /* required for FindExecutable() */
1906# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907#endif
1908
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001909/*
1910 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001911 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001912 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001914executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001916 char *dum;
1917 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001918 char *curpath, *newpath;
1919 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001921#ifdef FEAT_MBYTE
1922 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001924 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001925 WCHAR fnamew[_MAX_PATH];
1926 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001927 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001928
1929 if (p != NULL)
1930 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001931 wcurpath = _wgetenv(L"PATH");
1932 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1933 * sizeof(WCHAR));
1934 if (wnewpath == NULL)
1935 return FALSE;
1936 wcscpy(wnewpath, L".;");
1937 wcscat(wnewpath, wcurpath);
1938 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1939 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001940 vim_free(p);
1941 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1942 {
1943 if (n == 0)
1944 return FALSE;
1945 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1946 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001947 if (path != NULL)
1948 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001949 return TRUE;
1950 }
1951 /* Retry with non-wide function (for Windows 98). */
1952 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001954#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001955
1956 curpath = getenv("PATH");
1957 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1958 if (newpath == NULL)
1959 return FALSE;
1960 STRCPY(newpath, ".;");
1961 STRCAT(newpath, curpath);
1962 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1963 vim_free(newpath);
1964 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001965 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001966 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001967 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001968 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001969 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001970 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971}
1972
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001973#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001974 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001975/*
1976 * Bad parameter handler.
1977 *
1978 * Certain MS CRT functions will intentionally crash when passed invalid
1979 * parameters to highlight possible security holes. Setting this function as
1980 * the bad parameter handler will prevent the crash.
1981 *
1982 * In debug builds the parameters contain CRT information that might help track
1983 * down the source of a problem, but in non-debug builds the arguments are all
1984 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1985 * worth allowing these to make debugging of issues easier.
1986 */
1987 static void
1988bad_param_handler(const wchar_t *expression,
1989 const wchar_t *function,
1990 const wchar_t *file,
1991 unsigned int line,
1992 uintptr_t pReserved)
1993{
1994}
1995
1996# define SET_INVALID_PARAM_HANDLER \
1997 ((void)_set_invalid_parameter_handler(bad_param_handler))
1998#else
1999# define SET_INVALID_PARAM_HANDLER
2000#endif
2001
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002#ifdef FEAT_GUI_W32
2003
2004/*
2005 * GUI version of mch_init().
2006 */
2007 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002008mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009{
2010#ifndef __MINGW32__
2011 extern int _fmode;
2012#endif
2013
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002014 /* Silently handle invalid parameters to CRT functions */
2015 SET_INVALID_PARAM_HANDLER;
2016
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017 /* Let critical errors result in a failure, not in a dialog box. Required
2018 * for the timestamp test to work on removed floppies. */
2019 SetErrorMode(SEM_FAILCRITICALERRORS);
2020
2021 _fmode = O_BINARY; /* we do our own CR-LF translation */
2022
2023 /* Specify window size. Is there a place to get the default from? */
2024 Rows = 25;
2025 Columns = 80;
2026
2027 /* Look for 'vimrun' */
2028 if (!gui_is_win32s())
2029 {
2030 char_u vimrun_location[_MAX_PATH + 4];
2031
2032 /* First try in same directory as gvim.exe */
2033 STRCPY(vimrun_location, exe_name);
2034 STRCPY(gettail(vimrun_location), "vimrun.exe");
2035 if (mch_getperm(vimrun_location) >= 0)
2036 {
2037 if (*skiptowhite(vimrun_location) != NUL)
2038 {
2039 /* Enclose path with white space in double quotes. */
2040 mch_memmove(vimrun_location + 1, vimrun_location,
2041 STRLEN(vimrun_location) + 1);
2042 *vimrun_location = '"';
2043 STRCPY(gettail(vimrun_location), "vimrun\" ");
2044 }
2045 else
2046 STRCPY(gettail(vimrun_location), "vimrun ");
2047
2048 vimrun_path = (char *)vim_strsave(vimrun_location);
2049 s_dont_use_vimrun = FALSE;
2050 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002051 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052 s_dont_use_vimrun = FALSE;
2053
2054 /* Don't give the warning for a missing vimrun.exe right now, but only
2055 * when vimrun was supposed to be used. Don't bother people that do
2056 * not need vimrun.exe. */
2057 if (s_dont_use_vimrun)
2058 need_vimrun_warning = TRUE;
2059 }
2060
2061 /*
2062 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2063 * Otherwise the default "findstr /n" is used.
2064 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002065 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2067
2068#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002069 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070#endif
2071}
2072
2073
2074#else /* FEAT_GUI_W32 */
2075
2076#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2077#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2078
2079/*
2080 * ClearConsoleBuffer()
2081 * Description:
2082 * Clears the entire contents of the console screen buffer, using the
2083 * specified attribute.
2084 * Returns:
2085 * TRUE on success
2086 */
2087 static BOOL
2088ClearConsoleBuffer(WORD wAttribute)
2089{
2090 CONSOLE_SCREEN_BUFFER_INFO csbi;
2091 COORD coord;
2092 DWORD NumCells, dummy;
2093
2094 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2095 return FALSE;
2096
2097 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2098 coord.X = 0;
2099 coord.Y = 0;
2100 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2101 coord, &dummy))
2102 {
2103 return FALSE;
2104 }
2105 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2106 coord, &dummy))
2107 {
2108 return FALSE;
2109 }
2110
2111 return TRUE;
2112}
2113
2114/*
2115 * FitConsoleWindow()
2116 * Description:
2117 * Checks if the console window will fit within given buffer dimensions.
2118 * Also, if requested, will shrink the window to fit.
2119 * Returns:
2120 * TRUE on success
2121 */
2122 static BOOL
2123FitConsoleWindow(
2124 COORD dwBufferSize,
2125 BOOL WantAdjust)
2126{
2127 CONSOLE_SCREEN_BUFFER_INFO csbi;
2128 COORD dwWindowSize;
2129 BOOL NeedAdjust = FALSE;
2130
2131 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2132 {
2133 /*
2134 * A buffer resize will fail if the current console window does
2135 * not lie completely within that buffer. To avoid this, we might
2136 * have to move and possibly shrink the window.
2137 */
2138 if (csbi.srWindow.Right >= dwBufferSize.X)
2139 {
2140 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2141 if (dwWindowSize.X > dwBufferSize.X)
2142 dwWindowSize.X = dwBufferSize.X;
2143 csbi.srWindow.Right = dwBufferSize.X - 1;
2144 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2145 NeedAdjust = TRUE;
2146 }
2147 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2148 {
2149 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2150 if (dwWindowSize.Y > dwBufferSize.Y)
2151 dwWindowSize.Y = dwBufferSize.Y;
2152 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2153 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2154 NeedAdjust = TRUE;
2155 }
2156 if (NeedAdjust && WantAdjust)
2157 {
2158 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2159 return FALSE;
2160 }
2161 return TRUE;
2162 }
2163
2164 return FALSE;
2165}
2166
2167typedef struct ConsoleBufferStruct
2168{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002169 BOOL IsValid;
2170 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002171 PCHAR_INFO Buffer;
2172 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173} ConsoleBuffer;
2174
2175/*
2176 * SaveConsoleBuffer()
2177 * Description:
2178 * Saves important information about the console buffer, including the
2179 * actual buffer contents. The saved information is suitable for later
2180 * restoration by RestoreConsoleBuffer().
2181 * Returns:
2182 * TRUE if all information was saved; FALSE otherwise
2183 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2184 */
2185 static BOOL
2186SaveConsoleBuffer(
2187 ConsoleBuffer *cb)
2188{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002189 DWORD NumCells;
2190 COORD BufferCoord;
2191 SMALL_RECT ReadRegion;
2192 WORD Y, Y_incr;
2193
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194 if (cb == NULL)
2195 return FALSE;
2196
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002197 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 {
2199 cb->IsValid = FALSE;
2200 return FALSE;
2201 }
2202 cb->IsValid = TRUE;
2203
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002204 /*
2205 * Allocate a buffer large enough to hold the entire console screen
2206 * buffer. If this ConsoleBuffer structure has already been initialized
2207 * with a buffer of the correct size, then just use that one.
2208 */
2209 if (!cb->IsValid || cb->Buffer == NULL ||
2210 cb->BufferSize.X != cb->Info.dwSize.X ||
2211 cb->BufferSize.Y != cb->Info.dwSize.Y)
2212 {
2213 cb->BufferSize.X = cb->Info.dwSize.X;
2214 cb->BufferSize.Y = cb->Info.dwSize.Y;
2215 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2216 vim_free(cb->Buffer);
2217 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2218 if (cb->Buffer == NULL)
2219 return FALSE;
2220 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002221
2222 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002223 * We will now copy the console screen buffer into our buffer.
2224 * ReadConsoleOutput() seems to be limited as far as how much you
2225 * can read at a time. Empirically, this number seems to be about
2226 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2227 * in chunks until it is all copied. The chunks will all have the
2228 * same horizontal characteristics, so initialize them now. The
2229 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002231 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002232 ReadRegion.Left = 0;
2233 ReadRegion.Right = cb->Info.dwSize.X - 1;
2234 Y_incr = 12000 / cb->Info.dwSize.X;
2235 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002237 /*
2238 * Read into position (0, Y) in our buffer.
2239 */
2240 BufferCoord.Y = Y;
2241 /*
2242 * Read the region whose top left corner is (0, Y) and whose bottom
2243 * right corner is (width - 1, Y + Y_incr - 1). This should define
2244 * a region of size width by Y_incr. Don't worry if this region is
2245 * too large for the remaining buffer; it will be cropped.
2246 */
2247 ReadRegion.Top = Y;
2248 ReadRegion.Bottom = Y + Y_incr - 1;
2249 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2250 cb->Buffer, /* our buffer */
2251 cb->BufferSize, /* dimensions of our buffer */
2252 BufferCoord, /* offset in our buffer */
2253 &ReadRegion)) /* region to save */
2254 {
2255 vim_free(cb->Buffer);
2256 cb->Buffer = NULL;
2257 return FALSE;
2258 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259 }
2260
2261 return TRUE;
2262}
2263
2264/*
2265 * RestoreConsoleBuffer()
2266 * Description:
2267 * Restores important information about the console buffer, including the
2268 * actual buffer contents, if desired. The information to restore is in
2269 * the same format used by SaveConsoleBuffer().
2270 * Returns:
2271 * TRUE on success
2272 */
2273 static BOOL
2274RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002275 ConsoleBuffer *cb,
2276 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002278 COORD BufferCoord;
2279 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280
2281 if (cb == NULL || !cb->IsValid)
2282 return FALSE;
2283
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002284 /*
2285 * Before restoring the buffer contents, clear the current buffer, and
2286 * restore the cursor position and window information. Doing this now
2287 * prevents old buffer contents from "flashing" onto the screen.
2288 */
2289 if (RestoreScreen)
2290 ClearConsoleBuffer(cb->Info.wAttributes);
2291
2292 FitConsoleWindow(cb->Info.dwSize, TRUE);
2293 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2294 return FALSE;
2295 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2296 return FALSE;
2297
2298 if (!RestoreScreen)
2299 {
2300 /*
2301 * No need to restore the screen buffer contents, so we're done.
2302 */
2303 return TRUE;
2304 }
2305
2306 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2307 return FALSE;
2308 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2309 return FALSE;
2310
2311 /*
2312 * Restore the screen buffer contents.
2313 */
2314 if (cb->Buffer != NULL)
2315 {
2316 BufferCoord.X = 0;
2317 BufferCoord.Y = 0;
2318 WriteRegion.Left = 0;
2319 WriteRegion.Top = 0;
2320 WriteRegion.Right = cb->Info.dwSize.X - 1;
2321 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2322 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2323 cb->Buffer, /* our buffer */
2324 cb->BufferSize, /* dimensions of our buffer */
2325 BufferCoord, /* offset in our buffer */
2326 &WriteRegion)) /* region to restore */
2327 {
2328 return FALSE;
2329 }
2330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331
2332 return TRUE;
2333}
2334
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002335#define FEAT_RESTORE_ORIG_SCREEN
2336#ifdef FEAT_RESTORE_ORIG_SCREEN
2337static ConsoleBuffer g_cbOrig = { 0 };
2338#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339static ConsoleBuffer g_cbNonTermcap = { 0 };
2340static ConsoleBuffer g_cbTermcap = { 0 };
2341
2342#ifdef FEAT_TITLE
2343#ifdef __BORLANDC__
2344typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2345#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002346typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347#endif
2348char g_szOrigTitle[256] = { 0 };
2349HWND g_hWnd = NULL; /* also used in os_mswin.c */
2350static HICON g_hOrigIconSmall = NULL;
2351static HICON g_hOrigIcon = NULL;
2352static HICON g_hVimIcon = NULL;
2353static BOOL g_fCanChangeIcon = FALSE;
2354
2355/* ICON* are not defined in VC++ 4.0 */
2356#ifndef ICON_SMALL
2357#define ICON_SMALL 0
2358#endif
2359#ifndef ICON_BIG
2360#define ICON_BIG 1
2361#endif
2362/*
2363 * GetConsoleIcon()
2364 * Description:
2365 * Attempts to retrieve the small icon and/or the big icon currently in
2366 * use by a given window.
2367 * Returns:
2368 * TRUE on success
2369 */
2370 static BOOL
2371GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002372 HWND hWnd,
2373 HICON *phIconSmall,
2374 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375{
2376 if (hWnd == NULL)
2377 return FALSE;
2378
2379 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002380 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2381 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002383 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2384 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385 return TRUE;
2386}
2387
2388/*
2389 * SetConsoleIcon()
2390 * Description:
2391 * Attempts to change the small icon and/or the big icon currently in
2392 * use by a given window.
2393 * Returns:
2394 * TRUE on success
2395 */
2396 static BOOL
2397SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002398 HWND hWnd,
2399 HICON hIconSmall,
2400 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 if (hWnd == NULL)
2403 return FALSE;
2404
2405 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002406 SendMessage(hWnd, WM_SETICON,
2407 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002409 SendMessage(hWnd, WM_SETICON,
2410 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411 return TRUE;
2412}
2413
2414/*
2415 * SaveConsoleTitleAndIcon()
2416 * Description:
2417 * Saves the current console window title in g_szOrigTitle, for later
2418 * restoration. Also, attempts to obtain a handle to the console window,
2419 * and use it to save the small and big icons currently in use by the
2420 * console window. This is not always possible on some versions of Windows;
2421 * nor is it possible when running Vim remotely using Telnet (since the
2422 * console window the user sees is owned by a remote process).
2423 */
2424 static void
2425SaveConsoleTitleAndIcon(void)
2426{
2427 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2428
2429 /* Save the original title. */
2430 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2431 return;
2432
2433 /*
2434 * Obtain a handle to the console window using GetConsoleWindow() from
2435 * KERNEL32.DLL; we need to handle in order to change the window icon.
2436 * This function only exists on NT-based Windows, starting with Windows
2437 * 2000. On older operating systems, we can't change the window icon
2438 * anyway.
2439 */
2440 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2441 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2442 "GetConsoleWindow")) != NULL)
2443 {
2444 g_hWnd = (*GetConsoleWindowProc)();
2445 }
2446 if (g_hWnd == NULL)
2447 return;
2448
2449 /* Save the original console window icon. */
2450 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2451 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2452 return;
2453
2454 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002455 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002456 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 if (g_hVimIcon != NULL)
2458 g_fCanChangeIcon = TRUE;
2459}
2460#endif
2461
2462static int g_fWindInitCalled = FALSE;
2463static int g_fTermcapMode = FALSE;
2464static CONSOLE_CURSOR_INFO g_cci;
2465static DWORD g_cmodein = 0;
2466static DWORD g_cmodeout = 0;
2467
2468/*
2469 * non-GUI version of mch_init().
2470 */
2471 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002472mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002474#ifndef FEAT_RESTORE_ORIG_SCREEN
2475 CONSOLE_SCREEN_BUFFER_INFO csbi;
2476#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477#ifndef __MINGW32__
2478 extern int _fmode;
2479#endif
2480
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002481 /* Silently handle invalid parameters to CRT functions */
2482 SET_INVALID_PARAM_HANDLER;
2483
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484 /* Let critical errors result in a failure, not in a dialog box. Required
2485 * for the timestamp test to work on removed floppies. */
2486 SetErrorMode(SEM_FAILCRITICALERRORS);
2487
2488 _fmode = O_BINARY; /* we do our own CR-LF translation */
2489 out_flush();
2490
2491 /* Obtain handles for the standard Console I/O devices */
2492 if (read_cmd_fd == 0)
2493 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2494 else
2495 create_conin();
2496 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2497
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002498#ifdef FEAT_RESTORE_ORIG_SCREEN
2499 /* Save the initial console buffer for later restoration */
2500 SaveConsoleBuffer(&g_cbOrig);
2501 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2502#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002504 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2505 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2506#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507 if (cterm_normal_fg_color == 0)
2508 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2509 if (cterm_normal_bg_color == 0)
2510 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2511
2512 /* set termcap codes to current text attributes */
2513 update_tcap(g_attrCurrent);
2514
2515 GetConsoleCursorInfo(g_hConOut, &g_cci);
2516 GetConsoleMode(g_hConIn, &g_cmodein);
2517 GetConsoleMode(g_hConOut, &g_cmodeout);
2518
2519#ifdef FEAT_TITLE
2520 SaveConsoleTitleAndIcon();
2521 /*
2522 * Set both the small and big icons of the console window to Vim's icon.
2523 * Note that Vim presently only has one size of icon (32x32), but it
2524 * automatically gets scaled down to 16x16 when setting the small icon.
2525 */
2526 if (g_fCanChangeIcon)
2527 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2528#endif
2529
2530 ui_get_shellsize();
2531
2532#ifdef MCH_WRITE_DUMP
2533 fdDump = fopen("dump", "wt");
2534
2535 if (fdDump)
2536 {
2537 time_t t;
2538
2539 time(&t);
2540 fputs(ctime(&t), fdDump);
2541 fflush(fdDump);
2542 }
2543#endif
2544
2545 g_fWindInitCalled = TRUE;
2546
2547#ifdef FEAT_MOUSE
2548 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2549#endif
2550
2551#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002552 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553#endif
2554
2555 /* This will be NULL on anything but NT 4.0 */
2556 s_pfnGetConsoleKeyboardLayoutName =
2557 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2558 "GetConsoleKeyboardLayoutNameA");
2559}
2560
2561/*
2562 * non-GUI version of mch_exit().
2563 * Shut down and exit with status `r'
2564 * Careful: mch_exit() may be called before mch_init()!
2565 */
2566 void
2567mch_exit(int r)
2568{
2569 stoptermcap();
2570
2571 if (g_fWindInitCalled)
2572 settmode(TMODE_COOK);
2573
2574 ml_close_all(TRUE); /* remove all memfiles */
2575
2576 if (g_fWindInitCalled)
2577 {
2578#ifdef FEAT_TITLE
2579 mch_restore_title(3);
2580 /*
2581 * Restore both the small and big icons of the console window to
2582 * what they were at startup. Don't do this when the window is
2583 * closed, Vim would hang here.
2584 */
2585 if (g_fCanChangeIcon && !g_fForceExit)
2586 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2587#endif
2588
2589#ifdef MCH_WRITE_DUMP
2590 if (fdDump)
2591 {
2592 time_t t;
2593
2594 time(&t);
2595 fputs(ctime(&t), fdDump);
2596 fclose(fdDump);
2597 }
2598 fdDump = NULL;
2599#endif
2600 }
2601
2602 SetConsoleCursorInfo(g_hConOut, &g_cci);
2603 SetConsoleMode(g_hConIn, g_cmodein);
2604 SetConsoleMode(g_hConOut, g_cmodeout);
2605
2606#ifdef DYNAMIC_GETTEXT
2607 dyn_libintl_end();
2608#endif
2609
2610 exit(r);
2611}
2612#endif /* !FEAT_GUI_W32 */
2613
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614/*
2615 * Do we have an interactive window?
2616 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002617/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 int
2619mch_check_win(
2620 int argc,
2621 char **argv)
2622{
2623 get_exe_name();
2624
2625#ifdef FEAT_GUI_W32
2626 return OK; /* GUI always has a tty */
2627#else
2628 if (isatty(1))
2629 return OK;
2630 return FAIL;
2631#endif
2632}
2633
2634
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002635#ifdef FEAT_MBYTE
2636/*
2637 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2638 * if it already exists. When "len" is > 0, also expand short to long
2639 * filenames.
2640 * Return FAIL if wide functions are not available, OK otherwise.
2641 * NOTE: much of this is identical to fname_case(), keep in sync!
2642 */
2643 static int
2644fname_casew(
2645 WCHAR *name,
2646 int len)
2647{
2648 WCHAR szTrueName[_MAX_PATH + 2];
2649 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2650 WCHAR *ptrue, *ptruePrev;
2651 WCHAR *porig, *porigPrev;
2652 int flen;
2653 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002654 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002655 int c;
2656 int slen;
2657
2658 flen = (int)wcslen(name);
2659 if (flen > _MAX_PATH)
2660 return OK;
2661
2662 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2663
2664 /* Build the new name in szTrueName[] one component at a time. */
2665 porig = name;
2666 ptrue = szTrueName;
2667
2668 if (iswalpha(porig[0]) && porig[1] == L':')
2669 {
2670 /* copy leading drive letter */
2671 *ptrue++ = *porig++;
2672 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002673 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002674 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002675
2676 while (*porig != NUL)
2677 {
2678 /* copy \ characters */
2679 while (*porig == psepc)
2680 *ptrue++ = *porig++;
2681
2682 ptruePrev = ptrue;
2683 porigPrev = porig;
2684 while (*porig != NUL && *porig != psepc)
2685 {
2686 *ptrue++ = *porig++;
2687 }
2688 *ptrue = NUL;
2689
2690 /* To avoid a slow failure append "\*" when searching a directory,
2691 * server or network share. */
2692 wcscpy(szTrueNameTemp, szTrueName);
2693 slen = (int)wcslen(szTrueNameTemp);
2694 if (*porig == psepc && slen + 2 < _MAX_PATH)
2695 wcscpy(szTrueNameTemp + slen, L"\\*");
2696
2697 /* Skip "", "." and "..". */
2698 if (ptrue > ptruePrev
2699 && (ptruePrev[0] != L'.'
2700 || (ptruePrev[1] != NUL
2701 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2702 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2703 != INVALID_HANDLE_VALUE)
2704 {
2705 c = *porig;
2706 *porig = NUL;
2707
2708 /* Only use the match when it's the same name (ignoring case) or
2709 * expansion is allowed and there is a match with the short name
2710 * and there is enough room. */
2711 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2712 || (len > 0
2713 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2714 && (int)(ptruePrev - szTrueName)
2715 + (int)wcslen(fb.cFileName) < len)))
2716 {
2717 wcscpy(ptruePrev, fb.cFileName);
2718
2719 /* Look for exact match and prefer it if found. Must be a
2720 * long name, otherwise there would be only one match. */
2721 while (FindNextFileW(hFind, &fb))
2722 {
2723 if (*fb.cAlternateFileName != NUL
2724 && (wcscoll(porigPrev, fb.cFileName) == 0
2725 || (len > 0
2726 && (_wcsicoll(porigPrev,
2727 fb.cAlternateFileName) == 0
2728 && (int)(ptruePrev - szTrueName)
2729 + (int)wcslen(fb.cFileName) < len))))
2730 {
2731 wcscpy(ptruePrev, fb.cFileName);
2732 break;
2733 }
2734 }
2735 }
2736 FindClose(hFind);
2737 *porig = c;
2738 ptrue = ptruePrev + wcslen(ptruePrev);
2739 }
2740 else if (hFind == INVALID_HANDLE_VALUE
2741 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2742 return FAIL;
2743 }
2744
2745 wcscpy(name, szTrueName);
2746 return OK;
2747}
2748#endif
2749
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750/*
2751 * fname_case(): Set the case of the file name, if it already exists.
2752 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002753 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754 */
2755 void
2756fname_case(
2757 char_u *name,
2758 int len)
2759{
2760 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002761 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002762 char *ptrue, *ptruePrev;
2763 char *porig, *porigPrev;
2764 int flen;
2765 WIN32_FIND_DATA fb;
2766 HANDLE hFind;
2767 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002768 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002769
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002770 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002771 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772 return;
2773
2774 slash_adjust(name);
2775
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002776#ifdef FEAT_MBYTE
2777 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2778 {
2779 WCHAR *p = enc_to_utf16(name, NULL);
2780
2781 if (p != NULL)
2782 {
2783 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002784 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002785
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002786 wcsncpy(buf, p, _MAX_PATH);
2787 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002788 vim_free(p);
2789
2790 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2791 {
2792 q = utf16_to_enc(buf, NULL);
2793 if (q != NULL)
2794 {
2795 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2796 vim_free(q);
2797 return;
2798 }
2799 }
2800 }
2801 /* Retry with non-wide function (for Windows 98). */
2802 }
2803#endif
2804
2805 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2806 * So we should check this after calling wide function. */
2807 if (flen > _MAX_PATH)
2808 return;
2809
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002811 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002812 ptrue = szTrueName;
2813
2814 if (isalpha(porig[0]) && porig[1] == ':')
2815 {
2816 /* copy leading drive letter */
2817 *ptrue++ = *porig++;
2818 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002819 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002820 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002821
2822 while (*porig != NUL)
2823 {
2824 /* copy \ characters */
2825 while (*porig == psepc)
2826 *ptrue++ = *porig++;
2827
2828 ptruePrev = ptrue;
2829 porigPrev = porig;
2830 while (*porig != NUL && *porig != psepc)
2831 {
2832#ifdef FEAT_MBYTE
2833 int l;
2834
2835 if (enc_dbcs)
2836 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002837 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838 while (--l >= 0)
2839 *ptrue++ = *porig++;
2840 }
2841 else
2842#endif
2843 *ptrue++ = *porig++;
2844 }
2845 *ptrue = NUL;
2846
Bram Moolenaar464c9252010-10-13 20:37:41 +02002847 /* To avoid a slow failure append "\*" when searching a directory,
2848 * server or network share. */
2849 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002850 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002851 if (*porig == psepc && slen + 2 < _MAX_PATH)
2852 STRCPY(szTrueNameTemp + slen, "\\*");
2853
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854 /* Skip "", "." and "..". */
2855 if (ptrue > ptruePrev
2856 && (ptruePrev[0] != '.'
2857 || (ptruePrev[1] != NUL
2858 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002859 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860 != INVALID_HANDLE_VALUE)
2861 {
2862 c = *porig;
2863 *porig = NUL;
2864
2865 /* Only use the match when it's the same name (ignoring case) or
2866 * expansion is allowed and there is a match with the short name
2867 * and there is enough room. */
2868 if (_stricoll(porigPrev, fb.cFileName) == 0
2869 || (len > 0
2870 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2871 && (int)(ptruePrev - szTrueName)
2872 + (int)strlen(fb.cFileName) < len)))
2873 {
2874 STRCPY(ptruePrev, fb.cFileName);
2875
2876 /* Look for exact match and prefer it if found. Must be a
2877 * long name, otherwise there would be only one match. */
2878 while (FindNextFile(hFind, &fb))
2879 {
2880 if (*fb.cAlternateFileName != NUL
2881 && (strcoll(porigPrev, fb.cFileName) == 0
2882 || (len > 0
2883 && (_stricoll(porigPrev,
2884 fb.cAlternateFileName) == 0
2885 && (int)(ptruePrev - szTrueName)
2886 + (int)strlen(fb.cFileName) < len))))
2887 {
2888 STRCPY(ptruePrev, fb.cFileName);
2889 break;
2890 }
2891 }
2892 }
2893 FindClose(hFind);
2894 *porig = c;
2895 ptrue = ptruePrev + strlen(ptruePrev);
2896 }
2897 }
2898
2899 STRCPY(name, szTrueName);
2900}
2901
2902
2903/*
2904 * Insert user name in s[len].
2905 */
2906 int
2907mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002908 char_u *s,
2909 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002911 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912 DWORD cch = sizeof szUserName;
2913
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002914#ifdef FEAT_MBYTE
2915 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2916 {
2917 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2918 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2919
2920 if (GetUserNameW(wszUserName, &wcch))
2921 {
2922 char_u *p = utf16_to_enc(wszUserName, NULL);
2923
2924 if (p != NULL)
2925 {
2926 vim_strncpy(s, p, len - 1);
2927 vim_free(p);
2928 return OK;
2929 }
2930 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002931 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2932 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002933 /* Retry with non-wide function (for Windows 98). */
2934 }
2935#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936 if (GetUserName(szUserName, &cch))
2937 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002938 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 return OK;
2940 }
2941 s[0] = NUL;
2942 return FAIL;
2943}
2944
2945
2946/*
2947 * Insert host name in s[len].
2948 */
2949 void
2950mch_get_host_name(
2951 char_u *s,
2952 int len)
2953{
2954 DWORD cch = len;
2955
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002956#ifdef FEAT_MBYTE
2957 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2958 {
2959 WCHAR wszHostName[256 + 1];
2960 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2961
2962 if (GetComputerNameW(wszHostName, &wcch))
2963 {
2964 char_u *p = utf16_to_enc(wszHostName, NULL);
2965
2966 if (p != NULL)
2967 {
2968 vim_strncpy(s, p, len - 1);
2969 vim_free(p);
2970 return;
2971 }
2972 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002973 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2974 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002975 /* Retry with non-wide function (for Windows 98). */
2976 }
2977#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002978 if (!GetComputerName((LPSTR)s, &cch))
2979 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980}
2981
2982
2983/*
2984 * return process ID
2985 */
2986 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002987mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988{
2989 return (long)GetCurrentProcessId();
2990}
2991
2992
2993/*
2994 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2995 * Return OK for success, FAIL for failure.
2996 */
2997 int
2998mch_dirname(
2999 char_u *buf,
3000 int len)
3001{
3002 /*
3003 * Originally this was:
3004 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3005 * But the Win32s known bug list says that getcwd() doesn't work
3006 * so use the Win32 system call instead. <Negri>
3007 */
3008#ifdef FEAT_MBYTE
3009 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3010 {
3011 WCHAR wbuf[_MAX_PATH + 1];
3012
3013 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3014 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003015 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016
3017 if (p != NULL)
3018 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003019 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 vim_free(p);
3021 return OK;
3022 }
3023 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003024 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3025 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026 /* Retry with non-wide function (for Windows 98). */
3027 }
3028#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003029 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030}
3031
3032/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003033 * Get file permissions for "name".
3034 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 */
3036 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003037mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003039 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003040 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003042 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003043 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044}
3045
3046
3047/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003048 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003049 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003050 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 */
3052 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003053mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003055 long n = -1;
3056
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057#ifdef FEAT_MBYTE
3058 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3059 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003060 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061
3062 if (p != NULL)
3063 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003064 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003066 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003067 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068 /* Retry with non-wide function (for Windows 98). */
3069 }
3070 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003071 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003073 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003074 if (n == -1)
3075 return FAIL;
3076
3077 win32_set_archive(name);
3078
3079 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080}
3081
3082/*
3083 * Set hidden flag for "name".
3084 */
3085 void
3086mch_hide(char_u *name)
3087{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003088 int attrs = win32_getattrs(name);
3089 if (attrs == -1)
3090 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003092 attrs |= FILE_ATTRIBUTE_HIDDEN;
3093 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094}
3095
3096/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003097 * Return TRUE if file "name" exists and is hidden.
3098 */
3099 int
3100mch_ishidden(char_u *name)
3101{
3102 int f = win32_getattrs(name);
3103
3104 if (f == -1)
3105 return FALSE; /* file does not exist at all */
3106
3107 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3108}
3109
3110/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111 * return TRUE if "name" is a directory
3112 * return FALSE if "name" is not a directory or upon error
3113 */
3114 int
3115mch_isdir(char_u *name)
3116{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003117 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118
3119 if (f == -1)
3120 return FALSE; /* file does not exist at all */
3121
3122 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3123}
3124
3125/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003126 * return TRUE if "name" is a directory, NOT a symlink to a directory
3127 * return FALSE if "name" is not a directory
3128 * return FALSE for error
3129 */
3130 int
3131mch_isrealdir(char_u *name)
3132{
3133 return mch_isdir(name) && !mch_is_symbolic_link(name);
3134}
3135
3136/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003137 * Create directory "name".
3138 * Return 0 on success, -1 on error.
3139 */
3140 int
3141mch_mkdir(char_u *name)
3142{
3143#ifdef FEAT_MBYTE
3144 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3145 {
3146 WCHAR *p;
3147 int retval;
3148
3149 p = enc_to_utf16(name, NULL);
3150 if (p == NULL)
3151 return -1;
3152 retval = _wmkdir(p);
3153 vim_free(p);
3154 return retval;
3155 }
3156#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003157 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003158}
3159
3160/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003161 * Delete directory "name".
3162 * Return 0 on success, -1 on error.
3163 */
3164 int
3165mch_rmdir(char_u *name)
3166{
3167#ifdef FEAT_MBYTE
3168 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3169 {
3170 WCHAR *p;
3171 int retval;
3172
3173 p = enc_to_utf16(name, NULL);
3174 if (p == NULL)
3175 return -1;
3176 retval = _wrmdir(p);
3177 vim_free(p);
3178 return retval;
3179 }
3180#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003181 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003182}
3183
3184/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003185 * Return TRUE if file "fname" has more than one link.
3186 */
3187 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003188mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003189{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003190 BY_HANDLE_FILE_INFORMATION info;
3191
3192 return win32_fileinfo(fname, &info) == FILEINFO_OK
3193 && info.nNumberOfLinks > 1;
3194}
3195
3196/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003197 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003198 */
3199 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003200mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003201{
3202 HANDLE hFind;
3203 int res = FALSE;
3204 WIN32_FIND_DATAA findDataA;
3205 DWORD fileFlags = 0, reparseTag = 0;
3206#ifdef FEAT_MBYTE
3207 WCHAR *wn = NULL;
3208 WIN32_FIND_DATAW findDataW;
3209
3210 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003211 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003212 if (wn != NULL)
3213 {
3214 hFind = FindFirstFileW(wn, &findDataW);
3215 vim_free(wn);
3216 if (hFind == INVALID_HANDLE_VALUE
3217 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3218 {
3219 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003220 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003221 if (hFind != INVALID_HANDLE_VALUE)
3222 {
3223 fileFlags = findDataA.dwFileAttributes;
3224 reparseTag = findDataA.dwReserved0;
3225 }
3226 }
3227 else
3228 {
3229 fileFlags = findDataW.dwFileAttributes;
3230 reparseTag = findDataW.dwReserved0;
3231 }
3232 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003233 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003234#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003235 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003236 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003237 if (hFind != INVALID_HANDLE_VALUE)
3238 {
3239 fileFlags = findDataA.dwFileAttributes;
3240 reparseTag = findDataA.dwReserved0;
3241 }
3242 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003243
3244 if (hFind != INVALID_HANDLE_VALUE)
3245 FindClose(hFind);
3246
3247 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003248 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3249 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003250 res = TRUE;
3251
3252 return res;
3253}
3254
3255/*
3256 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3257 * link.
3258 */
3259 int
3260mch_is_linked(char_u *fname)
3261{
3262 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3263 return TRUE;
3264 return FALSE;
3265}
3266
3267/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003268 * Get the by-handle-file-information for "fname".
3269 * Returns FILEINFO_OK when OK.
3270 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3271 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3272 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3273 */
3274 int
3275win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3276{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003277 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003278 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003279#ifdef FEAT_MBYTE
3280 WCHAR *wn = NULL;
3281
3282 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003283 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003284 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003285 if (wn == NULL)
3286 res = FILEINFO_ENC_FAIL;
3287 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003288 if (wn != NULL)
3289 {
3290 hFile = CreateFileW(wn, /* file name */
3291 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003292 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003293 NULL, /* security descriptor */
3294 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003295 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003296 NULL); /* handle to template file */
3297 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003298 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003299 {
3300 /* Retry with non-wide function (for Windows 98). */
3301 vim_free(wn);
3302 wn = NULL;
3303 }
3304 }
3305 if (wn == NULL)
3306#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003307 hFile = CreateFile((LPCSTR)fname, /* file name */
3308 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003309 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003310 NULL, /* security descriptor */
3311 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003312 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003313 NULL); /* handle to template file */
3314
3315 if (hFile != INVALID_HANDLE_VALUE)
3316 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003317 if (GetFileInformationByHandle(hFile, info) != 0)
3318 res = FILEINFO_OK;
3319 else
3320 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003321 CloseHandle(hFile);
3322 }
3323
3324#ifdef FEAT_MBYTE
3325 vim_free(wn);
3326#endif
3327 return res;
3328}
3329
3330/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003331 * get file attributes for `name'
3332 * -1 : error
3333 * else FILE_ATTRIBUTE_* defined in winnt.h
3334 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003335 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003336win32_getattrs(char_u *name)
3337{
3338 int attr;
3339#ifdef FEAT_MBYTE
3340 WCHAR *p = NULL;
3341
3342 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3343 p = enc_to_utf16(name, NULL);
3344
3345 if (p != NULL)
3346 {
3347 attr = GetFileAttributesW(p);
3348 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3349 {
3350 /* Retry with non-wide function (for Windows 98). */
3351 vim_free(p);
3352 p = NULL;
3353 }
3354 }
3355 if (p == NULL)
3356#endif
3357 attr = GetFileAttributes((char *)name);
3358#ifdef FEAT_MBYTE
3359 vim_free(p);
3360#endif
3361 return attr;
3362}
3363
3364/*
3365 * set file attributes for `name' to `attrs'
3366 *
3367 * return -1 for failure, 0 otherwise
3368 */
3369 static
3370 int
3371win32_setattrs(char_u *name, int attrs)
3372{
3373 int res;
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 res = SetFileAttributesW(p, attrs);
3383 if (res == FALSE
3384 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3385 {
3386 /* Retry with non-wide function (for Windows 98). */
3387 vim_free(p);
3388 p = NULL;
3389 }
3390 }
3391 if (p == NULL)
3392#endif
3393 res = SetFileAttributes((char *)name, attrs);
3394#ifdef FEAT_MBYTE
3395 vim_free(p);
3396#endif
3397 return res ? 0 : -1;
3398}
3399
3400/*
3401 * Set archive flag for "name".
3402 */
3403 static
3404 int
3405win32_set_archive(char_u *name)
3406{
3407 int attrs = win32_getattrs(name);
3408 if (attrs == -1)
3409 return -1;
3410
3411 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3412 return win32_setattrs(name, attrs);
3413}
3414
3415/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003416 * Return TRUE if file or directory "name" is writable (not readonly).
3417 * Strange semantics of Win32: a readonly directory is writable, but you can't
3418 * delete a file. Let's say this means it is writable.
3419 */
3420 int
3421mch_writable(char_u *name)
3422{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003423 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003424
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003425 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3426 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427}
3428
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429/*
3430 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003431 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432 * Return -1 if unknown.
3433 */
3434 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003435mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003437 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003438 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003439 char_u *p;
3440
3441 if (len >= _MAX_PATH) /* safety check */
3442 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003443 if (!use_path)
3444 {
3445 /* TODO: check if file is really executable. */
3446 return mch_getperm(name) != -1 && !mch_isdir(name);
3447 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003448
3449 /* If there already is an extension try using the name directly. Also do
3450 * this with a Unix-shell like 'shell'. */
3451 if (vim_strchr(gettail(name), '.') != NULL
3452 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003453 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003454 return TRUE;
3455
3456 /*
3457 * Loop over all extensions in $PATHEXT.
3458 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003459 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003460 p = mch_getenv("PATHEXT");
3461 if (p == NULL)
3462 p = (char_u *)".com;.exe;.bat;.cmd";
3463 while (*p)
3464 {
3465 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3466 {
3467 /* A single "." means no extension is added. */
3468 buf[len] = NUL;
3469 ++p;
3470 if (*p)
3471 ++p;
3472 }
3473 else
3474 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003475 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003476 return TRUE;
3477 }
3478 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003479}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003480
3481/*
3482 * Check what "name" is:
3483 * NODE_NORMAL: file or directory (or doesn't exist)
3484 * NODE_WRITABLE: writable device, socket, fifo, etc.
3485 * NODE_OTHER: non-writable things
3486 */
3487 int
3488mch_nodetype(char_u *name)
3489{
3490 HANDLE hFile;
3491 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003492#ifdef FEAT_MBYTE
3493 WCHAR *wn = NULL;
3494#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495
Bram Moolenaar043545e2006-10-10 16:44:07 +00003496 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3497 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3498 * here. */
3499 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3500 return NODE_WRITABLE;
3501
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003502#ifdef FEAT_MBYTE
3503 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3504 {
3505 wn = enc_to_utf16(name, NULL);
3506 if (wn != NULL)
3507 {
3508 hFile = CreateFileW(wn, /* file name */
3509 GENERIC_WRITE, /* access mode */
3510 0, /* share mode */
3511 NULL, /* security descriptor */
3512 OPEN_EXISTING, /* creation disposition */
3513 0, /* file attributes */
3514 NULL); /* handle to template file */
3515 if (hFile == INVALID_HANDLE_VALUE
3516 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3517 {
3518 /* Retry with non-wide function (for Windows 98). */
3519 vim_free(wn);
3520 wn = NULL;
3521 }
3522 }
3523 }
3524 if (wn == NULL)
3525#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003526 hFile = CreateFile((LPCSTR)name, /* file name */
3527 GENERIC_WRITE, /* access mode */
3528 0, /* share mode */
3529 NULL, /* security descriptor */
3530 OPEN_EXISTING, /* creation disposition */
3531 0, /* file attributes */
3532 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003534#ifdef FEAT_MBYTE
3535 vim_free(wn);
3536#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537 if (hFile == INVALID_HANDLE_VALUE)
3538 return NODE_NORMAL;
3539
3540 type = GetFileType(hFile);
3541 CloseHandle(hFile);
3542 if (type == FILE_TYPE_CHAR)
3543 return NODE_WRITABLE;
3544 if (type == FILE_TYPE_DISK)
3545 return NODE_NORMAL;
3546 return NODE_OTHER;
3547}
3548
3549#ifdef HAVE_ACL
3550struct my_acl
3551{
3552 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3553 PSID pSidOwner;
3554 PSID pSidGroup;
3555 PACL pDacl;
3556 PACL pSacl;
3557};
3558#endif
3559
3560/*
3561 * Return a pointer to the ACL of file "fname" in allocated memory.
3562 * Return NULL if the ACL is not available for whatever reason.
3563 */
3564 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003565mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566{
3567#ifndef HAVE_ACL
3568 return (vim_acl_T)NULL;
3569#else
3570 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003571 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572
3573 /* This only works on Windows NT and 2000. */
3574 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3575 {
3576 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3577 if (p != NULL)
3578 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003579# ifdef FEAT_MBYTE
3580 WCHAR *wn = NULL;
3581
3582 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3583 wn = enc_to_utf16(fname, NULL);
3584 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003586 /* Try to retrieve the entire security descriptor. */
3587 err = pGetNamedSecurityInfoW(
3588 wn, // Abstract filename
3589 SE_FILE_OBJECT, // File Object
3590 OWNER_SECURITY_INFORMATION |
3591 GROUP_SECURITY_INFORMATION |
3592 DACL_SECURITY_INFORMATION |
3593 SACL_SECURITY_INFORMATION,
3594 &p->pSidOwner, // Ownership information.
3595 &p->pSidGroup, // Group membership.
3596 &p->pDacl, // Discretionary information.
3597 &p->pSacl, // For auditing purposes.
3598 &p->pSecurityDescriptor);
3599 if (err == ERROR_ACCESS_DENIED ||
3600 err == ERROR_PRIVILEGE_NOT_HELD)
3601 {
3602 /* Retrieve only DACL. */
3603 (void)pGetNamedSecurityInfoW(
3604 wn,
3605 SE_FILE_OBJECT,
3606 DACL_SECURITY_INFORMATION,
3607 NULL,
3608 NULL,
3609 &p->pDacl,
3610 NULL,
3611 &p->pSecurityDescriptor);
3612 }
3613 if (p->pSecurityDescriptor == NULL)
3614 {
3615 mch_free_acl((vim_acl_T)p);
3616 p = NULL;
3617 }
3618 vim_free(wn);
3619 }
3620 else
3621# endif
3622 {
3623 /* Try to retrieve the entire security descriptor. */
3624 err = pGetNamedSecurityInfo(
3625 (LPSTR)fname, // Abstract filename
3626 SE_FILE_OBJECT, // File Object
3627 OWNER_SECURITY_INFORMATION |
3628 GROUP_SECURITY_INFORMATION |
3629 DACL_SECURITY_INFORMATION |
3630 SACL_SECURITY_INFORMATION,
3631 &p->pSidOwner, // Ownership information.
3632 &p->pSidGroup, // Group membership.
3633 &p->pDacl, // Discretionary information.
3634 &p->pSacl, // For auditing purposes.
3635 &p->pSecurityDescriptor);
3636 if (err == ERROR_ACCESS_DENIED ||
3637 err == ERROR_PRIVILEGE_NOT_HELD)
3638 {
3639 /* Retrieve only DACL. */
3640 (void)pGetNamedSecurityInfo(
3641 (LPSTR)fname,
3642 SE_FILE_OBJECT,
3643 DACL_SECURITY_INFORMATION,
3644 NULL,
3645 NULL,
3646 &p->pDacl,
3647 NULL,
3648 &p->pSecurityDescriptor);
3649 }
3650 if (p->pSecurityDescriptor == NULL)
3651 {
3652 mch_free_acl((vim_acl_T)p);
3653 p = NULL;
3654 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655 }
3656 }
3657 }
3658
3659 return (vim_acl_T)p;
3660#endif
3661}
3662
Bram Moolenaar27515922013-06-29 15:36:26 +02003663#ifdef HAVE_ACL
3664/*
3665 * Check if "acl" contains inherited ACE.
3666 */
3667 static BOOL
3668is_acl_inherited(PACL acl)
3669{
3670 DWORD i;
3671 ACL_SIZE_INFORMATION acl_info;
3672 PACCESS_ALLOWED_ACE ace;
3673
3674 acl_info.AceCount = 0;
3675 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3676 for (i = 0; i < acl_info.AceCount; i++)
3677 {
3678 GetAce(acl, i, (LPVOID *)&ace);
3679 if (ace->Header.AceFlags & INHERITED_ACE)
3680 return TRUE;
3681 }
3682 return FALSE;
3683}
3684#endif
3685
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686/*
3687 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3688 * Errors are ignored.
3689 * This must only be called with "acl" equal to what mch_get_acl() returned.
3690 */
3691 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003692mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693{
3694#ifdef HAVE_ACL
3695 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003696 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697
3698 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003699 {
3700# ifdef FEAT_MBYTE
3701 WCHAR *wn = NULL;
3702# endif
3703
3704 /* Set security flags */
3705 if (p->pSidOwner)
3706 sec_info |= OWNER_SECURITY_INFORMATION;
3707 if (p->pSidGroup)
3708 sec_info |= GROUP_SECURITY_INFORMATION;
3709 if (p->pDacl)
3710 {
3711 sec_info |= DACL_SECURITY_INFORMATION;
3712 /* Do not inherit its parent's DACL.
3713 * If the DACL is inherited, Cygwin permissions would be changed.
3714 */
3715 if (!is_acl_inherited(p->pDacl))
3716 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3717 }
3718 if (p->pSacl)
3719 sec_info |= SACL_SECURITY_INFORMATION;
3720
3721# ifdef FEAT_MBYTE
3722 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3723 wn = enc_to_utf16(fname, NULL);
3724 if (wn != NULL)
3725 {
3726 (void)pSetNamedSecurityInfoW(
3727 wn, // Abstract filename
3728 SE_FILE_OBJECT, // File Object
3729 sec_info,
3730 p->pSidOwner, // Ownership information.
3731 p->pSidGroup, // Group membership.
3732 p->pDacl, // Discretionary information.
3733 p->pSacl // For auditing purposes.
3734 );
3735 vim_free(wn);
3736 }
3737 else
3738# endif
3739 {
3740 (void)pSetNamedSecurityInfo(
3741 (LPSTR)fname, // Abstract filename
3742 SE_FILE_OBJECT, // File Object
3743 sec_info,
3744 p->pSidOwner, // Ownership information.
3745 p->pSidGroup, // Group membership.
3746 p->pDacl, // Discretionary information.
3747 p->pSacl // For auditing purposes.
3748 );
3749 }
3750 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751#endif
3752}
3753
3754 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003755mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756{
3757#ifdef HAVE_ACL
3758 struct my_acl *p = (struct my_acl *)acl;
3759
3760 if (p != NULL)
3761 {
3762 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3763 vim_free(p);
3764 }
3765#endif
3766}
3767
3768#ifndef FEAT_GUI_W32
3769
3770/*
3771 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3772 */
3773 static BOOL WINAPI
3774handler_routine(
3775 DWORD dwCtrlType)
3776{
3777 switch (dwCtrlType)
3778 {
3779 case CTRL_C_EVENT:
3780 if (ctrl_c_interrupts)
3781 g_fCtrlCPressed = TRUE;
3782 return TRUE;
3783
3784 case CTRL_BREAK_EVENT:
3785 g_fCBrkPressed = TRUE;
3786 return TRUE;
3787
3788 /* fatal events: shut down gracefully */
3789 case CTRL_CLOSE_EVENT:
3790 case CTRL_LOGOFF_EVENT:
3791 case CTRL_SHUTDOWN_EVENT:
3792 windgoto((int)Rows - 1, 0);
3793 g_fForceExit = TRUE;
3794
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003795 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003796 (dwCtrlType == CTRL_CLOSE_EVENT
3797 ? _("close")
3798 : dwCtrlType == CTRL_LOGOFF_EVENT
3799 ? _("logoff")
3800 : _("shutdown")));
3801#ifdef DEBUG
3802 OutputDebugString(IObuff);
3803#endif
3804
3805 preserve_exit(); /* output IObuff, preserve files and exit */
3806
3807 return TRUE; /* not reached */
3808
3809 default:
3810 return FALSE;
3811 }
3812}
3813
3814
3815/*
3816 * set the tty in (raw) ? "raw" : "cooked" mode
3817 */
3818 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003819mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820{
3821 DWORD cmodein;
3822 DWORD cmodeout;
3823 BOOL bEnableHandler;
3824
3825 GetConsoleMode(g_hConIn, &cmodein);
3826 GetConsoleMode(g_hConOut, &cmodeout);
3827 if (tmode == TMODE_RAW)
3828 {
3829 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3830 ENABLE_ECHO_INPUT);
3831#ifdef FEAT_MOUSE
3832 if (g_fMouseActive)
3833 cmodein |= ENABLE_MOUSE_INPUT;
3834#endif
3835 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3836 bEnableHandler = TRUE;
3837 }
3838 else /* cooked */
3839 {
3840 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3841 ENABLE_ECHO_INPUT);
3842 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3843 bEnableHandler = FALSE;
3844 }
3845 SetConsoleMode(g_hConIn, cmodein);
3846 SetConsoleMode(g_hConOut, cmodeout);
3847 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3848
3849#ifdef MCH_WRITE_DUMP
3850 if (fdDump)
3851 {
3852 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3853 tmode == TMODE_RAW ? "raw" :
3854 tmode == TMODE_COOK ? "cooked" : "normal",
3855 cmodein, cmodeout);
3856 fflush(fdDump);
3857 }
3858#endif
3859}
3860
3861
3862/*
3863 * Get the size of the current window in `Rows' and `Columns'
3864 * Return OK when size could be determined, FAIL otherwise.
3865 */
3866 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003867mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868{
3869 CONSOLE_SCREEN_BUFFER_INFO csbi;
3870
3871 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3872 {
3873 /*
3874 * For some reason, we are trying to get the screen dimensions
3875 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3876 * variables are really intended to mean the size of Vim screen
3877 * while in termcap mode.
3878 */
3879 Rows = g_cbTermcap.Info.dwSize.Y;
3880 Columns = g_cbTermcap.Info.dwSize.X;
3881 }
3882 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3883 {
3884 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3885 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3886 }
3887 else
3888 {
3889 Rows = 25;
3890 Columns = 80;
3891 }
3892 return OK;
3893}
3894
3895/*
3896 * Set a console window to `xSize' * `ySize'
3897 */
3898 static void
3899ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003900 HANDLE hConsole,
3901 int xSize,
3902 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903{
3904 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3905 SMALL_RECT srWindowRect; /* hold the new console size */
3906 COORD coordScreen;
3907
3908#ifdef MCH_WRITE_DUMP
3909 if (fdDump)
3910 {
3911 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3912 fflush(fdDump);
3913 }
3914#endif
3915
3916 /* get the largest size we can size the console window to */
3917 coordScreen = GetLargestConsoleWindowSize(hConsole);
3918
3919 /* define the new console window size and scroll position */
3920 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3921 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3922 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3923
3924 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3925 {
3926 int sx, sy;
3927
3928 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3929 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3930 if (sy < ySize || sx < xSize)
3931 {
3932 /*
3933 * Increasing number of lines/columns, do buffer first.
3934 * Use the maximal size in x and y direction.
3935 */
3936 if (sy < ySize)
3937 coordScreen.Y = ySize;
3938 else
3939 coordScreen.Y = sy;
3940 if (sx < xSize)
3941 coordScreen.X = xSize;
3942 else
3943 coordScreen.X = sx;
3944 SetConsoleScreenBufferSize(hConsole, coordScreen);
3945 }
3946 }
3947
3948 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3949 {
3950#ifdef MCH_WRITE_DUMP
3951 if (fdDump)
3952 {
3953 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3954 GetLastError());
3955 fflush(fdDump);
3956 }
3957#endif
3958 }
3959
3960 /* define the new console buffer size */
3961 coordScreen.X = xSize;
3962 coordScreen.Y = ySize;
3963
3964 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3965 {
3966#ifdef MCH_WRITE_DUMP
3967 if (fdDump)
3968 {
3969 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3970 GetLastError());
3971 fflush(fdDump);
3972 }
3973#endif
3974 }
3975}
3976
3977
3978/*
3979 * Set the console window to `Rows' * `Columns'
3980 */
3981 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003982mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983{
3984 COORD coordScreen;
3985
3986 /* Don't change window size while still starting up */
3987 if (suppress_winsize != 0)
3988 {
3989 suppress_winsize = 2;
3990 return;
3991 }
3992
3993 if (term_console)
3994 {
3995 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3996
3997 /* Clamp Rows and Columns to reasonable values */
3998 if (Rows > coordScreen.Y)
3999 Rows = coordScreen.Y;
4000 if (Columns > coordScreen.X)
4001 Columns = coordScreen.X;
4002
4003 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4004 }
4005}
4006
4007/*
4008 * Rows and/or Columns has changed.
4009 */
4010 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004011mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012{
4013 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4014}
4015
4016
4017/*
4018 * Called when started up, to set the winsize that was delayed.
4019 */
4020 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004021mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004022{
4023 if (suppress_winsize == 2)
4024 {
4025 suppress_winsize = 0;
4026 mch_set_shellsize();
4027 shell_resized();
4028 }
4029 suppress_winsize = 0;
4030}
4031#endif /* FEAT_GUI_W32 */
4032
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004033 static BOOL
4034vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004035 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004036 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004037 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004038 STARTUPINFO *si,
4039 PROCESS_INFORMATION *pi)
4040{
4041# ifdef FEAT_MBYTE
4042 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4043 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004044 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004045
4046 if (wcmd != NULL)
4047 {
4048 BOOL ret;
4049 ret = CreateProcessW(
4050 NULL, /* Executable name */
4051 wcmd, /* Command to execute */
4052 NULL, /* Process security attributes */
4053 NULL, /* Thread security attributes */
4054 inherit_handles, /* Inherit handles */
4055 flags, /* Creation flags */
4056 NULL, /* Environment */
4057 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004058 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004059 pi); /* Process information */
4060 vim_free(wcmd);
4061 return ret;
4062 }
4063 }
4064#endif
4065 return CreateProcess(
4066 NULL, /* Executable name */
4067 cmd, /* Command to execute */
4068 NULL, /* Process security attributes */
4069 NULL, /* Thread security attributes */
4070 inherit_handles, /* Inherit handles */
4071 flags, /* Creation flags */
4072 NULL, /* Environment */
4073 NULL, /* Current directory */
4074 si, /* Startup information */
4075 pi); /* Process information */
4076}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004077
4078
4079#if defined(FEAT_GUI_W32) || defined(PROTO)
4080
4081/*
4082 * Specialised version of system() for Win32 GUI mode.
4083 * This version proceeds as follows:
4084 * 1. Create a console window for use by the subprocess
4085 * 2. Run the subprocess (it gets the allocated console by default)
4086 * 3. Wait for the subprocess to terminate and get its exit code
4087 * 4. Prompt the user to press a key to close the console window
4088 */
4089 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004090mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091{
4092 STARTUPINFO si;
4093 PROCESS_INFORMATION pi;
4094 DWORD ret = 0;
4095 HWND hwnd = GetFocus();
4096
4097 si.cb = sizeof(si);
4098 si.lpReserved = NULL;
4099 si.lpDesktop = NULL;
4100 si.lpTitle = NULL;
4101 si.dwFlags = STARTF_USESHOWWINDOW;
4102 /*
4103 * It's nicer to run a filter command in a minimized window, but in
4104 * Windows 95 this makes the command MUCH slower. We can't do it under
4105 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004106 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004107 */
4108 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004109 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004110 else
4111 si.wShowWindow = SW_SHOWNORMAL;
4112 si.cbReserved2 = 0;
4113 si.lpReserved2 = NULL;
4114
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004115 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 * When the "c:\\" is left out it works OK...? */
4117 if (mch_windows95()
4118 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4119 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4120 cmd += 3;
4121
4122 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004123 vim_create_process(cmd, FALSE,
4124 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125
4126 /* Wait for the command to terminate before continuing */
4127 if (g_PlatformId != VER_PLATFORM_WIN32s)
4128 {
4129#ifdef FEAT_GUI
4130 int delay = 1;
4131
4132 /* Keep updating the window while waiting for the shell to finish. */
4133 for (;;)
4134 {
4135 MSG msg;
4136
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004137 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 {
4139 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004140 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004141 delay = 1;
4142 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 }
4144 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4145 break;
4146
4147 /* We start waiting for a very short time and then increase it, so
4148 * that we respond quickly when the process is quick, and don't
4149 * consume too much overhead when it's slow. */
4150 if (delay < 50)
4151 delay += 10;
4152 }
4153#else
4154 WaitForSingleObject(pi.hProcess, INFINITE);
4155#endif
4156
4157 /* Get the command exit code */
4158 GetExitCodeProcess(pi.hProcess, &ret);
4159 }
4160 else
4161 {
4162 /*
4163 * This ugly code is the only quick way of performing
4164 * a synchronous spawn under Win32s. Yuk.
4165 */
4166 num_windows = 0;
4167 EnumWindows(win32ssynch_cb, 0);
4168 old_num_windows = num_windows;
4169 do
4170 {
4171 Sleep(1000);
4172 num_windows = 0;
4173 EnumWindows(win32ssynch_cb, 0);
4174 } while (num_windows == old_num_windows);
4175 ret = 0;
4176 }
4177
4178 /* Close the handles to the subprocess, so that it goes away */
4179 CloseHandle(pi.hThread);
4180 CloseHandle(pi.hProcess);
4181
4182 /* Try to get input focus back. Doesn't always work though. */
4183 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4184
4185 return ret;
4186}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004187
4188/*
4189 * Thread launched by the gui to send the current buffer data to the
4190 * process. This way avoid to hang up vim totally if the children
4191 * process take a long time to process the lines.
4192 */
4193 static DWORD WINAPI
4194sub_process_writer(LPVOID param)
4195{
4196 HANDLE g_hChildStd_IN_Wr = param;
4197 linenr_T lnum = curbuf->b_op_start.lnum;
4198 DWORD len = 0;
4199 DWORD l;
4200 char_u *lp = ml_get(lnum);
4201 char_u *s;
4202 int written = 0;
4203
4204 for (;;)
4205 {
4206 l = (DWORD)STRLEN(lp + written);
4207 if (l == 0)
4208 len = 0;
4209 else if (lp[written] == NL)
4210 {
4211 /* NL -> NUL translation */
4212 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4213 }
4214 else
4215 {
4216 s = vim_strchr(lp + written, NL);
4217 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4218 s == NULL ? l : (DWORD)(s - (lp + written)),
4219 &len, NULL);
4220 }
4221 if (len == (int)l)
4222 {
4223 /* Finished a line, add a NL, unless this line should not have
4224 * one. */
4225 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004226 || (!curbuf->b_p_bin
4227 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004228 || (lnum != curbuf->b_no_eol_lnum
4229 && (lnum != curbuf->b_ml.ml_line_count
4230 || curbuf->b_p_eol)))
4231 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004232 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004233 }
4234
4235 ++lnum;
4236 if (lnum > curbuf->b_op_end.lnum)
4237 break;
4238
4239 lp = ml_get(lnum);
4240 written = 0;
4241 }
4242 else if (len > 0)
4243 written += len;
4244 }
4245
4246 /* finished all the lines, close pipe */
4247 CloseHandle(g_hChildStd_IN_Wr);
4248 ExitThread(0);
4249}
4250
4251
4252# define BUFLEN 100 /* length for buffer, stolen from unix version */
4253
4254/*
4255 * This function read from the children's stdout and write the
4256 * data on screen or in the buffer accordingly.
4257 */
4258 static void
4259dump_pipe(int options,
4260 HANDLE g_hChildStd_OUT_Rd,
4261 garray_T *ga,
4262 char_u buffer[],
4263 DWORD *buffer_off)
4264{
4265 DWORD availableBytes = 0;
4266 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004267 int ret;
4268 DWORD len;
4269 DWORD toRead;
4270 int repeatCount;
4271
4272 /* we query the pipe to see if there is any data to read
4273 * to avoid to perform a blocking read */
4274 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4275 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004276 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004277 NULL, /* number of read bytes */
4278 &availableBytes, /* available bytes total */
4279 NULL); /* byteLeft */
4280
4281 repeatCount = 0;
4282 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004283 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004284 {
4285 repeatCount++;
4286 toRead =
4287# ifdef FEAT_MBYTE
4288 (DWORD)(BUFLEN - *buffer_off);
4289# else
4290 (DWORD)BUFLEN;
4291# endif
4292 toRead = availableBytes < toRead ? availableBytes : toRead;
4293 ReadFile(g_hChildStd_OUT_Rd, buffer
4294# ifdef FEAT_MBYTE
4295 + *buffer_off, toRead
4296# else
4297 , toRead
4298# endif
4299 , &len, NULL);
4300
4301 /* If we haven't read anything, there is a problem */
4302 if (len == 0)
4303 break;
4304
4305 availableBytes -= len;
4306
4307 if (options & SHELL_READ)
4308 {
4309 /* Do NUL -> NL translation, append NL separated
4310 * lines to the current buffer. */
4311 for (i = 0; i < len; ++i)
4312 {
4313 if (buffer[i] == NL)
4314 append_ga_line(ga);
4315 else if (buffer[i] == NUL)
4316 ga_append(ga, NL);
4317 else
4318 ga_append(ga, buffer[i]);
4319 }
4320 }
4321# ifdef FEAT_MBYTE
4322 else if (has_mbyte)
4323 {
4324 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004325 int c;
4326 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004327
4328 len += *buffer_off;
4329 buffer[len] = NUL;
4330
4331 /* Check if the last character in buffer[] is
4332 * incomplete, keep these bytes for the next
4333 * round. */
4334 for (p = buffer; p < buffer + len; p += l)
4335 {
4336 l = mb_cptr2len(p);
4337 if (l == 0)
4338 l = 1; /* NUL byte? */
4339 else if (MB_BYTE2LEN(*p) != l)
4340 break;
4341 }
4342 if (p == buffer) /* no complete character */
4343 {
4344 /* avoid getting stuck at an illegal byte */
4345 if (len >= 12)
4346 ++p;
4347 else
4348 {
4349 *buffer_off = len;
4350 return;
4351 }
4352 }
4353 c = *p;
4354 *p = NUL;
4355 msg_puts(buffer);
4356 if (p < buffer + len)
4357 {
4358 *p = c;
4359 *buffer_off = (DWORD)((buffer + len) - p);
4360 mch_memmove(buffer, p, *buffer_off);
4361 return;
4362 }
4363 *buffer_off = 0;
4364 }
4365# endif /* FEAT_MBYTE */
4366 else
4367 {
4368 buffer[len] = NUL;
4369 msg_puts(buffer);
4370 }
4371
4372 windgoto(msg_row, msg_col);
4373 cursor_on();
4374 out_flush();
4375 }
4376}
4377
4378/*
4379 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4380 * for communication and doesn't open any new window.
4381 */
4382 static int
4383mch_system_piped(char *cmd, int options)
4384{
4385 STARTUPINFO si;
4386 PROCESS_INFORMATION pi;
4387 DWORD ret = 0;
4388
4389 HANDLE g_hChildStd_IN_Rd = NULL;
4390 HANDLE g_hChildStd_IN_Wr = NULL;
4391 HANDLE g_hChildStd_OUT_Rd = NULL;
4392 HANDLE g_hChildStd_OUT_Wr = NULL;
4393
4394 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4395 DWORD len;
4396
4397 /* buffer used to receive keys */
4398 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4399 int ta_len = 0; /* valid bytes in ta_buf[] */
4400
4401 DWORD i;
4402 int c;
4403 int noread_cnt = 0;
4404 garray_T ga;
4405 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004406 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004407 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004408
4409 SECURITY_ATTRIBUTES saAttr;
4410
4411 /* Set the bInheritHandle flag so pipe handles are inherited. */
4412 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4413 saAttr.bInheritHandle = TRUE;
4414 saAttr.lpSecurityDescriptor = NULL;
4415
4416 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4417 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4418 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4419 /* Create a pipe for the child process's STDIN. */
4420 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4421 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4422 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4423 {
4424 CloseHandle(g_hChildStd_IN_Rd);
4425 CloseHandle(g_hChildStd_IN_Wr);
4426 CloseHandle(g_hChildStd_OUT_Rd);
4427 CloseHandle(g_hChildStd_OUT_Wr);
4428 MSG_PUTS(_("\nCannot create pipes\n"));
4429 }
4430
4431 si.cb = sizeof(si);
4432 si.lpReserved = NULL;
4433 si.lpDesktop = NULL;
4434 si.lpTitle = NULL;
4435 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4436
4437 /* set-up our file redirection */
4438 si.hStdError = g_hChildStd_OUT_Wr;
4439 si.hStdOutput = g_hChildStd_OUT_Wr;
4440 si.hStdInput = g_hChildStd_IN_Rd;
4441 si.wShowWindow = SW_HIDE;
4442 si.cbReserved2 = 0;
4443 si.lpReserved2 = NULL;
4444
4445 if (options & SHELL_READ)
4446 ga_init2(&ga, 1, BUFLEN);
4447
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004448 if (cmd != NULL)
4449 {
4450 p = (char *)vim_strsave((char_u *)cmd);
4451 if (p != NULL)
4452 unescape_shellxquote((char_u *)p, p_sxe);
4453 else
4454 p = cmd;
4455 }
4456
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004457 /* Now, run the command.
4458 * About "Inherit handles" being TRUE: this command can be litigious,
4459 * handle inheritance was deactivated for pending temp file, but, if we
4460 * deactivate it, the pipes don't work for some reason. */
4461 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004462
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004463 if (p != cmd)
4464 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004465
4466 /* Close our unused side of the pipes */
4467 CloseHandle(g_hChildStd_IN_Rd);
4468 CloseHandle(g_hChildStd_OUT_Wr);
4469
4470 if (options & SHELL_WRITE)
4471 {
4472 HANDLE thread =
4473 CreateThread(NULL, /* security attributes */
4474 0, /* default stack size */
4475 sub_process_writer, /* function to be executed */
4476 g_hChildStd_IN_Wr, /* parameter */
4477 0, /* creation flag, start immediately */
4478 NULL); /* we don't care about thread id */
4479 CloseHandle(thread);
4480 g_hChildStd_IN_Wr = NULL;
4481 }
4482
4483 /* Keep updating the window while waiting for the shell to finish. */
4484 for (;;)
4485 {
4486 MSG msg;
4487
Bram Moolenaar175d0702013-12-11 18:36:33 +01004488 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004489 {
4490 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004491 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004492 }
4493
4494 /* write pipe information in the window */
4495 if ((options & (SHELL_READ|SHELL_WRITE))
4496# ifdef FEAT_GUI
4497 || gui.in_use
4498# endif
4499 )
4500 {
4501 len = 0;
4502 if (!(options & SHELL_EXPAND)
4503 && ((options &
4504 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4505 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4506# ifdef FEAT_GUI
4507 || gui.in_use
4508# endif
4509 )
4510 && (ta_len > 0 || noread_cnt > 4))
4511 {
4512 if (ta_len == 0)
4513 {
4514 /* Get extra characters when we don't have any. Reset the
4515 * counter and timer. */
4516 noread_cnt = 0;
4517# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4518 gettimeofday(&start_tv, NULL);
4519# endif
4520 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4521 }
4522 if (ta_len > 0 || len > 0)
4523 {
4524 /*
4525 * For pipes: Check for CTRL-C: send interrupt signal to
4526 * child. Check for CTRL-D: EOF, close pipe to child.
4527 */
4528 if (len == 1 && cmd != NULL)
4529 {
4530 if (ta_buf[ta_len] == Ctrl_C)
4531 {
4532 /* Learn what exit code is expected, for
4533 * now put 9 as SIGKILL */
4534 TerminateProcess(pi.hProcess, 9);
4535 }
4536 if (ta_buf[ta_len] == Ctrl_D)
4537 {
4538 CloseHandle(g_hChildStd_IN_Wr);
4539 g_hChildStd_IN_Wr = NULL;
4540 }
4541 }
4542
4543 /* replace K_BS by <BS> and K_DEL by <DEL> */
4544 for (i = ta_len; i < ta_len + len; ++i)
4545 {
4546 if (ta_buf[i] == CSI && len - i > 2)
4547 {
4548 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4549 if (c == K_DEL || c == K_KDEL || c == K_BS)
4550 {
4551 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4552 (size_t)(len - i - 2));
4553 if (c == K_DEL || c == K_KDEL)
4554 ta_buf[i] = DEL;
4555 else
4556 ta_buf[i] = Ctrl_H;
4557 len -= 2;
4558 }
4559 }
4560 else if (ta_buf[i] == '\r')
4561 ta_buf[i] = '\n';
4562# ifdef FEAT_MBYTE
4563 if (has_mbyte)
4564 i += (*mb_ptr2len_len)(ta_buf + i,
4565 ta_len + len - i) - 1;
4566# endif
4567 }
4568
4569 /*
4570 * For pipes: echo the typed characters. For a pty this
4571 * does not seem to work.
4572 */
4573 for (i = ta_len; i < ta_len + len; ++i)
4574 {
4575 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4576 msg_putchar(ta_buf[i]);
4577# ifdef FEAT_MBYTE
4578 else if (has_mbyte)
4579 {
4580 int l = (*mb_ptr2len)(ta_buf + i);
4581
4582 msg_outtrans_len(ta_buf + i, l);
4583 i += l - 1;
4584 }
4585# endif
4586 else
4587 msg_outtrans_len(ta_buf + i, 1);
4588 }
4589 windgoto(msg_row, msg_col);
4590 out_flush();
4591
4592 ta_len += len;
4593
4594 /*
4595 * Write the characters to the child, unless EOF has been
4596 * typed for pipes. Write one character at a time, to
4597 * avoid losing too much typeahead. When writing buffer
4598 * lines, drop the typed characters (only check for
4599 * CTRL-C).
4600 */
4601 if (options & SHELL_WRITE)
4602 ta_len = 0;
4603 else if (g_hChildStd_IN_Wr != NULL)
4604 {
4605 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4606 1, &len, NULL);
4607 // if we are typing in, we want to keep things reactive
4608 delay = 1;
4609 if (len > 0)
4610 {
4611 ta_len -= len;
4612 mch_memmove(ta_buf, ta_buf + len, ta_len);
4613 }
4614 }
4615 }
4616 }
4617 }
4618
4619 if (ta_len)
4620 ui_inchar_undo(ta_buf, ta_len);
4621
4622 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4623 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004624 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004625 break;
4626 }
4627
4628 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004629 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004630
4631 /* We start waiting for a very short time and then increase it, so
4632 * that we respond quickly when the process is quick, and don't
4633 * consume too much overhead when it's slow. */
4634 if (delay < 50)
4635 delay += 10;
4636 }
4637
4638 /* Close the pipe */
4639 CloseHandle(g_hChildStd_OUT_Rd);
4640 if (g_hChildStd_IN_Wr != NULL)
4641 CloseHandle(g_hChildStd_IN_Wr);
4642
4643 WaitForSingleObject(pi.hProcess, INFINITE);
4644
4645 /* Get the command exit code */
4646 GetExitCodeProcess(pi.hProcess, &ret);
4647
4648 if (options & SHELL_READ)
4649 {
4650 if (ga.ga_len > 0)
4651 {
4652 append_ga_line(&ga);
4653 /* remember that the NL was missing */
4654 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4655 }
4656 else
4657 curbuf->b_no_eol_lnum = 0;
4658 ga_clear(&ga);
4659 }
4660
4661 /* Close the handles to the subprocess, so that it goes away */
4662 CloseHandle(pi.hThread);
4663 CloseHandle(pi.hProcess);
4664
4665 return ret;
4666}
4667
4668 static int
4669mch_system(char *cmd, int options)
4670{
4671 /* if we can pipe and the shelltemp option is off */
4672 if (allowPiping && !p_stmp)
4673 return mch_system_piped(cmd, options);
4674 else
4675 return mch_system_classic(cmd, options);
4676}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004677#else
4678
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004679# ifdef FEAT_MBYTE
4680 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004681mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004682{
4683 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4684 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004685 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004686 if (wcmd != NULL)
4687 {
4688 int ret = _wsystem(wcmd);
4689 vim_free(wcmd);
4690 return ret;
4691 }
4692 }
4693 return system(cmd);
4694}
4695# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004696# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004697# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004698
4699#endif
4700
4701/*
4702 * Either execute a command by calling the shell or start a new shell
4703 */
4704 int
4705mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004706 char_u *cmd,
4707 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708{
4709 int x = 0;
4710 int tmode = cur_tmode;
4711#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004712 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004713# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004714 int did_set_title = FALSE;
4715
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004716 /* Change the title to reflect that we are in a subshell. */
4717 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4718 {
4719 WCHAR szShellTitle[512];
4720
4721 if (GetConsoleTitleW(szShellTitle,
4722 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4723 {
4724 if (cmd == NULL)
4725 wcscat(szShellTitle, L" :sh");
4726 else
4727 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004728 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004729
4730 if (wn != NULL)
4731 {
4732 wcscat(szShellTitle, L" - !");
4733 if ((wcslen(szShellTitle) + wcslen(wn) <
4734 sizeof(szShellTitle)/sizeof(WCHAR)))
4735 wcscat(szShellTitle, wn);
4736 SetConsoleTitleW(szShellTitle);
4737 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004738 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004739 }
4740 }
4741 }
4742 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004743 if (!did_set_title)
4744# endif
4745 /* Change the title to reflect that we are in a subshell. */
4746 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004748 if (cmd == NULL)
4749 strcat(szShellTitle, " :sh");
4750 else
4751 {
4752 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004753 if ((strlen(szShellTitle) + strlen((char *)cmd)
4754 < sizeof(szShellTitle)))
4755 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004756 }
4757 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004759#endif
4760
4761 out_flush();
4762
4763#ifdef MCH_WRITE_DUMP
4764 if (fdDump)
4765 {
4766 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4767 fflush(fdDump);
4768 }
4769#endif
4770
4771 /*
4772 * Catch all deadly signals while running the external command, because a
4773 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4774 */
4775 signal(SIGINT, SIG_IGN);
4776#if defined(__GNUC__) && !defined(__MINGW32__)
4777 signal(SIGKILL, SIG_IGN);
4778#else
4779 signal(SIGBREAK, SIG_IGN);
4780#endif
4781 signal(SIGILL, SIG_IGN);
4782 signal(SIGFPE, SIG_IGN);
4783 signal(SIGSEGV, SIG_IGN);
4784 signal(SIGTERM, SIG_IGN);
4785 signal(SIGABRT, SIG_IGN);
4786
4787 if (options & SHELL_COOKED)
4788 settmode(TMODE_COOK); /* set to normal mode */
4789
4790 if (cmd == NULL)
4791 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004792 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004793 }
4794 else
4795 {
4796 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004797 char_u *newcmd = NULL;
4798 char_u *cmdbase = cmd;
4799 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004800
4801 /* Skip a leading ", ( and "(. */
4802 if (*cmdbase == '"' )
4803 ++cmdbase;
4804 if (*cmdbase == '(')
4805 ++cmdbase;
4806
4807 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4808 {
4809 STARTUPINFO si;
4810 PROCESS_INFORMATION pi;
4811 DWORD flags = CREATE_NEW_CONSOLE;
4812 char_u *p;
4813
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004814 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004815 si.cb = sizeof(si);
4816 si.lpReserved = NULL;
4817 si.lpDesktop = NULL;
4818 si.lpTitle = NULL;
4819 si.dwFlags = 0;
4820 si.cbReserved2 = 0;
4821 si.lpReserved2 = NULL;
4822
4823 cmdbase = skipwhite(cmdbase + 5);
4824 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4825 && vim_iswhite(cmdbase[4]))
4826 {
4827 cmdbase = skipwhite(cmdbase + 4);
4828 si.dwFlags = STARTF_USESHOWWINDOW;
4829 si.wShowWindow = SW_SHOWMINNOACTIVE;
4830 }
4831 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4832 && vim_iswhite(cmdbase[2]))
4833 {
4834 cmdbase = skipwhite(cmdbase + 2);
4835 flags = CREATE_NO_WINDOW;
4836 si.dwFlags = STARTF_USESTDHANDLES;
4837 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004838 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004839 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004840 NULL, // Security att.
4841 OPEN_EXISTING, // Open flags
4842 FILE_ATTRIBUTE_NORMAL, // File att.
4843 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004844 si.hStdOutput = si.hStdInput;
4845 si.hStdError = si.hStdInput;
4846 }
4847
4848 /* Remove a trailing ", ) and )" if they have a match
4849 * at the start of the command. */
4850 if (cmdbase > cmd)
4851 {
4852 p = cmdbase + STRLEN(cmdbase);
4853 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4854 *--p = NUL;
4855 if (p > cmdbase && p[-1] == ')'
4856 && (*cmd =='(' || cmd[1] == '('))
4857 *--p = NUL;
4858 }
4859
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004860 newcmd = cmdbase;
4861 unescape_shellxquote(cmdbase, p_sxe);
4862
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004863 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004864 * If creating new console, arguments are passed to the
4865 * 'cmd.exe' as-is. If it's not, arguments are not treated
4866 * correctly for current 'cmd.exe'. So unescape characters in
4867 * shellxescape except '|' for avoiding to be treated as
4868 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004869 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004870 if (flags != CREATE_NEW_CONSOLE)
4871 {
4872 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004873 char_u *cmd_shell = mch_getenv("COMSPEC");
4874
4875 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004876 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004878 subcmd = vim_strsave_escaped_ext(cmdbase,
4879 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004880 if (subcmd != NULL)
4881 {
4882 /* make "cmd.exe /c arguments" */
4883 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004884 newcmd = lalloc(cmdlen, TRUE);
4885 if (newcmd != NULL)
4886 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004887 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004888 else
4889 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004890 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004891 }
4892 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004893
4894 /*
4895 * Now, start the command as a process, so that it doesn't
4896 * inherit our handles which causes unpleasant dangling swap
4897 * files if we exit before the spawned process
4898 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004899 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004900 x = 0;
4901 else
4902 {
4903 x = -1;
4904#ifdef FEAT_GUI_W32
4905 EMSG(_("E371: Command not found"));
4906#endif
4907 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004908
4909 if (newcmd != cmdbase)
4910 vim_free(newcmd);
4911
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004912 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004913 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004914 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004915 CloseHandle(si.hStdInput);
4916 }
4917 /* Close the handles to the subprocess, so that it goes away */
4918 CloseHandle(pi.hThread);
4919 CloseHandle(pi.hProcess);
4920 }
4921 else
4922 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004923 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004924#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004925 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004926#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004927 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4928
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004929 newcmd = lalloc(cmdlen, TRUE);
4930 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004931 {
4932#if defined(FEAT_GUI_W32)
4933 if (need_vimrun_warning)
4934 {
4935 MessageBox(NULL,
4936 _("VIMRUN.EXE not found in your $PATH.\n"
4937 "External commands will not pause after completion.\n"
4938 "See :help win32-vimrun for more information."),
4939 _("Vim Warning"),
4940 MB_ICONWARNING);
4941 need_vimrun_warning = FALSE;
4942 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004943 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944 /* Use vimrun to execute the command. It opens a console
4945 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004946 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947 vimrun_path,
4948 (msg_silent != 0 || (options & SHELL_DOOUT))
4949 ? "-s " : "",
4950 p_sh, p_shcf, cmd);
4951 else
4952#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004953 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004954 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004955 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004956 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004957 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004958 }
4959 }
4960
4961 if (tmode == TMODE_RAW)
4962 settmode(TMODE_RAW); /* set to raw mode */
4963
4964 /* Print the return value, unless "vimrun" was used. */
4965 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4966#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004967 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4968 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004969#endif
4970 )
4971 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004972 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973 msg_putchar('\n');
4974 }
4975#ifdef FEAT_TITLE
4976 resettitle();
4977#endif
4978
4979 signal(SIGINT, SIG_DFL);
4980#if defined(__GNUC__) && !defined(__MINGW32__)
4981 signal(SIGKILL, SIG_DFL);
4982#else
4983 signal(SIGBREAK, SIG_DFL);
4984#endif
4985 signal(SIGILL, SIG_DFL);
4986 signal(SIGFPE, SIG_DFL);
4987 signal(SIGSEGV, SIG_DFL);
4988 signal(SIGTERM, SIG_DFL);
4989 signal(SIGABRT, SIG_DFL);
4990
4991 return x;
4992}
4993
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004994#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004995 static HANDLE
4996job_io_file_open(
4997 char_u *fname,
4998 DWORD dwDesiredAccess,
4999 DWORD dwShareMode,
5000 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5001 DWORD dwCreationDisposition,
5002 DWORD dwFlagsAndAttributes)
5003{
5004 HANDLE h;
5005# ifdef FEAT_MBYTE
5006 WCHAR *wn = NULL;
5007 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5008 {
5009 wn = enc_to_utf16(fname, NULL);
5010 if (wn != NULL)
5011 {
5012 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5013 lpSecurityAttributes, dwCreationDisposition,
5014 dwFlagsAndAttributes, NULL);
5015 vim_free(wn);
5016 if (h == INVALID_HANDLE_VALUE
5017 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5018 wn = NULL;
5019 }
5020 }
5021 if (wn == NULL)
5022# endif
5023
5024 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5025 lpSecurityAttributes, dwCreationDisposition,
5026 dwFlagsAndAttributes, NULL);
5027 return h;
5028}
5029
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005030 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005031mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005032{
5033 STARTUPINFO si;
5034 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005035 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005036 SECURITY_ATTRIBUTES saAttr;
5037 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005038 HANDLE ifd[2];
5039 HANDLE ofd[2];
5040 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005041
5042 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5043 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5044 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5045 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5046 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5047 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5048 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5049
5050 if (use_out_for_err && use_null_for_out)
5051 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005052
5053 ifd[0] = INVALID_HANDLE_VALUE;
5054 ifd[1] = INVALID_HANDLE_VALUE;
5055 ofd[0] = INVALID_HANDLE_VALUE;
5056 ofd[1] = INVALID_HANDLE_VALUE;
5057 efd[0] = INVALID_HANDLE_VALUE;
5058 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005059
Bram Moolenaar76467df2016-02-12 19:30:26 +01005060 jo = CreateJobObject(NULL, NULL);
5061 if (jo == NULL)
5062 {
5063 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005064 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005065 }
5066
5067 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005068 ZeroMemory(&si, sizeof(si));
5069 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005070 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005071 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005072
Bram Moolenaard8070362016-02-15 21:56:54 +01005073 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5074 saAttr.bInheritHandle = TRUE;
5075 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005076
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005077 if (use_file_for_in)
5078 {
5079 char_u *fname = options->jo_io_name[PART_IN];
5080
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005081 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5082 FILE_SHARE_READ | FILE_SHARE_WRITE,
5083 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5084 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005085 {
5086 EMSG2(_(e_notopen), fname);
5087 goto failed;
5088 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005089 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005090 else if (!use_null_for_in &&
5091 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5092 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005093 goto failed;
5094
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005095 if (use_file_for_out)
5096 {
5097 char_u *fname = options->jo_io_name[PART_OUT];
5098
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005099 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5100 FILE_SHARE_READ | FILE_SHARE_WRITE,
5101 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5102 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005103 {
5104 EMSG2(_(e_notopen), fname);
5105 goto failed;
5106 }
5107 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005108 else if (!use_null_for_out &&
5109 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5110 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005111 goto failed;
5112
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005113 if (use_file_for_err)
5114 {
5115 char_u *fname = options->jo_io_name[PART_ERR];
5116
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005117 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5118 FILE_SHARE_READ | FILE_SHARE_WRITE,
5119 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5120 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005121 {
5122 EMSG2(_(e_notopen), fname);
5123 goto failed;
5124 }
5125 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005126 else if (!use_out_for_err && !use_null_for_err &&
5127 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005128 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005129 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005130
Bram Moolenaard8070362016-02-15 21:56:54 +01005131 si.dwFlags |= STARTF_USESTDHANDLES;
5132 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005133 si.hStdOutput = ofd[1];
5134 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5135
5136 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5137 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005138 if (options->jo_set & JO_CHANNEL)
5139 {
5140 channel = options->jo_channel;
5141 if (channel != NULL)
5142 ++channel->ch_refcount;
5143 }
5144 else
5145 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005146 if (channel == NULL)
5147 goto failed;
5148 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005149
5150 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005151 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005152 CREATE_DEFAULT_ERROR_MODE |
5153 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005154 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005155 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005156 {
5157 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005158 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005159 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005160 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005161
5162 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005163 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005164 /* if failing, switch the way to terminate
5165 * process with TerminateProcess. */
5166 CloseHandle(jo);
5167 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005168 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005169 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005170 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005171 job->jv_proc_info = pi;
5172 job->jv_job_object = jo;
5173 job->jv_status = JOB_STARTED;
5174
Bram Moolenaar94d01912016-03-08 13:48:51 +01005175 if (!use_file_for_in)
5176 CloseHandle(ifd[0]);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005177 if (!use_file_for_out)
5178 CloseHandle(ofd[1]);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005179 if (!use_out_for_err && !use_file_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005180 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005181
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005182 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005183 if (channel != NULL)
5184 {
5185 channel_set_pipes(channel,
5186 use_file_for_in || use_null_for_in
5187 ? INVALID_FD : (sock_T)ifd[1],
5188 use_file_for_out || use_null_for_out
5189 ? INVALID_FD : (sock_T)ofd[0],
5190 use_out_for_err || use_file_for_err || use_null_for_err
5191 ? INVALID_FD : (sock_T)efd[0]);
5192 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005193 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005194 return;
5195
5196failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005197 CloseHandle(ifd[0]);
5198 CloseHandle(ofd[0]);
5199 CloseHandle(efd[0]);
5200 CloseHandle(ifd[1]);
5201 CloseHandle(ofd[1]);
5202 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005203 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005204}
5205
5206 char *
5207mch_job_status(job_T *job)
5208{
5209 DWORD dwExitCode = 0;
5210
Bram Moolenaar76467df2016-02-12 19:30:26 +01005211 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5212 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005213 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005214 job->jv_status = JOB_ENDED;
Bram Moolenaareab089d2016-02-21 19:32:02 +01005215 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005216 return "dead";
5217 }
5218 return "run";
5219}
5220
5221 int
5222mch_stop_job(job_T *job, char_u *how)
5223{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005224 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005225
Bram Moolenaar923d9262016-02-25 20:56:01 +01005226 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005227 {
5228 if (job->jv_job_object != NULL)
5229 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5230 else
5231 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5232 }
5233
5234 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5235 return FAIL;
5236 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005237 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5238 job->jv_proc_info.dwProcessId)
5239 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005240 FreeConsole();
5241 return ret;
5242}
5243
5244/*
5245 * Clear the data related to "job".
5246 */
5247 void
5248mch_clear_job(job_T *job)
5249{
5250 if (job->jv_status != JOB_FAILED)
5251 {
5252 if (job->jv_job_object != NULL)
5253 CloseHandle(job->jv_job_object);
5254 CloseHandle(job->jv_proc_info.hProcess);
5255 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005256}
5257#endif
5258
Bram Moolenaar071d4272004-06-13 20:20:40 +00005259
5260#ifndef FEAT_GUI_W32
5261
5262/*
5263 * Start termcap mode
5264 */
5265 static void
5266termcap_mode_start(void)
5267{
5268 DWORD cmodein;
5269
5270 if (g_fTermcapMode)
5271 return;
5272
5273 SaveConsoleBuffer(&g_cbNonTermcap);
5274
5275 if (g_cbTermcap.IsValid)
5276 {
5277 /*
5278 * We've been in termcap mode before. Restore certain screen
5279 * characteristics, including the buffer size and the window
5280 * size. Since we will be redrawing the screen, we don't need
5281 * to restore the actual contents of the buffer.
5282 */
5283 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5284 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5285 Rows = g_cbTermcap.Info.dwSize.Y;
5286 Columns = g_cbTermcap.Info.dwSize.X;
5287 }
5288 else
5289 {
5290 /*
5291 * This is our first time entering termcap mode. Clear the console
5292 * screen buffer, and resize the buffer to match the current window
5293 * size. We will use this as the size of our editing environment.
5294 */
5295 ClearConsoleBuffer(g_attrCurrent);
5296 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5297 }
5298
5299#ifdef FEAT_TITLE
5300 resettitle();
5301#endif
5302
5303 GetConsoleMode(g_hConIn, &cmodein);
5304#ifdef FEAT_MOUSE
5305 if (g_fMouseActive)
5306 cmodein |= ENABLE_MOUSE_INPUT;
5307 else
5308 cmodein &= ~ENABLE_MOUSE_INPUT;
5309#endif
5310 cmodein |= ENABLE_WINDOW_INPUT;
5311 SetConsoleMode(g_hConIn, cmodein);
5312
5313 redraw_later_clear();
5314 g_fTermcapMode = TRUE;
5315}
5316
5317
5318/*
5319 * End termcap mode
5320 */
5321 static void
5322termcap_mode_end(void)
5323{
5324 DWORD cmodein;
5325 ConsoleBuffer *cb;
5326 COORD coord;
5327 DWORD dwDummy;
5328
5329 if (!g_fTermcapMode)
5330 return;
5331
5332 SaveConsoleBuffer(&g_cbTermcap);
5333
5334 GetConsoleMode(g_hConIn, &cmodein);
5335 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5336 SetConsoleMode(g_hConIn, cmodein);
5337
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005338#ifdef FEAT_RESTORE_ORIG_SCREEN
5339 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5340#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005341 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005342#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005343 RestoreConsoleBuffer(cb, p_rs);
5344 SetConsoleCursorInfo(g_hConOut, &g_cci);
5345
5346 if (p_rs || exiting)
5347 {
5348 /*
5349 * Clear anything that happens to be on the current line.
5350 */
5351 coord.X = 0;
5352 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5353 FillConsoleOutputCharacter(g_hConOut, ' ',
5354 cb->Info.dwSize.X, coord, &dwDummy);
5355 /*
5356 * The following is just for aesthetics. If we are exiting without
5357 * restoring the screen, then we want to have a prompt string
5358 * appear at the bottom line. However, the command interpreter
5359 * seems to always advance the cursor one line before displaying
5360 * the prompt string, which causes the screen to scroll. To
5361 * counter this, move the cursor up one line before exiting.
5362 */
5363 if (exiting && !p_rs)
5364 coord.Y--;
5365 /*
5366 * Position the cursor at the leftmost column of the desired row.
5367 */
5368 SetConsoleCursorPosition(g_hConOut, coord);
5369 }
5370
5371 g_fTermcapMode = FALSE;
5372}
5373#endif /* FEAT_GUI_W32 */
5374
5375
5376#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005377/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005378 void
5379mch_write(
5380 char_u *s,
5381 int len)
5382{
5383 /* never used */
5384}
5385
5386#else
5387
5388/*
5389 * clear `n' chars, starting from `coord'
5390 */
5391 static void
5392clear_chars(
5393 COORD coord,
5394 DWORD n)
5395{
5396 DWORD dwDummy;
5397
5398 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5399 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5400}
5401
5402
5403/*
5404 * Clear the screen
5405 */
5406 static void
5407clear_screen(void)
5408{
5409 g_coord.X = g_coord.Y = 0;
5410 clear_chars(g_coord, Rows * Columns);
5411}
5412
5413
5414/*
5415 * Clear to end of display
5416 */
5417 static void
5418clear_to_end_of_display(void)
5419{
5420 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5421 * Columns + (Columns - g_coord.X));
5422}
5423
5424
5425/*
5426 * Clear to end of line
5427 */
5428 static void
5429clear_to_end_of_line(void)
5430{
5431 clear_chars(g_coord, Columns - g_coord.X);
5432}
5433
5434
5435/*
5436 * Scroll the scroll region up by `cLines' lines
5437 */
5438 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005439scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440{
5441 COORD oldcoord = g_coord;
5442
5443 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5444 delete_lines(cLines);
5445
5446 g_coord = oldcoord;
5447}
5448
5449
5450/*
5451 * Set the scroll region
5452 */
5453 static void
5454set_scroll_region(
5455 unsigned left,
5456 unsigned top,
5457 unsigned right,
5458 unsigned bottom)
5459{
5460 if (left >= right
5461 || top >= bottom
5462 || right > (unsigned) Columns - 1
5463 || bottom > (unsigned) Rows - 1)
5464 return;
5465
5466 g_srScrollRegion.Left = left;
5467 g_srScrollRegion.Top = top;
5468 g_srScrollRegion.Right = right;
5469 g_srScrollRegion.Bottom = bottom;
5470}
5471
5472
5473/*
5474 * Insert `cLines' lines at the current cursor position
5475 */
5476 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005477insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005478{
5479 SMALL_RECT source;
5480 COORD dest;
5481 CHAR_INFO fill;
5482
5483 dest.X = 0;
5484 dest.Y = g_coord.Y + cLines;
5485
5486 source.Left = 0;
5487 source.Top = g_coord.Y;
5488 source.Right = g_srScrollRegion.Right;
5489 source.Bottom = g_srScrollRegion.Bottom - cLines;
5490
5491 fill.Char.AsciiChar = ' ';
5492 fill.Attributes = g_attrCurrent;
5493
5494 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5495
5496 /* Here we have to deal with a win32 console flake: If the scroll
5497 * region looks like abc and we scroll c to a and fill with d we get
5498 * cbd... if we scroll block c one line at a time to a, we get cdd...
5499 * vim expects cdd consistently... So we have to deal with that
5500 * here... (this also occurs scrolling the same way in the other
5501 * direction). */
5502
5503 if (source.Bottom < dest.Y)
5504 {
5505 COORD coord;
5506
5507 coord.X = 0;
5508 coord.Y = source.Bottom;
5509 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5510 }
5511}
5512
5513
5514/*
5515 * Delete `cLines' lines at the current cursor position
5516 */
5517 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005518delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005519{
5520 SMALL_RECT source;
5521 COORD dest;
5522 CHAR_INFO fill;
5523 int nb;
5524
5525 dest.X = 0;
5526 dest.Y = g_coord.Y;
5527
5528 source.Left = 0;
5529 source.Top = g_coord.Y + cLines;
5530 source.Right = g_srScrollRegion.Right;
5531 source.Bottom = g_srScrollRegion.Bottom;
5532
5533 fill.Char.AsciiChar = ' ';
5534 fill.Attributes = g_attrCurrent;
5535
5536 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5537
5538 /* Here we have to deal with a win32 console flake: If the scroll
5539 * region looks like abc and we scroll c to a and fill with d we get
5540 * cbd... if we scroll block c one line at a time to a, we get cdd...
5541 * vim expects cdd consistently... So we have to deal with that
5542 * here... (this also occurs scrolling the same way in the other
5543 * direction). */
5544
5545 nb = dest.Y + (source.Bottom - source.Top) + 1;
5546
5547 if (nb < source.Top)
5548 {
5549 COORD coord;
5550
5551 coord.X = 0;
5552 coord.Y = nb;
5553 clear_chars(coord, Columns * (source.Top - nb));
5554 }
5555}
5556
5557
5558/*
5559 * Set the cursor position
5560 */
5561 static void
5562gotoxy(
5563 unsigned x,
5564 unsigned y)
5565{
5566 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5567 return;
5568
5569 /* external cursor coords are 1-based; internal are 0-based */
5570 g_coord.X = x - 1;
5571 g_coord.Y = y - 1;
5572 SetConsoleCursorPosition(g_hConOut, g_coord);
5573}
5574
5575
5576/*
5577 * Set the current text attribute = (foreground | background)
5578 * See ../doc/os_win32.txt for the numbers.
5579 */
5580 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005581textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005582{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005583 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005584
5585 SetConsoleTextAttribute(g_hConOut, wAttr);
5586}
5587
5588
5589 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005590textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005592 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593
5594 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5595}
5596
5597
5598 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005599textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005600{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005601 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602
5603 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5604}
5605
5606
5607/*
5608 * restore the default text attribute (whatever we started with)
5609 */
5610 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005611normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612{
5613 textattr(g_attrDefault);
5614}
5615
5616
5617static WORD g_attrPreStandout = 0;
5618
5619/*
5620 * Make the text standout, by brightening it
5621 */
5622 static void
5623standout(void)
5624{
5625 g_attrPreStandout = g_attrCurrent;
5626 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5627}
5628
5629
5630/*
5631 * Turn off standout mode
5632 */
5633 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005634standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635{
5636 if (g_attrPreStandout)
5637 {
5638 textattr(g_attrPreStandout);
5639 g_attrPreStandout = 0;
5640 }
5641}
5642
5643
5644/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005645 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646 */
5647 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005648mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649{
5650 char_u *p;
5651 int n;
5652
5653 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5654 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5655 if (T_ME[0] == ESC && T_ME[1] == '|')
5656 {
5657 p = T_ME + 2;
5658 n = getdigits(&p);
5659 if (*p == 'm' && n > 0)
5660 {
5661 cterm_normal_fg_color = (n & 0xf) + 1;
5662 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5663 }
5664 }
5665}
5666
5667
5668/*
5669 * visual bell: flash the screen
5670 */
5671 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005672visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673{
5674 COORD coordOrigin = {0, 0};
5675 WORD attrFlash = ~g_attrCurrent & 0xff;
5676
5677 DWORD dwDummy;
5678 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5679
5680 if (oldattrs == NULL)
5681 return;
5682 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5683 coordOrigin, &dwDummy);
5684 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5685 coordOrigin, &dwDummy);
5686
5687 Sleep(15); /* wait for 15 msec */
5688 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5689 coordOrigin, &dwDummy);
5690 vim_free(oldattrs);
5691}
5692
5693
5694/*
5695 * Make the cursor visible or invisible
5696 */
5697 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005698cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699{
5700 s_cursor_visible = fVisible;
5701#ifdef MCH_CURSOR_SHAPE
5702 mch_update_cursor();
5703#endif
5704}
5705
5706
5707/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005708 * write `cbToWrite' bytes in `pchBuf' to the screen
5709 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005711 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005712write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005713 char_u *pchBuf,
5714 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715{
5716 COORD coord = g_coord;
5717 DWORD written;
5718
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005719#ifdef FEAT_MBYTE
5720 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5721 {
5722 static WCHAR *unicodebuf = NULL;
5723 static int unibuflen = 0;
5724 int length;
5725 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005726
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005727 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5728 if (unicodebuf == NULL || length > unibuflen)
5729 {
5730 vim_free(unicodebuf);
5731 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5732 unibuflen = length;
5733 }
5734 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5735 unicodebuf, unibuflen);
5736
5737 cells = mb_string2cells(pchBuf, cbToWrite);
5738 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5739 coord, &written);
5740 /* When writing fails or didn't write a single character, pretend one
5741 * character was written, otherwise we get stuck. */
5742 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5743 coord, &cchwritten) == 0
5744 || cchwritten == 0)
5745 cchwritten = 1;
5746
5747 if (cchwritten == length)
5748 {
5749 written = cbToWrite;
5750 g_coord.X += (SHORT)cells;
5751 }
5752 else
5753 {
5754 char_u *p = pchBuf;
5755 for (n = 0; n < cchwritten; n++)
5756 mb_cptr_adv(p);
5757 written = p - pchBuf;
5758 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5759 }
5760 }
5761 else
5762#endif
5763 {
5764 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5765 coord, &written);
5766 /* When writing fails or didn't write a single character, pretend one
5767 * character was written, otherwise we get stuck. */
5768 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5769 coord, &written) == 0
5770 || written == 0)
5771 written = 1;
5772
5773 g_coord.X += (SHORT) written;
5774 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775
5776 while (g_coord.X > g_srScrollRegion.Right)
5777 {
5778 g_coord.X -= (SHORT) Columns;
5779 if (g_coord.Y < g_srScrollRegion.Bottom)
5780 g_coord.Y++;
5781 }
5782
5783 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5784
5785 return written;
5786}
5787
5788
5789/*
5790 * mch_write(): write the output buffer to the screen, translating ESC
5791 * sequences into calls to console output routines.
5792 */
5793 void
5794mch_write(
5795 char_u *s,
5796 int len)
5797{
5798 s[len] = NUL;
5799
5800 if (!term_console)
5801 {
5802 write(1, s, (unsigned)len);
5803 return;
5804 }
5805
5806 /* translate ESC | sequences into faked bios calls */
5807 while (len--)
5808 {
5809 /* optimization: use one single write_chars for runs of text,
5810 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005811 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005812
5813 if (p_wd)
5814 {
5815 WaitForChar(p_wd);
5816 if (prefix != 0)
5817 prefix = 1;
5818 }
5819
5820 if (prefix != 0)
5821 {
5822 DWORD nWritten;
5823
5824 nWritten = write_chars(s, prefix);
5825#ifdef MCH_WRITE_DUMP
5826 if (fdDump)
5827 {
5828 fputc('>', fdDump);
5829 fwrite(s, sizeof(char_u), nWritten, fdDump);
5830 fputs("<\n", fdDump);
5831 }
5832#endif
5833 len -= (nWritten - 1);
5834 s += nWritten;
5835 }
5836 else if (s[0] == '\n')
5837 {
5838 /* \n, newline: go to the beginning of the next line or scroll */
5839 if (g_coord.Y == g_srScrollRegion.Bottom)
5840 {
5841 scroll(1);
5842 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5843 }
5844 else
5845 {
5846 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5847 }
5848#ifdef MCH_WRITE_DUMP
5849 if (fdDump)
5850 fputs("\\n\n", fdDump);
5851#endif
5852 s++;
5853 }
5854 else if (s[0] == '\r')
5855 {
5856 /* \r, carriage return: go to beginning of line */
5857 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5858#ifdef MCH_WRITE_DUMP
5859 if (fdDump)
5860 fputs("\\r\n", fdDump);
5861#endif
5862 s++;
5863 }
5864 else if (s[0] == '\b')
5865 {
5866 /* \b, backspace: move cursor one position left */
5867 if (g_coord.X > g_srScrollRegion.Left)
5868 g_coord.X--;
5869 else if (g_coord.Y > g_srScrollRegion.Top)
5870 {
5871 g_coord.X = g_srScrollRegion.Right;
5872 g_coord.Y--;
5873 }
5874 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5875#ifdef MCH_WRITE_DUMP
5876 if (fdDump)
5877 fputs("\\b\n", fdDump);
5878#endif
5879 s++;
5880 }
5881 else if (s[0] == '\a')
5882 {
5883 /* \a, bell */
5884 MessageBeep(0xFFFFFFFF);
5885#ifdef MCH_WRITE_DUMP
5886 if (fdDump)
5887 fputs("\\a\n", fdDump);
5888#endif
5889 s++;
5890 }
5891 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5892 {
5893#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005894 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005895#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005896 char_u *p;
5897 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898
5899 switch (s[2])
5900 {
5901 /* one or two numeric arguments, separated by ';' */
5902
5903 case '0': case '1': case '2': case '3': case '4':
5904 case '5': case '6': case '7': case '8': case '9':
5905 p = s + 2;
5906 arg1 = getdigits(&p); /* no check for length! */
5907 if (p > s + len)
5908 break;
5909
5910 if (*p == ';')
5911 {
5912 ++p;
5913 arg2 = getdigits(&p); /* no check for length! */
5914 if (p > s + len)
5915 break;
5916
5917 if (*p == 'H')
5918 gotoxy(arg2, arg1);
5919 else if (*p == 'r')
5920 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5921 }
5922 else if (*p == 'A')
5923 {
5924 /* move cursor up arg1 lines in same column */
5925 gotoxy(g_coord.X + 1,
5926 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5927 }
5928 else if (*p == 'C')
5929 {
5930 /* move cursor right arg1 columns in same line */
5931 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5932 g_coord.Y + 1);
5933 }
5934 else if (*p == 'H')
5935 {
5936 gotoxy(1, arg1);
5937 }
5938 else if (*p == 'L')
5939 {
5940 insert_lines(arg1);
5941 }
5942 else if (*p == 'm')
5943 {
5944 if (arg1 == 0)
5945 normvideo();
5946 else
5947 textattr((WORD) arg1);
5948 }
5949 else if (*p == 'f')
5950 {
5951 textcolor((WORD) arg1);
5952 }
5953 else if (*p == 'b')
5954 {
5955 textbackground((WORD) arg1);
5956 }
5957 else if (*p == 'M')
5958 {
5959 delete_lines(arg1);
5960 }
5961
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005962 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005963 s = p + 1;
5964 break;
5965
5966
5967 /* Three-character escape sequences */
5968
5969 case 'A':
5970 /* move cursor up one line in same column */
5971 gotoxy(g_coord.X + 1,
5972 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5973 goto got3;
5974
5975 case 'B':
5976 visual_bell();
5977 goto got3;
5978
5979 case 'C':
5980 /* move cursor right one column in same line */
5981 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5982 g_coord.Y + 1);
5983 goto got3;
5984
5985 case 'E':
5986 termcap_mode_end();
5987 goto got3;
5988
5989 case 'F':
5990 standout();
5991 goto got3;
5992
5993 case 'f':
5994 standend();
5995 goto got3;
5996
5997 case 'H':
5998 gotoxy(1, 1);
5999 goto got3;
6000
6001 case 'j':
6002 clear_to_end_of_display();
6003 goto got3;
6004
6005 case 'J':
6006 clear_screen();
6007 goto got3;
6008
6009 case 'K':
6010 clear_to_end_of_line();
6011 goto got3;
6012
6013 case 'L':
6014 insert_lines(1);
6015 goto got3;
6016
6017 case 'M':
6018 delete_lines(1);
6019 goto got3;
6020
6021 case 'S':
6022 termcap_mode_start();
6023 goto got3;
6024
6025 case 'V':
6026 cursor_visible(TRUE);
6027 goto got3;
6028
6029 case 'v':
6030 cursor_visible(FALSE);
6031 goto got3;
6032
6033 got3:
6034 s += 3;
6035 len -= 2;
6036 }
6037
6038#ifdef MCH_WRITE_DUMP
6039 if (fdDump)
6040 {
6041 fputs("ESC | ", fdDump);
6042 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6043 fputc('\n', fdDump);
6044 }
6045#endif
6046 }
6047 else
6048 {
6049 /* Write a single character */
6050 DWORD nWritten;
6051
6052 nWritten = write_chars(s, 1);
6053#ifdef MCH_WRITE_DUMP
6054 if (fdDump)
6055 {
6056 fputc('>', fdDump);
6057 fwrite(s, sizeof(char_u), nWritten, fdDump);
6058 fputs("<\n", fdDump);
6059 }
6060#endif
6061
6062 len -= (nWritten - 1);
6063 s += nWritten;
6064 }
6065 }
6066
6067#ifdef MCH_WRITE_DUMP
6068 if (fdDump)
6069 fflush(fdDump);
6070#endif
6071}
6072
6073#endif /* FEAT_GUI_W32 */
6074
6075
6076/*
6077 * Delay for half a second.
6078 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006079/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080 void
6081mch_delay(
6082 long msec,
6083 int ignoreinput)
6084{
6085#ifdef FEAT_GUI_W32
6086 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006087#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006088 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006089# ifdef FEAT_MZSCHEME
6090 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6091 {
6092 int towait = p_mzq;
6093
6094 /* if msec is large enough, wait by portions in p_mzq */
6095 while (msec > 0)
6096 {
6097 mzvim_check_threads();
6098 if (msec < towait)
6099 towait = msec;
6100 Sleep(towait);
6101 msec -= towait;
6102 }
6103 }
6104 else
6105# endif
6106 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107 else
6108 WaitForChar(msec);
6109#endif
6110}
6111
6112
6113/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006114 * This version of remove is not scared by a readonly (backup) file.
6115 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 * Return 0 for success, -1 for failure.
6117 */
6118 int
6119mch_remove(char_u *name)
6120{
6121#ifdef FEAT_MBYTE
6122 WCHAR *wn = NULL;
6123 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006124#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125
Bram Moolenaar203258c2016-01-17 22:15:16 +01006126 /*
6127 * On Windows, deleting a directory's symbolic link is done by
6128 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6129 */
6130 if (mch_isdir(name) && mch_is_symbolic_link(name))
6131 return mch_rmdir(name);
6132
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006133 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6134
6135#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6137 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006138 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139 if (wn != NULL)
6140 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141 n = DeleteFileW(wn) ? 0 : -1;
6142 vim_free(wn);
6143 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6144 return n;
6145 /* Retry with non-wide function (for Windows 98). */
6146 }
6147 }
6148#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006149 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150}
6151
6152
6153/*
6154 * check for an "interrupt signal": CTRL-break or CTRL-C
6155 */
6156 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006157mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006158{
6159#ifndef FEAT_GUI_W32 /* never used */
6160 if (g_fCtrlCPressed || g_fCBrkPressed)
6161 {
6162 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6163 got_int = TRUE;
6164 }
6165#endif
6166}
6167
Bram Moolenaaree273972016-01-02 21:11:51 +01006168/* physical RAM to leave for the OS */
6169#define WINNT_RESERVE_BYTES (256*1024*1024)
6170#define WIN95_RESERVE_BYTES (8*1024*1024)
6171
6172/*
6173 * How much main memory in KiB that can be used by VIM.
6174 */
6175/*ARGSUSED*/
6176 long_u
6177mch_total_mem(int special)
6178{
6179 PlatformId();
6180#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6181 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6182 {
6183 MEMORYSTATUSEX ms;
6184
6185 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6186 * what fits in 32 bits. But it's not always available. */
6187 ms.dwLength = sizeof(MEMORYSTATUSEX);
6188 GlobalMemoryStatusEx(&ms);
6189 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6190 {
6191 /* Process address space fits in physical RAM, use all of it. */
6192 return (long_u)(ms.ullAvailVirtual / 1024);
6193 }
6194 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6195 {
6196 /* Catch old NT box or perverse hardware setup. */
6197 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6198 }
6199 /* Use physical RAM less reserve for OS + data. */
6200 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6201 }
6202 else
6203#endif
6204 {
6205 /* Pre-XP or 95 OS handling. */
6206 MEMORYSTATUS ms;
6207 long_u os_reserve_bytes;
6208
6209 ms.dwLength = sizeof(MEMORYSTATUS);
6210 GlobalMemoryStatus(&ms);
6211 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6212 {
6213 /* Process address space fits in physical RAM, use all of it. */
6214 return (long_u)(ms.dwAvailVirtual / 1024);
6215 }
6216 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6217 ? WINNT_RESERVE_BYTES
6218 : WIN95_RESERVE_BYTES;
6219 if (ms.dwTotalPhys <= os_reserve_bytes)
6220 {
6221 /* Catch old boxes or perverse hardware setup. */
6222 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6223 }
6224 /* Use physical RAM less reserve for OS + data. */
6225 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6226 }
6227}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229#ifdef FEAT_MBYTE
6230/*
6231 * Same code as below, but with wide functions and no comments.
6232 * Return 0 for success, non-zero for failure.
6233 */
6234 int
6235mch_wrename(WCHAR *wold, WCHAR *wnew)
6236{
6237 WCHAR *p;
6238 int i;
6239 WCHAR szTempFile[_MAX_PATH + 1];
6240 WCHAR szNewPath[_MAX_PATH + 1];
6241 HANDLE hf;
6242
6243 if (!mch_windows95())
6244 {
6245 p = wold;
6246 for (i = 0; wold[i] != NUL; ++i)
6247 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6248 && wold[i + 1] != 0)
6249 p = wold + i + 1;
6250 if ((int)(wold + i - p) < 8 || p[6] != '~')
6251 return (MoveFileW(wold, wnew) == 0);
6252 }
6253
6254 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6255 return -1;
6256 *p = NUL;
6257
6258 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6259 return -2;
6260
6261 if (!DeleteFileW(szTempFile))
6262 return -3;
6263
6264 if (!MoveFileW(wold, szTempFile))
6265 return -4;
6266
6267 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6268 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6269 return -5;
6270 if (!CloseHandle(hf))
6271 return -6;
6272
6273 if (!MoveFileW(szTempFile, wnew))
6274 {
6275 (void)MoveFileW(szTempFile, wold);
6276 return -7;
6277 }
6278
6279 DeleteFileW(szTempFile);
6280
6281 if (!DeleteFileW(wold))
6282 return -8;
6283
6284 return 0;
6285}
6286#endif
6287
6288
6289/*
6290 * mch_rename() works around a bug in rename (aka MoveFile) in
6291 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6292 * file whose short file name is "FOO.BAR" (its long file name will
6293 * be correct: "foo.bar~"). Because a file can be accessed by
6294 * either its SFN or its LFN, "foo.bar" has effectively been
6295 * renamed to "foo.bar", which is not at all what was wanted. This
6296 * seems to happen only when renaming files with three-character
6297 * extensions by appending a suffix that does not include ".".
6298 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6299 *
6300 * There is another problem, which isn't really a bug but isn't right either:
6301 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6302 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6303 * service pack 6. Doesn't seem to happen on Windows 98.
6304 *
6305 * Like rename(), returns 0 upon success, non-zero upon failure.
6306 * Should probably set errno appropriately when errors occur.
6307 */
6308 int
6309mch_rename(
6310 const char *pszOldFile,
6311 const char *pszNewFile)
6312{
6313 char szTempFile[_MAX_PATH+1];
6314 char szNewPath[_MAX_PATH+1];
6315 char *pszFilePart;
6316 HANDLE hf;
6317#ifdef FEAT_MBYTE
6318 WCHAR *wold = NULL;
6319 WCHAR *wnew = NULL;
6320 int retval = -1;
6321
6322 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6323 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006324 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6325 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326 if (wold != NULL && wnew != NULL)
6327 retval = mch_wrename(wold, wnew);
6328 vim_free(wold);
6329 vim_free(wnew);
6330 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6331 return retval;
6332 /* Retry with non-wide function (for Windows 98). */
6333 }
6334#endif
6335
6336 /*
6337 * No need to play tricks if not running Windows 95, unless the file name
6338 * contains a "~" as the seventh character.
6339 */
6340 if (!mch_windows95())
6341 {
6342 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6343 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6344 return rename(pszOldFile, pszNewFile);
6345 }
6346
6347 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6348 * a directory, no error is returned and pszFilePart will be NULL. */
6349 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6350 || pszFilePart == NULL)
6351 return -1;
6352 *pszFilePart = NUL;
6353
6354 /* Get (and create) a unique temporary file name in directory of new file */
6355 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6356 return -2;
6357
6358 /* blow the temp file away */
6359 if (!DeleteFile(szTempFile))
6360 return -3;
6361
6362 /* rename old file to the temp file */
6363 if (!MoveFile(pszOldFile, szTempFile))
6364 return -4;
6365
6366 /* now create an empty file called pszOldFile; this prevents the operating
6367 * system using pszOldFile as an alias (SFN) if we're renaming within the
6368 * same directory. For example, we're editing a file called
6369 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6370 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6371 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006372 * cause all sorts of problems later in buf_write(). So, we create an
6373 * empty file called filena~1.txt and the system will have to find some
6374 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 */
6376 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6377 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6378 return -5;
6379 if (!CloseHandle(hf))
6380 return -6;
6381
6382 /* rename the temp file to the new file */
6383 if (!MoveFile(szTempFile, pszNewFile))
6384 {
6385 /* Renaming failed. Rename the file back to its old name, so that it
6386 * looks like nothing happened. */
6387 (void)MoveFile(szTempFile, pszOldFile);
6388
6389 return -7;
6390 }
6391
6392 /* Seems to be left around on Novell filesystems */
6393 DeleteFile(szTempFile);
6394
6395 /* finally, remove the empty old file */
6396 if (!DeleteFile(pszOldFile))
6397 return -8;
6398
6399 return 0; /* success */
6400}
6401
6402/*
6403 * Get the default shell for the current hardware platform
6404 */
6405 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006406default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407{
6408 char* psz = NULL;
6409
6410 PlatformId();
6411
6412 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6413 psz = "cmd.exe";
6414 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6415 psz = "command.com";
6416
6417 return psz;
6418}
6419
6420/*
6421 * mch_access() extends access() to do more detailed check on network drives.
6422 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6423 */
6424 int
6425mch_access(char *n, int p)
6426{
6427 HANDLE hFile;
6428 DWORD am;
6429 int retval = -1; /* default: fail */
6430#ifdef FEAT_MBYTE
6431 WCHAR *wn = NULL;
6432
6433 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006434 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006435#endif
6436
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006437 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006438 {
6439 char TempName[_MAX_PATH + 16] = "";
6440#ifdef FEAT_MBYTE
6441 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6442#endif
6443
6444 if (p & R_OK)
6445 {
6446 /* Read check is performed by seeing if we can do a find file on
6447 * the directory for any file. */
6448#ifdef FEAT_MBYTE
6449 if (wn != NULL)
6450 {
6451 int i;
6452 WIN32_FIND_DATAW d;
6453
6454 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6455 TempNameW[i] = wn[i];
6456 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6457 TempNameW[i++] = '\\';
6458 TempNameW[i++] = '*';
6459 TempNameW[i++] = 0;
6460
6461 hFile = FindFirstFileW(TempNameW, &d);
6462 if (hFile == INVALID_HANDLE_VALUE)
6463 {
6464 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6465 goto getout;
6466
6467 /* Retry with non-wide function (for Windows 98). */
6468 vim_free(wn);
6469 wn = NULL;
6470 }
6471 else
6472 (void)FindClose(hFile);
6473 }
6474 if (wn == NULL)
6475#endif
6476 {
6477 char *pch;
6478 WIN32_FIND_DATA d;
6479
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006480 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481 pch = TempName + STRLEN(TempName) - 1;
6482 if (*pch != '\\' && *pch != '/')
6483 *++pch = '\\';
6484 *++pch = '*';
6485 *++pch = NUL;
6486
6487 hFile = FindFirstFile(TempName, &d);
6488 if (hFile == INVALID_HANDLE_VALUE)
6489 goto getout;
6490 (void)FindClose(hFile);
6491 }
6492 }
6493
6494 if (p & W_OK)
6495 {
6496 /* Trying to create a temporary file in the directory should catch
6497 * directories on read-only network shares. However, in
6498 * directories whose ACL allows writes but denies deletes will end
6499 * up keeping the temporary file :-(. */
6500#ifdef FEAT_MBYTE
6501 if (wn != NULL)
6502 {
6503 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6504 {
6505 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6506 goto getout;
6507
6508 /* Retry with non-wide function (for Windows 98). */
6509 vim_free(wn);
6510 wn = NULL;
6511 }
6512 else
6513 DeleteFileW(TempNameW);
6514 }
6515 if (wn == NULL)
6516#endif
6517 {
6518 if (!GetTempFileName(n, "VIM", 0, TempName))
6519 goto getout;
6520 mch_remove((char_u *)TempName);
6521 }
6522 }
6523 }
6524 else
6525 {
6526 /* Trying to open the file for the required access does ACL, read-only
6527 * network share, and file attribute checks. */
6528 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6529 | ((p & R_OK) ? GENERIC_READ : 0);
6530#ifdef FEAT_MBYTE
6531 if (wn != NULL)
6532 {
6533 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6534 if (hFile == INVALID_HANDLE_VALUE
6535 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6536 {
6537 /* Retry with non-wide function (for Windows 98). */
6538 vim_free(wn);
6539 wn = NULL;
6540 }
6541 }
6542 if (wn == NULL)
6543#endif
6544 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6545 if (hFile == INVALID_HANDLE_VALUE)
6546 goto getout;
6547 CloseHandle(hFile);
6548 }
6549
6550 retval = 0; /* success */
6551getout:
6552#ifdef FEAT_MBYTE
6553 vim_free(wn);
6554#endif
6555 return retval;
6556}
6557
6558#if defined(FEAT_MBYTE) || defined(PROTO)
6559/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006560 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561 */
6562 int
6563mch_open(char *name, int flags, int mode)
6564{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006565 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6566# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567 WCHAR *wn;
6568 int f;
6569
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006570 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006572 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006573 if (wn != NULL)
6574 {
6575 f = _wopen(wn, flags, mode);
6576 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006577 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006578 return f;
6579 /* Retry with non-wide function (for Windows 98). Can't use
6580 * GetLastError() here and it's unclear what errno gets set to if
6581 * the _wopen() fails for missing wide functions. */
6582 }
6583 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006584# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006586 /* open() can open a file which name is longer than _MAX_PATH bytes
6587 * and shorter than _MAX_PATH characters successfully, but sometimes it
6588 * causes unexpected error in another part. We make it an error explicitly
6589 * here. */
6590 if (strlen(name) >= _MAX_PATH)
6591 return -1;
6592
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 return open(name, flags, mode);
6594}
6595
6596/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006597 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598 */
6599 FILE *
6600mch_fopen(char *name, char *mode)
6601{
6602 WCHAR *wn, *wm;
6603 FILE *f = NULL;
6604
6605 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6606# ifdef __BORLANDC__
6607 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6608 && g_PlatformId == VER_PLATFORM_WIN32_NT
6609# endif
6610 )
6611 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006612# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006613 /* Work around an annoying assertion in the Microsoft debug CRT
6614 * when mode's text/binary setting doesn't match _get_fmode(). */
6615 char newMode = mode[strlen(mode) - 1];
6616 int oldMode = 0;
6617
6618 _get_fmode(&oldMode);
6619 if (newMode == 't')
6620 _set_fmode(_O_TEXT);
6621 else if (newMode == 'b')
6622 _set_fmode(_O_BINARY);
6623# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006624 wn = enc_to_utf16((char_u *)name, NULL);
6625 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626 if (wn != NULL && wm != NULL)
6627 f = _wfopen(wn, wm);
6628 vim_free(wn);
6629 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006630
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006631# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006632 _set_fmode(oldMode);
6633# endif
6634
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006635 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636 return f;
6637 /* Retry with non-wide function (for Windows 98). Can't use
6638 * GetLastError() here and it's unclear what errno gets set to if
6639 * the _wfopen() fails for missing wide functions. */
6640 }
6641
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006642 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6643 * and shorter than _MAX_PATH characters successfully, but sometimes it
6644 * causes unexpected error in another part. We make it an error explicitly
6645 * here. */
6646 if (strlen(name) >= _MAX_PATH)
6647 return NULL;
6648
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 return fopen(name, mode);
6650}
6651#endif
6652
6653#ifdef FEAT_MBYTE
6654/*
6655 * SUB STREAM (aka info stream) handling:
6656 *
6657 * NTFS can have sub streams for each file. Normal contents of file is
6658 * stored in the main stream, and extra contents (author information and
6659 * title and so on) can be stored in sub stream. After Windows 2000, user
6660 * can access and store those informations in sub streams via explorer's
6661 * property menuitem in right click menu. Those informations in sub streams
6662 * were lost when copying only the main stream. So we have to copy sub
6663 * streams.
6664 *
6665 * Incomplete explanation:
6666 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6667 * More useful info and an example:
6668 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6669 */
6670
6671/*
6672 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6673 * and write to stream "substream" of file "to".
6674 * Errors are ignored.
6675 */
6676 static void
6677copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6678{
6679 HANDLE hTo;
6680 WCHAR *to_name;
6681
6682 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6683 wcscpy(to_name, to);
6684 wcscat(to_name, substream);
6685
6686 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6687 FILE_ATTRIBUTE_NORMAL, NULL);
6688 if (hTo != INVALID_HANDLE_VALUE)
6689 {
6690 long done;
6691 DWORD todo;
6692 DWORD readcnt, written;
6693 char buf[4096];
6694
6695 /* Copy block of bytes at a time. Abort when something goes wrong. */
6696 for (done = 0; done < len; done += written)
6697 {
6698 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006699 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6700 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6702 FALSE, FALSE, context)
6703 || readcnt != todo
6704 || !WriteFile(hTo, buf, todo, &written, NULL)
6705 || written != todo)
6706 break;
6707 }
6708 CloseHandle(hTo);
6709 }
6710
6711 free(to_name);
6712}
6713
6714/*
6715 * Copy info streams from file "from" to file "to".
6716 */
6717 static void
6718copy_infostreams(char_u *from, char_u *to)
6719{
6720 WCHAR *fromw;
6721 WCHAR *tow;
6722 HANDLE sh;
6723 WIN32_STREAM_ID sid;
6724 int headersize;
6725 WCHAR streamname[_MAX_PATH];
6726 DWORD readcount;
6727 void *context = NULL;
6728 DWORD lo, hi;
6729 int len;
6730
6731 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006732 fromw = enc_to_utf16(from, NULL);
6733 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734 if (fromw != NULL && tow != NULL)
6735 {
6736 /* Open the file for reading. */
6737 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6738 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6739 if (sh != INVALID_HANDLE_VALUE)
6740 {
6741 /* Use BackupRead() to find the info streams. Repeat until we
6742 * have done them all.*/
6743 for (;;)
6744 {
6745 /* Get the header to find the length of the stream name. If
6746 * the "readcount" is zero we have done all info streams. */
6747 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006748 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6750 &readcount, FALSE, FALSE, &context)
6751 || readcount == 0)
6752 break;
6753
6754 /* We only deal with streams that have a name. The normal
6755 * file data appears to be without a name, even though docs
6756 * suggest it is called "::$DATA". */
6757 if (sid.dwStreamNameSize > 0)
6758 {
6759 /* Read the stream name. */
6760 if (!BackupRead(sh, (LPBYTE)streamname,
6761 sid.dwStreamNameSize,
6762 &readcount, FALSE, FALSE, &context))
6763 break;
6764
6765 /* Copy an info stream with a name ":anything:$DATA".
6766 * Skip "::$DATA", it has no stream name (examples suggest
6767 * it might be used for the normal file contents).
6768 * Note that BackupRead() counts bytes, but the name is in
6769 * wide characters. */
6770 len = readcount / sizeof(WCHAR);
6771 streamname[len] = 0;
6772 if (len > 7 && wcsicmp(streamname + len - 6,
6773 L":$DATA") == 0)
6774 {
6775 streamname[len - 6] = 0;
6776 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006777 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778 }
6779 }
6780
6781 /* Advance to the next stream. We might try seeking too far,
6782 * but BackupSeek() doesn't skip over stream borders, thus
6783 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006784 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785 &lo, &hi, &context);
6786 }
6787
6788 /* Clear the context. */
6789 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6790
6791 CloseHandle(sh);
6792 }
6793 }
6794 vim_free(fromw);
6795 vim_free(tow);
6796}
6797#endif
6798
6799/*
6800 * Copy file attributes from file "from" to file "to".
6801 * For Windows NT and later we copy info streams.
6802 * Always returns zero, errors are ignored.
6803 */
6804 int
6805mch_copy_file_attribute(char_u *from, char_u *to)
6806{
6807#ifdef FEAT_MBYTE
6808 /* File streams only work on Windows NT and later. */
6809 PlatformId();
6810 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6811 copy_infostreams(from, to);
6812#endif
6813 return 0;
6814}
6815
6816#if defined(MYRESETSTKOFLW) || defined(PROTO)
6817/*
6818 * Recreate a destroyed stack guard page in win32.
6819 * Written by Benjamin Peterson.
6820 */
6821
6822/* These magic numbers are from the MS header files */
6823#define MIN_STACK_WIN9X 17
6824#define MIN_STACK_WINNT 2
6825
6826/*
6827 * This function does the same thing as _resetstkoflw(), which is only
6828 * available in DevStudio .net and later.
6829 * Returns 0 for failure, 1 for success.
6830 */
6831 int
6832myresetstkoflw(void)
6833{
6834 BYTE *pStackPtr;
6835 BYTE *pGuardPage;
6836 BYTE *pStackBase;
6837 BYTE *pLowestPossiblePage;
6838 MEMORY_BASIC_INFORMATION mbi;
6839 SYSTEM_INFO si;
6840 DWORD nPageSize;
6841 DWORD dummy;
6842
6843 /* This code will not work on win32s. */
6844 PlatformId();
6845 if (g_PlatformId == VER_PLATFORM_WIN32s)
6846 return 0;
6847
6848 /* We need to know the system page size. */
6849 GetSystemInfo(&si);
6850 nPageSize = si.dwPageSize;
6851
6852 /* ...and the current stack pointer */
6853 pStackPtr = (BYTE*)_alloca(1);
6854
6855 /* ...and the base of the stack. */
6856 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6857 return 0;
6858 pStackBase = (BYTE*)mbi.AllocationBase;
6859
6860 /* ...and the page thats min_stack_req pages away from stack base; this is
6861 * the lowest page we could use. */
6862 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6863 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6864
6865 /* On Win95, we want the next page down from the end of the stack. */
6866 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6867 {
6868 /* Find the page that's only 1 page down from the page that the stack
6869 * ptr is in. */
6870 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6871 / (DWORD)nPageSize) - 1));
6872 if (pGuardPage < pLowestPossiblePage)
6873 return 0;
6874
6875 /* Apply the noaccess attribute to the page -- there's no guard
6876 * attribute in win95-type OSes. */
6877 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6878 return 0;
6879 }
6880 else
6881 {
6882 /* On NT, however, we want the first committed page in the stack Start
6883 * at the stack base and move forward through memory until we find a
6884 * committed block. */
6885 BYTE *pBlock = pStackBase;
6886
Bram Moolenaara466c992005-07-09 21:03:22 +00006887 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 {
6889 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6890 return 0;
6891
6892 pBlock += mbi.RegionSize;
6893
6894 if (mbi.State & MEM_COMMIT)
6895 break;
6896 }
6897
6898 /* mbi now describes the first committed block in the stack. */
6899 if (mbi.Protect & PAGE_GUARD)
6900 return 1;
6901
6902 /* decide where the guard page should start */
6903 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6904 pGuardPage = pLowestPossiblePage;
6905 else
6906 pGuardPage = (BYTE*)mbi.BaseAddress;
6907
6908 /* allocate the guard page */
6909 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6910 return 0;
6911
6912 /* apply the guard attribute to the page */
6913 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6914 &dummy))
6915 return 0;
6916 }
6917
6918 return 1;
6919}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006920#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006922
6923#if defined(FEAT_MBYTE) || defined(PROTO)
6924/*
6925 * The command line arguments in UCS2
6926 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006927static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006928static LPWSTR *ArglistW = NULL;
6929static int global_argc = 0;
6930static char **global_argv;
6931
6932static int used_file_argc = 0; /* last argument in global_argv[] used
6933 for the argument list. */
6934static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6935 command line arguments added to
6936 the argument list */
6937static int used_file_count = 0; /* nr of entries in used_file_indexes */
6938static int used_file_literal = FALSE; /* take file names literally */
6939static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006940static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006941static int used_alist_count = 0;
6942
6943
6944/*
6945 * Get the command line arguments. Unicode version.
6946 * Returns argc. Zero when something fails.
6947 */
6948 int
6949get_cmd_argsW(char ***argvp)
6950{
6951 char **argv = NULL;
6952 int argc = 0;
6953 int i;
6954
Bram Moolenaar14993322014-09-09 12:25:33 +02006955 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006956 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6957 if (ArglistW != NULL)
6958 {
6959 argv = malloc((nArgsW + 1) * sizeof(char *));
6960 if (argv != NULL)
6961 {
6962 argc = nArgsW;
6963 argv[argc] = NULL;
6964 for (i = 0; i < argc; ++i)
6965 {
6966 int len;
6967
6968 /* Convert each Unicode argument to the current codepage. */
6969 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006970 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006971 (LPSTR *)&argv[i], &len, 0, 0);
6972 if (argv[i] == NULL)
6973 {
6974 /* Out of memory, clear everything. */
6975 while (i > 0)
6976 free(argv[--i]);
6977 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006978 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006979 argc = 0;
6980 }
6981 }
6982 }
6983 }
6984
6985 global_argc = argc;
6986 global_argv = argv;
6987 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006988 {
6989 if (used_file_indexes != NULL)
6990 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006991 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006992 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006993
6994 if (argvp != NULL)
6995 *argvp = argv;
6996 return argc;
6997}
6998
6999 void
7000free_cmd_argsW(void)
7001{
7002 if (ArglistW != NULL)
7003 {
7004 GlobalFree(ArglistW);
7005 ArglistW = NULL;
7006 }
7007}
7008
7009/*
7010 * Remember "name" is an argument that was added to the argument list.
7011 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7012 * is called.
7013 */
7014 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007015used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007016{
7017 int i;
7018
7019 if (used_file_indexes == NULL)
7020 return;
7021 for (i = used_file_argc + 1; i < global_argc; ++i)
7022 if (STRCMP(global_argv[i], name) == 0)
7023 {
7024 used_file_argc = i;
7025 used_file_indexes[used_file_count++] = i;
7026 break;
7027 }
7028 used_file_literal = literal;
7029 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007030 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007031}
7032
7033/*
7034 * Remember the length of the argument list as it was. If it changes then we
7035 * leave it alone when 'encoding' is set.
7036 */
7037 void
7038set_alist_count(void)
7039{
7040 used_alist_count = GARGCOUNT;
7041}
7042
7043/*
7044 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7045 * has been changed while starting up. Use the UCS-2 command line arguments
7046 * and convert them to 'encoding'.
7047 */
7048 void
7049fix_arg_enc(void)
7050{
7051 int i;
7052 int idx;
7053 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007054 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007055
7056 /* Safety checks:
7057 * - if argument count differs between the wide and non-wide argument
7058 * list, something must be wrong.
7059 * - the file name arguments must have been located.
7060 * - the length of the argument list wasn't changed by the user.
7061 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007062 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007063 || ArglistW == NULL
7064 || used_file_indexes == NULL
7065 || used_file_count == 0
7066 || used_alist_count != GARGCOUNT)
7067 return;
7068
Bram Moolenaar86b68352004-12-27 21:59:20 +00007069 /* Remember the buffer numbers for the arguments. */
7070 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7071 if (fnum_list == NULL)
7072 return; /* out of memory */
7073 for (i = 0; i < GARGCOUNT; ++i)
7074 fnum_list[i] = GARGLIST[i].ae_fnum;
7075
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007076 /* Clear the argument list. Make room for the new arguments. */
7077 alist_clear(&global_alist);
7078 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007079 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007080
7081 for (i = 0; i < used_file_count; ++i)
7082 {
7083 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007084 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007085 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007086 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007087#ifdef FEAT_DIFF
7088 /* When using diff mode may need to concatenate file name to
7089 * directory name. Just like it's done in main(). */
7090 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7091 && !mch_isdir(alist_name(&GARGLIST[0])))
7092 {
7093 char_u *r;
7094
7095 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7096 if (r != NULL)
7097 {
7098 vim_free(str);
7099 str = r;
7100 }
7101 }
7102#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007103 /* Re-use the old buffer by renaming it. When not using literal
7104 * names it's done by alist_expand() below. */
7105 if (used_file_literal)
7106 buf_set_name(fnum_list[i], str);
7107
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007108 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007109 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007110 }
7111
7112 if (!used_file_literal)
7113 {
7114 /* Now expand wildcards in the arguments. */
7115 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7116 * filename characters but are excluded from 'isfname' to make
7117 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7118 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007119 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007120 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7121 }
7122
7123 /* If wildcard expansion failed, we are editing the first file of the
7124 * arglist and there is no file name: Edit the first argument now. */
7125 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7126 {
7127 do_cmdline_cmd((char_u *)":rewind");
7128 if (GARGCOUNT == 1 && used_file_full_path)
7129 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7130 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007131
7132 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007133}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134#endif