blob: 030b4b0da75a1c7d76d7cb97b3eb88cad3b745f6 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
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
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
114typedef int KEY_EVENT_RECORD;
115typedef int LOGFONT;
116typedef int LPBOOL;
117typedef int LPCTSTR;
118typedef int LPDWORD;
119typedef int LPSTR;
120typedef int LPTSTR;
121typedef int LPVOID;
122typedef int MOUSE_EVENT_RECORD;
123typedef int PACL;
124typedef int PDWORD;
125typedef int PHANDLE;
126typedef int PRINTDLG;
127typedef int PSECURITY_DESCRIPTOR;
128typedef int PSID;
129typedef int SECURITY_INFORMATION;
130typedef int SHORT;
131typedef int SMALL_RECT;
132typedef int TEXTMETRIC;
133typedef int TOKEN_INFORMATION_CLASS;
134typedef int TRUSTEE;
135typedef int WORD;
136typedef int WCHAR;
137typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100138typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200139typedef int SE_OBJECT_TYPE;
140typedef int PSNSECINFO;
141typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100142typedef int STARTUPINFO;
143typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200144typedef int LPSECURITY_ATTRIBUTES;
145# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146#endif
147
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#if defined(__BORLANDC__)
149/* Strangely Borland uses a non-standard name. */
150# define wcsicmp(a, b) wcscmpi((a), (b))
151#endif
152
153#ifndef FEAT_GUI_W32
154/* Win32 Console handles for input and output */
155static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
156static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
157
158/* Win32 Screen buffer,coordinate,console I/O information */
159static SMALL_RECT g_srScrollRegion;
160static COORD g_coord; /* 0-based, but external coords are 1-based */
161
162/* The attribute of the screen when the editor was started */
163static WORD g_attrDefault = 7; /* lightgray text on black background */
164static WORD g_attrCurrent;
165
166static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
167static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
168static int g_fForceExit = FALSE; /* set when forcefully exiting */
169
170static void termcap_mode_start(void);
171static void termcap_mode_end(void);
172static void clear_chars(COORD coord, DWORD n);
173static void clear_screen(void);
174static void clear_to_end_of_display(void);
175static void clear_to_end_of_line(void);
176static void scroll(unsigned cLines);
177static void set_scroll_region(unsigned left, unsigned top,
178 unsigned right, unsigned bottom);
179static void insert_lines(unsigned cLines);
180static void delete_lines(unsigned cLines);
181static void gotoxy(unsigned x, unsigned y);
182static void normvideo(void);
183static void textattr(WORD wAttr);
184static void textcolor(WORD wAttr);
185static void textbackground(WORD wAttr);
186static void standout(void);
187static void standend(void);
188static void visual_bell(void);
189static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200190static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000191static void create_conin(void);
192static int s_cursor_visible = TRUE;
193static int did_create_conin = FALSE;
194#else
195static int s_dont_use_vimrun = TRUE;
196static int need_vimrun_warning = FALSE;
197static char *vimrun_path = "vimrun ";
198#endif
199
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200200static int win32_getattrs(char_u *name);
201static int win32_setattrs(char_u *name, int attrs);
202static int win32_set_archive(char_u *name);
203
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204#ifndef FEAT_GUI_W32
205static int suppress_winsize = 1; /* don't fiddle with console */
206#endif
207
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200208static char_u *exe_path = NULL;
209
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100210static BOOL win8_or_later = FALSE;
211
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100212#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100213/*
214 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100215 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100216 */
217 static BOOL
218read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100219 HANDLE hInput,
220 INPUT_RECORD *lpBuffer,
221 DWORD nLength,
222 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100223{
224 enum
225 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100226 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100227 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100228 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100229 static DWORD s_dwIndex = 0;
230 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100231 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100232 int head;
233 int tail;
234 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100235
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200236 if (nLength == -2)
237 return (s_dwMax > 0) ? TRUE : FALSE;
238
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100239 if (!win8_or_later)
240 {
241 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200242 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
243 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100244 }
245
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100246 if (s_dwMax == 0)
247 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100248 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200249 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
250 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100251 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100252 s_dwIndex = 0;
253 s_dwMax = dwEvents;
254 if (dwEvents == 0)
255 {
256 *lpEvents = 0;
257 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100258 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100259
260 if (s_dwMax > 1)
261 {
262 head = 0;
263 tail = s_dwMax - 1;
264 while (head != tail)
265 {
266 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
267 && s_irCache[head + 1].EventType
268 == WINDOW_BUFFER_SIZE_EVENT)
269 {
270 /* Remove duplicate event to avoid flicker. */
271 for (i = head; i < tail; ++i)
272 s_irCache[i] = s_irCache[i + 1];
273 --tail;
274 continue;
275 }
276 head++;
277 }
278 s_dwMax = tail + 1;
279 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100281
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100282 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200283 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100284 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100285 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100286 return TRUE;
287}
288
289/*
290 * Version of PeekConsoleInput() that works with IME.
291 */
292 static BOOL
293peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100299 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100300}
301
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100302# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200303 static DWORD
304msg_wait_for_multiple_objects(
305 DWORD nCount,
306 LPHANDLE pHandles,
307 BOOL fWaitAll,
308 DWORD dwMilliseconds,
309 DWORD dwWakeMask)
310{
311 if (read_console_input(NULL, NULL, -2, NULL))
312 return WAIT_OBJECT_0;
313 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
314 dwMilliseconds, dwWakeMask);
315}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100316# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200317
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100318# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200319 static DWORD
320wait_for_single_object(
321 HANDLE hHandle,
322 DWORD dwMilliseconds)
323{
324 if (read_console_input(NULL, NULL, -2, NULL))
325 return WAIT_OBJECT_0;
326 return WaitForSingleObject(hHandle, dwMilliseconds);
327}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100328# endif
329#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200330
Bram Moolenaar071d4272004-06-13 20:20:40 +0000331 static void
332get_exe_name(void)
333{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100334 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
335 * as the maximum length that works (plus a NUL byte). */
336#define MAX_ENV_PATH_LEN 8192
337 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200338 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000339
340 if (exe_name == NULL)
341 {
342 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100343 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 if (*temp != NUL)
345 exe_name = FullName_save((char_u *)temp, FALSE);
346 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000347
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200348 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000349 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200350 exe_path = vim_strnsave(exe_name,
351 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200352 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000353 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200354 /* Append our starting directory to $PATH, so that when doing
355 * "!xxd" it's found in our starting directory. Needed because
356 * SearchPath() also looks there. */
357 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100358 if (p == NULL
359 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200360 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100361 if (p == NULL || *p == NUL)
362 temp[0] = NUL;
363 else
364 {
365 STRCPY(temp, p);
366 STRCAT(temp, ";");
367 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200368 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100369 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200370 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000371 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373}
374
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200375/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100376 * Unescape characters in "p" that appear in "escaped".
377 */
378 static void
379unescape_shellxquote(char_u *p, char_u *escaped)
380{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100381 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100382 int n;
383
384 while (*p != NUL)
385 {
386 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
387 mch_memmove(p, p + 1, l--);
388#ifdef FEAT_MBYTE
389 n = (*mb_ptr2len)(p);
390#else
391 n = 1;
392#endif
393 p += n;
394 l -= n;
395 }
396}
397
398/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200399 * Load library "name".
400 */
401 HINSTANCE
402vimLoadLib(char *name)
403{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200404 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200405
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200406 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
407 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200408 if (exe_path == NULL)
409 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200410 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200411 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200412 WCHAR old_dirw[MAXPATHL];
413
414 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
415 {
416 /* Change directory to where the executable is, both to make
417 * sure we find a .dll there and to avoid looking for a .dll
418 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100419 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200420 dll = LoadLibrary(name);
421 SetCurrentDirectoryW(old_dirw);
422 return dll;
423 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200424 }
425 return dll;
426}
427
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100428#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
429/*
430 * Get related information about 'funcname' which is imported by 'hInst'.
431 * If 'info' is 0, return the function address.
432 * If 'info' is 1, return the module name which the function is imported from.
433 */
434 static void *
435get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
436{
437 PBYTE pImage = (PBYTE)hInst;
438 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
439 PIMAGE_NT_HEADERS pPE;
440 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
441 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
442 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
443 PIMAGE_IMPORT_BY_NAME pImpName;
444
445 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
446 return NULL;
447 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
448 if (pPE->Signature != IMAGE_NT_SIGNATURE)
449 return NULL;
450 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
451 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
452 .VirtualAddress);
453 for (; pImpDesc->FirstThunk; ++pImpDesc)
454 {
455 if (!pImpDesc->OriginalFirstThunk)
456 continue;
457 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
458 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
459 for (; pIAT->u1.Function; ++pIAT, ++pINT)
460 {
461 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
462 continue;
463 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
464 + (UINT_PTR)(pINT->u1.AddressOfData));
465 if (strcmp((char *)pImpName->Name, funcname) == 0)
466 {
467 switch (info)
468 {
469 case 0:
470 return (void *)pIAT->u1.Function;
471 case 1:
472 return (void *)(pImage + pImpDesc->Name);
473 default:
474 return NULL;
475 }
476 }
477 }
478 }
479 return NULL;
480}
481
482/*
483 * Get the module handle which 'funcname' in 'hInst' is imported from.
484 */
485 HINSTANCE
486find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
487{
488 char *modulename;
489
490 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
491 if (modulename != NULL)
492 return GetModuleHandleA(modulename);
493 return NULL;
494}
495
496/*
497 * Get the address of 'funcname' which is imported by 'hInst' DLL.
498 */
499 void *
500get_dll_import_func(HINSTANCE hInst, const char *funcname)
501{
502 return get_imported_func_info(hInst, funcname, 0);
503}
504#endif
505
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
507# ifndef GETTEXT_DLL
508# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100509# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200511/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000512static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200513static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000514static char *null_libintl_textdomain(const char *);
515static char *null_libintl_bindtextdomain(const char *, const char *);
516static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100517static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100518static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200520static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000521char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200522char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
523 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000524char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
525char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000527char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
528 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100529int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100530int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000531
532 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100533dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000534{
535 int i;
536 static struct
537 {
538 char *name;
539 FARPROC *ptr;
540 } libintl_entry[] =
541 {
542 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200543 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
545 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
546 {NULL, NULL}
547 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100548 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549
550 /* No need to initialize twice. */
551 if (hLibintlDLL)
552 return 1;
553 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100554 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100555#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100556 if (!hLibintlDLL)
557 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100558#endif
559 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200561 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000562 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200563 verbose_enter();
564 EMSG2(_(e_loadlib), GETTEXT_DLL);
565 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000566 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200567 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000568 }
569 for (i = 0; libintl_entry[i].name != NULL
570 && libintl_entry[i].ptr != NULL; ++i)
571 {
572 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
573 libintl_entry[i].name)) == NULL)
574 {
575 dyn_libintl_end();
576 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000577 {
578 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000579 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000580 verbose_leave();
581 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582 return 0;
583 }
584 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000585
586 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000587 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000588 "bind_textdomain_codeset");
589 if (dyn_libintl_bind_textdomain_codeset == NULL)
590 dyn_libintl_bind_textdomain_codeset =
591 null_libintl_bind_textdomain_codeset;
592
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100593 /* _putenv() function for the libintl.dll is optional. */
594 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
595 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100596 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100597 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100598 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
599 }
600 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100601 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100602 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
603 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100604
Bram Moolenaar071d4272004-06-13 20:20:40 +0000605 return 1;
606}
607
608 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100609dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610{
611 if (hLibintlDLL)
612 FreeLibrary(hLibintlDLL);
613 hLibintlDLL = NULL;
614 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200615 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 dyn_libintl_textdomain = null_libintl_textdomain;
617 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000618 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100619 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100620 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000621}
622
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000623/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000625null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626{
627 return (char*)msgid;
628}
629
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000630/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000631 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200632null_libintl_ngettext(
633 const char *msgid,
634 const char *msgid_plural,
635 unsigned long n)
636{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200637 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200638}
639
640/*ARGSUSED*/
641 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000642null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643{
644 return NULL;
645}
646
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000647/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000648 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000649null_libintl_bind_textdomain_codeset(const char *domainname,
650 const char *codeset)
651{
652 return NULL;
653}
654
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000655/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000656 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000657null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658{
659 return NULL;
660}
661
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100662/*ARGSUSED*/
663 int
664null_libintl_putenv(const char *envstring)
665{
666 return 0;
667}
668
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100669/*ARGSUSED*/
670 int
671null_libintl_wputenv(const wchar_t *envstring)
672{
673 return 0;
674}
675
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676#endif /* DYNAMIC_GETTEXT */
677
678/* This symbol is not defined in older versions of the SDK or Visual C++ */
679
680#ifndef VER_PLATFORM_WIN32_WINDOWS
681# define VER_PLATFORM_WIN32_WINDOWS 1
682#endif
683
684DWORD g_PlatformId;
685
686#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100687# ifndef PROTO
688# include <aclapi.h>
689# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200690# ifndef PROTECTED_DACL_SECURITY_INFORMATION
691# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
692# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693#endif
694
Bram Moolenaar27515922013-06-29 15:36:26 +0200695#ifdef HAVE_ACL
696/*
697 * Enables or disables the specified privilege.
698 */
699 static BOOL
700win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
701{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100702 BOOL bResult;
703 LUID luid;
704 HANDLE hToken;
705 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200706
707 if (!OpenProcessToken(GetCurrentProcess(),
708 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
709 return FALSE;
710
711 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
712 {
713 CloseHandle(hToken);
714 return FALSE;
715 }
716
Bram Moolenaar45500912014-07-09 20:51:07 +0200717 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200718 tokenPrivileges.Privileges[0].Luid = luid;
719 tokenPrivileges.Privileges[0].Attributes = bEnable ?
720 SE_PRIVILEGE_ENABLED : 0;
721
722 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
723 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
724
725 CloseHandle(hToken);
726
727 return bResult && GetLastError() == ERROR_SUCCESS;
728}
729#endif
730
Bram Moolenaar071d4272004-06-13 20:20:40 +0000731/*
732 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
733 * VER_PLATFORM_WIN32_WINDOWS (Win95).
734 */
735 void
736PlatformId(void)
737{
738 static int done = FALSE;
739
740 if (!done)
741 {
742 OSVERSIONINFO ovi;
743
744 ovi.dwOSVersionInfoSize = sizeof(ovi);
745 GetVersionEx(&ovi);
746
747 g_PlatformId = ovi.dwPlatformId;
748
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100749 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
750 || ovi.dwMajorVersion > 6)
751 win8_or_later = TRUE;
752
Bram Moolenaar071d4272004-06-13 20:20:40 +0000753#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200754 /* Enable privilege for getting or setting SACLs. */
755 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000756#endif
757 done = TRUE;
758 }
759}
760
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761#ifndef FEAT_GUI_W32
762
763#define SHIFT (SHIFT_PRESSED)
764#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
765#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
766#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
767
768
769/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
770 * We map function keys to their ANSI terminal equivalents, as produced
771 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
772 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
773 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
774 * combinations of function/arrow/etc keys.
775 */
776
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000777static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778{
779 WORD wVirtKey;
780 BOOL fAnsiKey;
781 int chAlone;
782 int chShift;
783 int chCtrl;
784 int chAlt;
785} VirtKeyMap[] =
786{
787
788/* Key ANSI alone shift ctrl alt */
789 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
790
791 { VK_F1, TRUE, ';', 'T', '^', 'h', },
792 { VK_F2, TRUE, '<', 'U', '_', 'i', },
793 { VK_F3, TRUE, '=', 'V', '`', 'j', },
794 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
795 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
796 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
797 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
798 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
799 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
800 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
801 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
802 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
803
804 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
805 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
806 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
807 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
808 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
809 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
810 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
811 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
812 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
813 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
814
815 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
816
817#if 0
818 /* Most people don't have F13-F20, but what the hell... */
819 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
820 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
821 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
822 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
823 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
824 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
825 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
826 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
827#endif
828 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
829 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
830 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
831 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
832
833 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
834 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
835 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
836 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
837 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
838 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
839 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
840 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
841 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
842 /* Sorry, out of number space! <negri>*/
843 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
844
845};
846
847
848#ifdef _MSC_VER
849// The ToAscii bug destroys several registers. Need to turn off optimization
850// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000851# pragma warning(push)
852# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853# pragma optimize("", off)
854#endif
855
856#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200857# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200859# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860#endif
861
862/* The return code indicates key code size. */
863 static int
864#ifdef __BORLANDC__
865 __stdcall
866#endif
867win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000868 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869{
870 UINT uMods = pker->dwControlKeyState;
871 static int s_iIsDead = 0;
872 static WORD awAnsiCode[2];
873 static BYTE abKeystate[256];
874
875
876 if (s_iIsDead == 2)
877 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200878 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 s_iIsDead = 0;
880 return 1;
881 }
882
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200883 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000884 return 1;
885
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200886 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887
Bram Moolenaar071d4272004-06-13 20:20:40 +0000888 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200889 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890
891 if (uMods & SHIFT_PRESSED)
892 abKeystate[VK_SHIFT] = 0x80;
893 if (uMods & CAPSLOCK_ON)
894 abKeystate[VK_CAPITAL] = 1;
895
896 if ((uMods & ALT_GR) == ALT_GR)
897 {
898 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
899 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
900 }
901
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200902 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
903 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904
905 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200906 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907
908 return s_iIsDead;
909}
910
911#ifdef _MSC_VER
912/* MUST switch optimization on again here, otherwise a call to
913 * decode_key_event() may crash (e.g. when hitting caps-lock) */
914# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000915# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916
917# if (_MSC_VER < 1100)
918/* MUST turn off global optimisation for this next function, or
919 * pressing ctrl-minus in insert mode crashes Vim when built with
920 * VC4.1. -- negri. */
921# pragma optimize("g", off)
922# endif
923#endif
924
925static BOOL g_fJustGotFocus = FALSE;
926
927/*
928 * Decode a KEY_EVENT into one or two keystrokes
929 */
930 static BOOL
931decode_key_event(
932 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200933 WCHAR *pch,
934 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935 int *pmodifiers,
936 BOOL fDoPost)
937{
938 int i;
939 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
940
941 *pch = *pch2 = NUL;
942 g_fJustGotFocus = FALSE;
943
944 /* ignore key up events */
945 if (!pker->bKeyDown)
946 return FALSE;
947
948 /* ignore some keystrokes */
949 switch (pker->wVirtualKeyCode)
950 {
951 /* modifiers */
952 case VK_SHIFT:
953 case VK_CONTROL:
954 case VK_MENU: /* Alt key */
955 return FALSE;
956
957 default:
958 break;
959 }
960
961 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200962 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963 {
964 /* Ctrl-6 is Ctrl-^ */
965 if (pker->wVirtualKeyCode == '6')
966 {
967 *pch = Ctrl_HAT;
968 return TRUE;
969 }
970 /* Ctrl-2 is Ctrl-@ */
971 else if (pker->wVirtualKeyCode == '2')
972 {
973 *pch = NUL;
974 return TRUE;
975 }
976 /* Ctrl-- is Ctrl-_ */
977 else if (pker->wVirtualKeyCode == 0xBD)
978 {
979 *pch = Ctrl__;
980 return TRUE;
981 }
982 }
983
984 /* Shift-TAB */
985 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
986 {
987 *pch = K_NUL;
988 *pch2 = '\017';
989 return TRUE;
990 }
991
992 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
993 {
994 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
995 {
996 if (nModifs == 0)
997 *pch = VirtKeyMap[i].chAlone;
998 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
999 *pch = VirtKeyMap[i].chShift;
1000 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1001 *pch = VirtKeyMap[i].chCtrl;
1002 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1003 *pch = VirtKeyMap[i].chAlt;
1004
1005 if (*pch != 0)
1006 {
1007 if (VirtKeyMap[i].fAnsiKey)
1008 {
1009 *pch2 = *pch;
1010 *pch = K_NUL;
1011 }
1012
1013 return TRUE;
1014 }
1015 }
1016 }
1017
1018 i = win32_kbd_patch_key(pker);
1019
1020 if (i < 0)
1021 *pch = NUL;
1022 else
1023 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001024 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001025
1026 if (pmodifiers != NULL)
1027 {
1028 /* Pass on the ALT key as a modifier, but only when not combined
1029 * with CTRL (which is ALTGR). */
1030 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1031 *pmodifiers |= MOD_MASK_ALT;
1032
1033 /* Pass on SHIFT only for special keys, because we don't know when
1034 * it's already included with the character. */
1035 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1036 *pmodifiers |= MOD_MASK_SHIFT;
1037
1038 /* Pass on CTRL only for non-special keys, because we don't know
1039 * when it's already included with the character. And not when
1040 * combined with ALT (which is ALTGR). */
1041 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1042 && *pch >= 0x20 && *pch < 0x80)
1043 *pmodifiers |= MOD_MASK_CTRL;
1044 }
1045 }
1046
1047 return (*pch != NUL);
1048}
1049
1050#ifdef _MSC_VER
1051# pragma optimize("", on)
1052#endif
1053
1054#endif /* FEAT_GUI_W32 */
1055
1056
1057#ifdef FEAT_MOUSE
1058
1059/*
1060 * For the GUI the mouse handling is in gui_w32.c.
1061 */
1062# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001063/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001065mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066{
1067}
1068# else
1069static int g_fMouseAvail = FALSE; /* mouse present */
1070static int g_fMouseActive = FALSE; /* mouse enabled */
1071static int g_nMouseClick = -1; /* mouse status */
1072static int g_xMouse; /* mouse x coordinate */
1073static int g_yMouse; /* mouse y coordinate */
1074
1075/*
1076 * Enable or disable mouse input
1077 */
1078 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001079mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080{
1081 DWORD cmodein;
1082
1083 if (!g_fMouseAvail)
1084 return;
1085
1086 g_fMouseActive = on;
1087 GetConsoleMode(g_hConIn, &cmodein);
1088
1089 if (g_fMouseActive)
1090 cmodein |= ENABLE_MOUSE_INPUT;
1091 else
1092 cmodein &= ~ENABLE_MOUSE_INPUT;
1093
1094 SetConsoleMode(g_hConIn, cmodein);
1095}
1096
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097/*
1098 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1099 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1100 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1101 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1102 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1103 * and we return the mouse position in g_xMouse and g_yMouse.
1104 *
1105 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1106 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1107 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1108 *
1109 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1110 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1111 *
1112 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1113 * moves, even if it stays within the same character cell. We ignore
1114 * all MOUSE_MOVED messages if the position hasn't really changed, and
1115 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1116 * we're only interested in MOUSE_DRAG).
1117 *
1118 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1119 * 2-button mouses by pressing the left & right buttons simultaneously.
1120 * In practice, it's almost impossible to click both at the same time,
1121 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1122 * in such cases, if the user is clicking quickly.
1123 */
1124 static BOOL
1125decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001126 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127{
1128 static int s_nOldButton = -1;
1129 static int s_nOldMouseClick = -1;
1130 static int s_xOldMouse = -1;
1131 static int s_yOldMouse = -1;
1132 static linenr_T s_old_topline = 0;
1133#ifdef FEAT_DIFF
1134 static int s_old_topfill = 0;
1135#endif
1136 static int s_cClicks = 1;
1137 static BOOL s_fReleased = TRUE;
1138 static DWORD s_dwLastClickTime = 0;
1139 static BOOL s_fNextIsMiddle = FALSE;
1140
1141 static DWORD cButtons = 0; /* number of buttons supported */
1142
1143 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1144 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1145 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1146 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1147
1148 int nButton;
1149
1150 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1151 cButtons = 2;
1152
1153 if (!g_fMouseAvail || !g_fMouseActive)
1154 {
1155 g_nMouseClick = -1;
1156 return FALSE;
1157 }
1158
1159 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1160 if (g_fJustGotFocus)
1161 {
1162 g_fJustGotFocus = FALSE;
1163 return FALSE;
1164 }
1165
1166 /* unprocessed mouse click? */
1167 if (g_nMouseClick != -1)
1168 return TRUE;
1169
1170 nButton = -1;
1171 g_xMouse = pmer->dwMousePosition.X;
1172 g_yMouse = pmer->dwMousePosition.Y;
1173
1174 if (pmer->dwEventFlags == MOUSE_MOVED)
1175 {
1176 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1177 * events even when the mouse moves only within a char cell.) */
1178 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1179 return FALSE;
1180 }
1181
1182 /* If no buttons are pressed... */
1183 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1184 {
1185 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1186 if (s_fReleased)
1187 return FALSE;
1188
1189 nButton = MOUSE_RELEASE;
1190 s_fReleased = TRUE;
1191 }
1192 else /* one or more buttons pressed */
1193 {
1194 /* on a 2-button mouse, hold down left and right buttons
1195 * simultaneously to get MIDDLE. */
1196
1197 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1198 {
1199 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1200
1201 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001202 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203 if (dwLR == LEFT || dwLR == RIGHT)
1204 {
1205 for (;;)
1206 {
1207 /* wait a short time for next input event */
1208 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1209 != WAIT_OBJECT_0)
1210 break;
1211 else
1212 {
1213 DWORD cRecords = 0;
1214 INPUT_RECORD ir;
1215 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1216
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001217 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218
1219 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1220 || !(pmer2->dwButtonState & LEFT_RIGHT))
1221 break;
1222 else
1223 {
1224 if (pmer2->dwEventFlags != MOUSE_MOVED)
1225 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001226 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001227
1228 return decode_mouse_event(pmer2);
1229 }
1230 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1231 s_yOldMouse == pmer2->dwMousePosition.Y)
1232 {
1233 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001234 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235
1236 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001237 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238
1239 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1240 break;
1241 }
1242 else
1243 break;
1244 }
1245 }
1246 }
1247 }
1248 }
1249
1250 if (s_fNextIsMiddle)
1251 {
1252 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1253 ? MOUSE_DRAG : MOUSE_MIDDLE;
1254 s_fNextIsMiddle = FALSE;
1255 }
1256 else if (cButtons == 2 &&
1257 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1258 {
1259 nButton = MOUSE_MIDDLE;
1260
1261 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1262 {
1263 s_fNextIsMiddle = TRUE;
1264 nButton = MOUSE_RELEASE;
1265 }
1266 }
1267 else if ((pmer->dwButtonState & LEFT) == LEFT)
1268 nButton = MOUSE_LEFT;
1269 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1270 nButton = MOUSE_MIDDLE;
1271 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1272 nButton = MOUSE_RIGHT;
1273
1274 if (! s_fReleased && ! s_fNextIsMiddle
1275 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1276 return FALSE;
1277
1278 s_fReleased = s_fNextIsMiddle;
1279 }
1280
1281 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1282 {
1283 /* button pressed or released, without mouse moving */
1284 if (nButton != -1 && nButton != MOUSE_RELEASE)
1285 {
1286 DWORD dwCurrentTime = GetTickCount();
1287
1288 if (s_xOldMouse != g_xMouse
1289 || s_yOldMouse != g_yMouse
1290 || s_nOldButton != nButton
1291 || s_old_topline != curwin->w_topline
1292#ifdef FEAT_DIFF
1293 || s_old_topfill != curwin->w_topfill
1294#endif
1295 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1296 {
1297 s_cClicks = 1;
1298 }
1299 else if (++s_cClicks > 4)
1300 {
1301 s_cClicks = 1;
1302 }
1303
1304 s_dwLastClickTime = dwCurrentTime;
1305 }
1306 }
1307 else if (pmer->dwEventFlags == MOUSE_MOVED)
1308 {
1309 if (nButton != -1 && nButton != MOUSE_RELEASE)
1310 nButton = MOUSE_DRAG;
1311
1312 s_cClicks = 1;
1313 }
1314
1315 if (nButton == -1)
1316 return FALSE;
1317
1318 if (nButton != MOUSE_RELEASE)
1319 s_nOldButton = nButton;
1320
1321 g_nMouseClick = nButton;
1322
1323 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1324 g_nMouseClick |= MOUSE_SHIFT;
1325 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1326 g_nMouseClick |= MOUSE_CTRL;
1327 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1328 g_nMouseClick |= MOUSE_ALT;
1329
1330 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1331 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1332
1333 /* only pass on interesting (i.e., different) mouse events */
1334 if (s_xOldMouse == g_xMouse
1335 && s_yOldMouse == g_yMouse
1336 && s_nOldMouseClick == g_nMouseClick)
1337 {
1338 g_nMouseClick = -1;
1339 return FALSE;
1340 }
1341
1342 s_xOldMouse = g_xMouse;
1343 s_yOldMouse = g_yMouse;
1344 s_old_topline = curwin->w_topline;
1345#ifdef FEAT_DIFF
1346 s_old_topfill = curwin->w_topfill;
1347#endif
1348 s_nOldMouseClick = g_nMouseClick;
1349
1350 return TRUE;
1351}
1352
1353# endif /* FEAT_GUI_W32 */
1354#endif /* FEAT_MOUSE */
1355
1356
1357#ifdef MCH_CURSOR_SHAPE
1358/*
1359 * Set the shape of the cursor.
1360 * 'thickness' can be from 1 (thin) to 99 (block)
1361 */
1362 static void
1363mch_set_cursor_shape(int thickness)
1364{
1365 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1366 ConsoleCursorInfo.dwSize = thickness;
1367 ConsoleCursorInfo.bVisible = s_cursor_visible;
1368
1369 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1370 if (s_cursor_visible)
1371 SetConsoleCursorPosition(g_hConOut, g_coord);
1372}
1373
1374 void
1375mch_update_cursor(void)
1376{
1377 int idx;
1378 int thickness;
1379
1380 /*
1381 * How the cursor is drawn depends on the current mode.
1382 */
1383 idx = get_shape_idx(FALSE);
1384
1385 if (shape_table[idx].shape == SHAPE_BLOCK)
1386 thickness = 99; /* 100 doesn't work on W95 */
1387 else
1388 thickness = shape_table[idx].percentage;
1389 mch_set_cursor_shape(thickness);
1390}
1391#endif
1392
1393#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1394/*
1395 * Handle FOCUS_EVENT.
1396 */
1397 static void
1398handle_focus_event(INPUT_RECORD ir)
1399{
1400 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1401 ui_focus_change((int)g_fJustGotFocus);
1402}
1403
1404/*
1405 * Wait until console input from keyboard or mouse is available,
1406 * or the time is up.
1407 * Return TRUE if something is available FALSE if not.
1408 */
1409 static int
1410WaitForChar(long msec)
1411{
1412 DWORD dwNow = 0, dwEndTime = 0;
1413 INPUT_RECORD ir;
1414 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001415 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001416#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001417 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001418#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001419
1420 if (msec > 0)
1421 /* Wait until the specified time has elapsed. */
1422 dwEndTime = GetTickCount() + msec;
1423 else if (msec < 0)
1424 /* Wait forever. */
1425 dwEndTime = INFINITE;
1426
1427 /* We need to loop until the end of the time period, because
1428 * we might get multiple unusable mouse events in that time.
1429 */
1430 for (;;)
1431 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001432#ifdef MESSAGE_QUEUE
1433 parse_queued_messages();
1434#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001435#ifdef FEAT_MZSCHEME
1436 mzvim_check_threads();
1437#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438#ifdef FEAT_CLIENTSERVER
1439 serverProcessPendingMessages();
1440#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001441
Bram Moolenaar071d4272004-06-13 20:20:40 +00001442 if (0
1443#ifdef FEAT_MOUSE
1444 || g_nMouseClick != -1
1445#endif
1446#ifdef FEAT_CLIENTSERVER
1447 || input_available()
1448#endif
1449 )
1450 return TRUE;
1451
1452 if (msec > 0)
1453 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001454 /* If the specified wait time has passed, return. Beware that
1455 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001457 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458 break;
1459 }
1460 if (msec != 0)
1461 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001462 DWORD dwWaitTime = dwEndTime - dwNow;
1463
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001464#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001465 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001466 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001467 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001468 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001469 /* If there is readahead then parse_queued_messages() timed out
1470 * and we should call it again soon. */
1471 if (channel_any_readahead())
1472 dwWaitTime = 10;
1473 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001474#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001475#ifdef FEAT_MZSCHEME
1476 if (mzthreads_allowed() && p_mzq > 0
1477 && (msec < 0 || (long)dwWaitTime > p_mzq))
1478 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1479#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001480#ifdef FEAT_TIMERS
1481 {
1482 long due_time;
1483
1484 /* When waiting very briefly don't trigger timers. */
1485 if (dwWaitTime > 10)
1486 {
1487 /* Trigger timers and then get the time in msec until the
1488 * next one is due. Wait up to that time. */
1489 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001490 if (typebuf.tb_change_cnt != tb_change_cnt)
1491 {
1492 /* timer may have used feedkeys() */
1493 return FALSE;
1494 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001495 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1496 dwWaitTime = due_time;
1497 }
1498 }
1499#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001500#ifdef FEAT_CLIENTSERVER
1501 /* Wait for either an event on the console input or a message in
1502 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001503 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001504 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001506 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507#endif
1508 continue;
1509 }
1510
1511 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001512 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513
1514#ifdef FEAT_MBYTE_IME
1515 if (State & CMDLINE && msg_row == Rows - 1)
1516 {
1517 CONSOLE_SCREEN_BUFFER_INFO csbi;
1518
1519 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1520 {
1521 if (csbi.dwCursorPosition.Y != msg_row)
1522 {
1523 /* The screen is now messed up, must redraw the
1524 * command line and later all the windows. */
1525 redraw_all_later(CLEAR);
1526 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1527 redrawcmd();
1528 }
1529 }
1530 }
1531#endif
1532
1533 if (cRecords > 0)
1534 {
1535 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1536 {
1537#ifdef FEAT_MBYTE_IME
1538 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1539 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001540 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1542 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001543 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 continue;
1545 }
1546#endif
1547 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1548 NULL, FALSE))
1549 return TRUE;
1550 }
1551
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001552 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553
1554 if (ir.EventType == FOCUS_EVENT)
1555 handle_focus_event(ir);
1556 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1557 shell_resized();
1558#ifdef FEAT_MOUSE
1559 else if (ir.EventType == MOUSE_EVENT
1560 && decode_mouse_event(&ir.Event.MouseEvent))
1561 return TRUE;
1562#endif
1563 }
1564 else if (msec == 0)
1565 break;
1566 }
1567
1568#ifdef FEAT_CLIENTSERVER
1569 /* Something might have been received while we were waiting. */
1570 if (input_available())
1571 return TRUE;
1572#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001573
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574 return FALSE;
1575}
1576
1577#ifndef FEAT_GUI_MSWIN
1578/*
1579 * return non-zero if a character is available
1580 */
1581 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001582mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583{
1584 return WaitForChar(0L);
1585}
1586#endif
1587
1588/*
1589 * Create the console input. Used when reading stdin doesn't work.
1590 */
1591 static void
1592create_conin(void)
1593{
1594 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1595 FILE_SHARE_READ|FILE_SHARE_WRITE,
1596 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001597 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 did_create_conin = TRUE;
1599}
1600
1601/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001602 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001604 static WCHAR
1605tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001607 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608
1609 for (;;)
1610 {
1611 INPUT_RECORD ir;
1612 DWORD cRecords = 0;
1613
1614#ifdef FEAT_CLIENTSERVER
1615 (void)WaitForChar(-1L);
1616 if (input_available())
1617 return 0;
1618# ifdef FEAT_MOUSE
1619 if (g_nMouseClick != -1)
1620 return 0;
1621# endif
1622#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001623 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 {
1625 if (did_create_conin)
1626 read_error_exit();
1627 create_conin();
1628 continue;
1629 }
1630
1631 if (ir.EventType == KEY_EVENT)
1632 {
1633 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1634 pmodifiers, TRUE))
1635 return ch;
1636 }
1637 else if (ir.EventType == FOCUS_EVENT)
1638 handle_focus_event(ir);
1639 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1640 shell_resized();
1641#ifdef FEAT_MOUSE
1642 else if (ir.EventType == MOUSE_EVENT)
1643 {
1644 if (decode_mouse_event(&ir.Event.MouseEvent))
1645 return 0;
1646 }
1647#endif
1648 }
1649}
1650#endif /* !FEAT_GUI_W32 */
1651
1652
1653/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001654 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001655 * Get one or more characters from the keyboard or the mouse.
1656 * If time == 0, do not wait for characters.
1657 * If time == n, wait a short time for characters.
1658 * If time == -1, wait forever for characters.
1659 * Returns the number of characters read into buf.
1660 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001661/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662 int
1663mch_inchar(
1664 char_u *buf,
1665 int maxlen,
1666 long time,
1667 int tb_change_cnt)
1668{
1669#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1670
1671 int len;
1672 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673#define TYPEAHEADLEN 20
1674 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1675 static int typeaheadlen = 0;
1676
1677 /* First use any typeahead that was kept because "buf" was too small. */
1678 if (typeaheadlen > 0)
1679 goto theend;
1680
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681 if (time >= 0)
1682 {
1683 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685 }
1686 else /* time == -1, wait forever */
1687 {
1688 mch_set_winsize_now(); /* Allow winsize changes from now on */
1689
Bram Moolenaar3918c952005-03-15 22:34:55 +00001690 /*
1691 * If there is no character available within 2 seconds (default)
1692 * write the autoscript file to disk. Or cause the CursorHold event
1693 * to be triggered.
1694 */
1695 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696 {
1697#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001698 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001700 buf[0] = K_SPECIAL;
1701 buf[1] = KS_EXTRA;
1702 buf[2] = (int)KE_CURSORHOLD;
1703 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704 }
1705#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001706 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001707 }
1708 }
1709
1710 /*
1711 * Try to read as many characters as there are, until the buffer is full.
1712 */
1713
1714 /* we will get at least one key. Get more if they are available. */
1715 g_fCBrkPressed = FALSE;
1716
1717#ifdef MCH_WRITE_DUMP
1718 if (fdDump)
1719 fputc('[', fdDump);
1720#endif
1721
1722 /* Keep looping until there is something in the typeahead buffer and more
1723 * to get and still room in the buffer (up to two bytes for a char and
1724 * three bytes for a modifier). */
1725 while ((typeaheadlen == 0 || WaitForChar(0L))
1726 && typeaheadlen + 5 <= TYPEAHEADLEN)
1727 {
1728 if (typebuf_changed(tb_change_cnt))
1729 {
1730 /* "buf" may be invalid now if a client put something in the
1731 * typeahead buffer and "buf" is in the typeahead buffer. */
1732 typeaheadlen = 0;
1733 break;
1734 }
1735#ifdef FEAT_MOUSE
1736 if (g_nMouseClick != -1)
1737 {
1738# ifdef MCH_WRITE_DUMP
1739 if (fdDump)
1740 fprintf(fdDump, "{%02x @ %d, %d}",
1741 g_nMouseClick, g_xMouse, g_yMouse);
1742# endif
1743 typeahead[typeaheadlen++] = ESC + 128;
1744 typeahead[typeaheadlen++] = 'M';
1745 typeahead[typeaheadlen++] = g_nMouseClick;
1746 typeahead[typeaheadlen++] = g_xMouse + '!';
1747 typeahead[typeaheadlen++] = g_yMouse + '!';
1748 g_nMouseClick = -1;
1749 }
1750 else
1751#endif
1752 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001753 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754 int modifiers = 0;
1755
1756 c = tgetch(&modifiers, &ch2);
1757
1758 if (typebuf_changed(tb_change_cnt))
1759 {
1760 /* "buf" may be invalid now if a client put something in the
1761 * typeahead buffer and "buf" is in the typeahead buffer. */
1762 typeaheadlen = 0;
1763 break;
1764 }
1765
1766 if (c == Ctrl_C && ctrl_c_interrupts)
1767 {
1768#if defined(FEAT_CLIENTSERVER)
1769 trash_input_buf();
1770#endif
1771 got_int = TRUE;
1772 }
1773
1774#ifdef FEAT_MOUSE
1775 if (g_nMouseClick == -1)
1776#endif
1777 {
1778 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001779 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001780
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001781#ifdef FEAT_MBYTE
1782 if (ch2 == NUL)
1783 {
1784 int i;
1785 char_u *p;
1786 WCHAR ch[2];
1787
1788 ch[0] = c;
1789 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1790 {
1791 ch[1] = tgetch(&modifiers, &ch2);
1792 n++;
1793 }
1794 p = utf16_to_enc(ch, &n);
1795 if (p != NULL)
1796 {
1797 for (i = 0; i < n; i++)
1798 typeahead[typeaheadlen + i] = p[i];
1799 vim_free(p);
1800 }
1801 }
1802 else
1803#endif
1804 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805 if (ch2 != NUL)
1806 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001807 typeahead[typeaheadlen + n] = 3;
1808 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001809 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811
Bram Moolenaar45500912014-07-09 20:51:07 +02001812 if (conv)
1813 {
1814 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001815
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001816 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001817 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001818 char_u *e = typeahead + TYPEAHEADLEN;
1819
1820 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001821 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001822 if (*p == K_NUL)
1823 {
1824 ++p;
1825 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1826 *p = 3;
1827 ++n;
1828 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001829 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001830 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001831 }
1832 }
1833
Bram Moolenaar071d4272004-06-13 20:20:40 +00001834 /* Use the ALT key to set the 8th bit of the character
1835 * when it's one byte, the 8th bit isn't set yet and not
1836 * using a double-byte encoding (would become a lead
1837 * byte). */
1838 if ((modifiers & MOD_MASK_ALT)
1839 && n == 1
1840 && (typeahead[typeaheadlen] & 0x80) == 0
1841#ifdef FEAT_MBYTE
1842 && !enc_dbcs
1843#endif
1844 )
1845 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001846#ifdef FEAT_MBYTE
1847 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1848 typeahead + typeaheadlen);
1849#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001851#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852 modifiers &= ~MOD_MASK_ALT;
1853 }
1854
1855 if (modifiers != 0)
1856 {
1857 /* Prepend modifiers to the character. */
1858 mch_memmove(typeahead + typeaheadlen + 3,
1859 typeahead + typeaheadlen, n);
1860 typeahead[typeaheadlen++] = K_SPECIAL;
1861 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1862 typeahead[typeaheadlen++] = modifiers;
1863 }
1864
1865 typeaheadlen += n;
1866
1867#ifdef MCH_WRITE_DUMP
1868 if (fdDump)
1869 fputc(c, fdDump);
1870#endif
1871 }
1872 }
1873 }
1874
1875#ifdef MCH_WRITE_DUMP
1876 if (fdDump)
1877 {
1878 fputs("]\n", fdDump);
1879 fflush(fdDump);
1880 }
1881#endif
1882
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883theend:
1884 /* Move typeahead to "buf", as much as fits. */
1885 len = 0;
1886 while (len < maxlen && typeaheadlen > 0)
1887 {
1888 buf[len++] = typeahead[0];
1889 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1890 }
1891 return len;
1892
1893#else /* FEAT_GUI_W32 */
1894 return 0;
1895#endif /* FEAT_GUI_W32 */
1896}
1897
Bram Moolenaar82881492012-11-20 16:53:39 +01001898#ifndef PROTO
1899# ifndef __MINGW32__
1900# include <shellapi.h> /* required for FindExecutable() */
1901# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902#endif
1903
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001904/*
1905 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001906 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001907 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001909executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001911 char *dum;
1912 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001913 char *curpath, *newpath;
1914 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001916#ifdef FEAT_MBYTE
1917 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001919 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001920 WCHAR fnamew[_MAX_PATH];
1921 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001922 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001923
1924 if (p != NULL)
1925 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001926 wcurpath = _wgetenv(L"PATH");
1927 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1928 * sizeof(WCHAR));
1929 if (wnewpath == NULL)
1930 return FALSE;
1931 wcscpy(wnewpath, L".;");
1932 wcscat(wnewpath, wcurpath);
1933 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1934 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001935 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02001936 if (n == 0)
1937 return FALSE;
1938 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1939 return FALSE;
1940 if (path != NULL)
1941 *path = utf16_to_enc(fnamew, NULL);
1942 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001943 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001945#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001946
1947 curpath = getenv("PATH");
1948 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1949 if (newpath == NULL)
1950 return FALSE;
1951 STRCPY(newpath, ".;");
1952 STRCAT(newpath, curpath);
1953 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1954 vim_free(newpath);
1955 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001956 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001957 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001958 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001959 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001960 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001961 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962}
1963
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001964#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001965 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001966/*
1967 * Bad parameter handler.
1968 *
1969 * Certain MS CRT functions will intentionally crash when passed invalid
1970 * parameters to highlight possible security holes. Setting this function as
1971 * the bad parameter handler will prevent the crash.
1972 *
1973 * In debug builds the parameters contain CRT information that might help track
1974 * down the source of a problem, but in non-debug builds the arguments are all
1975 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1976 * worth allowing these to make debugging of issues easier.
1977 */
1978 static void
1979bad_param_handler(const wchar_t *expression,
1980 const wchar_t *function,
1981 const wchar_t *file,
1982 unsigned int line,
1983 uintptr_t pReserved)
1984{
1985}
1986
1987# define SET_INVALID_PARAM_HANDLER \
1988 ((void)_set_invalid_parameter_handler(bad_param_handler))
1989#else
1990# define SET_INVALID_PARAM_HANDLER
1991#endif
1992
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993#ifdef FEAT_GUI_W32
1994
1995/*
1996 * GUI version of mch_init().
1997 */
1998 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001999mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000{
2001#ifndef __MINGW32__
2002 extern int _fmode;
2003#endif
2004
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002005 /* Silently handle invalid parameters to CRT functions */
2006 SET_INVALID_PARAM_HANDLER;
2007
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 /* Let critical errors result in a failure, not in a dialog box. Required
2009 * for the timestamp test to work on removed floppies. */
2010 SetErrorMode(SEM_FAILCRITICALERRORS);
2011
2012 _fmode = O_BINARY; /* we do our own CR-LF translation */
2013
2014 /* Specify window size. Is there a place to get the default from? */
2015 Rows = 25;
2016 Columns = 80;
2017
2018 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019 {
2020 char_u vimrun_location[_MAX_PATH + 4];
2021
2022 /* First try in same directory as gvim.exe */
2023 STRCPY(vimrun_location, exe_name);
2024 STRCPY(gettail(vimrun_location), "vimrun.exe");
2025 if (mch_getperm(vimrun_location) >= 0)
2026 {
2027 if (*skiptowhite(vimrun_location) != NUL)
2028 {
2029 /* Enclose path with white space in double quotes. */
2030 mch_memmove(vimrun_location + 1, vimrun_location,
2031 STRLEN(vimrun_location) + 1);
2032 *vimrun_location = '"';
2033 STRCPY(gettail(vimrun_location), "vimrun\" ");
2034 }
2035 else
2036 STRCPY(gettail(vimrun_location), "vimrun ");
2037
2038 vimrun_path = (char *)vim_strsave(vimrun_location);
2039 s_dont_use_vimrun = FALSE;
2040 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002041 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042 s_dont_use_vimrun = FALSE;
2043
2044 /* Don't give the warning for a missing vimrun.exe right now, but only
2045 * when vimrun was supposed to be used. Don't bother people that do
2046 * not need vimrun.exe. */
2047 if (s_dont_use_vimrun)
2048 need_vimrun_warning = TRUE;
2049 }
2050
2051 /*
2052 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2053 * Otherwise the default "findstr /n" is used.
2054 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002055 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2057
2058#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002059 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060#endif
2061}
2062
2063
2064#else /* FEAT_GUI_W32 */
2065
2066#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2067#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2068
2069/*
2070 * ClearConsoleBuffer()
2071 * Description:
2072 * Clears the entire contents of the console screen buffer, using the
2073 * specified attribute.
2074 * Returns:
2075 * TRUE on success
2076 */
2077 static BOOL
2078ClearConsoleBuffer(WORD wAttribute)
2079{
2080 CONSOLE_SCREEN_BUFFER_INFO csbi;
2081 COORD coord;
2082 DWORD NumCells, dummy;
2083
2084 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2085 return FALSE;
2086
2087 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2088 coord.X = 0;
2089 coord.Y = 0;
2090 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2091 coord, &dummy))
2092 {
2093 return FALSE;
2094 }
2095 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2096 coord, &dummy))
2097 {
2098 return FALSE;
2099 }
2100
2101 return TRUE;
2102}
2103
2104/*
2105 * FitConsoleWindow()
2106 * Description:
2107 * Checks if the console window will fit within given buffer dimensions.
2108 * Also, if requested, will shrink the window to fit.
2109 * Returns:
2110 * TRUE on success
2111 */
2112 static BOOL
2113FitConsoleWindow(
2114 COORD dwBufferSize,
2115 BOOL WantAdjust)
2116{
2117 CONSOLE_SCREEN_BUFFER_INFO csbi;
2118 COORD dwWindowSize;
2119 BOOL NeedAdjust = FALSE;
2120
2121 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2122 {
2123 /*
2124 * A buffer resize will fail if the current console window does
2125 * not lie completely within that buffer. To avoid this, we might
2126 * have to move and possibly shrink the window.
2127 */
2128 if (csbi.srWindow.Right >= dwBufferSize.X)
2129 {
2130 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2131 if (dwWindowSize.X > dwBufferSize.X)
2132 dwWindowSize.X = dwBufferSize.X;
2133 csbi.srWindow.Right = dwBufferSize.X - 1;
2134 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2135 NeedAdjust = TRUE;
2136 }
2137 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2138 {
2139 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2140 if (dwWindowSize.Y > dwBufferSize.Y)
2141 dwWindowSize.Y = dwBufferSize.Y;
2142 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2143 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2144 NeedAdjust = TRUE;
2145 }
2146 if (NeedAdjust && WantAdjust)
2147 {
2148 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2149 return FALSE;
2150 }
2151 return TRUE;
2152 }
2153
2154 return FALSE;
2155}
2156
2157typedef struct ConsoleBufferStruct
2158{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002159 BOOL IsValid;
2160 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002161 PCHAR_INFO Buffer;
2162 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002163} ConsoleBuffer;
2164
2165/*
2166 * SaveConsoleBuffer()
2167 * Description:
2168 * Saves important information about the console buffer, including the
2169 * actual buffer contents. The saved information is suitable for later
2170 * restoration by RestoreConsoleBuffer().
2171 * Returns:
2172 * TRUE if all information was saved; FALSE otherwise
2173 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2174 */
2175 static BOOL
2176SaveConsoleBuffer(
2177 ConsoleBuffer *cb)
2178{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002179 DWORD NumCells;
2180 COORD BufferCoord;
2181 SMALL_RECT ReadRegion;
2182 WORD Y, Y_incr;
2183
Bram Moolenaar071d4272004-06-13 20:20:40 +00002184 if (cb == NULL)
2185 return FALSE;
2186
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002187 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002188 {
2189 cb->IsValid = FALSE;
2190 return FALSE;
2191 }
2192 cb->IsValid = TRUE;
2193
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002194 /*
2195 * Allocate a buffer large enough to hold the entire console screen
2196 * buffer. If this ConsoleBuffer structure has already been initialized
2197 * with a buffer of the correct size, then just use that one.
2198 */
2199 if (!cb->IsValid || cb->Buffer == NULL ||
2200 cb->BufferSize.X != cb->Info.dwSize.X ||
2201 cb->BufferSize.Y != cb->Info.dwSize.Y)
2202 {
2203 cb->BufferSize.X = cb->Info.dwSize.X;
2204 cb->BufferSize.Y = cb->Info.dwSize.Y;
2205 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2206 vim_free(cb->Buffer);
2207 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2208 if (cb->Buffer == NULL)
2209 return FALSE;
2210 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211
2212 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002213 * We will now copy the console screen buffer into our buffer.
2214 * ReadConsoleOutput() seems to be limited as far as how much you
2215 * can read at a time. Empirically, this number seems to be about
2216 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2217 * in chunks until it is all copied. The chunks will all have the
2218 * same horizontal characteristics, so initialize them now. The
2219 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002221 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002222 ReadRegion.Left = 0;
2223 ReadRegion.Right = cb->Info.dwSize.X - 1;
2224 Y_incr = 12000 / cb->Info.dwSize.X;
2225 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002227 /*
2228 * Read into position (0, Y) in our buffer.
2229 */
2230 BufferCoord.Y = Y;
2231 /*
2232 * Read the region whose top left corner is (0, Y) and whose bottom
2233 * right corner is (width - 1, Y + Y_incr - 1). This should define
2234 * a region of size width by Y_incr. Don't worry if this region is
2235 * too large for the remaining buffer; it will be cropped.
2236 */
2237 ReadRegion.Top = Y;
2238 ReadRegion.Bottom = Y + Y_incr - 1;
2239 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2240 cb->Buffer, /* our buffer */
2241 cb->BufferSize, /* dimensions of our buffer */
2242 BufferCoord, /* offset in our buffer */
2243 &ReadRegion)) /* region to save */
2244 {
2245 vim_free(cb->Buffer);
2246 cb->Buffer = NULL;
2247 return FALSE;
2248 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002249 }
2250
2251 return TRUE;
2252}
2253
2254/*
2255 * RestoreConsoleBuffer()
2256 * Description:
2257 * Restores important information about the console buffer, including the
2258 * actual buffer contents, if desired. The information to restore is in
2259 * the same format used by SaveConsoleBuffer().
2260 * Returns:
2261 * TRUE on success
2262 */
2263 static BOOL
2264RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002265 ConsoleBuffer *cb,
2266 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002267{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002268 COORD BufferCoord;
2269 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270
2271 if (cb == NULL || !cb->IsValid)
2272 return FALSE;
2273
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002274 /*
2275 * Before restoring the buffer contents, clear the current buffer, and
2276 * restore the cursor position and window information. Doing this now
2277 * prevents old buffer contents from "flashing" onto the screen.
2278 */
2279 if (RestoreScreen)
2280 ClearConsoleBuffer(cb->Info.wAttributes);
2281
2282 FitConsoleWindow(cb->Info.dwSize, TRUE);
2283 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2284 return FALSE;
2285 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2286 return FALSE;
2287
2288 if (!RestoreScreen)
2289 {
2290 /*
2291 * No need to restore the screen buffer contents, so we're done.
2292 */
2293 return TRUE;
2294 }
2295
2296 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2297 return FALSE;
2298 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2299 return FALSE;
2300
2301 /*
2302 * Restore the screen buffer contents.
2303 */
2304 if (cb->Buffer != NULL)
2305 {
2306 BufferCoord.X = 0;
2307 BufferCoord.Y = 0;
2308 WriteRegion.Left = 0;
2309 WriteRegion.Top = 0;
2310 WriteRegion.Right = cb->Info.dwSize.X - 1;
2311 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2312 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2313 cb->Buffer, /* our buffer */
2314 cb->BufferSize, /* dimensions of our buffer */
2315 BufferCoord, /* offset in our buffer */
2316 &WriteRegion)) /* region to restore */
2317 {
2318 return FALSE;
2319 }
2320 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321
2322 return TRUE;
2323}
2324
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002325#define FEAT_RESTORE_ORIG_SCREEN
2326#ifdef FEAT_RESTORE_ORIG_SCREEN
2327static ConsoleBuffer g_cbOrig = { 0 };
2328#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329static ConsoleBuffer g_cbNonTermcap = { 0 };
2330static ConsoleBuffer g_cbTermcap = { 0 };
2331
2332#ifdef FEAT_TITLE
2333#ifdef __BORLANDC__
2334typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2335#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002336typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337#endif
2338char g_szOrigTitle[256] = { 0 };
2339HWND g_hWnd = NULL; /* also used in os_mswin.c */
2340static HICON g_hOrigIconSmall = NULL;
2341static HICON g_hOrigIcon = NULL;
2342static HICON g_hVimIcon = NULL;
2343static BOOL g_fCanChangeIcon = FALSE;
2344
2345/* ICON* are not defined in VC++ 4.0 */
2346#ifndef ICON_SMALL
2347#define ICON_SMALL 0
2348#endif
2349#ifndef ICON_BIG
2350#define ICON_BIG 1
2351#endif
2352/*
2353 * GetConsoleIcon()
2354 * Description:
2355 * Attempts to retrieve the small icon and/or the big icon currently in
2356 * use by a given window.
2357 * Returns:
2358 * TRUE on success
2359 */
2360 static BOOL
2361GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002362 HWND hWnd,
2363 HICON *phIconSmall,
2364 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365{
2366 if (hWnd == NULL)
2367 return FALSE;
2368
2369 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002370 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2371 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002373 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2374 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375 return TRUE;
2376}
2377
2378/*
2379 * SetConsoleIcon()
2380 * Description:
2381 * Attempts to change the small icon and/or the big icon currently in
2382 * use by a given window.
2383 * Returns:
2384 * TRUE on success
2385 */
2386 static BOOL
2387SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002388 HWND hWnd,
2389 HICON hIconSmall,
2390 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392 if (hWnd == NULL)
2393 return FALSE;
2394
2395 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002396 SendMessage(hWnd, WM_SETICON,
2397 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002399 SendMessage(hWnd, WM_SETICON,
2400 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401 return TRUE;
2402}
2403
2404/*
2405 * SaveConsoleTitleAndIcon()
2406 * Description:
2407 * Saves the current console window title in g_szOrigTitle, for later
2408 * restoration. Also, attempts to obtain a handle to the console window,
2409 * and use it to save the small and big icons currently in use by the
2410 * console window. This is not always possible on some versions of Windows;
2411 * nor is it possible when running Vim remotely using Telnet (since the
2412 * console window the user sees is owned by a remote process).
2413 */
2414 static void
2415SaveConsoleTitleAndIcon(void)
2416{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417 /* Save the original title. */
2418 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2419 return;
2420
2421 /*
2422 * Obtain a handle to the console window using GetConsoleWindow() from
2423 * KERNEL32.DLL; we need to handle in order to change the window icon.
2424 * This function only exists on NT-based Windows, starting with Windows
2425 * 2000. On older operating systems, we can't change the window icon
2426 * anyway.
2427 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002428 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429 if (g_hWnd == NULL)
2430 return;
2431
2432 /* Save the original console window icon. */
2433 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2434 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2435 return;
2436
2437 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002438 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002439 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440 if (g_hVimIcon != NULL)
2441 g_fCanChangeIcon = TRUE;
2442}
2443#endif
2444
2445static int g_fWindInitCalled = FALSE;
2446static int g_fTermcapMode = FALSE;
2447static CONSOLE_CURSOR_INFO g_cci;
2448static DWORD g_cmodein = 0;
2449static DWORD g_cmodeout = 0;
2450
2451/*
2452 * non-GUI version of mch_init().
2453 */
2454 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002455mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002457#ifndef FEAT_RESTORE_ORIG_SCREEN
2458 CONSOLE_SCREEN_BUFFER_INFO csbi;
2459#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002460#ifndef __MINGW32__
2461 extern int _fmode;
2462#endif
2463
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002464 /* Silently handle invalid parameters to CRT functions */
2465 SET_INVALID_PARAM_HANDLER;
2466
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 /* Let critical errors result in a failure, not in a dialog box. Required
2468 * for the timestamp test to work on removed floppies. */
2469 SetErrorMode(SEM_FAILCRITICALERRORS);
2470
2471 _fmode = O_BINARY; /* we do our own CR-LF translation */
2472 out_flush();
2473
2474 /* Obtain handles for the standard Console I/O devices */
2475 if (read_cmd_fd == 0)
2476 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2477 else
2478 create_conin();
2479 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2480
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002481#ifdef FEAT_RESTORE_ORIG_SCREEN
2482 /* Save the initial console buffer for later restoration */
2483 SaveConsoleBuffer(&g_cbOrig);
2484 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2485#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002487 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2488 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2489#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 if (cterm_normal_fg_color == 0)
2491 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2492 if (cterm_normal_bg_color == 0)
2493 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2494
2495 /* set termcap codes to current text attributes */
2496 update_tcap(g_attrCurrent);
2497
2498 GetConsoleCursorInfo(g_hConOut, &g_cci);
2499 GetConsoleMode(g_hConIn, &g_cmodein);
2500 GetConsoleMode(g_hConOut, &g_cmodeout);
2501
2502#ifdef FEAT_TITLE
2503 SaveConsoleTitleAndIcon();
2504 /*
2505 * Set both the small and big icons of the console window to Vim's icon.
2506 * Note that Vim presently only has one size of icon (32x32), but it
2507 * automatically gets scaled down to 16x16 when setting the small icon.
2508 */
2509 if (g_fCanChangeIcon)
2510 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2511#endif
2512
2513 ui_get_shellsize();
2514
2515#ifdef MCH_WRITE_DUMP
2516 fdDump = fopen("dump", "wt");
2517
2518 if (fdDump)
2519 {
2520 time_t t;
2521
2522 time(&t);
2523 fputs(ctime(&t), fdDump);
2524 fflush(fdDump);
2525 }
2526#endif
2527
2528 g_fWindInitCalled = TRUE;
2529
2530#ifdef FEAT_MOUSE
2531 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2532#endif
2533
2534#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002535 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537}
2538
2539/*
2540 * non-GUI version of mch_exit().
2541 * Shut down and exit with status `r'
2542 * Careful: mch_exit() may be called before mch_init()!
2543 */
2544 void
2545mch_exit(int r)
2546{
2547 stoptermcap();
2548
2549 if (g_fWindInitCalled)
2550 settmode(TMODE_COOK);
2551
2552 ml_close_all(TRUE); /* remove all memfiles */
2553
2554 if (g_fWindInitCalled)
2555 {
2556#ifdef FEAT_TITLE
2557 mch_restore_title(3);
2558 /*
2559 * Restore both the small and big icons of the console window to
2560 * what they were at startup. Don't do this when the window is
2561 * closed, Vim would hang here.
2562 */
2563 if (g_fCanChangeIcon && !g_fForceExit)
2564 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2565#endif
2566
2567#ifdef MCH_WRITE_DUMP
2568 if (fdDump)
2569 {
2570 time_t t;
2571
2572 time(&t);
2573 fputs(ctime(&t), fdDump);
2574 fclose(fdDump);
2575 }
2576 fdDump = NULL;
2577#endif
2578 }
2579
2580 SetConsoleCursorInfo(g_hConOut, &g_cci);
2581 SetConsoleMode(g_hConIn, g_cmodein);
2582 SetConsoleMode(g_hConOut, g_cmodeout);
2583
2584#ifdef DYNAMIC_GETTEXT
2585 dyn_libintl_end();
2586#endif
2587
2588 exit(r);
2589}
2590#endif /* !FEAT_GUI_W32 */
2591
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592/*
2593 * Do we have an interactive window?
2594 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002595/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596 int
2597mch_check_win(
2598 int argc,
2599 char **argv)
2600{
2601 get_exe_name();
2602
2603#ifdef FEAT_GUI_W32
2604 return OK; /* GUI always has a tty */
2605#else
2606 if (isatty(1))
2607 return OK;
2608 return FAIL;
2609#endif
2610}
2611
2612
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002613#ifdef FEAT_MBYTE
2614/*
2615 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2616 * if it already exists. When "len" is > 0, also expand short to long
2617 * filenames.
2618 * Return FAIL if wide functions are not available, OK otherwise.
2619 * NOTE: much of this is identical to fname_case(), keep in sync!
2620 */
2621 static int
2622fname_casew(
2623 WCHAR *name,
2624 int len)
2625{
2626 WCHAR szTrueName[_MAX_PATH + 2];
2627 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2628 WCHAR *ptrue, *ptruePrev;
2629 WCHAR *porig, *porigPrev;
2630 int flen;
2631 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002632 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002633 int c;
2634 int slen;
2635
2636 flen = (int)wcslen(name);
2637 if (flen > _MAX_PATH)
2638 return OK;
2639
2640 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2641
2642 /* Build the new name in szTrueName[] one component at a time. */
2643 porig = name;
2644 ptrue = szTrueName;
2645
2646 if (iswalpha(porig[0]) && porig[1] == L':')
2647 {
2648 /* copy leading drive letter */
2649 *ptrue++ = *porig++;
2650 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002651 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002652 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002653
2654 while (*porig != NUL)
2655 {
2656 /* copy \ characters */
2657 while (*porig == psepc)
2658 *ptrue++ = *porig++;
2659
2660 ptruePrev = ptrue;
2661 porigPrev = porig;
2662 while (*porig != NUL && *porig != psepc)
2663 {
2664 *ptrue++ = *porig++;
2665 }
2666 *ptrue = NUL;
2667
2668 /* To avoid a slow failure append "\*" when searching a directory,
2669 * server or network share. */
2670 wcscpy(szTrueNameTemp, szTrueName);
2671 slen = (int)wcslen(szTrueNameTemp);
2672 if (*porig == psepc && slen + 2 < _MAX_PATH)
2673 wcscpy(szTrueNameTemp + slen, L"\\*");
2674
2675 /* Skip "", "." and "..". */
2676 if (ptrue > ptruePrev
2677 && (ptruePrev[0] != L'.'
2678 || (ptruePrev[1] != NUL
2679 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2680 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2681 != INVALID_HANDLE_VALUE)
2682 {
2683 c = *porig;
2684 *porig = NUL;
2685
2686 /* Only use the match when it's the same name (ignoring case) or
2687 * expansion is allowed and there is a match with the short name
2688 * and there is enough room. */
2689 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2690 || (len > 0
2691 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2692 && (int)(ptruePrev - szTrueName)
2693 + (int)wcslen(fb.cFileName) < len)))
2694 {
2695 wcscpy(ptruePrev, fb.cFileName);
2696
2697 /* Look for exact match and prefer it if found. Must be a
2698 * long name, otherwise there would be only one match. */
2699 while (FindNextFileW(hFind, &fb))
2700 {
2701 if (*fb.cAlternateFileName != NUL
2702 && (wcscoll(porigPrev, fb.cFileName) == 0
2703 || (len > 0
2704 && (_wcsicoll(porigPrev,
2705 fb.cAlternateFileName) == 0
2706 && (int)(ptruePrev - szTrueName)
2707 + (int)wcslen(fb.cFileName) < len))))
2708 {
2709 wcscpy(ptruePrev, fb.cFileName);
2710 break;
2711 }
2712 }
2713 }
2714 FindClose(hFind);
2715 *porig = c;
2716 ptrue = ptruePrev + wcslen(ptruePrev);
2717 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002718 }
2719
2720 wcscpy(name, szTrueName);
2721 return OK;
2722}
2723#endif
2724
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725/*
2726 * fname_case(): Set the case of the file name, if it already exists.
2727 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002728 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 */
2730 void
2731fname_case(
2732 char_u *name,
2733 int len)
2734{
2735 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002736 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737 char *ptrue, *ptruePrev;
2738 char *porig, *porigPrev;
2739 int flen;
2740 WIN32_FIND_DATA fb;
2741 HANDLE hFind;
2742 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002743 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002745 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002746 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002747 return;
2748
2749 slash_adjust(name);
2750
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002751#ifdef FEAT_MBYTE
2752 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2753 {
2754 WCHAR *p = enc_to_utf16(name, NULL);
2755
2756 if (p != NULL)
2757 {
2758 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002759 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002760
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002761 wcsncpy(buf, p, _MAX_PATH);
2762 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002763 vim_free(p);
2764
2765 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2766 {
2767 q = utf16_to_enc(buf, NULL);
2768 if (q != NULL)
2769 {
2770 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2771 vim_free(q);
2772 return;
2773 }
2774 }
2775 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002776 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002777 }
2778#endif
2779
2780 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2781 * So we should check this after calling wide function. */
2782 if (flen > _MAX_PATH)
2783 return;
2784
Bram Moolenaar071d4272004-06-13 20:20:40 +00002785 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002786 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787 ptrue = szTrueName;
2788
2789 if (isalpha(porig[0]) && porig[1] == ':')
2790 {
2791 /* copy leading drive letter */
2792 *ptrue++ = *porig++;
2793 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002795 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796
2797 while (*porig != NUL)
2798 {
2799 /* copy \ characters */
2800 while (*porig == psepc)
2801 *ptrue++ = *porig++;
2802
2803 ptruePrev = ptrue;
2804 porigPrev = porig;
2805 while (*porig != NUL && *porig != psepc)
2806 {
2807#ifdef FEAT_MBYTE
2808 int l;
2809
2810 if (enc_dbcs)
2811 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002812 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002813 while (--l >= 0)
2814 *ptrue++ = *porig++;
2815 }
2816 else
2817#endif
2818 *ptrue++ = *porig++;
2819 }
2820 *ptrue = NUL;
2821
Bram Moolenaar464c9252010-10-13 20:37:41 +02002822 /* To avoid a slow failure append "\*" when searching a directory,
2823 * server or network share. */
2824 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002825 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002826 if (*porig == psepc && slen + 2 < _MAX_PATH)
2827 STRCPY(szTrueNameTemp + slen, "\\*");
2828
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829 /* Skip "", "." and "..". */
2830 if (ptrue > ptruePrev
2831 && (ptruePrev[0] != '.'
2832 || (ptruePrev[1] != NUL
2833 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002834 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 != INVALID_HANDLE_VALUE)
2836 {
2837 c = *porig;
2838 *porig = NUL;
2839
2840 /* Only use the match when it's the same name (ignoring case) or
2841 * expansion is allowed and there is a match with the short name
2842 * and there is enough room. */
2843 if (_stricoll(porigPrev, fb.cFileName) == 0
2844 || (len > 0
2845 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2846 && (int)(ptruePrev - szTrueName)
2847 + (int)strlen(fb.cFileName) < len)))
2848 {
2849 STRCPY(ptruePrev, fb.cFileName);
2850
2851 /* Look for exact match and prefer it if found. Must be a
2852 * long name, otherwise there would be only one match. */
2853 while (FindNextFile(hFind, &fb))
2854 {
2855 if (*fb.cAlternateFileName != NUL
2856 && (strcoll(porigPrev, fb.cFileName) == 0
2857 || (len > 0
2858 && (_stricoll(porigPrev,
2859 fb.cAlternateFileName) == 0
2860 && (int)(ptruePrev - szTrueName)
2861 + (int)strlen(fb.cFileName) < len))))
2862 {
2863 STRCPY(ptruePrev, fb.cFileName);
2864 break;
2865 }
2866 }
2867 }
2868 FindClose(hFind);
2869 *porig = c;
2870 ptrue = ptruePrev + strlen(ptruePrev);
2871 }
2872 }
2873
2874 STRCPY(name, szTrueName);
2875}
2876
2877
2878/*
2879 * Insert user name in s[len].
2880 */
2881 int
2882mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002883 char_u *s,
2884 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002886 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887 DWORD cch = sizeof szUserName;
2888
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002889#ifdef FEAT_MBYTE
2890 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2891 {
2892 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2893 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2894
2895 if (GetUserNameW(wszUserName, &wcch))
2896 {
2897 char_u *p = utf16_to_enc(wszUserName, NULL);
2898
2899 if (p != NULL)
2900 {
2901 vim_strncpy(s, p, len - 1);
2902 vim_free(p);
2903 return OK;
2904 }
2905 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002906 }
2907#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908 if (GetUserName(szUserName, &cch))
2909 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002910 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911 return OK;
2912 }
2913 s[0] = NUL;
2914 return FAIL;
2915}
2916
2917
2918/*
2919 * Insert host name in s[len].
2920 */
2921 void
2922mch_get_host_name(
2923 char_u *s,
2924 int len)
2925{
2926 DWORD cch = len;
2927
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002928#ifdef FEAT_MBYTE
2929 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2930 {
2931 WCHAR wszHostName[256 + 1];
2932 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2933
2934 if (GetComputerNameW(wszHostName, &wcch))
2935 {
2936 char_u *p = utf16_to_enc(wszHostName, NULL);
2937
2938 if (p != NULL)
2939 {
2940 vim_strncpy(s, p, len - 1);
2941 vim_free(p);
2942 return;
2943 }
2944 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002945 }
2946#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002947 if (!GetComputerName((LPSTR)s, &cch))
2948 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949}
2950
2951
2952/*
2953 * return process ID
2954 */
2955 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002956mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957{
2958 return (long)GetCurrentProcessId();
2959}
2960
2961
2962/*
2963 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2964 * Return OK for success, FAIL for failure.
2965 */
2966 int
2967mch_dirname(
2968 char_u *buf,
2969 int len)
2970{
2971 /*
2972 * Originally this was:
2973 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2974 * But the Win32s known bug list says that getcwd() doesn't work
2975 * so use the Win32 system call instead. <Negri>
2976 */
2977#ifdef FEAT_MBYTE
2978 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2979 {
2980 WCHAR wbuf[_MAX_PATH + 1];
2981
2982 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2983 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002984 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985
2986 if (p != NULL)
2987 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002988 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989 vim_free(p);
2990 return OK;
2991 }
2992 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002993 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 }
2995#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002996 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997}
2998
2999/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003000 * Get file permissions for "name".
3001 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002 */
3003 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003004mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003006 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003007 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003009 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003010 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011}
3012
3013
3014/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003015 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003016 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003017 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018 */
3019 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003020mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003022 long n = -1;
3023
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024#ifdef FEAT_MBYTE
3025 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3026 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003027 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028
3029 if (p != NULL)
3030 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003031 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003033 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003034 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 }
3036 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003037 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003039 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003040 if (n == -1)
3041 return FAIL;
3042
3043 win32_set_archive(name);
3044
3045 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046}
3047
3048/*
3049 * Set hidden flag for "name".
3050 */
3051 void
3052mch_hide(char_u *name)
3053{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003054 int attrs = win32_getattrs(name);
3055 if (attrs == -1)
3056 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003058 attrs |= FILE_ATTRIBUTE_HIDDEN;
3059 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060}
3061
3062/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003063 * Return TRUE if file "name" exists and is hidden.
3064 */
3065 int
3066mch_ishidden(char_u *name)
3067{
3068 int f = win32_getattrs(name);
3069
3070 if (f == -1)
3071 return FALSE; /* file does not exist at all */
3072
3073 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3074}
3075
3076/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077 * return TRUE if "name" is a directory
3078 * return FALSE if "name" is not a directory or upon error
3079 */
3080 int
3081mch_isdir(char_u *name)
3082{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003083 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084
3085 if (f == -1)
3086 return FALSE; /* file does not exist at all */
3087
3088 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3089}
3090
3091/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003092 * return TRUE if "name" is a directory, NOT a symlink to a directory
3093 * return FALSE if "name" is not a directory
3094 * return FALSE for error
3095 */
3096 int
3097mch_isrealdir(char_u *name)
3098{
3099 return mch_isdir(name) && !mch_is_symbolic_link(name);
3100}
3101
3102/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003103 * Create directory "name".
3104 * Return 0 on success, -1 on error.
3105 */
3106 int
3107mch_mkdir(char_u *name)
3108{
3109#ifdef FEAT_MBYTE
3110 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3111 {
3112 WCHAR *p;
3113 int retval;
3114
3115 p = enc_to_utf16(name, NULL);
3116 if (p == NULL)
3117 return -1;
3118 retval = _wmkdir(p);
3119 vim_free(p);
3120 return retval;
3121 }
3122#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003123 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003124}
3125
3126/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003127 * Delete directory "name".
3128 * Return 0 on success, -1 on error.
3129 */
3130 int
3131mch_rmdir(char_u *name)
3132{
3133#ifdef FEAT_MBYTE
3134 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3135 {
3136 WCHAR *p;
3137 int retval;
3138
3139 p = enc_to_utf16(name, NULL);
3140 if (p == NULL)
3141 return -1;
3142 retval = _wrmdir(p);
3143 vim_free(p);
3144 return retval;
3145 }
3146#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003147 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003148}
3149
3150/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003151 * Return TRUE if file "fname" has more than one link.
3152 */
3153 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003154mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003155{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003156 BY_HANDLE_FILE_INFORMATION info;
3157
3158 return win32_fileinfo(fname, &info) == FILEINFO_OK
3159 && info.nNumberOfLinks > 1;
3160}
3161
3162/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003163 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003164 */
3165 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003166mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003167{
3168 HANDLE hFind;
3169 int res = FALSE;
3170 WIN32_FIND_DATAA findDataA;
3171 DWORD fileFlags = 0, reparseTag = 0;
3172#ifdef FEAT_MBYTE
3173 WCHAR *wn = NULL;
3174 WIN32_FIND_DATAW findDataW;
3175
3176 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003177 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003178 if (wn != NULL)
3179 {
3180 hFind = FindFirstFileW(wn, &findDataW);
3181 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003182 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003183 {
3184 fileFlags = findDataW.dwFileAttributes;
3185 reparseTag = findDataW.dwReserved0;
3186 }
3187 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003188 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003189#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003190 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003191 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003192 if (hFind != INVALID_HANDLE_VALUE)
3193 {
3194 fileFlags = findDataA.dwFileAttributes;
3195 reparseTag = findDataA.dwReserved0;
3196 }
3197 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003198
3199 if (hFind != INVALID_HANDLE_VALUE)
3200 FindClose(hFind);
3201
3202 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003203 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3204 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003205 res = TRUE;
3206
3207 return res;
3208}
3209
3210/*
3211 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3212 * link.
3213 */
3214 int
3215mch_is_linked(char_u *fname)
3216{
3217 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3218 return TRUE;
3219 return FALSE;
3220}
3221
3222/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003223 * Get the by-handle-file-information for "fname".
3224 * Returns FILEINFO_OK when OK.
3225 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3226 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3227 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3228 */
3229 int
3230win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3231{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003232 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003233 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003234#ifdef FEAT_MBYTE
3235 WCHAR *wn = NULL;
3236
3237 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003238 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003239 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003240 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003241 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003242 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003243 if (wn != NULL)
3244 {
3245 hFile = CreateFileW(wn, /* file name */
3246 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003247 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003248 NULL, /* security descriptor */
3249 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003250 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003251 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003252 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003253 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003254 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003255#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003256 hFile = CreateFile((LPCSTR)fname, /* file name */
3257 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003258 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003259 NULL, /* security descriptor */
3260 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003261 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003262 NULL); /* handle to template file */
3263
3264 if (hFile != INVALID_HANDLE_VALUE)
3265 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003266 if (GetFileInformationByHandle(hFile, info) != 0)
3267 res = FILEINFO_OK;
3268 else
3269 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003270 CloseHandle(hFile);
3271 }
3272
Bram Moolenaar03f48552006-02-28 23:52:23 +00003273 return res;
3274}
3275
3276/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003277 * get file attributes for `name'
3278 * -1 : error
3279 * else FILE_ATTRIBUTE_* defined in winnt.h
3280 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003281 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003282win32_getattrs(char_u *name)
3283{
3284 int attr;
3285#ifdef FEAT_MBYTE
3286 WCHAR *p = NULL;
3287
3288 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3289 p = enc_to_utf16(name, NULL);
3290
3291 if (p != NULL)
3292 {
3293 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003294 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003295 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003296 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003297#endif
3298 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003299
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003300 return attr;
3301}
3302
3303/*
3304 * set file attributes for `name' to `attrs'
3305 *
3306 * return -1 for failure, 0 otherwise
3307 */
3308 static
3309 int
3310win32_setattrs(char_u *name, int attrs)
3311{
3312 int res;
3313#ifdef FEAT_MBYTE
3314 WCHAR *p = NULL;
3315
3316 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3317 p = enc_to_utf16(name, NULL);
3318
3319 if (p != NULL)
3320 {
3321 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003322 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003323 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003324 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003325#endif
3326 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003327
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003328 return res ? 0 : -1;
3329}
3330
3331/*
3332 * Set archive flag for "name".
3333 */
3334 static
3335 int
3336win32_set_archive(char_u *name)
3337{
3338 int attrs = win32_getattrs(name);
3339 if (attrs == -1)
3340 return -1;
3341
3342 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3343 return win32_setattrs(name, attrs);
3344}
3345
3346/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003347 * Return TRUE if file or directory "name" is writable (not readonly).
3348 * Strange semantics of Win32: a readonly directory is writable, but you can't
3349 * delete a file. Let's say this means it is writable.
3350 */
3351 int
3352mch_writable(char_u *name)
3353{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003354 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003355
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003356 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3357 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003358}
3359
Bram Moolenaar071d4272004-06-13 20:20:40 +00003360/*
3361 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003362 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 * Return -1 if unknown.
3364 */
3365 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003366mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003367{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003368 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003369 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003370 char_u *p;
3371
3372 if (len >= _MAX_PATH) /* safety check */
3373 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003374 if (!use_path)
3375 {
3376 /* TODO: check if file is really executable. */
3377 return mch_getperm(name) != -1 && !mch_isdir(name);
3378 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003379
3380 /* If there already is an extension try using the name directly. Also do
3381 * this with a Unix-shell like 'shell'. */
3382 if (vim_strchr(gettail(name), '.') != NULL
3383 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003384 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003385 return TRUE;
3386
3387 /*
3388 * Loop over all extensions in $PATHEXT.
3389 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003390 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003391 p = mch_getenv("PATHEXT");
3392 if (p == NULL)
3393 p = (char_u *)".com;.exe;.bat;.cmd";
3394 while (*p)
3395 {
3396 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3397 {
3398 /* A single "." means no extension is added. */
3399 buf[len] = NUL;
3400 ++p;
3401 if (*p)
3402 ++p;
3403 }
3404 else
3405 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003406 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003407 return TRUE;
3408 }
3409 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411
3412/*
3413 * Check what "name" is:
3414 * NODE_NORMAL: file or directory (or doesn't exist)
3415 * NODE_WRITABLE: writable device, socket, fifo, etc.
3416 * NODE_OTHER: non-writable things
3417 */
3418 int
3419mch_nodetype(char_u *name)
3420{
3421 HANDLE hFile;
3422 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003423#ifdef FEAT_MBYTE
3424 WCHAR *wn = NULL;
3425#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003426
Bram Moolenaar043545e2006-10-10 16:44:07 +00003427 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3428 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3429 * here. */
3430 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3431 return NODE_WRITABLE;
3432
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003433#ifdef FEAT_MBYTE
3434 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003435 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003436
3437 if (wn != NULL)
3438 {
3439 hFile = CreateFileW(wn, /* file name */
3440 GENERIC_WRITE, /* access mode */
3441 0, /* share mode */
3442 NULL, /* security descriptor */
3443 OPEN_EXISTING, /* creation disposition */
3444 0, /* file attributes */
3445 NULL); /* handle to template file */
3446 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003447 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003448 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003449#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003450 hFile = CreateFile((LPCSTR)name, /* file name */
3451 GENERIC_WRITE, /* access mode */
3452 0, /* share mode */
3453 NULL, /* security descriptor */
3454 OPEN_EXISTING, /* creation disposition */
3455 0, /* file attributes */
3456 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457
3458 if (hFile == INVALID_HANDLE_VALUE)
3459 return NODE_NORMAL;
3460
3461 type = GetFileType(hFile);
3462 CloseHandle(hFile);
3463 if (type == FILE_TYPE_CHAR)
3464 return NODE_WRITABLE;
3465 if (type == FILE_TYPE_DISK)
3466 return NODE_NORMAL;
3467 return NODE_OTHER;
3468}
3469
3470#ifdef HAVE_ACL
3471struct my_acl
3472{
3473 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3474 PSID pSidOwner;
3475 PSID pSidGroup;
3476 PACL pDacl;
3477 PACL pSacl;
3478};
3479#endif
3480
3481/*
3482 * Return a pointer to the ACL of file "fname" in allocated memory.
3483 * Return NULL if the ACL is not available for whatever reason.
3484 */
3485 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003486mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487{
3488#ifndef HAVE_ACL
3489 return (vim_acl_T)NULL;
3490#else
3491 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003492 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003494 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3495 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003497# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003498 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003499
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003500 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3501 wn = enc_to_utf16(fname, NULL);
3502 if (wn != NULL)
3503 {
3504 /* Try to retrieve the entire security descriptor. */
3505 err = GetNamedSecurityInfoW(
3506 wn, // Abstract filename
3507 SE_FILE_OBJECT, // File Object
3508 OWNER_SECURITY_INFORMATION |
3509 GROUP_SECURITY_INFORMATION |
3510 DACL_SECURITY_INFORMATION |
3511 SACL_SECURITY_INFORMATION,
3512 &p->pSidOwner, // Ownership information.
3513 &p->pSidGroup, // Group membership.
3514 &p->pDacl, // Discretionary information.
3515 &p->pSacl, // For auditing purposes.
3516 &p->pSecurityDescriptor);
3517 if (err == ERROR_ACCESS_DENIED ||
3518 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003520 /* Retrieve only DACL. */
3521 (void)GetNamedSecurityInfoW(
3522 wn,
3523 SE_FILE_OBJECT,
3524 DACL_SECURITY_INFORMATION,
3525 NULL,
3526 NULL,
3527 &p->pDacl,
3528 NULL,
3529 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003530 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003531 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003532 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003533 mch_free_acl((vim_acl_T)p);
3534 p = NULL;
3535 }
3536 vim_free(wn);
3537 }
3538 else
3539# endif
3540 {
3541 /* Try to retrieve the entire security descriptor. */
3542 err = GetNamedSecurityInfo(
3543 (LPSTR)fname, // Abstract filename
3544 SE_FILE_OBJECT, // File Object
3545 OWNER_SECURITY_INFORMATION |
3546 GROUP_SECURITY_INFORMATION |
3547 DACL_SECURITY_INFORMATION |
3548 SACL_SECURITY_INFORMATION,
3549 &p->pSidOwner, // Ownership information.
3550 &p->pSidGroup, // Group membership.
3551 &p->pDacl, // Discretionary information.
3552 &p->pSacl, // For auditing purposes.
3553 &p->pSecurityDescriptor);
3554 if (err == ERROR_ACCESS_DENIED ||
3555 err == ERROR_PRIVILEGE_NOT_HELD)
3556 {
3557 /* Retrieve only DACL. */
3558 (void)GetNamedSecurityInfo(
3559 (LPSTR)fname,
3560 SE_FILE_OBJECT,
3561 DACL_SECURITY_INFORMATION,
3562 NULL,
3563 NULL,
3564 &p->pDacl,
3565 NULL,
3566 &p->pSecurityDescriptor);
3567 }
3568 if (p->pSecurityDescriptor == NULL)
3569 {
3570 mch_free_acl((vim_acl_T)p);
3571 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 }
3573 }
3574 }
3575
3576 return (vim_acl_T)p;
3577#endif
3578}
3579
Bram Moolenaar27515922013-06-29 15:36:26 +02003580#ifdef HAVE_ACL
3581/*
3582 * Check if "acl" contains inherited ACE.
3583 */
3584 static BOOL
3585is_acl_inherited(PACL acl)
3586{
3587 DWORD i;
3588 ACL_SIZE_INFORMATION acl_info;
3589 PACCESS_ALLOWED_ACE ace;
3590
3591 acl_info.AceCount = 0;
3592 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3593 for (i = 0; i < acl_info.AceCount; i++)
3594 {
3595 GetAce(acl, i, (LPVOID *)&ace);
3596 if (ace->Header.AceFlags & INHERITED_ACE)
3597 return TRUE;
3598 }
3599 return FALSE;
3600}
3601#endif
3602
Bram Moolenaar071d4272004-06-13 20:20:40 +00003603/*
3604 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3605 * Errors are ignored.
3606 * This must only be called with "acl" equal to what mch_get_acl() returned.
3607 */
3608 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003609mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610{
3611#ifdef HAVE_ACL
3612 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003613 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003615 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003616 {
3617# ifdef FEAT_MBYTE
3618 WCHAR *wn = NULL;
3619# endif
3620
3621 /* Set security flags */
3622 if (p->pSidOwner)
3623 sec_info |= OWNER_SECURITY_INFORMATION;
3624 if (p->pSidGroup)
3625 sec_info |= GROUP_SECURITY_INFORMATION;
3626 if (p->pDacl)
3627 {
3628 sec_info |= DACL_SECURITY_INFORMATION;
3629 /* Do not inherit its parent's DACL.
3630 * If the DACL is inherited, Cygwin permissions would be changed.
3631 */
3632 if (!is_acl_inherited(p->pDacl))
3633 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3634 }
3635 if (p->pSacl)
3636 sec_info |= SACL_SECURITY_INFORMATION;
3637
3638# ifdef FEAT_MBYTE
3639 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3640 wn = enc_to_utf16(fname, NULL);
3641 if (wn != NULL)
3642 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003643 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003644 wn, // Abstract filename
3645 SE_FILE_OBJECT, // File Object
3646 sec_info,
3647 p->pSidOwner, // Ownership information.
3648 p->pSidGroup, // Group membership.
3649 p->pDacl, // Discretionary information.
3650 p->pSacl // For auditing purposes.
3651 );
3652 vim_free(wn);
3653 }
3654 else
3655# endif
3656 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003657 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003658 (LPSTR)fname, // Abstract filename
3659 SE_FILE_OBJECT, // File Object
3660 sec_info,
3661 p->pSidOwner, // Ownership information.
3662 p->pSidGroup, // Group membership.
3663 p->pDacl, // Discretionary information.
3664 p->pSacl // For auditing purposes.
3665 );
3666 }
3667 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668#endif
3669}
3670
3671 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003672mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003673{
3674#ifdef HAVE_ACL
3675 struct my_acl *p = (struct my_acl *)acl;
3676
3677 if (p != NULL)
3678 {
3679 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3680 vim_free(p);
3681 }
3682#endif
3683}
3684
3685#ifndef FEAT_GUI_W32
3686
3687/*
3688 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3689 */
3690 static BOOL WINAPI
3691handler_routine(
3692 DWORD dwCtrlType)
3693{
3694 switch (dwCtrlType)
3695 {
3696 case CTRL_C_EVENT:
3697 if (ctrl_c_interrupts)
3698 g_fCtrlCPressed = TRUE;
3699 return TRUE;
3700
3701 case CTRL_BREAK_EVENT:
3702 g_fCBrkPressed = TRUE;
3703 return TRUE;
3704
3705 /* fatal events: shut down gracefully */
3706 case CTRL_CLOSE_EVENT:
3707 case CTRL_LOGOFF_EVENT:
3708 case CTRL_SHUTDOWN_EVENT:
3709 windgoto((int)Rows - 1, 0);
3710 g_fForceExit = TRUE;
3711
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003712 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713 (dwCtrlType == CTRL_CLOSE_EVENT
3714 ? _("close")
3715 : dwCtrlType == CTRL_LOGOFF_EVENT
3716 ? _("logoff")
3717 : _("shutdown")));
3718#ifdef DEBUG
3719 OutputDebugString(IObuff);
3720#endif
3721
3722 preserve_exit(); /* output IObuff, preserve files and exit */
3723
3724 return TRUE; /* not reached */
3725
3726 default:
3727 return FALSE;
3728 }
3729}
3730
3731
3732/*
3733 * set the tty in (raw) ? "raw" : "cooked" mode
3734 */
3735 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003736mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737{
3738 DWORD cmodein;
3739 DWORD cmodeout;
3740 BOOL bEnableHandler;
3741
3742 GetConsoleMode(g_hConIn, &cmodein);
3743 GetConsoleMode(g_hConOut, &cmodeout);
3744 if (tmode == TMODE_RAW)
3745 {
3746 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3747 ENABLE_ECHO_INPUT);
3748#ifdef FEAT_MOUSE
3749 if (g_fMouseActive)
3750 cmodein |= ENABLE_MOUSE_INPUT;
3751#endif
3752 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3753 bEnableHandler = TRUE;
3754 }
3755 else /* cooked */
3756 {
3757 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3758 ENABLE_ECHO_INPUT);
3759 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3760 bEnableHandler = FALSE;
3761 }
3762 SetConsoleMode(g_hConIn, cmodein);
3763 SetConsoleMode(g_hConOut, cmodeout);
3764 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3765
3766#ifdef MCH_WRITE_DUMP
3767 if (fdDump)
3768 {
3769 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3770 tmode == TMODE_RAW ? "raw" :
3771 tmode == TMODE_COOK ? "cooked" : "normal",
3772 cmodein, cmodeout);
3773 fflush(fdDump);
3774 }
3775#endif
3776}
3777
3778
3779/*
3780 * Get the size of the current window in `Rows' and `Columns'
3781 * Return OK when size could be determined, FAIL otherwise.
3782 */
3783 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003784mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785{
3786 CONSOLE_SCREEN_BUFFER_INFO csbi;
3787
3788 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3789 {
3790 /*
3791 * For some reason, we are trying to get the screen dimensions
3792 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3793 * variables are really intended to mean the size of Vim screen
3794 * while in termcap mode.
3795 */
3796 Rows = g_cbTermcap.Info.dwSize.Y;
3797 Columns = g_cbTermcap.Info.dwSize.X;
3798 }
3799 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3800 {
3801 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3802 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3803 }
3804 else
3805 {
3806 Rows = 25;
3807 Columns = 80;
3808 }
3809 return OK;
3810}
3811
3812/*
3813 * Set a console window to `xSize' * `ySize'
3814 */
3815 static void
3816ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003817 HANDLE hConsole,
3818 int xSize,
3819 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820{
3821 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3822 SMALL_RECT srWindowRect; /* hold the new console size */
3823 COORD coordScreen;
3824
3825#ifdef MCH_WRITE_DUMP
3826 if (fdDump)
3827 {
3828 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3829 fflush(fdDump);
3830 }
3831#endif
3832
3833 /* get the largest size we can size the console window to */
3834 coordScreen = GetLargestConsoleWindowSize(hConsole);
3835
3836 /* define the new console window size and scroll position */
3837 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3838 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3839 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3840
3841 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3842 {
3843 int sx, sy;
3844
3845 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3846 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3847 if (sy < ySize || sx < xSize)
3848 {
3849 /*
3850 * Increasing number of lines/columns, do buffer first.
3851 * Use the maximal size in x and y direction.
3852 */
3853 if (sy < ySize)
3854 coordScreen.Y = ySize;
3855 else
3856 coordScreen.Y = sy;
3857 if (sx < xSize)
3858 coordScreen.X = xSize;
3859 else
3860 coordScreen.X = sx;
3861 SetConsoleScreenBufferSize(hConsole, coordScreen);
3862 }
3863 }
3864
3865 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3866 {
3867#ifdef MCH_WRITE_DUMP
3868 if (fdDump)
3869 {
3870 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3871 GetLastError());
3872 fflush(fdDump);
3873 }
3874#endif
3875 }
3876
3877 /* define the new console buffer size */
3878 coordScreen.X = xSize;
3879 coordScreen.Y = ySize;
3880
3881 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3882 {
3883#ifdef MCH_WRITE_DUMP
3884 if (fdDump)
3885 {
3886 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3887 GetLastError());
3888 fflush(fdDump);
3889 }
3890#endif
3891 }
3892}
3893
3894
3895/*
3896 * Set the console window to `Rows' * `Columns'
3897 */
3898 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003899mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003900{
3901 COORD coordScreen;
3902
3903 /* Don't change window size while still starting up */
3904 if (suppress_winsize != 0)
3905 {
3906 suppress_winsize = 2;
3907 return;
3908 }
3909
3910 if (term_console)
3911 {
3912 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3913
3914 /* Clamp Rows and Columns to reasonable values */
3915 if (Rows > coordScreen.Y)
3916 Rows = coordScreen.Y;
3917 if (Columns > coordScreen.X)
3918 Columns = coordScreen.X;
3919
3920 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3921 }
3922}
3923
3924/*
3925 * Rows and/or Columns has changed.
3926 */
3927 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003928mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929{
3930 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3931}
3932
3933
3934/*
3935 * Called when started up, to set the winsize that was delayed.
3936 */
3937 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003938mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939{
3940 if (suppress_winsize == 2)
3941 {
3942 suppress_winsize = 0;
3943 mch_set_shellsize();
3944 shell_resized();
3945 }
3946 suppress_winsize = 0;
3947}
3948#endif /* FEAT_GUI_W32 */
3949
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003950 static BOOL
3951vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003952 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003953 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003954 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003955 STARTUPINFO *si,
3956 PROCESS_INFORMATION *pi)
3957{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003958#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003959 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3960 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003961 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003962
3963 if (wcmd != NULL)
3964 {
3965 BOOL ret;
3966 ret = CreateProcessW(
3967 NULL, /* Executable name */
3968 wcmd, /* Command to execute */
3969 NULL, /* Process security attributes */
3970 NULL, /* Thread security attributes */
3971 inherit_handles, /* Inherit handles */
3972 flags, /* Creation flags */
3973 NULL, /* Environment */
3974 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003975 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003976 pi); /* Process information */
3977 vim_free(wcmd);
3978 return ret;
3979 }
3980 }
3981#endif
3982 return CreateProcess(
3983 NULL, /* Executable name */
3984 cmd, /* Command to execute */
3985 NULL, /* Process security attributes */
3986 NULL, /* Thread security attributes */
3987 inherit_handles, /* Inherit handles */
3988 flags, /* Creation flags */
3989 NULL, /* Environment */
3990 NULL, /* Current directory */
3991 si, /* Startup information */
3992 pi); /* Process information */
3993}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994
3995
3996#if defined(FEAT_GUI_W32) || defined(PROTO)
3997
3998/*
3999 * Specialised version of system() for Win32 GUI mode.
4000 * This version proceeds as follows:
4001 * 1. Create a console window for use by the subprocess
4002 * 2. Run the subprocess (it gets the allocated console by default)
4003 * 3. Wait for the subprocess to terminate and get its exit code
4004 * 4. Prompt the user to press a key to close the console window
4005 */
4006 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004007mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004008{
4009 STARTUPINFO si;
4010 PROCESS_INFORMATION pi;
4011 DWORD ret = 0;
4012 HWND hwnd = GetFocus();
4013
4014 si.cb = sizeof(si);
4015 si.lpReserved = NULL;
4016 si.lpDesktop = NULL;
4017 si.lpTitle = NULL;
4018 si.dwFlags = STARTF_USESHOWWINDOW;
4019 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004020 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004021 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004022 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004023 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004024 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004025 else
4026 si.wShowWindow = SW_SHOWNORMAL;
4027 si.cbReserved2 = 0;
4028 si.lpReserved2 = NULL;
4029
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004031 vim_create_process(cmd, FALSE,
4032 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004033
4034 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 {
4036#ifdef FEAT_GUI
4037 int delay = 1;
4038
4039 /* Keep updating the window while waiting for the shell to finish. */
4040 for (;;)
4041 {
4042 MSG msg;
4043
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004044 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004045 {
4046 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004047 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004048 delay = 1;
4049 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004050 }
4051 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4052 break;
4053
4054 /* We start waiting for a very short time and then increase it, so
4055 * that we respond quickly when the process is quick, and don't
4056 * consume too much overhead when it's slow. */
4057 if (delay < 50)
4058 delay += 10;
4059 }
4060#else
4061 WaitForSingleObject(pi.hProcess, INFINITE);
4062#endif
4063
4064 /* Get the command exit code */
4065 GetExitCodeProcess(pi.hProcess, &ret);
4066 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004067
4068 /* Close the handles to the subprocess, so that it goes away */
4069 CloseHandle(pi.hThread);
4070 CloseHandle(pi.hProcess);
4071
4072 /* Try to get input focus back. Doesn't always work though. */
4073 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4074
4075 return ret;
4076}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004077
4078/*
4079 * Thread launched by the gui to send the current buffer data to the
4080 * process. This way avoid to hang up vim totally if the children
4081 * process take a long time to process the lines.
4082 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004083 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004084sub_process_writer(LPVOID param)
4085{
4086 HANDLE g_hChildStd_IN_Wr = param;
4087 linenr_T lnum = curbuf->b_op_start.lnum;
4088 DWORD len = 0;
4089 DWORD l;
4090 char_u *lp = ml_get(lnum);
4091 char_u *s;
4092 int written = 0;
4093
4094 for (;;)
4095 {
4096 l = (DWORD)STRLEN(lp + written);
4097 if (l == 0)
4098 len = 0;
4099 else if (lp[written] == NL)
4100 {
4101 /* NL -> NUL translation */
4102 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4103 }
4104 else
4105 {
4106 s = vim_strchr(lp + written, NL);
4107 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4108 s == NULL ? l : (DWORD)(s - (lp + written)),
4109 &len, NULL);
4110 }
4111 if (len == (int)l)
4112 {
4113 /* Finished a line, add a NL, unless this line should not have
4114 * one. */
4115 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004116 || (!curbuf->b_p_bin
4117 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004118 || (lnum != curbuf->b_no_eol_lnum
4119 && (lnum != curbuf->b_ml.ml_line_count
4120 || curbuf->b_p_eol)))
4121 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004122 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004123 }
4124
4125 ++lnum;
4126 if (lnum > curbuf->b_op_end.lnum)
4127 break;
4128
4129 lp = ml_get(lnum);
4130 written = 0;
4131 }
4132 else if (len > 0)
4133 written += len;
4134 }
4135
4136 /* finished all the lines, close pipe */
4137 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004138 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004139}
4140
4141
4142# define BUFLEN 100 /* length for buffer, stolen from unix version */
4143
4144/*
4145 * This function read from the children's stdout and write the
4146 * data on screen or in the buffer accordingly.
4147 */
4148 static void
4149dump_pipe(int options,
4150 HANDLE g_hChildStd_OUT_Rd,
4151 garray_T *ga,
4152 char_u buffer[],
4153 DWORD *buffer_off)
4154{
4155 DWORD availableBytes = 0;
4156 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004157 int ret;
4158 DWORD len;
4159 DWORD toRead;
4160 int repeatCount;
4161
4162 /* we query the pipe to see if there is any data to read
4163 * to avoid to perform a blocking read */
4164 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4165 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004166 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004167 NULL, /* number of read bytes */
4168 &availableBytes, /* available bytes total */
4169 NULL); /* byteLeft */
4170
4171 repeatCount = 0;
4172 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004173 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004174 {
4175 repeatCount++;
4176 toRead =
4177# ifdef FEAT_MBYTE
4178 (DWORD)(BUFLEN - *buffer_off);
4179# else
4180 (DWORD)BUFLEN;
4181# endif
4182 toRead = availableBytes < toRead ? availableBytes : toRead;
4183 ReadFile(g_hChildStd_OUT_Rd, buffer
4184# ifdef FEAT_MBYTE
4185 + *buffer_off, toRead
4186# else
4187 , toRead
4188# endif
4189 , &len, NULL);
4190
4191 /* If we haven't read anything, there is a problem */
4192 if (len == 0)
4193 break;
4194
4195 availableBytes -= len;
4196
4197 if (options & SHELL_READ)
4198 {
4199 /* Do NUL -> NL translation, append NL separated
4200 * lines to the current buffer. */
4201 for (i = 0; i < len; ++i)
4202 {
4203 if (buffer[i] == NL)
4204 append_ga_line(ga);
4205 else if (buffer[i] == NUL)
4206 ga_append(ga, NL);
4207 else
4208 ga_append(ga, buffer[i]);
4209 }
4210 }
4211# ifdef FEAT_MBYTE
4212 else if (has_mbyte)
4213 {
4214 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004215 int c;
4216 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004217
4218 len += *buffer_off;
4219 buffer[len] = NUL;
4220
4221 /* Check if the last character in buffer[] is
4222 * incomplete, keep these bytes for the next
4223 * round. */
4224 for (p = buffer; p < buffer + len; p += l)
4225 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004226 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004227 if (l == 0)
4228 l = 1; /* NUL byte? */
4229 else if (MB_BYTE2LEN(*p) != l)
4230 break;
4231 }
4232 if (p == buffer) /* no complete character */
4233 {
4234 /* avoid getting stuck at an illegal byte */
4235 if (len >= 12)
4236 ++p;
4237 else
4238 {
4239 *buffer_off = len;
4240 return;
4241 }
4242 }
4243 c = *p;
4244 *p = NUL;
4245 msg_puts(buffer);
4246 if (p < buffer + len)
4247 {
4248 *p = c;
4249 *buffer_off = (DWORD)((buffer + len) - p);
4250 mch_memmove(buffer, p, *buffer_off);
4251 return;
4252 }
4253 *buffer_off = 0;
4254 }
4255# endif /* FEAT_MBYTE */
4256 else
4257 {
4258 buffer[len] = NUL;
4259 msg_puts(buffer);
4260 }
4261
4262 windgoto(msg_row, msg_col);
4263 cursor_on();
4264 out_flush();
4265 }
4266}
4267
4268/*
4269 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4270 * for communication and doesn't open any new window.
4271 */
4272 static int
4273mch_system_piped(char *cmd, int options)
4274{
4275 STARTUPINFO si;
4276 PROCESS_INFORMATION pi;
4277 DWORD ret = 0;
4278
4279 HANDLE g_hChildStd_IN_Rd = NULL;
4280 HANDLE g_hChildStd_IN_Wr = NULL;
4281 HANDLE g_hChildStd_OUT_Rd = NULL;
4282 HANDLE g_hChildStd_OUT_Wr = NULL;
4283
4284 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4285 DWORD len;
4286
4287 /* buffer used to receive keys */
4288 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4289 int ta_len = 0; /* valid bytes in ta_buf[] */
4290
4291 DWORD i;
4292 int c;
4293 int noread_cnt = 0;
4294 garray_T ga;
4295 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004296 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004297 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298
4299 SECURITY_ATTRIBUTES saAttr;
4300
4301 /* Set the bInheritHandle flag so pipe handles are inherited. */
4302 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4303 saAttr.bInheritHandle = TRUE;
4304 saAttr.lpSecurityDescriptor = NULL;
4305
4306 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4307 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004308 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004309 /* Create a pipe for the child process's STDIN. */
4310 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4311 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004312 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004313 {
4314 CloseHandle(g_hChildStd_IN_Rd);
4315 CloseHandle(g_hChildStd_IN_Wr);
4316 CloseHandle(g_hChildStd_OUT_Rd);
4317 CloseHandle(g_hChildStd_OUT_Wr);
4318 MSG_PUTS(_("\nCannot create pipes\n"));
4319 }
4320
4321 si.cb = sizeof(si);
4322 si.lpReserved = NULL;
4323 si.lpDesktop = NULL;
4324 si.lpTitle = NULL;
4325 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4326
4327 /* set-up our file redirection */
4328 si.hStdError = g_hChildStd_OUT_Wr;
4329 si.hStdOutput = g_hChildStd_OUT_Wr;
4330 si.hStdInput = g_hChildStd_IN_Rd;
4331 si.wShowWindow = SW_HIDE;
4332 si.cbReserved2 = 0;
4333 si.lpReserved2 = NULL;
4334
4335 if (options & SHELL_READ)
4336 ga_init2(&ga, 1, BUFLEN);
4337
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004338 if (cmd != NULL)
4339 {
4340 p = (char *)vim_strsave((char_u *)cmd);
4341 if (p != NULL)
4342 unescape_shellxquote((char_u *)p, p_sxe);
4343 else
4344 p = cmd;
4345 }
4346
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004347 /* Now, run the command.
4348 * About "Inherit handles" being TRUE: this command can be litigious,
4349 * handle inheritance was deactivated for pending temp file, but, if we
4350 * deactivate it, the pipes don't work for some reason. */
4351 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004352
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004353 if (p != cmd)
4354 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004355
4356 /* Close our unused side of the pipes */
4357 CloseHandle(g_hChildStd_IN_Rd);
4358 CloseHandle(g_hChildStd_OUT_Wr);
4359
4360 if (options & SHELL_WRITE)
4361 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004362 HANDLE thread = (HANDLE)
4363 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004364 0, /* default stack size */
4365 sub_process_writer, /* function to be executed */
4366 g_hChildStd_IN_Wr, /* parameter */
4367 0, /* creation flag, start immediately */
4368 NULL); /* we don't care about thread id */
4369 CloseHandle(thread);
4370 g_hChildStd_IN_Wr = NULL;
4371 }
4372
4373 /* Keep updating the window while waiting for the shell to finish. */
4374 for (;;)
4375 {
4376 MSG msg;
4377
Bram Moolenaar175d0702013-12-11 18:36:33 +01004378 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004379 {
4380 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004381 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004382 }
4383
4384 /* write pipe information in the window */
4385 if ((options & (SHELL_READ|SHELL_WRITE))
4386# ifdef FEAT_GUI
4387 || gui.in_use
4388# endif
4389 )
4390 {
4391 len = 0;
4392 if (!(options & SHELL_EXPAND)
4393 && ((options &
4394 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4395 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4396# ifdef FEAT_GUI
4397 || gui.in_use
4398# endif
4399 )
4400 && (ta_len > 0 || noread_cnt > 4))
4401 {
4402 if (ta_len == 0)
4403 {
4404 /* Get extra characters when we don't have any. Reset the
4405 * counter and timer. */
4406 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004407 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4408 }
4409 if (ta_len > 0 || len > 0)
4410 {
4411 /*
4412 * For pipes: Check for CTRL-C: send interrupt signal to
4413 * child. Check for CTRL-D: EOF, close pipe to child.
4414 */
4415 if (len == 1 && cmd != NULL)
4416 {
4417 if (ta_buf[ta_len] == Ctrl_C)
4418 {
4419 /* Learn what exit code is expected, for
4420 * now put 9 as SIGKILL */
4421 TerminateProcess(pi.hProcess, 9);
4422 }
4423 if (ta_buf[ta_len] == Ctrl_D)
4424 {
4425 CloseHandle(g_hChildStd_IN_Wr);
4426 g_hChildStd_IN_Wr = NULL;
4427 }
4428 }
4429
4430 /* replace K_BS by <BS> and K_DEL by <DEL> */
4431 for (i = ta_len; i < ta_len + len; ++i)
4432 {
4433 if (ta_buf[i] == CSI && len - i > 2)
4434 {
4435 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4436 if (c == K_DEL || c == K_KDEL || c == K_BS)
4437 {
4438 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4439 (size_t)(len - i - 2));
4440 if (c == K_DEL || c == K_KDEL)
4441 ta_buf[i] = DEL;
4442 else
4443 ta_buf[i] = Ctrl_H;
4444 len -= 2;
4445 }
4446 }
4447 else if (ta_buf[i] == '\r')
4448 ta_buf[i] = '\n';
4449# ifdef FEAT_MBYTE
4450 if (has_mbyte)
4451 i += (*mb_ptr2len_len)(ta_buf + i,
4452 ta_len + len - i) - 1;
4453# endif
4454 }
4455
4456 /*
4457 * For pipes: echo the typed characters. For a pty this
4458 * does not seem to work.
4459 */
4460 for (i = ta_len; i < ta_len + len; ++i)
4461 {
4462 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4463 msg_putchar(ta_buf[i]);
4464# ifdef FEAT_MBYTE
4465 else if (has_mbyte)
4466 {
4467 int l = (*mb_ptr2len)(ta_buf + i);
4468
4469 msg_outtrans_len(ta_buf + i, l);
4470 i += l - 1;
4471 }
4472# endif
4473 else
4474 msg_outtrans_len(ta_buf + i, 1);
4475 }
4476 windgoto(msg_row, msg_col);
4477 out_flush();
4478
4479 ta_len += len;
4480
4481 /*
4482 * Write the characters to the child, unless EOF has been
4483 * typed for pipes. Write one character at a time, to
4484 * avoid losing too much typeahead. When writing buffer
4485 * lines, drop the typed characters (only check for
4486 * CTRL-C).
4487 */
4488 if (options & SHELL_WRITE)
4489 ta_len = 0;
4490 else if (g_hChildStd_IN_Wr != NULL)
4491 {
4492 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4493 1, &len, NULL);
4494 // if we are typing in, we want to keep things reactive
4495 delay = 1;
4496 if (len > 0)
4497 {
4498 ta_len -= len;
4499 mch_memmove(ta_buf, ta_buf + len, ta_len);
4500 }
4501 }
4502 }
4503 }
4504 }
4505
4506 if (ta_len)
4507 ui_inchar_undo(ta_buf, ta_len);
4508
4509 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4510 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004511 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004512 break;
4513 }
4514
4515 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004516 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004517
4518 /* We start waiting for a very short time and then increase it, so
4519 * that we respond quickly when the process is quick, and don't
4520 * consume too much overhead when it's slow. */
4521 if (delay < 50)
4522 delay += 10;
4523 }
4524
4525 /* Close the pipe */
4526 CloseHandle(g_hChildStd_OUT_Rd);
4527 if (g_hChildStd_IN_Wr != NULL)
4528 CloseHandle(g_hChildStd_IN_Wr);
4529
4530 WaitForSingleObject(pi.hProcess, INFINITE);
4531
4532 /* Get the command exit code */
4533 GetExitCodeProcess(pi.hProcess, &ret);
4534
4535 if (options & SHELL_READ)
4536 {
4537 if (ga.ga_len > 0)
4538 {
4539 append_ga_line(&ga);
4540 /* remember that the NL was missing */
4541 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4542 }
4543 else
4544 curbuf->b_no_eol_lnum = 0;
4545 ga_clear(&ga);
4546 }
4547
4548 /* Close the handles to the subprocess, so that it goes away */
4549 CloseHandle(pi.hThread);
4550 CloseHandle(pi.hProcess);
4551
4552 return ret;
4553}
4554
4555 static int
4556mch_system(char *cmd, int options)
4557{
4558 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004559 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004560 return mch_system_piped(cmd, options);
4561 else
4562 return mch_system_classic(cmd, options);
4563}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004564#else
4565
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004566# ifdef FEAT_MBYTE
4567 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004568mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004569{
4570 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4571 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004572 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004573 if (wcmd != NULL)
4574 {
4575 int ret = _wsystem(wcmd);
4576 vim_free(wcmd);
4577 return ret;
4578 }
4579 }
4580 return system(cmd);
4581}
4582# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004583# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004584# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004585
4586#endif
4587
4588/*
4589 * Either execute a command by calling the shell or start a new shell
4590 */
4591 int
4592mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004593 char_u *cmd,
4594 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004595{
4596 int x = 0;
4597 int tmode = cur_tmode;
4598#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004599 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004600# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004601 int did_set_title = FALSE;
4602
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004603 /* Change the title to reflect that we are in a subshell. */
4604 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4605 {
4606 WCHAR szShellTitle[512];
4607
4608 if (GetConsoleTitleW(szShellTitle,
4609 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4610 {
4611 if (cmd == NULL)
4612 wcscat(szShellTitle, L" :sh");
4613 else
4614 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004615 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004616
4617 if (wn != NULL)
4618 {
4619 wcscat(szShellTitle, L" - !");
4620 if ((wcslen(szShellTitle) + wcslen(wn) <
4621 sizeof(szShellTitle)/sizeof(WCHAR)))
4622 wcscat(szShellTitle, wn);
4623 SetConsoleTitleW(szShellTitle);
4624 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004625 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004626 }
4627 }
4628 }
4629 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004630 if (!did_set_title)
4631# endif
4632 /* Change the title to reflect that we are in a subshell. */
4633 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004635 if (cmd == NULL)
4636 strcat(szShellTitle, " :sh");
4637 else
4638 {
4639 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004640 if ((strlen(szShellTitle) + strlen((char *)cmd)
4641 < sizeof(szShellTitle)))
4642 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004643 }
4644 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004645 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004646#endif
4647
4648 out_flush();
4649
4650#ifdef MCH_WRITE_DUMP
4651 if (fdDump)
4652 {
4653 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4654 fflush(fdDump);
4655 }
4656#endif
4657
4658 /*
4659 * Catch all deadly signals while running the external command, because a
4660 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4661 */
4662 signal(SIGINT, SIG_IGN);
4663#if defined(__GNUC__) && !defined(__MINGW32__)
4664 signal(SIGKILL, SIG_IGN);
4665#else
4666 signal(SIGBREAK, SIG_IGN);
4667#endif
4668 signal(SIGILL, SIG_IGN);
4669 signal(SIGFPE, SIG_IGN);
4670 signal(SIGSEGV, SIG_IGN);
4671 signal(SIGTERM, SIG_IGN);
4672 signal(SIGABRT, SIG_IGN);
4673
4674 if (options & SHELL_COOKED)
4675 settmode(TMODE_COOK); /* set to normal mode */
4676
4677 if (cmd == NULL)
4678 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004679 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004680 }
4681 else
4682 {
4683 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004684 char_u *newcmd = NULL;
4685 char_u *cmdbase = cmd;
4686 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004687
4688 /* Skip a leading ", ( and "(. */
4689 if (*cmdbase == '"' )
4690 ++cmdbase;
4691 if (*cmdbase == '(')
4692 ++cmdbase;
4693
4694 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4695 {
4696 STARTUPINFO si;
4697 PROCESS_INFORMATION pi;
4698 DWORD flags = CREATE_NEW_CONSOLE;
4699 char_u *p;
4700
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004701 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004702 si.cb = sizeof(si);
4703 si.lpReserved = NULL;
4704 si.lpDesktop = NULL;
4705 si.lpTitle = NULL;
4706 si.dwFlags = 0;
4707 si.cbReserved2 = 0;
4708 si.lpReserved2 = NULL;
4709
4710 cmdbase = skipwhite(cmdbase + 5);
4711 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4712 && vim_iswhite(cmdbase[4]))
4713 {
4714 cmdbase = skipwhite(cmdbase + 4);
4715 si.dwFlags = STARTF_USESHOWWINDOW;
4716 si.wShowWindow = SW_SHOWMINNOACTIVE;
4717 }
4718 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4719 && vim_iswhite(cmdbase[2]))
4720 {
4721 cmdbase = skipwhite(cmdbase + 2);
4722 flags = CREATE_NO_WINDOW;
4723 si.dwFlags = STARTF_USESTDHANDLES;
4724 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004725 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004726 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004727 NULL, // Security att.
4728 OPEN_EXISTING, // Open flags
4729 FILE_ATTRIBUTE_NORMAL, // File att.
4730 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004731 si.hStdOutput = si.hStdInput;
4732 si.hStdError = si.hStdInput;
4733 }
4734
4735 /* Remove a trailing ", ) and )" if they have a match
4736 * at the start of the command. */
4737 if (cmdbase > cmd)
4738 {
4739 p = cmdbase + STRLEN(cmdbase);
4740 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4741 *--p = NUL;
4742 if (p > cmdbase && p[-1] == ')'
4743 && (*cmd =='(' || cmd[1] == '('))
4744 *--p = NUL;
4745 }
4746
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004747 newcmd = cmdbase;
4748 unescape_shellxquote(cmdbase, p_sxe);
4749
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004750 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004751 * If creating new console, arguments are passed to the
4752 * 'cmd.exe' as-is. If it's not, arguments are not treated
4753 * correctly for current 'cmd.exe'. So unescape characters in
4754 * shellxescape except '|' for avoiding to be treated as
4755 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004756 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004757 if (flags != CREATE_NEW_CONSOLE)
4758 {
4759 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004760 char_u *cmd_shell = mch_getenv("COMSPEC");
4761
4762 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004763 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004764
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004765 subcmd = vim_strsave_escaped_ext(cmdbase,
4766 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004767 if (subcmd != NULL)
4768 {
4769 /* make "cmd.exe /c arguments" */
4770 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004771 newcmd = lalloc(cmdlen, TRUE);
4772 if (newcmd != NULL)
4773 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004774 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004775 else
4776 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004777 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004778 }
4779 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004780
4781 /*
4782 * Now, start the command as a process, so that it doesn't
4783 * inherit our handles which causes unpleasant dangling swap
4784 * files if we exit before the spawned process
4785 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004786 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004787 x = 0;
4788 else
4789 {
4790 x = -1;
4791#ifdef FEAT_GUI_W32
4792 EMSG(_("E371: Command not found"));
4793#endif
4794 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004795
4796 if (newcmd != cmdbase)
4797 vim_free(newcmd);
4798
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004799 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004800 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004801 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004802 CloseHandle(si.hStdInput);
4803 }
4804 /* Close the handles to the subprocess, so that it goes away */
4805 CloseHandle(pi.hThread);
4806 CloseHandle(pi.hProcess);
4807 }
4808 else
4809 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004810 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004811#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004812 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004814 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4815
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004816 newcmd = lalloc(cmdlen, TRUE);
4817 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818 {
4819#if defined(FEAT_GUI_W32)
4820 if (need_vimrun_warning)
4821 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004822 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4823 "External commands will not pause after completion.\n"
4824 "See :help win32-vimrun for more information.");
4825 char *title = _("Vim Warning");
4826# ifdef FEAT_MBYTE
4827 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4828 {
4829 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4830 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
4831
4832 if (wmsg != NULL && wtitle != NULL)
4833 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4834 vim_free(wmsg);
4835 vim_free(wtitle);
4836 }
4837 else
4838# endif
4839 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004840 need_vimrun_warning = FALSE;
4841 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004842 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843 /* Use vimrun to execute the command. It opens a console
4844 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004845 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846 vimrun_path,
4847 (msg_silent != 0 || (options & SHELL_DOOUT))
4848 ? "-s " : "",
4849 p_sh, p_shcf, cmd);
4850 else
4851#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004852 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004853 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004854 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004855 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004856 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 }
4858 }
4859
4860 if (tmode == TMODE_RAW)
4861 settmode(TMODE_RAW); /* set to raw mode */
4862
4863 /* Print the return value, unless "vimrun" was used. */
4864 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4865#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004866 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867#endif
4868 )
4869 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004870 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871 msg_putchar('\n');
4872 }
4873#ifdef FEAT_TITLE
4874 resettitle();
4875#endif
4876
4877 signal(SIGINT, SIG_DFL);
4878#if defined(__GNUC__) && !defined(__MINGW32__)
4879 signal(SIGKILL, SIG_DFL);
4880#else
4881 signal(SIGBREAK, SIG_DFL);
4882#endif
4883 signal(SIGILL, SIG_DFL);
4884 signal(SIGFPE, SIG_DFL);
4885 signal(SIGSEGV, SIG_DFL);
4886 signal(SIGTERM, SIG_DFL);
4887 signal(SIGABRT, SIG_DFL);
4888
4889 return x;
4890}
4891
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004892#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004893 static HANDLE
4894job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004895 char_u *fname,
4896 DWORD dwDesiredAccess,
4897 DWORD dwShareMode,
4898 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4899 DWORD dwCreationDisposition,
4900 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004901{
4902 HANDLE h;
4903# ifdef FEAT_MBYTE
4904 WCHAR *wn = NULL;
4905 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4906 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004907 wn = enc_to_utf16(fname, NULL);
4908 if (wn != NULL)
4909 {
4910 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4911 lpSecurityAttributes, dwCreationDisposition,
4912 dwFlagsAndAttributes, NULL);
4913 vim_free(wn);
4914 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004915 }
4916 if (wn == NULL)
4917# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004918 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
4919 lpSecurityAttributes, dwCreationDisposition,
4920 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004921 return h;
4922}
4923
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004924 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01004925mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004926{
4927 STARTUPINFO si;
4928 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02004929 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004930 SECURITY_ATTRIBUTES saAttr;
4931 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01004932 HANDLE ifd[2];
4933 HANDLE ofd[2];
4934 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004935
4936 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
4937 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
4938 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
4939 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
4940 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
4941 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
4942 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
4943
4944 if (use_out_for_err && use_null_for_out)
4945 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01004946
4947 ifd[0] = INVALID_HANDLE_VALUE;
4948 ifd[1] = INVALID_HANDLE_VALUE;
4949 ofd[0] = INVALID_HANDLE_VALUE;
4950 ofd[1] = INVALID_HANDLE_VALUE;
4951 efd[0] = INVALID_HANDLE_VALUE;
4952 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004953
Bram Moolenaar14207f42016-10-27 21:13:10 +02004954 jo = CreateJobObject(NULL, NULL);
4955 if (jo == NULL)
4956 {
4957 job->jv_status = JOB_FAILED;
4958 goto failed;
4959 }
4960
Bram Moolenaar76467df2016-02-12 19:30:26 +01004961 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004962 ZeroMemory(&si, sizeof(si));
4963 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01004964 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004965 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004966
Bram Moolenaard8070362016-02-15 21:56:54 +01004967 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4968 saAttr.bInheritHandle = TRUE;
4969 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004970
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004971 if (use_file_for_in)
4972 {
4973 char_u *fname = options->jo_io_name[PART_IN];
4974
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004975 ifd[0] = job_io_file_open(fname, GENERIC_READ,
4976 FILE_SHARE_READ | FILE_SHARE_WRITE,
4977 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
4978 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01004979 {
4980 EMSG2(_(e_notopen), fname);
4981 goto failed;
4982 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004983 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004984 else if (!use_null_for_in &&
4985 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004986 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004987 goto failed;
4988
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004989 if (use_file_for_out)
4990 {
4991 char_u *fname = options->jo_io_name[PART_OUT];
4992
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004993 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
4994 FILE_SHARE_READ | FILE_SHARE_WRITE,
4995 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
4996 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004997 {
4998 EMSG2(_(e_notopen), fname);
4999 goto failed;
5000 }
5001 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005002 else if (!use_null_for_out &&
5003 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005004 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005005 goto failed;
5006
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005007 if (use_file_for_err)
5008 {
5009 char_u *fname = options->jo_io_name[PART_ERR];
5010
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005011 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5012 FILE_SHARE_READ | FILE_SHARE_WRITE,
5013 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5014 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005015 {
5016 EMSG2(_(e_notopen), fname);
5017 goto failed;
5018 }
5019 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005020 else if (!use_out_for_err && !use_null_for_err &&
5021 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005022 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005023 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005024
Bram Moolenaard8070362016-02-15 21:56:54 +01005025 si.dwFlags |= STARTF_USESTDHANDLES;
5026 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005027 si.hStdOutput = ofd[1];
5028 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5029
5030 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5031 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005032 if (options->jo_set & JO_CHANNEL)
5033 {
5034 channel = options->jo_channel;
5035 if (channel != NULL)
5036 ++channel->ch_refcount;
5037 }
5038 else
5039 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005040 if (channel == NULL)
5041 goto failed;
5042 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005043
5044 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005045 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005046 CREATE_DEFAULT_ERROR_MODE |
5047 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005048 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005049 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005050 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005051 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005052 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005053 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005054 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005055
Bram Moolenaar14207f42016-10-27 21:13:10 +02005056 if (!AssignProcessToJobObject(jo, pi.hProcess))
5057 {
5058 /* if failing, switch the way to terminate
5059 * process with TerminateProcess. */
5060 CloseHandle(jo);
5061 jo = NULL;
5062 }
5063 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005064 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005065 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005066 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005067 job->jv_status = JOB_STARTED;
5068
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005069 CloseHandle(ifd[0]);
5070 CloseHandle(ofd[1]);
5071 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005072 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005073
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005074 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005075 if (channel != NULL)
5076 {
5077 channel_set_pipes(channel,
5078 use_file_for_in || use_null_for_in
5079 ? INVALID_FD : (sock_T)ifd[1],
5080 use_file_for_out || use_null_for_out
5081 ? INVALID_FD : (sock_T)ofd[0],
5082 use_out_for_err || use_file_for_err || use_null_for_err
5083 ? INVALID_FD : (sock_T)efd[0]);
5084 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005085 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005086 return;
5087
5088failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005089 CloseHandle(ifd[0]);
5090 CloseHandle(ofd[0]);
5091 CloseHandle(efd[0]);
5092 CloseHandle(ifd[1]);
5093 CloseHandle(ofd[1]);
5094 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005095 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005096}
5097
5098 char *
5099mch_job_status(job_T *job)
5100{
5101 DWORD dwExitCode = 0;
5102
Bram Moolenaar76467df2016-02-12 19:30:26 +01005103 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5104 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005105 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005106 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005107 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005108 {
5109 ch_log(job->jv_channel, "Job ended");
5110 job->jv_status = JOB_ENDED;
5111 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005112 return "dead";
5113 }
5114 return "run";
5115}
5116
Bram Moolenaar97792de2016-10-15 18:36:49 +02005117 job_T *
5118mch_detect_ended_job(job_T *job_list)
5119{
5120 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5121 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5122 job_T *job = job_list;
5123
5124 while (job != NULL)
5125 {
5126 DWORD n;
5127 DWORD result;
5128
5129 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5130 && job != NULL; job = job->jv_next)
5131 {
5132 if (job->jv_status == JOB_STARTED)
5133 {
5134 jobHandles[n] = job->jv_proc_info.hProcess;
5135 jobArray[n] = job;
5136 ++n;
5137 }
5138 }
5139 if (n == 0)
5140 continue;
5141 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5142 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5143 {
5144 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5145
5146 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5147 return wait_job;
5148 }
5149 }
5150 return NULL;
5151}
5152
Bram Moolenaarfb630902016-10-29 14:55:00 +02005153 static BOOL
5154terminate_all(HANDLE process, int code)
5155{
5156 PROCESSENTRY32 pe;
5157 HANDLE h = INVALID_HANDLE_VALUE;
5158 DWORD pid = GetProcessId(process);
5159
5160 if (pid != 0)
5161 {
5162 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5163 if (h != INVALID_HANDLE_VALUE)
5164 {
5165 pe.dwSize = sizeof(PROCESSENTRY32);
5166 if (!Process32First(h, &pe))
5167 goto theend;
5168
5169 do
5170 {
5171 if (pe.th32ParentProcessID == pid)
5172 {
5173 HANDLE ph = OpenProcess(
5174 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5175 if (ph != NULL)
5176 {
5177 terminate_all(ph, code);
5178 CloseHandle(ph);
5179 }
5180 }
5181 } while (Process32Next(h, &pe));
5182
5183 CloseHandle(h);
5184 }
5185 }
5186
5187theend:
5188 return TerminateProcess(process, code);
5189}
5190
5191/*
5192 * Send a (deadly) signal to "job".
5193 * Return FAIL if it didn't work.
5194 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005195 int
5196mch_stop_job(job_T *job, char_u *how)
5197{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005198 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005199
Bram Moolenaar923d9262016-02-25 20:56:01 +01005200 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005201 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005202 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005203 if (job->jv_job_object != NULL)
5204 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005205 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005206 }
5207
5208 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5209 return FAIL;
5210 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005211 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5212 job->jv_proc_info.dwProcessId)
5213 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005214 FreeConsole();
5215 return ret;
5216}
5217
5218/*
5219 * Clear the data related to "job".
5220 */
5221 void
5222mch_clear_job(job_T *job)
5223{
5224 if (job->jv_status != JOB_FAILED)
5225 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005226 if (job->jv_job_object != NULL)
5227 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005228 CloseHandle(job->jv_proc_info.hProcess);
5229 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005230}
5231#endif
5232
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233
5234#ifndef FEAT_GUI_W32
5235
5236/*
5237 * Start termcap mode
5238 */
5239 static void
5240termcap_mode_start(void)
5241{
5242 DWORD cmodein;
5243
5244 if (g_fTermcapMode)
5245 return;
5246
5247 SaveConsoleBuffer(&g_cbNonTermcap);
5248
5249 if (g_cbTermcap.IsValid)
5250 {
5251 /*
5252 * We've been in termcap mode before. Restore certain screen
5253 * characteristics, including the buffer size and the window
5254 * size. Since we will be redrawing the screen, we don't need
5255 * to restore the actual contents of the buffer.
5256 */
5257 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5258 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5259 Rows = g_cbTermcap.Info.dwSize.Y;
5260 Columns = g_cbTermcap.Info.dwSize.X;
5261 }
5262 else
5263 {
5264 /*
5265 * This is our first time entering termcap mode. Clear the console
5266 * screen buffer, and resize the buffer to match the current window
5267 * size. We will use this as the size of our editing environment.
5268 */
5269 ClearConsoleBuffer(g_attrCurrent);
5270 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5271 }
5272
5273#ifdef FEAT_TITLE
5274 resettitle();
5275#endif
5276
5277 GetConsoleMode(g_hConIn, &cmodein);
5278#ifdef FEAT_MOUSE
5279 if (g_fMouseActive)
5280 cmodein |= ENABLE_MOUSE_INPUT;
5281 else
5282 cmodein &= ~ENABLE_MOUSE_INPUT;
5283#endif
5284 cmodein |= ENABLE_WINDOW_INPUT;
5285 SetConsoleMode(g_hConIn, cmodein);
5286
5287 redraw_later_clear();
5288 g_fTermcapMode = TRUE;
5289}
5290
5291
5292/*
5293 * End termcap mode
5294 */
5295 static void
5296termcap_mode_end(void)
5297{
5298 DWORD cmodein;
5299 ConsoleBuffer *cb;
5300 COORD coord;
5301 DWORD dwDummy;
5302
5303 if (!g_fTermcapMode)
5304 return;
5305
5306 SaveConsoleBuffer(&g_cbTermcap);
5307
5308 GetConsoleMode(g_hConIn, &cmodein);
5309 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5310 SetConsoleMode(g_hConIn, cmodein);
5311
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005312#ifdef FEAT_RESTORE_ORIG_SCREEN
5313 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5314#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005315 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005316#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005317 RestoreConsoleBuffer(cb, p_rs);
5318 SetConsoleCursorInfo(g_hConOut, &g_cci);
5319
5320 if (p_rs || exiting)
5321 {
5322 /*
5323 * Clear anything that happens to be on the current line.
5324 */
5325 coord.X = 0;
5326 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5327 FillConsoleOutputCharacter(g_hConOut, ' ',
5328 cb->Info.dwSize.X, coord, &dwDummy);
5329 /*
5330 * The following is just for aesthetics. If we are exiting without
5331 * restoring the screen, then we want to have a prompt string
5332 * appear at the bottom line. However, the command interpreter
5333 * seems to always advance the cursor one line before displaying
5334 * the prompt string, which causes the screen to scroll. To
5335 * counter this, move the cursor up one line before exiting.
5336 */
5337 if (exiting && !p_rs)
5338 coord.Y--;
5339 /*
5340 * Position the cursor at the leftmost column of the desired row.
5341 */
5342 SetConsoleCursorPosition(g_hConOut, coord);
5343 }
5344
5345 g_fTermcapMode = FALSE;
5346}
5347#endif /* FEAT_GUI_W32 */
5348
5349
5350#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005351/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005352 void
5353mch_write(
5354 char_u *s,
5355 int len)
5356{
5357 /* never used */
5358}
5359
5360#else
5361
5362/*
5363 * clear `n' chars, starting from `coord'
5364 */
5365 static void
5366clear_chars(
5367 COORD coord,
5368 DWORD n)
5369{
5370 DWORD dwDummy;
5371
5372 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5373 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5374}
5375
5376
5377/*
5378 * Clear the screen
5379 */
5380 static void
5381clear_screen(void)
5382{
5383 g_coord.X = g_coord.Y = 0;
5384 clear_chars(g_coord, Rows * Columns);
5385}
5386
5387
5388/*
5389 * Clear to end of display
5390 */
5391 static void
5392clear_to_end_of_display(void)
5393{
5394 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5395 * Columns + (Columns - g_coord.X));
5396}
5397
5398
5399/*
5400 * Clear to end of line
5401 */
5402 static void
5403clear_to_end_of_line(void)
5404{
5405 clear_chars(g_coord, Columns - g_coord.X);
5406}
5407
5408
5409/*
5410 * Scroll the scroll region up by `cLines' lines
5411 */
5412 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005413scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414{
5415 COORD oldcoord = g_coord;
5416
5417 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5418 delete_lines(cLines);
5419
5420 g_coord = oldcoord;
5421}
5422
5423
5424/*
5425 * Set the scroll region
5426 */
5427 static void
5428set_scroll_region(
5429 unsigned left,
5430 unsigned top,
5431 unsigned right,
5432 unsigned bottom)
5433{
5434 if (left >= right
5435 || top >= bottom
5436 || right > (unsigned) Columns - 1
5437 || bottom > (unsigned) Rows - 1)
5438 return;
5439
5440 g_srScrollRegion.Left = left;
5441 g_srScrollRegion.Top = top;
5442 g_srScrollRegion.Right = right;
5443 g_srScrollRegion.Bottom = bottom;
5444}
5445
5446
5447/*
5448 * Insert `cLines' lines at the current cursor position
5449 */
5450 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005451insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005452{
5453 SMALL_RECT source;
5454 COORD dest;
5455 CHAR_INFO fill;
5456
5457 dest.X = 0;
5458 dest.Y = g_coord.Y + cLines;
5459
5460 source.Left = 0;
5461 source.Top = g_coord.Y;
5462 source.Right = g_srScrollRegion.Right;
5463 source.Bottom = g_srScrollRegion.Bottom - cLines;
5464
5465 fill.Char.AsciiChar = ' ';
5466 fill.Attributes = g_attrCurrent;
5467
5468 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5469
5470 /* Here we have to deal with a win32 console flake: If the scroll
5471 * region looks like abc and we scroll c to a and fill with d we get
5472 * cbd... if we scroll block c one line at a time to a, we get cdd...
5473 * vim expects cdd consistently... So we have to deal with that
5474 * here... (this also occurs scrolling the same way in the other
5475 * direction). */
5476
5477 if (source.Bottom < dest.Y)
5478 {
5479 COORD coord;
5480
5481 coord.X = 0;
5482 coord.Y = source.Bottom;
5483 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5484 }
5485}
5486
5487
5488/*
5489 * Delete `cLines' lines at the current cursor position
5490 */
5491 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005492delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005493{
5494 SMALL_RECT source;
5495 COORD dest;
5496 CHAR_INFO fill;
5497 int nb;
5498
5499 dest.X = 0;
5500 dest.Y = g_coord.Y;
5501
5502 source.Left = 0;
5503 source.Top = g_coord.Y + cLines;
5504 source.Right = g_srScrollRegion.Right;
5505 source.Bottom = g_srScrollRegion.Bottom;
5506
5507 fill.Char.AsciiChar = ' ';
5508 fill.Attributes = g_attrCurrent;
5509
5510 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5511
5512 /* Here we have to deal with a win32 console flake: If the scroll
5513 * region looks like abc and we scroll c to a and fill with d we get
5514 * cbd... if we scroll block c one line at a time to a, we get cdd...
5515 * vim expects cdd consistently... So we have to deal with that
5516 * here... (this also occurs scrolling the same way in the other
5517 * direction). */
5518
5519 nb = dest.Y + (source.Bottom - source.Top) + 1;
5520
5521 if (nb < source.Top)
5522 {
5523 COORD coord;
5524
5525 coord.X = 0;
5526 coord.Y = nb;
5527 clear_chars(coord, Columns * (source.Top - nb));
5528 }
5529}
5530
5531
5532/*
5533 * Set the cursor position
5534 */
5535 static void
5536gotoxy(
5537 unsigned x,
5538 unsigned y)
5539{
5540 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5541 return;
5542
5543 /* external cursor coords are 1-based; internal are 0-based */
5544 g_coord.X = x - 1;
5545 g_coord.Y = y - 1;
5546 SetConsoleCursorPosition(g_hConOut, g_coord);
5547}
5548
5549
5550/*
5551 * Set the current text attribute = (foreground | background)
5552 * See ../doc/os_win32.txt for the numbers.
5553 */
5554 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005555textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005557 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558
5559 SetConsoleTextAttribute(g_hConOut, wAttr);
5560}
5561
5562
5563 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005564textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005566 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567
5568 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5569}
5570
5571
5572 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005573textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005575 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005576
5577 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5578}
5579
5580
5581/*
5582 * restore the default text attribute (whatever we started with)
5583 */
5584 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005585normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586{
5587 textattr(g_attrDefault);
5588}
5589
5590
5591static WORD g_attrPreStandout = 0;
5592
5593/*
5594 * Make the text standout, by brightening it
5595 */
5596 static void
5597standout(void)
5598{
5599 g_attrPreStandout = g_attrCurrent;
5600 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5601}
5602
5603
5604/*
5605 * Turn off standout mode
5606 */
5607 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005608standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005609{
5610 if (g_attrPreStandout)
5611 {
5612 textattr(g_attrPreStandout);
5613 g_attrPreStandout = 0;
5614 }
5615}
5616
5617
5618/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005619 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 */
5621 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005622mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623{
5624 char_u *p;
5625 int n;
5626
5627 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5628 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5629 if (T_ME[0] == ESC && T_ME[1] == '|')
5630 {
5631 p = T_ME + 2;
5632 n = getdigits(&p);
5633 if (*p == 'm' && n > 0)
5634 {
5635 cterm_normal_fg_color = (n & 0xf) + 1;
5636 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5637 }
5638 }
5639}
5640
5641
5642/*
5643 * visual bell: flash the screen
5644 */
5645 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005646visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647{
5648 COORD coordOrigin = {0, 0};
5649 WORD attrFlash = ~g_attrCurrent & 0xff;
5650
5651 DWORD dwDummy;
5652 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5653
5654 if (oldattrs == NULL)
5655 return;
5656 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5657 coordOrigin, &dwDummy);
5658 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5659 coordOrigin, &dwDummy);
5660
5661 Sleep(15); /* wait for 15 msec */
5662 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5663 coordOrigin, &dwDummy);
5664 vim_free(oldattrs);
5665}
5666
5667
5668/*
5669 * Make the cursor visible or invisible
5670 */
5671 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005672cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673{
5674 s_cursor_visible = fVisible;
5675#ifdef MCH_CURSOR_SHAPE
5676 mch_update_cursor();
5677#endif
5678}
5679
5680
5681/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005682 * write `cbToWrite' bytes in `pchBuf' to the screen
5683 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005684 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005685 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005687 char_u *pchBuf,
5688 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689{
5690 COORD coord = g_coord;
5691 DWORD written;
5692
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005693#ifdef FEAT_MBYTE
5694 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5695 {
5696 static WCHAR *unicodebuf = NULL;
5697 static int unibuflen = 0;
5698 int length;
5699 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005701 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5702 if (unicodebuf == NULL || length > unibuflen)
5703 {
5704 vim_free(unicodebuf);
5705 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5706 unibuflen = length;
5707 }
5708 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5709 unicodebuf, unibuflen);
5710
5711 cells = mb_string2cells(pchBuf, cbToWrite);
5712 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5713 coord, &written);
5714 /* When writing fails or didn't write a single character, pretend one
5715 * character was written, otherwise we get stuck. */
5716 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5717 coord, &cchwritten) == 0
5718 || cchwritten == 0)
5719 cchwritten = 1;
5720
5721 if (cchwritten == length)
5722 {
5723 written = cbToWrite;
5724 g_coord.X += (SHORT)cells;
5725 }
5726 else
5727 {
5728 char_u *p = pchBuf;
5729 for (n = 0; n < cchwritten; n++)
5730 mb_cptr_adv(p);
5731 written = p - pchBuf;
5732 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5733 }
5734 }
5735 else
5736#endif
5737 {
5738 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
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 (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5743 coord, &written) == 0
5744 || written == 0)
5745 written = 1;
5746
5747 g_coord.X += (SHORT) written;
5748 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005749
5750 while (g_coord.X > g_srScrollRegion.Right)
5751 {
5752 g_coord.X -= (SHORT) Columns;
5753 if (g_coord.Y < g_srScrollRegion.Bottom)
5754 g_coord.Y++;
5755 }
5756
5757 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5758
5759 return written;
5760}
5761
5762
5763/*
5764 * mch_write(): write the output buffer to the screen, translating ESC
5765 * sequences into calls to console output routines.
5766 */
5767 void
5768mch_write(
5769 char_u *s,
5770 int len)
5771{
5772 s[len] = NUL;
5773
5774 if (!term_console)
5775 {
5776 write(1, s, (unsigned)len);
5777 return;
5778 }
5779
5780 /* translate ESC | sequences into faked bios calls */
5781 while (len--)
5782 {
5783 /* optimization: use one single write_chars for runs of text,
5784 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005785 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786
5787 if (p_wd)
5788 {
5789 WaitForChar(p_wd);
5790 if (prefix != 0)
5791 prefix = 1;
5792 }
5793
5794 if (prefix != 0)
5795 {
5796 DWORD nWritten;
5797
5798 nWritten = write_chars(s, prefix);
5799#ifdef MCH_WRITE_DUMP
5800 if (fdDump)
5801 {
5802 fputc('>', fdDump);
5803 fwrite(s, sizeof(char_u), nWritten, fdDump);
5804 fputs("<\n", fdDump);
5805 }
5806#endif
5807 len -= (nWritten - 1);
5808 s += nWritten;
5809 }
5810 else if (s[0] == '\n')
5811 {
5812 /* \n, newline: go to the beginning of the next line or scroll */
5813 if (g_coord.Y == g_srScrollRegion.Bottom)
5814 {
5815 scroll(1);
5816 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5817 }
5818 else
5819 {
5820 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5821 }
5822#ifdef MCH_WRITE_DUMP
5823 if (fdDump)
5824 fputs("\\n\n", fdDump);
5825#endif
5826 s++;
5827 }
5828 else if (s[0] == '\r')
5829 {
5830 /* \r, carriage return: go to beginning of line */
5831 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5832#ifdef MCH_WRITE_DUMP
5833 if (fdDump)
5834 fputs("\\r\n", fdDump);
5835#endif
5836 s++;
5837 }
5838 else if (s[0] == '\b')
5839 {
5840 /* \b, backspace: move cursor one position left */
5841 if (g_coord.X > g_srScrollRegion.Left)
5842 g_coord.X--;
5843 else if (g_coord.Y > g_srScrollRegion.Top)
5844 {
5845 g_coord.X = g_srScrollRegion.Right;
5846 g_coord.Y--;
5847 }
5848 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5849#ifdef MCH_WRITE_DUMP
5850 if (fdDump)
5851 fputs("\\b\n", fdDump);
5852#endif
5853 s++;
5854 }
5855 else if (s[0] == '\a')
5856 {
5857 /* \a, bell */
5858 MessageBeep(0xFFFFFFFF);
5859#ifdef MCH_WRITE_DUMP
5860 if (fdDump)
5861 fputs("\\a\n", fdDump);
5862#endif
5863 s++;
5864 }
5865 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5866 {
5867#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005868 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005870 char_u *p;
5871 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872
5873 switch (s[2])
5874 {
5875 /* one or two numeric arguments, separated by ';' */
5876
5877 case '0': case '1': case '2': case '3': case '4':
5878 case '5': case '6': case '7': case '8': case '9':
5879 p = s + 2;
5880 arg1 = getdigits(&p); /* no check for length! */
5881 if (p > s + len)
5882 break;
5883
5884 if (*p == ';')
5885 {
5886 ++p;
5887 arg2 = getdigits(&p); /* no check for length! */
5888 if (p > s + len)
5889 break;
5890
5891 if (*p == 'H')
5892 gotoxy(arg2, arg1);
5893 else if (*p == 'r')
5894 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5895 }
5896 else if (*p == 'A')
5897 {
5898 /* move cursor up arg1 lines in same column */
5899 gotoxy(g_coord.X + 1,
5900 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5901 }
5902 else if (*p == 'C')
5903 {
5904 /* move cursor right arg1 columns in same line */
5905 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5906 g_coord.Y + 1);
5907 }
5908 else if (*p == 'H')
5909 {
5910 gotoxy(1, arg1);
5911 }
5912 else if (*p == 'L')
5913 {
5914 insert_lines(arg1);
5915 }
5916 else if (*p == 'm')
5917 {
5918 if (arg1 == 0)
5919 normvideo();
5920 else
5921 textattr((WORD) arg1);
5922 }
5923 else if (*p == 'f')
5924 {
5925 textcolor((WORD) arg1);
5926 }
5927 else if (*p == 'b')
5928 {
5929 textbackground((WORD) arg1);
5930 }
5931 else if (*p == 'M')
5932 {
5933 delete_lines(arg1);
5934 }
5935
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005936 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937 s = p + 1;
5938 break;
5939
5940
5941 /* Three-character escape sequences */
5942
5943 case 'A':
5944 /* move cursor up one line in same column */
5945 gotoxy(g_coord.X + 1,
5946 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5947 goto got3;
5948
5949 case 'B':
5950 visual_bell();
5951 goto got3;
5952
5953 case 'C':
5954 /* move cursor right one column in same line */
5955 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5956 g_coord.Y + 1);
5957 goto got3;
5958
5959 case 'E':
5960 termcap_mode_end();
5961 goto got3;
5962
5963 case 'F':
5964 standout();
5965 goto got3;
5966
5967 case 'f':
5968 standend();
5969 goto got3;
5970
5971 case 'H':
5972 gotoxy(1, 1);
5973 goto got3;
5974
5975 case 'j':
5976 clear_to_end_of_display();
5977 goto got3;
5978
5979 case 'J':
5980 clear_screen();
5981 goto got3;
5982
5983 case 'K':
5984 clear_to_end_of_line();
5985 goto got3;
5986
5987 case 'L':
5988 insert_lines(1);
5989 goto got3;
5990
5991 case 'M':
5992 delete_lines(1);
5993 goto got3;
5994
5995 case 'S':
5996 termcap_mode_start();
5997 goto got3;
5998
5999 case 'V':
6000 cursor_visible(TRUE);
6001 goto got3;
6002
6003 case 'v':
6004 cursor_visible(FALSE);
6005 goto got3;
6006
6007 got3:
6008 s += 3;
6009 len -= 2;
6010 }
6011
6012#ifdef MCH_WRITE_DUMP
6013 if (fdDump)
6014 {
6015 fputs("ESC | ", fdDump);
6016 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6017 fputc('\n', fdDump);
6018 }
6019#endif
6020 }
6021 else
6022 {
6023 /* Write a single character */
6024 DWORD nWritten;
6025
6026 nWritten = write_chars(s, 1);
6027#ifdef MCH_WRITE_DUMP
6028 if (fdDump)
6029 {
6030 fputc('>', fdDump);
6031 fwrite(s, sizeof(char_u), nWritten, fdDump);
6032 fputs("<\n", fdDump);
6033 }
6034#endif
6035
6036 len -= (nWritten - 1);
6037 s += nWritten;
6038 }
6039 }
6040
6041#ifdef MCH_WRITE_DUMP
6042 if (fdDump)
6043 fflush(fdDump);
6044#endif
6045}
6046
6047#endif /* FEAT_GUI_W32 */
6048
6049
6050/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006051 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006053/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054 void
6055mch_delay(
6056 long msec,
6057 int ignoreinput)
6058{
6059#ifdef FEAT_GUI_W32
6060 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006061#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006063# ifdef FEAT_MZSCHEME
6064 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6065 {
6066 int towait = p_mzq;
6067
6068 /* if msec is large enough, wait by portions in p_mzq */
6069 while (msec > 0)
6070 {
6071 mzvim_check_threads();
6072 if (msec < towait)
6073 towait = msec;
6074 Sleep(towait);
6075 msec -= towait;
6076 }
6077 }
6078 else
6079# endif
6080 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081 else
6082 WaitForChar(msec);
6083#endif
6084}
6085
6086
6087/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006088 * This version of remove is not scared by a readonly (backup) file.
6089 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006090 * Return 0 for success, -1 for failure.
6091 */
6092 int
6093mch_remove(char_u *name)
6094{
6095#ifdef FEAT_MBYTE
6096 WCHAR *wn = NULL;
6097 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006098#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006099
Bram Moolenaar203258c2016-01-17 22:15:16 +01006100 /*
6101 * On Windows, deleting a directory's symbolic link is done by
6102 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6103 */
6104 if (mch_isdir(name) && mch_is_symbolic_link(name))
6105 return mch_rmdir(name);
6106
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006107 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6108
6109#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6111 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006112 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113 if (wn != NULL)
6114 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115 n = DeleteFileW(wn) ? 0 : -1;
6116 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006117 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118 }
6119 }
6120#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006121 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122}
6123
6124
6125/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006126 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127 */
6128 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006129mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130{
6131#ifndef FEAT_GUI_W32 /* never used */
6132 if (g_fCtrlCPressed || g_fCBrkPressed)
6133 {
6134 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6135 got_int = TRUE;
6136 }
6137#endif
6138}
6139
Bram Moolenaaree273972016-01-02 21:11:51 +01006140/* physical RAM to leave for the OS */
6141#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006142
6143/*
6144 * How much main memory in KiB that can be used by VIM.
6145 */
6146/*ARGSUSED*/
6147 long_u
6148mch_total_mem(int special)
6149{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006150 MEMORYSTATUSEX ms;
6151
Bram Moolenaaree273972016-01-02 21:11:51 +01006152 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006153 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6154 * what fits in 32 bits. But it's not always available. */
6155 ms.dwLength = sizeof(MEMORYSTATUSEX);
6156 GlobalMemoryStatusEx(&ms);
6157 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006158 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006159 /* Process address space fits in physical RAM, use all of it. */
6160 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006161 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006162 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006163 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006164 /* Catch old NT box or perverse hardware setup. */
6165 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006166 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006167 /* Use physical RAM less reserve for OS + data. */
6168 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006169}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170
Bram Moolenaar071d4272004-06-13 20:20:40 +00006171#ifdef FEAT_MBYTE
6172/*
6173 * Same code as below, but with wide functions and no comments.
6174 * Return 0 for success, non-zero for failure.
6175 */
6176 int
6177mch_wrename(WCHAR *wold, WCHAR *wnew)
6178{
6179 WCHAR *p;
6180 int i;
6181 WCHAR szTempFile[_MAX_PATH + 1];
6182 WCHAR szNewPath[_MAX_PATH + 1];
6183 HANDLE hf;
6184
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006185 p = wold;
6186 for (i = 0; wold[i] != NUL; ++i)
6187 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6188 && wold[i + 1] != 0)
6189 p = wold + i + 1;
6190 if ((int)(wold + i - p) < 8 || p[6] != '~')
6191 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006192
6193 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6194 return -1;
6195 *p = NUL;
6196
6197 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6198 return -2;
6199
6200 if (!DeleteFileW(szTempFile))
6201 return -3;
6202
6203 if (!MoveFileW(wold, szTempFile))
6204 return -4;
6205
6206 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6207 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6208 return -5;
6209 if (!CloseHandle(hf))
6210 return -6;
6211
6212 if (!MoveFileW(szTempFile, wnew))
6213 {
6214 (void)MoveFileW(szTempFile, wold);
6215 return -7;
6216 }
6217
6218 DeleteFileW(szTempFile);
6219
6220 if (!DeleteFileW(wold))
6221 return -8;
6222
6223 return 0;
6224}
6225#endif
6226
6227
6228/*
6229 * mch_rename() works around a bug in rename (aka MoveFile) in
6230 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6231 * file whose short file name is "FOO.BAR" (its long file name will
6232 * be correct: "foo.bar~"). Because a file can be accessed by
6233 * either its SFN or its LFN, "foo.bar" has effectively been
6234 * renamed to "foo.bar", which is not at all what was wanted. This
6235 * seems to happen only when renaming files with three-character
6236 * extensions by appending a suffix that does not include ".".
6237 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6238 *
6239 * There is another problem, which isn't really a bug but isn't right either:
6240 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6241 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6242 * service pack 6. Doesn't seem to happen on Windows 98.
6243 *
6244 * Like rename(), returns 0 upon success, non-zero upon failure.
6245 * Should probably set errno appropriately when errors occur.
6246 */
6247 int
6248mch_rename(
6249 const char *pszOldFile,
6250 const char *pszNewFile)
6251{
6252 char szTempFile[_MAX_PATH+1];
6253 char szNewPath[_MAX_PATH+1];
6254 char *pszFilePart;
6255 HANDLE hf;
6256#ifdef FEAT_MBYTE
6257 WCHAR *wold = NULL;
6258 WCHAR *wnew = NULL;
6259 int retval = -1;
6260
6261 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6262 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006263 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6264 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 if (wold != NULL && wnew != NULL)
6266 retval = mch_wrename(wold, wnew);
6267 vim_free(wold);
6268 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006269 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 }
6271#endif
6272
6273 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006274 * No need to play tricks unless the file name contains a "~" as the
6275 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006277 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6278 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6279 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280
6281 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6282 * a directory, no error is returned and pszFilePart will be NULL. */
6283 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6284 || pszFilePart == NULL)
6285 return -1;
6286 *pszFilePart = NUL;
6287
6288 /* Get (and create) a unique temporary file name in directory of new file */
6289 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6290 return -2;
6291
6292 /* blow the temp file away */
6293 if (!DeleteFile(szTempFile))
6294 return -3;
6295
6296 /* rename old file to the temp file */
6297 if (!MoveFile(pszOldFile, szTempFile))
6298 return -4;
6299
6300 /* now create an empty file called pszOldFile; this prevents the operating
6301 * system using pszOldFile as an alias (SFN) if we're renaming within the
6302 * same directory. For example, we're editing a file called
6303 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6304 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6305 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006306 * cause all sorts of problems later in buf_write(). So, we create an
6307 * empty file called filena~1.txt and the system will have to find some
6308 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 */
6310 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6311 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6312 return -5;
6313 if (!CloseHandle(hf))
6314 return -6;
6315
6316 /* rename the temp file to the new file */
6317 if (!MoveFile(szTempFile, pszNewFile))
6318 {
6319 /* Renaming failed. Rename the file back to its old name, so that it
6320 * looks like nothing happened. */
6321 (void)MoveFile(szTempFile, pszOldFile);
6322
6323 return -7;
6324 }
6325
6326 /* Seems to be left around on Novell filesystems */
6327 DeleteFile(szTempFile);
6328
6329 /* finally, remove the empty old file */
6330 if (!DeleteFile(pszOldFile))
6331 return -8;
6332
6333 return 0; /* success */
6334}
6335
6336/*
6337 * Get the default shell for the current hardware platform
6338 */
6339 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006340default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342 PlatformId();
6343
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006344 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345}
6346
6347/*
6348 * mch_access() extends access() to do more detailed check on network drives.
6349 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6350 */
6351 int
6352mch_access(char *n, int p)
6353{
6354 HANDLE hFile;
6355 DWORD am;
6356 int retval = -1; /* default: fail */
6357#ifdef FEAT_MBYTE
6358 WCHAR *wn = NULL;
6359
6360 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006361 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362#endif
6363
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006364 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365 {
6366 char TempName[_MAX_PATH + 16] = "";
6367#ifdef FEAT_MBYTE
6368 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6369#endif
6370
6371 if (p & R_OK)
6372 {
6373 /* Read check is performed by seeing if we can do a find file on
6374 * the directory for any file. */
6375#ifdef FEAT_MBYTE
6376 if (wn != NULL)
6377 {
6378 int i;
6379 WIN32_FIND_DATAW d;
6380
6381 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6382 TempNameW[i] = wn[i];
6383 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6384 TempNameW[i++] = '\\';
6385 TempNameW[i++] = '*';
6386 TempNameW[i++] = 0;
6387
6388 hFile = FindFirstFileW(TempNameW, &d);
6389 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006390 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391 else
6392 (void)FindClose(hFile);
6393 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006394 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395#endif
6396 {
6397 char *pch;
6398 WIN32_FIND_DATA d;
6399
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006400 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006401 pch = TempName + STRLEN(TempName) - 1;
6402 if (*pch != '\\' && *pch != '/')
6403 *++pch = '\\';
6404 *++pch = '*';
6405 *++pch = NUL;
6406
6407 hFile = FindFirstFile(TempName, &d);
6408 if (hFile == INVALID_HANDLE_VALUE)
6409 goto getout;
6410 (void)FindClose(hFile);
6411 }
6412 }
6413
6414 if (p & W_OK)
6415 {
6416 /* Trying to create a temporary file in the directory should catch
6417 * directories on read-only network shares. However, in
6418 * directories whose ACL allows writes but denies deletes will end
6419 * up keeping the temporary file :-(. */
6420#ifdef FEAT_MBYTE
6421 if (wn != NULL)
6422 {
6423 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006424 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 else
6426 DeleteFileW(TempNameW);
6427 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006428 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429#endif
6430 {
6431 if (!GetTempFileName(n, "VIM", 0, TempName))
6432 goto getout;
6433 mch_remove((char_u *)TempName);
6434 }
6435 }
6436 }
6437 else
6438 {
6439 /* Trying to open the file for the required access does ACL, read-only
6440 * network share, and file attribute checks. */
6441 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6442 | ((p & R_OK) ? GENERIC_READ : 0);
6443#ifdef FEAT_MBYTE
6444 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006445 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006446 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006447#endif
6448 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6449 if (hFile == INVALID_HANDLE_VALUE)
6450 goto getout;
6451 CloseHandle(hFile);
6452 }
6453
6454 retval = 0; /* success */
6455getout:
6456#ifdef FEAT_MBYTE
6457 vim_free(wn);
6458#endif
6459 return retval;
6460}
6461
6462#if defined(FEAT_MBYTE) || defined(PROTO)
6463/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006464 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006465 */
6466 int
6467mch_open(char *name, int flags, int mode)
6468{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006469 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6470# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471 WCHAR *wn;
6472 int f;
6473
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006474 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006476 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477 if (wn != NULL)
6478 {
6479 f = _wopen(wn, flags, mode);
6480 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006481 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482 }
6483 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006484# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006486 /* open() can open a file which name is longer than _MAX_PATH bytes
6487 * and shorter than _MAX_PATH characters successfully, but sometimes it
6488 * causes unexpected error in another part. We make it an error explicitly
6489 * here. */
6490 if (strlen(name) >= _MAX_PATH)
6491 return -1;
6492
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493 return open(name, flags, mode);
6494}
6495
6496/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006497 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 */
6499 FILE *
6500mch_fopen(char *name, char *mode)
6501{
6502 WCHAR *wn, *wm;
6503 FILE *f = NULL;
6504
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006505 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006507# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006508 /* Work around an annoying assertion in the Microsoft debug CRT
6509 * when mode's text/binary setting doesn't match _get_fmode(). */
6510 char newMode = mode[strlen(mode) - 1];
6511 int oldMode = 0;
6512
6513 _get_fmode(&oldMode);
6514 if (newMode == 't')
6515 _set_fmode(_O_TEXT);
6516 else if (newMode == 'b')
6517 _set_fmode(_O_BINARY);
6518# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006519 wn = enc_to_utf16((char_u *)name, NULL);
6520 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 if (wn != NULL && wm != NULL)
6522 f = _wfopen(wn, wm);
6523 vim_free(wn);
6524 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006525
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006526# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006527 _set_fmode(oldMode);
6528# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006529 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 }
6531
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006532 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6533 * and shorter than _MAX_PATH characters successfully, but sometimes it
6534 * causes unexpected error in another part. We make it an error explicitly
6535 * here. */
6536 if (strlen(name) >= _MAX_PATH)
6537 return NULL;
6538
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 return fopen(name, mode);
6540}
6541#endif
6542
6543#ifdef FEAT_MBYTE
6544/*
6545 * SUB STREAM (aka info stream) handling:
6546 *
6547 * NTFS can have sub streams for each file. Normal contents of file is
6548 * stored in the main stream, and extra contents (author information and
6549 * title and so on) can be stored in sub stream. After Windows 2000, user
6550 * can access and store those informations in sub streams via explorer's
6551 * property menuitem in right click menu. Those informations in sub streams
6552 * were lost when copying only the main stream. So we have to copy sub
6553 * streams.
6554 *
6555 * Incomplete explanation:
6556 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6557 * More useful info and an example:
6558 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6559 */
6560
6561/*
6562 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6563 * and write to stream "substream" of file "to".
6564 * Errors are ignored.
6565 */
6566 static void
6567copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6568{
6569 HANDLE hTo;
6570 WCHAR *to_name;
6571
6572 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6573 wcscpy(to_name, to);
6574 wcscat(to_name, substream);
6575
6576 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6577 FILE_ATTRIBUTE_NORMAL, NULL);
6578 if (hTo != INVALID_HANDLE_VALUE)
6579 {
6580 long done;
6581 DWORD todo;
6582 DWORD readcnt, written;
6583 char buf[4096];
6584
6585 /* Copy block of bytes at a time. Abort when something goes wrong. */
6586 for (done = 0; done < len; done += written)
6587 {
6588 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006589 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6590 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6592 FALSE, FALSE, context)
6593 || readcnt != todo
6594 || !WriteFile(hTo, buf, todo, &written, NULL)
6595 || written != todo)
6596 break;
6597 }
6598 CloseHandle(hTo);
6599 }
6600
6601 free(to_name);
6602}
6603
6604/*
6605 * Copy info streams from file "from" to file "to".
6606 */
6607 static void
6608copy_infostreams(char_u *from, char_u *to)
6609{
6610 WCHAR *fromw;
6611 WCHAR *tow;
6612 HANDLE sh;
6613 WIN32_STREAM_ID sid;
6614 int headersize;
6615 WCHAR streamname[_MAX_PATH];
6616 DWORD readcount;
6617 void *context = NULL;
6618 DWORD lo, hi;
6619 int len;
6620
6621 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006622 fromw = enc_to_utf16(from, NULL);
6623 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624 if (fromw != NULL && tow != NULL)
6625 {
6626 /* Open the file for reading. */
6627 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6628 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6629 if (sh != INVALID_HANDLE_VALUE)
6630 {
6631 /* Use BackupRead() to find the info streams. Repeat until we
6632 * have done them all.*/
6633 for (;;)
6634 {
6635 /* Get the header to find the length of the stream name. If
6636 * the "readcount" is zero we have done all info streams. */
6637 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006638 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6640 &readcount, FALSE, FALSE, &context)
6641 || readcount == 0)
6642 break;
6643
6644 /* We only deal with streams that have a name. The normal
6645 * file data appears to be without a name, even though docs
6646 * suggest it is called "::$DATA". */
6647 if (sid.dwStreamNameSize > 0)
6648 {
6649 /* Read the stream name. */
6650 if (!BackupRead(sh, (LPBYTE)streamname,
6651 sid.dwStreamNameSize,
6652 &readcount, FALSE, FALSE, &context))
6653 break;
6654
6655 /* Copy an info stream with a name ":anything:$DATA".
6656 * Skip "::$DATA", it has no stream name (examples suggest
6657 * it might be used for the normal file contents).
6658 * Note that BackupRead() counts bytes, but the name is in
6659 * wide characters. */
6660 len = readcount / sizeof(WCHAR);
6661 streamname[len] = 0;
6662 if (len > 7 && wcsicmp(streamname + len - 6,
6663 L":$DATA") == 0)
6664 {
6665 streamname[len - 6] = 0;
6666 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006667 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 }
6669 }
6670
6671 /* Advance to the next stream. We might try seeking too far,
6672 * but BackupSeek() doesn't skip over stream borders, thus
6673 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006674 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675 &lo, &hi, &context);
6676 }
6677
6678 /* Clear the context. */
6679 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6680
6681 CloseHandle(sh);
6682 }
6683 }
6684 vim_free(fromw);
6685 vim_free(tow);
6686}
6687#endif
6688
6689/*
6690 * Copy file attributes from file "from" to file "to".
6691 * For Windows NT and later we copy info streams.
6692 * Always returns zero, errors are ignored.
6693 */
6694 int
6695mch_copy_file_attribute(char_u *from, char_u *to)
6696{
6697#ifdef FEAT_MBYTE
6698 /* File streams only work on Windows NT and later. */
6699 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006700 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701#endif
6702 return 0;
6703}
6704
6705#if defined(MYRESETSTKOFLW) || defined(PROTO)
6706/*
6707 * Recreate a destroyed stack guard page in win32.
6708 * Written by Benjamin Peterson.
6709 */
6710
6711/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712#define MIN_STACK_WINNT 2
6713
6714/*
6715 * This function does the same thing as _resetstkoflw(), which is only
6716 * available in DevStudio .net and later.
6717 * Returns 0 for failure, 1 for success.
6718 */
6719 int
6720myresetstkoflw(void)
6721{
6722 BYTE *pStackPtr;
6723 BYTE *pGuardPage;
6724 BYTE *pStackBase;
6725 BYTE *pLowestPossiblePage;
6726 MEMORY_BASIC_INFORMATION mbi;
6727 SYSTEM_INFO si;
6728 DWORD nPageSize;
6729 DWORD dummy;
6730
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732
6733 /* We need to know the system page size. */
6734 GetSystemInfo(&si);
6735 nPageSize = si.dwPageSize;
6736
6737 /* ...and the current stack pointer */
6738 pStackPtr = (BYTE*)_alloca(1);
6739
6740 /* ...and the base of the stack. */
6741 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6742 return 0;
6743 pStackBase = (BYTE*)mbi.AllocationBase;
6744
6745 /* ...and the page thats min_stack_req pages away from stack base; this is
6746 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006747 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006750 /* We want the first committed page in the stack Start at the stack
6751 * base and move forward through memory until we find a committed block.
6752 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753 BYTE *pBlock = pStackBase;
6754
Bram Moolenaara466c992005-07-09 21:03:22 +00006755 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756 {
6757 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6758 return 0;
6759
6760 pBlock += mbi.RegionSize;
6761
6762 if (mbi.State & MEM_COMMIT)
6763 break;
6764 }
6765
6766 /* mbi now describes the first committed block in the stack. */
6767 if (mbi.Protect & PAGE_GUARD)
6768 return 1;
6769
6770 /* decide where the guard page should start */
6771 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6772 pGuardPage = pLowestPossiblePage;
6773 else
6774 pGuardPage = (BYTE*)mbi.BaseAddress;
6775
6776 /* allocate the guard page */
6777 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6778 return 0;
6779
6780 /* apply the guard attribute to the page */
6781 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6782 &dummy))
6783 return 0;
6784 }
6785
6786 return 1;
6787}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006788#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006790
6791#if defined(FEAT_MBYTE) || defined(PROTO)
6792/*
6793 * The command line arguments in UCS2
6794 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006795static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006796static LPWSTR *ArglistW = NULL;
6797static int global_argc = 0;
6798static char **global_argv;
6799
6800static int used_file_argc = 0; /* last argument in global_argv[] used
6801 for the argument list. */
6802static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6803 command line arguments added to
6804 the argument list */
6805static int used_file_count = 0; /* nr of entries in used_file_indexes */
6806static int used_file_literal = FALSE; /* take file names literally */
6807static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006808static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006809static int used_alist_count = 0;
6810
6811
6812/*
6813 * Get the command line arguments. Unicode version.
6814 * Returns argc. Zero when something fails.
6815 */
6816 int
6817get_cmd_argsW(char ***argvp)
6818{
6819 char **argv = NULL;
6820 int argc = 0;
6821 int i;
6822
Bram Moolenaar14993322014-09-09 12:25:33 +02006823 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006824 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6825 if (ArglistW != NULL)
6826 {
6827 argv = malloc((nArgsW + 1) * sizeof(char *));
6828 if (argv != NULL)
6829 {
6830 argc = nArgsW;
6831 argv[argc] = NULL;
6832 for (i = 0; i < argc; ++i)
6833 {
6834 int len;
6835
6836 /* Convert each Unicode argument to the current codepage. */
6837 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006838 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006839 (LPSTR *)&argv[i], &len, 0, 0);
6840 if (argv[i] == NULL)
6841 {
6842 /* Out of memory, clear everything. */
6843 while (i > 0)
6844 free(argv[--i]);
6845 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006846 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006847 argc = 0;
6848 }
6849 }
6850 }
6851 }
6852
6853 global_argc = argc;
6854 global_argv = argv;
6855 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006856 {
6857 if (used_file_indexes != NULL)
6858 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006859 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006860 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006861
6862 if (argvp != NULL)
6863 *argvp = argv;
6864 return argc;
6865}
6866
6867 void
6868free_cmd_argsW(void)
6869{
6870 if (ArglistW != NULL)
6871 {
6872 GlobalFree(ArglistW);
6873 ArglistW = NULL;
6874 }
6875}
6876
6877/*
6878 * Remember "name" is an argument that was added to the argument list.
6879 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6880 * is called.
6881 */
6882 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006883used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006884{
6885 int i;
6886
6887 if (used_file_indexes == NULL)
6888 return;
6889 for (i = used_file_argc + 1; i < global_argc; ++i)
6890 if (STRCMP(global_argv[i], name) == 0)
6891 {
6892 used_file_argc = i;
6893 used_file_indexes[used_file_count++] = i;
6894 break;
6895 }
6896 used_file_literal = literal;
6897 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006898 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006899}
6900
6901/*
6902 * Remember the length of the argument list as it was. If it changes then we
6903 * leave it alone when 'encoding' is set.
6904 */
6905 void
6906set_alist_count(void)
6907{
6908 used_alist_count = GARGCOUNT;
6909}
6910
6911/*
6912 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6913 * has been changed while starting up. Use the UCS-2 command line arguments
6914 * and convert them to 'encoding'.
6915 */
6916 void
6917fix_arg_enc(void)
6918{
6919 int i;
6920 int idx;
6921 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006922 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006923
6924 /* Safety checks:
6925 * - if argument count differs between the wide and non-wide argument
6926 * list, something must be wrong.
6927 * - the file name arguments must have been located.
6928 * - the length of the argument list wasn't changed by the user.
6929 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006930 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006931 || ArglistW == NULL
6932 || used_file_indexes == NULL
6933 || used_file_count == 0
6934 || used_alist_count != GARGCOUNT)
6935 return;
6936
Bram Moolenaar86b68352004-12-27 21:59:20 +00006937 /* Remember the buffer numbers for the arguments. */
6938 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6939 if (fnum_list == NULL)
6940 return; /* out of memory */
6941 for (i = 0; i < GARGCOUNT; ++i)
6942 fnum_list[i] = GARGLIST[i].ae_fnum;
6943
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006944 /* Clear the argument list. Make room for the new arguments. */
6945 alist_clear(&global_alist);
6946 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006947 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006948
6949 for (i = 0; i < used_file_count; ++i)
6950 {
6951 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006952 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006953 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006954 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006955#ifdef FEAT_DIFF
6956 /* When using diff mode may need to concatenate file name to
6957 * directory name. Just like it's done in main(). */
6958 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6959 && !mch_isdir(alist_name(&GARGLIST[0])))
6960 {
6961 char_u *r;
6962
6963 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6964 if (r != NULL)
6965 {
6966 vim_free(str);
6967 str = r;
6968 }
6969 }
6970#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006971 /* Re-use the old buffer by renaming it. When not using literal
6972 * names it's done by alist_expand() below. */
6973 if (used_file_literal)
6974 buf_set_name(fnum_list[i], str);
6975
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006976 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006977 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006978 }
6979
6980 if (!used_file_literal)
6981 {
6982 /* Now expand wildcards in the arguments. */
6983 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6984 * filename characters but are excluded from 'isfname' to make
6985 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6986 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006987 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006988 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6989 }
6990
6991 /* If wildcard expansion failed, we are editing the first file of the
6992 * arglist and there is no file name: Edit the first argument now. */
6993 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6994 {
6995 do_cmdline_cmd((char_u *)":rewind");
6996 if (GARGCOUNT == 1 && used_file_full_path)
6997 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6998 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006999
7000 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007001}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007003
7004 int
7005mch_setenv(char *var, char *value, int x)
7006{
7007 char_u *envbuf;
7008
7009 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7010 if (envbuf == NULL)
7011 return -1;
7012
7013 sprintf((char *)envbuf, "%s=%s", var, value);
7014
7015#ifdef FEAT_MBYTE
7016 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7017 {
7018 WCHAR *p = enc_to_utf16(envbuf, NULL);
7019
7020 vim_free(envbuf);
7021 if (p == NULL)
7022 return -1;
7023 _wputenv(p);
7024# ifdef libintl_wputenv
7025 libintl_wputenv(p);
7026# endif
7027 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7028 vim_free(p);
7029 }
7030 else
7031#endif
7032 {
7033 _putenv((char *)envbuf);
7034# ifdef libintl_putenv
7035 libintl_putenv((char *)envbuf);
7036# endif
7037 /* Unlike Un*x systems, we can free the string for _putenv(). */
7038 vim_free(envbuf);
7039 }
7040
7041 return 0;
7042}