blob: d3cab022348da4c36c2a6daaad80e03770d38e18 [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;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149#if defined(__BORLANDC__)
150/* Strangely Borland uses a non-standard name. */
151# define wcsicmp(a, b) wcscmpi((a), (b))
152#endif
153
154#ifndef FEAT_GUI_W32
155/* Win32 Console handles for input and output */
156static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
157static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
158
159/* Win32 Screen buffer,coordinate,console I/O information */
160static SMALL_RECT g_srScrollRegion;
161static COORD g_coord; /* 0-based, but external coords are 1-based */
162
163/* The attribute of the screen when the editor was started */
164static WORD g_attrDefault = 7; /* lightgray text on black background */
165static WORD g_attrCurrent;
166
167static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
168static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
169static int g_fForceExit = FALSE; /* set when forcefully exiting */
170
171static void termcap_mode_start(void);
172static void termcap_mode_end(void);
173static void clear_chars(COORD coord, DWORD n);
174static void clear_screen(void);
175static void clear_to_end_of_display(void);
176static void clear_to_end_of_line(void);
177static void scroll(unsigned cLines);
178static void set_scroll_region(unsigned left, unsigned top,
179 unsigned right, unsigned bottom);
180static void insert_lines(unsigned cLines);
181static void delete_lines(unsigned cLines);
182static void gotoxy(unsigned x, unsigned y);
183static void normvideo(void);
184static void textattr(WORD wAttr);
185static void textcolor(WORD wAttr);
186static void textbackground(WORD wAttr);
187static void standout(void);
188static void standend(void);
189static void visual_bell(void);
190static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200191static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000192static void create_conin(void);
193static int s_cursor_visible = TRUE;
194static int did_create_conin = FALSE;
195#else
196static int s_dont_use_vimrun = TRUE;
197static int need_vimrun_warning = FALSE;
198static char *vimrun_path = "vimrun ";
199#endif
200
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200201static int win32_getattrs(char_u *name);
202static int win32_setattrs(char_u *name, int attrs);
203static int win32_set_archive(char_u *name);
204
Bram Moolenaar071d4272004-06-13 20:20:40 +0000205#ifndef FEAT_GUI_W32
206static int suppress_winsize = 1; /* don't fiddle with console */
207#endif
208
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200209static char_u *exe_path = NULL;
210
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100211static BOOL win8_or_later = FALSE;
212
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100213#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100214/*
215 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100216 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100217 */
218 static BOOL
219read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100220 HANDLE hInput,
221 INPUT_RECORD *lpBuffer,
222 DWORD nLength,
223 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100224{
225 enum
226 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100227 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100228 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100229 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100230 static DWORD s_dwIndex = 0;
231 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100232 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100233 int head;
234 int tail;
235 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100236
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200237 if (nLength == -2)
238 return (s_dwMax > 0) ? TRUE : FALSE;
239
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100240 if (!win8_or_later)
241 {
242 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200243 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
244 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100245 }
246
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100247 if (s_dwMax == 0)
248 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100249 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200250 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
251 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100252 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100253 s_dwIndex = 0;
254 s_dwMax = dwEvents;
255 if (dwEvents == 0)
256 {
257 *lpEvents = 0;
258 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100259 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100260
261 if (s_dwMax > 1)
262 {
263 head = 0;
264 tail = s_dwMax - 1;
265 while (head != tail)
266 {
267 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
268 && s_irCache[head + 1].EventType
269 == WINDOW_BUFFER_SIZE_EVENT)
270 {
271 /* Remove duplicate event to avoid flicker. */
272 for (i = head; i < tail; ++i)
273 s_irCache[i] = s_irCache[i + 1];
274 --tail;
275 continue;
276 }
277 head++;
278 }
279 s_dwMax = tail + 1;
280 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100281 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100282
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100283 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200284 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100286 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100287 return TRUE;
288}
289
290/*
291 * Version of PeekConsoleInput() that works with IME.
292 */
293 static BOOL
294peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 HANDLE hInput,
296 INPUT_RECORD *lpBuffer,
297 DWORD nLength,
298 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301}
302
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100303# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200304 static DWORD
305msg_wait_for_multiple_objects(
306 DWORD nCount,
307 LPHANDLE pHandles,
308 BOOL fWaitAll,
309 DWORD dwMilliseconds,
310 DWORD dwWakeMask)
311{
312 if (read_console_input(NULL, NULL, -2, NULL))
313 return WAIT_OBJECT_0;
314 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
315 dwMilliseconds, dwWakeMask);
316}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100317# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200318
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100319# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200320 static DWORD
321wait_for_single_object(
322 HANDLE hHandle,
323 DWORD dwMilliseconds)
324{
325 if (read_console_input(NULL, NULL, -2, NULL))
326 return WAIT_OBJECT_0;
327 return WaitForSingleObject(hHandle, dwMilliseconds);
328}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100329# endif
330#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200331
Bram Moolenaar071d4272004-06-13 20:20:40 +0000332 static void
333get_exe_name(void)
334{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100335 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
336 * as the maximum length that works (plus a NUL byte). */
337#define MAX_ENV_PATH_LEN 8192
338 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200339 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340
341 if (exe_name == NULL)
342 {
343 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100344 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000345 if (*temp != NUL)
346 exe_name = FullName_save((char_u *)temp, FALSE);
347 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000348
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200349 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000350 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200351 exe_path = vim_strnsave(exe_name,
352 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200353 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000354 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200355 /* Append our starting directory to $PATH, so that when doing
356 * "!xxd" it's found in our starting directory. Needed because
357 * SearchPath() also looks there. */
358 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100359 if (p == NULL
360 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200361 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100362 if (p == NULL || *p == NUL)
363 temp[0] = NUL;
364 else
365 {
366 STRCPY(temp, p);
367 STRCAT(temp, ";");
368 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200369 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100370 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200371 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000372 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000373 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000374}
375
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200376/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100377 * Unescape characters in "p" that appear in "escaped".
378 */
379 static void
380unescape_shellxquote(char_u *p, char_u *escaped)
381{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100382 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100383 int n;
384
385 while (*p != NUL)
386 {
387 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
388 mch_memmove(p, p + 1, l--);
389#ifdef FEAT_MBYTE
390 n = (*mb_ptr2len)(p);
391#else
392 n = 1;
393#endif
394 p += n;
395 l -= n;
396 }
397}
398
399/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200400 * Load library "name".
401 */
402 HINSTANCE
403vimLoadLib(char *name)
404{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200405 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200406
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200407 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
408 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200409 if (exe_path == NULL)
410 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200411 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200412 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200413 WCHAR old_dirw[MAXPATHL];
414
415 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
416 {
417 /* Change directory to where the executable is, both to make
418 * sure we find a .dll there and to avoid looking for a .dll
419 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100420 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200421 dll = LoadLibrary(name);
422 SetCurrentDirectoryW(old_dirw);
423 return dll;
424 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200425 }
426 return dll;
427}
428
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100429#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
430/*
431 * Get related information about 'funcname' which is imported by 'hInst'.
432 * If 'info' is 0, return the function address.
433 * If 'info' is 1, return the module name which the function is imported from.
434 */
435 static void *
436get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
437{
438 PBYTE pImage = (PBYTE)hInst;
439 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
440 PIMAGE_NT_HEADERS pPE;
441 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
442 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
443 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
444 PIMAGE_IMPORT_BY_NAME pImpName;
445
446 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
447 return NULL;
448 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
449 if (pPE->Signature != IMAGE_NT_SIGNATURE)
450 return NULL;
451 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
452 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
453 .VirtualAddress);
454 for (; pImpDesc->FirstThunk; ++pImpDesc)
455 {
456 if (!pImpDesc->OriginalFirstThunk)
457 continue;
458 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
459 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
460 for (; pIAT->u1.Function; ++pIAT, ++pINT)
461 {
462 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
463 continue;
464 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
465 + (UINT_PTR)(pINT->u1.AddressOfData));
466 if (strcmp((char *)pImpName->Name, funcname) == 0)
467 {
468 switch (info)
469 {
470 case 0:
471 return (void *)pIAT->u1.Function;
472 case 1:
473 return (void *)(pImage + pImpDesc->Name);
474 default:
475 return NULL;
476 }
477 }
478 }
479 }
480 return NULL;
481}
482
483/*
484 * Get the module handle which 'funcname' in 'hInst' is imported from.
485 */
486 HINSTANCE
487find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
488{
489 char *modulename;
490
491 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
492 if (modulename != NULL)
493 return GetModuleHandleA(modulename);
494 return NULL;
495}
496
497/*
498 * Get the address of 'funcname' which is imported by 'hInst' DLL.
499 */
500 void *
501get_dll_import_func(HINSTANCE hInst, const char *funcname)
502{
503 return get_imported_func_info(hInst, funcname, 0);
504}
505#endif
506
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
508# ifndef GETTEXT_DLL
509# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100510# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200512/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000513static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200514static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000515static char *null_libintl_textdomain(const char *);
516static char *null_libintl_bindtextdomain(const char *, const char *);
517static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100518static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100519static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200521static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000522char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200523char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
524 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000525char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
526char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000527 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000528char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
529 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100530int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100531int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532
533 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100534dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535{
536 int i;
537 static struct
538 {
539 char *name;
540 FARPROC *ptr;
541 } libintl_entry[] =
542 {
543 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200544 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000545 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
546 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
547 {NULL, NULL}
548 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100549 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000550
551 /* No need to initialize twice. */
552 if (hLibintlDLL)
553 return 1;
554 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100555 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100556#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100557 if (!hLibintlDLL)
558 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100559#endif
560 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200562 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000563 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200564 verbose_enter();
565 EMSG2(_(e_loadlib), GETTEXT_DLL);
566 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000567 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200568 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569 }
570 for (i = 0; libintl_entry[i].name != NULL
571 && libintl_entry[i].ptr != NULL; ++i)
572 {
573 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
574 libintl_entry[i].name)) == NULL)
575 {
576 dyn_libintl_end();
577 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000578 {
579 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000580 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000581 verbose_leave();
582 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000583 return 0;
584 }
585 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000586
587 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000588 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000589 "bind_textdomain_codeset");
590 if (dyn_libintl_bind_textdomain_codeset == NULL)
591 dyn_libintl_bind_textdomain_codeset =
592 null_libintl_bind_textdomain_codeset;
593
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100594 /* _putenv() function for the libintl.dll is optional. */
595 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
596 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100597 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100598 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100599 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
600 }
601 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100602 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100603 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
604 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100605
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606 return 1;
607}
608
609 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100610dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611{
612 if (hLibintlDLL)
613 FreeLibrary(hLibintlDLL);
614 hLibintlDLL = NULL;
615 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200616 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617 dyn_libintl_textdomain = null_libintl_textdomain;
618 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000619 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100620 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100621 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622}
623
624 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
630 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200631null_libintl_ngettext(
632 const char *msgid,
633 const char *msgid_plural,
634 unsigned long n)
635{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200636 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200637}
638
Bram Moolenaaree695f72016-08-03 22:08:45 +0200639 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100640null_libintl_bindtextdomain(
641 const char *domainname UNUSED,
642 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643{
644 return NULL;
645}
646
647 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100648null_libintl_bind_textdomain_codeset(
649 const char *domainname UNUSED,
650 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000651{
652 return NULL;
653}
654
655 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100656null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657{
658 return NULL;
659}
660
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200661 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100662null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100663{
664 return 0;
665}
666
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200667 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100668null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100669{
670 return 0;
671}
672
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673#endif /* DYNAMIC_GETTEXT */
674
675/* This symbol is not defined in older versions of the SDK or Visual C++ */
676
677#ifndef VER_PLATFORM_WIN32_WINDOWS
678# define VER_PLATFORM_WIN32_WINDOWS 1
679#endif
680
681DWORD g_PlatformId;
682
683#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100684# ifndef PROTO
685# include <aclapi.h>
686# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200687# ifndef PROTECTED_DACL_SECURITY_INFORMATION
688# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
689# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690#endif
691
Bram Moolenaar27515922013-06-29 15:36:26 +0200692#ifdef HAVE_ACL
693/*
694 * Enables or disables the specified privilege.
695 */
696 static BOOL
697win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
698{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100699 BOOL bResult;
700 LUID luid;
701 HANDLE hToken;
702 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200703
704 if (!OpenProcessToken(GetCurrentProcess(),
705 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
706 return FALSE;
707
708 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
709 {
710 CloseHandle(hToken);
711 return FALSE;
712 }
713
Bram Moolenaar45500912014-07-09 20:51:07 +0200714 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200715 tokenPrivileges.Privileges[0].Luid = luid;
716 tokenPrivileges.Privileges[0].Attributes = bEnable ?
717 SE_PRIVILEGE_ENABLED : 0;
718
719 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
720 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
721
722 CloseHandle(hToken);
723
724 return bResult && GetLastError() == ERROR_SUCCESS;
725}
726#endif
727
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728/*
729 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
730 * VER_PLATFORM_WIN32_WINDOWS (Win95).
731 */
732 void
733PlatformId(void)
734{
735 static int done = FALSE;
736
737 if (!done)
738 {
739 OSVERSIONINFO ovi;
740
741 ovi.dwOSVersionInfoSize = sizeof(ovi);
742 GetVersionEx(&ovi);
743
744 g_PlatformId = ovi.dwPlatformId;
745
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100746 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
747 || ovi.dwMajorVersion > 6)
748 win8_or_later = TRUE;
749
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200751 /* Enable privilege for getting or setting SACLs. */
752 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000753#endif
754 done = TRUE;
755 }
756}
757
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758#ifndef FEAT_GUI_W32
759
760#define SHIFT (SHIFT_PRESSED)
761#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
762#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
763#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
764
765
766/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
767 * We map function keys to their ANSI terminal equivalents, as produced
768 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
769 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
770 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
771 * combinations of function/arrow/etc keys.
772 */
773
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000774static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775{
776 WORD wVirtKey;
777 BOOL fAnsiKey;
778 int chAlone;
779 int chShift;
780 int chCtrl;
781 int chAlt;
782} VirtKeyMap[] =
783{
784
785/* Key ANSI alone shift ctrl alt */
786 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
787
788 { VK_F1, TRUE, ';', 'T', '^', 'h', },
789 { VK_F2, TRUE, '<', 'U', '_', 'i', },
790 { VK_F3, TRUE, '=', 'V', '`', 'j', },
791 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
792 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
793 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
794 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
795 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
796 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
797 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
798 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
799 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
800
801 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
802 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
803 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
804 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
805 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
806 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
807 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
808 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
809 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
810 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
811
812 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
813
814#if 0
815 /* Most people don't have F13-F20, but what the hell... */
816 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
817 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
818 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
819 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
820 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
821 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
822 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
823 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
824#endif
825 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
826 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
827 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
828 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
829
830 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
831 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
832 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
833 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
834 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
835 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
836 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
837 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
838 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
839 /* Sorry, out of number space! <negri>*/
840 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
841
842};
843
844
845#ifdef _MSC_VER
846// The ToAscii bug destroys several registers. Need to turn off optimization
847// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000848# pragma warning(push)
849# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850# pragma optimize("", off)
851#endif
852
853#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200854# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200856# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000857#endif
858
859/* The return code indicates key code size. */
860 static int
861#ifdef __BORLANDC__
862 __stdcall
863#endif
864win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000865 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866{
867 UINT uMods = pker->dwControlKeyState;
868 static int s_iIsDead = 0;
869 static WORD awAnsiCode[2];
870 static BYTE abKeystate[256];
871
872
873 if (s_iIsDead == 2)
874 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200875 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876 s_iIsDead = 0;
877 return 1;
878 }
879
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200880 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881 return 1;
882
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200883 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000884
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200886 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887
888 if (uMods & SHIFT_PRESSED)
889 abKeystate[VK_SHIFT] = 0x80;
890 if (uMods & CAPSLOCK_ON)
891 abKeystate[VK_CAPITAL] = 1;
892
893 if ((uMods & ALT_GR) == ALT_GR)
894 {
895 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
896 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
897 }
898
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200899 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
900 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901
902 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200903 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904
905 return s_iIsDead;
906}
907
908#ifdef _MSC_VER
909/* MUST switch optimization on again here, otherwise a call to
910 * decode_key_event() may crash (e.g. when hitting caps-lock) */
911# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000912# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
914# if (_MSC_VER < 1100)
915/* MUST turn off global optimisation for this next function, or
916 * pressing ctrl-minus in insert mode crashes Vim when built with
917 * VC4.1. -- negri. */
918# pragma optimize("g", off)
919# endif
920#endif
921
922static BOOL g_fJustGotFocus = FALSE;
923
924/*
925 * Decode a KEY_EVENT into one or two keystrokes
926 */
927 static BOOL
928decode_key_event(
929 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200930 WCHAR *pch,
931 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932 int *pmodifiers,
933 BOOL fDoPost)
934{
935 int i;
936 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
937
938 *pch = *pch2 = NUL;
939 g_fJustGotFocus = FALSE;
940
941 /* ignore key up events */
942 if (!pker->bKeyDown)
943 return FALSE;
944
945 /* ignore some keystrokes */
946 switch (pker->wVirtualKeyCode)
947 {
948 /* modifiers */
949 case VK_SHIFT:
950 case VK_CONTROL:
951 case VK_MENU: /* Alt key */
952 return FALSE;
953
954 default:
955 break;
956 }
957
958 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200959 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 {
961 /* Ctrl-6 is Ctrl-^ */
962 if (pker->wVirtualKeyCode == '6')
963 {
964 *pch = Ctrl_HAT;
965 return TRUE;
966 }
967 /* Ctrl-2 is Ctrl-@ */
968 else if (pker->wVirtualKeyCode == '2')
969 {
970 *pch = NUL;
971 return TRUE;
972 }
973 /* Ctrl-- is Ctrl-_ */
974 else if (pker->wVirtualKeyCode == 0xBD)
975 {
976 *pch = Ctrl__;
977 return TRUE;
978 }
979 }
980
981 /* Shift-TAB */
982 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
983 {
984 *pch = K_NUL;
985 *pch2 = '\017';
986 return TRUE;
987 }
988
989 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
990 {
991 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
992 {
993 if (nModifs == 0)
994 *pch = VirtKeyMap[i].chAlone;
995 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
996 *pch = VirtKeyMap[i].chShift;
997 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
998 *pch = VirtKeyMap[i].chCtrl;
999 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1000 *pch = VirtKeyMap[i].chAlt;
1001
1002 if (*pch != 0)
1003 {
1004 if (VirtKeyMap[i].fAnsiKey)
1005 {
1006 *pch2 = *pch;
1007 *pch = K_NUL;
1008 }
1009
1010 return TRUE;
1011 }
1012 }
1013 }
1014
1015 i = win32_kbd_patch_key(pker);
1016
1017 if (i < 0)
1018 *pch = NUL;
1019 else
1020 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001021 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022
1023 if (pmodifiers != NULL)
1024 {
1025 /* Pass on the ALT key as a modifier, but only when not combined
1026 * with CTRL (which is ALTGR). */
1027 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1028 *pmodifiers |= MOD_MASK_ALT;
1029
1030 /* Pass on SHIFT only for special keys, because we don't know when
1031 * it's already included with the character. */
1032 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1033 *pmodifiers |= MOD_MASK_SHIFT;
1034
1035 /* Pass on CTRL only for non-special keys, because we don't know
1036 * when it's already included with the character. And not when
1037 * combined with ALT (which is ALTGR). */
1038 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1039 && *pch >= 0x20 && *pch < 0x80)
1040 *pmodifiers |= MOD_MASK_CTRL;
1041 }
1042 }
1043
1044 return (*pch != NUL);
1045}
1046
1047#ifdef _MSC_VER
1048# pragma optimize("", on)
1049#endif
1050
1051#endif /* FEAT_GUI_W32 */
1052
1053
1054#ifdef FEAT_MOUSE
1055
1056/*
1057 * For the GUI the mouse handling is in gui_w32.c.
1058 */
1059# ifdef FEAT_GUI_W32
1060 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001061mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001062{
1063}
1064# else
1065static int g_fMouseAvail = FALSE; /* mouse present */
1066static int g_fMouseActive = FALSE; /* mouse enabled */
1067static int g_nMouseClick = -1; /* mouse status */
1068static int g_xMouse; /* mouse x coordinate */
1069static int g_yMouse; /* mouse y coordinate */
1070
1071/*
1072 * Enable or disable mouse input
1073 */
1074 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001075mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076{
1077 DWORD cmodein;
1078
1079 if (!g_fMouseAvail)
1080 return;
1081
1082 g_fMouseActive = on;
1083 GetConsoleMode(g_hConIn, &cmodein);
1084
1085 if (g_fMouseActive)
1086 cmodein |= ENABLE_MOUSE_INPUT;
1087 else
1088 cmodein &= ~ENABLE_MOUSE_INPUT;
1089
1090 SetConsoleMode(g_hConIn, cmodein);
1091}
1092
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093/*
1094 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1095 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1096 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1097 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1098 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1099 * and we return the mouse position in g_xMouse and g_yMouse.
1100 *
1101 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1102 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1103 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1104 *
1105 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1106 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1107 *
1108 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1109 * moves, even if it stays within the same character cell. We ignore
1110 * all MOUSE_MOVED messages if the position hasn't really changed, and
1111 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1112 * we're only interested in MOUSE_DRAG).
1113 *
1114 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1115 * 2-button mouses by pressing the left & right buttons simultaneously.
1116 * In practice, it's almost impossible to click both at the same time,
1117 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1118 * in such cases, if the user is clicking quickly.
1119 */
1120 static BOOL
1121decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001122 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123{
1124 static int s_nOldButton = -1;
1125 static int s_nOldMouseClick = -1;
1126 static int s_xOldMouse = -1;
1127 static int s_yOldMouse = -1;
1128 static linenr_T s_old_topline = 0;
1129#ifdef FEAT_DIFF
1130 static int s_old_topfill = 0;
1131#endif
1132 static int s_cClicks = 1;
1133 static BOOL s_fReleased = TRUE;
1134 static DWORD s_dwLastClickTime = 0;
1135 static BOOL s_fNextIsMiddle = FALSE;
1136
1137 static DWORD cButtons = 0; /* number of buttons supported */
1138
1139 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1140 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1141 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1142 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1143
1144 int nButton;
1145
1146 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1147 cButtons = 2;
1148
1149 if (!g_fMouseAvail || !g_fMouseActive)
1150 {
1151 g_nMouseClick = -1;
1152 return FALSE;
1153 }
1154
1155 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1156 if (g_fJustGotFocus)
1157 {
1158 g_fJustGotFocus = FALSE;
1159 return FALSE;
1160 }
1161
1162 /* unprocessed mouse click? */
1163 if (g_nMouseClick != -1)
1164 return TRUE;
1165
1166 nButton = -1;
1167 g_xMouse = pmer->dwMousePosition.X;
1168 g_yMouse = pmer->dwMousePosition.Y;
1169
1170 if (pmer->dwEventFlags == MOUSE_MOVED)
1171 {
1172 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1173 * events even when the mouse moves only within a char cell.) */
1174 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1175 return FALSE;
1176 }
1177
1178 /* If no buttons are pressed... */
1179 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1180 {
1181 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1182 if (s_fReleased)
1183 return FALSE;
1184
1185 nButton = MOUSE_RELEASE;
1186 s_fReleased = TRUE;
1187 }
1188 else /* one or more buttons pressed */
1189 {
1190 /* on a 2-button mouse, hold down left and right buttons
1191 * simultaneously to get MIDDLE. */
1192
1193 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1194 {
1195 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1196
1197 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001198 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001199 if (dwLR == LEFT || dwLR == RIGHT)
1200 {
1201 for (;;)
1202 {
1203 /* wait a short time for next input event */
1204 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1205 != WAIT_OBJECT_0)
1206 break;
1207 else
1208 {
1209 DWORD cRecords = 0;
1210 INPUT_RECORD ir;
1211 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1212
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001213 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214
1215 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1216 || !(pmer2->dwButtonState & LEFT_RIGHT))
1217 break;
1218 else
1219 {
1220 if (pmer2->dwEventFlags != MOUSE_MOVED)
1221 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001222 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223
1224 return decode_mouse_event(pmer2);
1225 }
1226 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1227 s_yOldMouse == pmer2->dwMousePosition.Y)
1228 {
1229 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001230 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231
1232 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001233 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234
1235 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1236 break;
1237 }
1238 else
1239 break;
1240 }
1241 }
1242 }
1243 }
1244 }
1245
1246 if (s_fNextIsMiddle)
1247 {
1248 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1249 ? MOUSE_DRAG : MOUSE_MIDDLE;
1250 s_fNextIsMiddle = FALSE;
1251 }
1252 else if (cButtons == 2 &&
1253 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1254 {
1255 nButton = MOUSE_MIDDLE;
1256
1257 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1258 {
1259 s_fNextIsMiddle = TRUE;
1260 nButton = MOUSE_RELEASE;
1261 }
1262 }
1263 else if ((pmer->dwButtonState & LEFT) == LEFT)
1264 nButton = MOUSE_LEFT;
1265 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1266 nButton = MOUSE_MIDDLE;
1267 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1268 nButton = MOUSE_RIGHT;
1269
1270 if (! s_fReleased && ! s_fNextIsMiddle
1271 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1272 return FALSE;
1273
1274 s_fReleased = s_fNextIsMiddle;
1275 }
1276
1277 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1278 {
1279 /* button pressed or released, without mouse moving */
1280 if (nButton != -1 && nButton != MOUSE_RELEASE)
1281 {
1282 DWORD dwCurrentTime = GetTickCount();
1283
1284 if (s_xOldMouse != g_xMouse
1285 || s_yOldMouse != g_yMouse
1286 || s_nOldButton != nButton
1287 || s_old_topline != curwin->w_topline
1288#ifdef FEAT_DIFF
1289 || s_old_topfill != curwin->w_topfill
1290#endif
1291 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1292 {
1293 s_cClicks = 1;
1294 }
1295 else if (++s_cClicks > 4)
1296 {
1297 s_cClicks = 1;
1298 }
1299
1300 s_dwLastClickTime = dwCurrentTime;
1301 }
1302 }
1303 else if (pmer->dwEventFlags == MOUSE_MOVED)
1304 {
1305 if (nButton != -1 && nButton != MOUSE_RELEASE)
1306 nButton = MOUSE_DRAG;
1307
1308 s_cClicks = 1;
1309 }
1310
1311 if (nButton == -1)
1312 return FALSE;
1313
1314 if (nButton != MOUSE_RELEASE)
1315 s_nOldButton = nButton;
1316
1317 g_nMouseClick = nButton;
1318
1319 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1320 g_nMouseClick |= MOUSE_SHIFT;
1321 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1322 g_nMouseClick |= MOUSE_CTRL;
1323 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1324 g_nMouseClick |= MOUSE_ALT;
1325
1326 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1327 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1328
1329 /* only pass on interesting (i.e., different) mouse events */
1330 if (s_xOldMouse == g_xMouse
1331 && s_yOldMouse == g_yMouse
1332 && s_nOldMouseClick == g_nMouseClick)
1333 {
1334 g_nMouseClick = -1;
1335 return FALSE;
1336 }
1337
1338 s_xOldMouse = g_xMouse;
1339 s_yOldMouse = g_yMouse;
1340 s_old_topline = curwin->w_topline;
1341#ifdef FEAT_DIFF
1342 s_old_topfill = curwin->w_topfill;
1343#endif
1344 s_nOldMouseClick = g_nMouseClick;
1345
1346 return TRUE;
1347}
1348
1349# endif /* FEAT_GUI_W32 */
1350#endif /* FEAT_MOUSE */
1351
1352
1353#ifdef MCH_CURSOR_SHAPE
1354/*
1355 * Set the shape of the cursor.
1356 * 'thickness' can be from 1 (thin) to 99 (block)
1357 */
1358 static void
1359mch_set_cursor_shape(int thickness)
1360{
1361 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1362 ConsoleCursorInfo.dwSize = thickness;
1363 ConsoleCursorInfo.bVisible = s_cursor_visible;
1364
1365 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1366 if (s_cursor_visible)
1367 SetConsoleCursorPosition(g_hConOut, g_coord);
1368}
1369
1370 void
1371mch_update_cursor(void)
1372{
1373 int idx;
1374 int thickness;
1375
1376 /*
1377 * How the cursor is drawn depends on the current mode.
1378 */
1379 idx = get_shape_idx(FALSE);
1380
1381 if (shape_table[idx].shape == SHAPE_BLOCK)
1382 thickness = 99; /* 100 doesn't work on W95 */
1383 else
1384 thickness = shape_table[idx].percentage;
1385 mch_set_cursor_shape(thickness);
1386}
1387#endif
1388
1389#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1390/*
1391 * Handle FOCUS_EVENT.
1392 */
1393 static void
1394handle_focus_event(INPUT_RECORD ir)
1395{
1396 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1397 ui_focus_change((int)g_fJustGotFocus);
1398}
1399
1400/*
1401 * Wait until console input from keyboard or mouse is available,
1402 * or the time is up.
1403 * Return TRUE if something is available FALSE if not.
1404 */
1405 static int
1406WaitForChar(long msec)
1407{
1408 DWORD dwNow = 0, dwEndTime = 0;
1409 INPUT_RECORD ir;
1410 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001411 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001412#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001413 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001414#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001415
1416 if (msec > 0)
1417 /* Wait until the specified time has elapsed. */
1418 dwEndTime = GetTickCount() + msec;
1419 else if (msec < 0)
1420 /* Wait forever. */
1421 dwEndTime = INFINITE;
1422
1423 /* We need to loop until the end of the time period, because
1424 * we might get multiple unusable mouse events in that time.
1425 */
1426 for (;;)
1427 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001428#ifdef MESSAGE_QUEUE
1429 parse_queued_messages();
1430#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001431#ifdef FEAT_MZSCHEME
1432 mzvim_check_threads();
1433#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001434#ifdef FEAT_CLIENTSERVER
1435 serverProcessPendingMessages();
1436#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001437
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438 if (0
1439#ifdef FEAT_MOUSE
1440 || g_nMouseClick != -1
1441#endif
1442#ifdef FEAT_CLIENTSERVER
1443 || input_available()
1444#endif
1445 )
1446 return TRUE;
1447
1448 if (msec > 0)
1449 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001450 /* If the specified wait time has passed, return. Beware that
1451 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001453 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001454 break;
1455 }
1456 if (msec != 0)
1457 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001458 DWORD dwWaitTime = dwEndTime - dwNow;
1459
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001460#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001461 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001462 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001463 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001464 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001465 /* If there is readahead then parse_queued_messages() timed out
1466 * and we should call it again soon. */
1467 if (channel_any_readahead())
1468 dwWaitTime = 10;
1469 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001470#endif
Bram Moolenaar59716a22017-03-01 20:32:44 +01001471#ifdef FEAT_BEVAL
1472 if (p_beval && dwWaitTime > 100)
1473 /* The 'balloonexpr' may indirectly invoke a callback while
1474 * waiting for a character, need to check often. */
1475 dwWaitTime = 100;
1476#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001477#ifdef FEAT_MZSCHEME
1478 if (mzthreads_allowed() && p_mzq > 0
1479 && (msec < 0 || (long)dwWaitTime > p_mzq))
1480 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1481#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001482#ifdef FEAT_TIMERS
1483 {
1484 long due_time;
1485
1486 /* When waiting very briefly don't trigger timers. */
1487 if (dwWaitTime > 10)
1488 {
1489 /* Trigger timers and then get the time in msec until the
1490 * next one is due. Wait up to that time. */
1491 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001492 if (typebuf.tb_change_cnt != tb_change_cnt)
1493 {
1494 /* timer may have used feedkeys() */
1495 return FALSE;
1496 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001497 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1498 dwWaitTime = due_time;
1499 }
1500 }
1501#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001502#ifdef FEAT_CLIENTSERVER
1503 /* Wait for either an event on the console input or a message in
1504 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001505 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001506 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001508 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509#endif
1510 continue;
1511 }
1512
1513 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001514 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515
1516#ifdef FEAT_MBYTE_IME
1517 if (State & CMDLINE && msg_row == Rows - 1)
1518 {
1519 CONSOLE_SCREEN_BUFFER_INFO csbi;
1520
1521 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1522 {
1523 if (csbi.dwCursorPosition.Y != msg_row)
1524 {
1525 /* The screen is now messed up, must redraw the
1526 * command line and later all the windows. */
1527 redraw_all_later(CLEAR);
1528 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1529 redrawcmd();
1530 }
1531 }
1532 }
1533#endif
1534
1535 if (cRecords > 0)
1536 {
1537 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1538 {
1539#ifdef FEAT_MBYTE_IME
1540 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1541 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001542 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1544 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001545 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 continue;
1547 }
1548#endif
1549 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1550 NULL, FALSE))
1551 return TRUE;
1552 }
1553
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001554 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555
1556 if (ir.EventType == FOCUS_EVENT)
1557 handle_focus_event(ir);
1558 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1559 shell_resized();
1560#ifdef FEAT_MOUSE
1561 else if (ir.EventType == MOUSE_EVENT
1562 && decode_mouse_event(&ir.Event.MouseEvent))
1563 return TRUE;
1564#endif
1565 }
1566 else if (msec == 0)
1567 break;
1568 }
1569
1570#ifdef FEAT_CLIENTSERVER
1571 /* Something might have been received while we were waiting. */
1572 if (input_available())
1573 return TRUE;
1574#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001575
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576 return FALSE;
1577}
1578
1579#ifndef FEAT_GUI_MSWIN
1580/*
1581 * return non-zero if a character is available
1582 */
1583 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001584mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585{
1586 return WaitForChar(0L);
1587}
1588#endif
1589
1590/*
1591 * Create the console input. Used when reading stdin doesn't work.
1592 */
1593 static void
1594create_conin(void)
1595{
1596 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1597 FILE_SHARE_READ|FILE_SHARE_WRITE,
1598 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001599 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600 did_create_conin = TRUE;
1601}
1602
1603/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001604 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001606 static WCHAR
1607tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001609 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610
1611 for (;;)
1612 {
1613 INPUT_RECORD ir;
1614 DWORD cRecords = 0;
1615
1616#ifdef FEAT_CLIENTSERVER
1617 (void)WaitForChar(-1L);
1618 if (input_available())
1619 return 0;
1620# ifdef FEAT_MOUSE
1621 if (g_nMouseClick != -1)
1622 return 0;
1623# endif
1624#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001625 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 {
1627 if (did_create_conin)
1628 read_error_exit();
1629 create_conin();
1630 continue;
1631 }
1632
1633 if (ir.EventType == KEY_EVENT)
1634 {
1635 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1636 pmodifiers, TRUE))
1637 return ch;
1638 }
1639 else if (ir.EventType == FOCUS_EVENT)
1640 handle_focus_event(ir);
1641 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1642 shell_resized();
1643#ifdef FEAT_MOUSE
1644 else if (ir.EventType == MOUSE_EVENT)
1645 {
1646 if (decode_mouse_event(&ir.Event.MouseEvent))
1647 return 0;
1648 }
1649#endif
1650 }
1651}
1652#endif /* !FEAT_GUI_W32 */
1653
1654
1655/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001656 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657 * Get one or more characters from the keyboard or the mouse.
1658 * If time == 0, do not wait for characters.
1659 * If time == n, wait a short time for characters.
1660 * If time == -1, wait forever for characters.
1661 * Returns the number of characters read into buf.
1662 */
1663 int
1664mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001665 char_u *buf UNUSED,
1666 int maxlen UNUSED,
1667 long time UNUSED,
1668 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669{
1670#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1671
1672 int len;
1673 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674#define TYPEAHEADLEN 20
1675 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1676 static int typeaheadlen = 0;
1677
1678 /* First use any typeahead that was kept because "buf" was too small. */
1679 if (typeaheadlen > 0)
1680 goto theend;
1681
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682 if (time >= 0)
1683 {
1684 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 }
1687 else /* time == -1, wait forever */
1688 {
1689 mch_set_winsize_now(); /* Allow winsize changes from now on */
1690
Bram Moolenaar3918c952005-03-15 22:34:55 +00001691 /*
1692 * If there is no character available within 2 seconds (default)
1693 * write the autoscript file to disk. Or cause the CursorHold event
1694 * to be triggered.
1695 */
1696 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697 {
1698#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001699 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001701 buf[0] = K_SPECIAL;
1702 buf[1] = KS_EXTRA;
1703 buf[2] = (int)KE_CURSORHOLD;
1704 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001705 }
1706#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001707 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 }
1709 }
1710
1711 /*
1712 * Try to read as many characters as there are, until the buffer is full.
1713 */
1714
1715 /* we will get at least one key. Get more if they are available. */
1716 g_fCBrkPressed = FALSE;
1717
1718#ifdef MCH_WRITE_DUMP
1719 if (fdDump)
1720 fputc('[', fdDump);
1721#endif
1722
1723 /* Keep looping until there is something in the typeahead buffer and more
1724 * to get and still room in the buffer (up to two bytes for a char and
1725 * three bytes for a modifier). */
1726 while ((typeaheadlen == 0 || WaitForChar(0L))
1727 && typeaheadlen + 5 <= TYPEAHEADLEN)
1728 {
1729 if (typebuf_changed(tb_change_cnt))
1730 {
1731 /* "buf" may be invalid now if a client put something in the
1732 * typeahead buffer and "buf" is in the typeahead buffer. */
1733 typeaheadlen = 0;
1734 break;
1735 }
1736#ifdef FEAT_MOUSE
1737 if (g_nMouseClick != -1)
1738 {
1739# ifdef MCH_WRITE_DUMP
1740 if (fdDump)
1741 fprintf(fdDump, "{%02x @ %d, %d}",
1742 g_nMouseClick, g_xMouse, g_yMouse);
1743# endif
1744 typeahead[typeaheadlen++] = ESC + 128;
1745 typeahead[typeaheadlen++] = 'M';
1746 typeahead[typeaheadlen++] = g_nMouseClick;
1747 typeahead[typeaheadlen++] = g_xMouse + '!';
1748 typeahead[typeaheadlen++] = g_yMouse + '!';
1749 g_nMouseClick = -1;
1750 }
1751 else
1752#endif
1753 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001754 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 int modifiers = 0;
1756
1757 c = tgetch(&modifiers, &ch2);
1758
1759 if (typebuf_changed(tb_change_cnt))
1760 {
1761 /* "buf" may be invalid now if a client put something in the
1762 * typeahead buffer and "buf" is in the typeahead buffer. */
1763 typeaheadlen = 0;
1764 break;
1765 }
1766
1767 if (c == Ctrl_C && ctrl_c_interrupts)
1768 {
1769#if defined(FEAT_CLIENTSERVER)
1770 trash_input_buf();
1771#endif
1772 got_int = TRUE;
1773 }
1774
1775#ifdef FEAT_MOUSE
1776 if (g_nMouseClick == -1)
1777#endif
1778 {
1779 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001780 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001782#ifdef FEAT_MBYTE
1783 if (ch2 == NUL)
1784 {
1785 int i;
1786 char_u *p;
1787 WCHAR ch[2];
1788
1789 ch[0] = c;
1790 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1791 {
1792 ch[1] = tgetch(&modifiers, &ch2);
1793 n++;
1794 }
1795 p = utf16_to_enc(ch, &n);
1796 if (p != NULL)
1797 {
1798 for (i = 0; i < n; i++)
1799 typeahead[typeaheadlen + i] = p[i];
1800 vim_free(p);
1801 }
1802 }
1803 else
1804#endif
1805 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 if (ch2 != NUL)
1807 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001808 typeahead[typeaheadlen + n] = 3;
1809 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001810 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812
Bram Moolenaar45500912014-07-09 20:51:07 +02001813 if (conv)
1814 {
1815 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001816
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001817 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001818 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001819 char_u *e = typeahead + TYPEAHEADLEN;
1820
1821 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001822 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001823 if (*p == K_NUL)
1824 {
1825 ++p;
1826 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1827 *p = 3;
1828 ++n;
1829 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001830 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001831 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001832 }
1833 }
1834
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 /* Use the ALT key to set the 8th bit of the character
1836 * when it's one byte, the 8th bit isn't set yet and not
1837 * using a double-byte encoding (would become a lead
1838 * byte). */
1839 if ((modifiers & MOD_MASK_ALT)
1840 && n == 1
1841 && (typeahead[typeaheadlen] & 0x80) == 0
1842#ifdef FEAT_MBYTE
1843 && !enc_dbcs
1844#endif
1845 )
1846 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001847#ifdef FEAT_MBYTE
1848 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1849 typeahead + typeaheadlen);
1850#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001852#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001853 modifiers &= ~MOD_MASK_ALT;
1854 }
1855
1856 if (modifiers != 0)
1857 {
1858 /* Prepend modifiers to the character. */
1859 mch_memmove(typeahead + typeaheadlen + 3,
1860 typeahead + typeaheadlen, n);
1861 typeahead[typeaheadlen++] = K_SPECIAL;
1862 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1863 typeahead[typeaheadlen++] = modifiers;
1864 }
1865
1866 typeaheadlen += n;
1867
1868#ifdef MCH_WRITE_DUMP
1869 if (fdDump)
1870 fputc(c, fdDump);
1871#endif
1872 }
1873 }
1874 }
1875
1876#ifdef MCH_WRITE_DUMP
1877 if (fdDump)
1878 {
1879 fputs("]\n", fdDump);
1880 fflush(fdDump);
1881 }
1882#endif
1883
Bram Moolenaar071d4272004-06-13 20:20:40 +00001884theend:
1885 /* Move typeahead to "buf", as much as fits. */
1886 len = 0;
1887 while (len < maxlen && typeaheadlen > 0)
1888 {
1889 buf[len++] = typeahead[0];
1890 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1891 }
1892 return len;
1893
1894#else /* FEAT_GUI_W32 */
1895 return 0;
1896#endif /* FEAT_GUI_W32 */
1897}
1898
Bram Moolenaar82881492012-11-20 16:53:39 +01001899#ifndef PROTO
1900# ifndef __MINGW32__
1901# include <shellapi.h> /* required for FindExecutable() */
1902# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001903#endif
1904
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001905/*
Bram Moolenaar43663192017-03-05 14:29:12 +01001906 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
1907 * If "use_path" is FALSE: Return TRUE if "name" exists.
1908 * When returning TRUE and "path" is not NULL save the path and set "*path" to
1909 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001910 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001911 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01001913executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001915 char *dum;
1916 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001917 char *curpath, *newpath;
1918 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001919
Bram Moolenaar43663192017-03-05 14:29:12 +01001920 if (!use_path)
1921 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01001922 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01001923 {
1924 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01001925 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01001926 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01001927 *path = vim_strsave((char_u *)name);
1928 else
1929 *path = FullName_save((char_u *)name, FALSE);
1930 }
Bram Moolenaar43663192017-03-05 14:29:12 +01001931 return TRUE;
1932 }
1933 return FALSE;
1934 }
1935
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001936#ifdef FEAT_MBYTE
1937 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001939 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001940 WCHAR fnamew[_MAX_PATH];
1941 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001942 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001943
1944 if (p != NULL)
1945 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001946 wcurpath = _wgetenv(L"PATH");
1947 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1948 * sizeof(WCHAR));
1949 if (wnewpath == NULL)
1950 return FALSE;
1951 wcscpy(wnewpath, L".;");
1952 wcscat(wnewpath, wcurpath);
1953 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1954 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001955 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02001956 if (n == 0)
1957 return FALSE;
1958 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1959 return FALSE;
1960 if (path != NULL)
1961 *path = utf16_to_enc(fnamew, NULL);
1962 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001963 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001965#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001966
1967 curpath = getenv("PATH");
1968 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1969 if (newpath == NULL)
1970 return FALSE;
1971 STRCPY(newpath, ".;");
1972 STRCAT(newpath, curpath);
1973 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1974 vim_free(newpath);
1975 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001976 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001977 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001978 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001979 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001980 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001981 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001982}
1983
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001984#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001985 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001986/*
1987 * Bad parameter handler.
1988 *
1989 * Certain MS CRT functions will intentionally crash when passed invalid
1990 * parameters to highlight possible security holes. Setting this function as
1991 * the bad parameter handler will prevent the crash.
1992 *
1993 * In debug builds the parameters contain CRT information that might help track
1994 * down the source of a problem, but in non-debug builds the arguments are all
1995 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1996 * worth allowing these to make debugging of issues easier.
1997 */
1998 static void
1999bad_param_handler(const wchar_t *expression,
2000 const wchar_t *function,
2001 const wchar_t *file,
2002 unsigned int line,
2003 uintptr_t pReserved)
2004{
2005}
2006
2007# define SET_INVALID_PARAM_HANDLER \
2008 ((void)_set_invalid_parameter_handler(bad_param_handler))
2009#else
2010# define SET_INVALID_PARAM_HANDLER
2011#endif
2012
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013#ifdef FEAT_GUI_W32
2014
2015/*
2016 * GUI version of mch_init().
2017 */
2018 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002019mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020{
2021#ifndef __MINGW32__
2022 extern int _fmode;
2023#endif
2024
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002025 /* Silently handle invalid parameters to CRT functions */
2026 SET_INVALID_PARAM_HANDLER;
2027
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028 /* Let critical errors result in a failure, not in a dialog box. Required
2029 * for the timestamp test to work on removed floppies. */
2030 SetErrorMode(SEM_FAILCRITICALERRORS);
2031
2032 _fmode = O_BINARY; /* we do our own CR-LF translation */
2033
2034 /* Specify window size. Is there a place to get the default from? */
2035 Rows = 25;
2036 Columns = 80;
2037
2038 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039 {
2040 char_u vimrun_location[_MAX_PATH + 4];
2041
2042 /* First try in same directory as gvim.exe */
2043 STRCPY(vimrun_location, exe_name);
2044 STRCPY(gettail(vimrun_location), "vimrun.exe");
2045 if (mch_getperm(vimrun_location) >= 0)
2046 {
2047 if (*skiptowhite(vimrun_location) != NUL)
2048 {
2049 /* Enclose path with white space in double quotes. */
2050 mch_memmove(vimrun_location + 1, vimrun_location,
2051 STRLEN(vimrun_location) + 1);
2052 *vimrun_location = '"';
2053 STRCPY(gettail(vimrun_location), "vimrun\" ");
2054 }
2055 else
2056 STRCPY(gettail(vimrun_location), "vimrun ");
2057
2058 vimrun_path = (char *)vim_strsave(vimrun_location);
2059 s_dont_use_vimrun = FALSE;
2060 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002061 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 s_dont_use_vimrun = FALSE;
2063
2064 /* Don't give the warning for a missing vimrun.exe right now, but only
2065 * when vimrun was supposed to be used. Don't bother people that do
2066 * not need vimrun.exe. */
2067 if (s_dont_use_vimrun)
2068 need_vimrun_warning = TRUE;
2069 }
2070
2071 /*
2072 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2073 * Otherwise the default "findstr /n" is used.
2074 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002075 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002076 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2077
2078#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002079 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080#endif
2081}
2082
2083
2084#else /* FEAT_GUI_W32 */
2085
2086#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2087#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2088
2089/*
2090 * ClearConsoleBuffer()
2091 * Description:
2092 * Clears the entire contents of the console screen buffer, using the
2093 * specified attribute.
2094 * Returns:
2095 * TRUE on success
2096 */
2097 static BOOL
2098ClearConsoleBuffer(WORD wAttribute)
2099{
2100 CONSOLE_SCREEN_BUFFER_INFO csbi;
2101 COORD coord;
2102 DWORD NumCells, dummy;
2103
2104 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2105 return FALSE;
2106
2107 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2108 coord.X = 0;
2109 coord.Y = 0;
2110 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2111 coord, &dummy))
2112 {
2113 return FALSE;
2114 }
2115 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2116 coord, &dummy))
2117 {
2118 return FALSE;
2119 }
2120
2121 return TRUE;
2122}
2123
2124/*
2125 * FitConsoleWindow()
2126 * Description:
2127 * Checks if the console window will fit within given buffer dimensions.
2128 * Also, if requested, will shrink the window to fit.
2129 * Returns:
2130 * TRUE on success
2131 */
2132 static BOOL
2133FitConsoleWindow(
2134 COORD dwBufferSize,
2135 BOOL WantAdjust)
2136{
2137 CONSOLE_SCREEN_BUFFER_INFO csbi;
2138 COORD dwWindowSize;
2139 BOOL NeedAdjust = FALSE;
2140
2141 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2142 {
2143 /*
2144 * A buffer resize will fail if the current console window does
2145 * not lie completely within that buffer. To avoid this, we might
2146 * have to move and possibly shrink the window.
2147 */
2148 if (csbi.srWindow.Right >= dwBufferSize.X)
2149 {
2150 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2151 if (dwWindowSize.X > dwBufferSize.X)
2152 dwWindowSize.X = dwBufferSize.X;
2153 csbi.srWindow.Right = dwBufferSize.X - 1;
2154 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2155 NeedAdjust = TRUE;
2156 }
2157 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2158 {
2159 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2160 if (dwWindowSize.Y > dwBufferSize.Y)
2161 dwWindowSize.Y = dwBufferSize.Y;
2162 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2163 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2164 NeedAdjust = TRUE;
2165 }
2166 if (NeedAdjust && WantAdjust)
2167 {
2168 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2169 return FALSE;
2170 }
2171 return TRUE;
2172 }
2173
2174 return FALSE;
2175}
2176
2177typedef struct ConsoleBufferStruct
2178{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002179 BOOL IsValid;
2180 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002181 PCHAR_INFO Buffer;
2182 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002183} ConsoleBuffer;
2184
2185/*
2186 * SaveConsoleBuffer()
2187 * Description:
2188 * Saves important information about the console buffer, including the
2189 * actual buffer contents. The saved information is suitable for later
2190 * restoration by RestoreConsoleBuffer().
2191 * Returns:
2192 * TRUE if all information was saved; FALSE otherwise
2193 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2194 */
2195 static BOOL
2196SaveConsoleBuffer(
2197 ConsoleBuffer *cb)
2198{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002199 DWORD NumCells;
2200 COORD BufferCoord;
2201 SMALL_RECT ReadRegion;
2202 WORD Y, Y_incr;
2203
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204 if (cb == NULL)
2205 return FALSE;
2206
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002207 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208 {
2209 cb->IsValid = FALSE;
2210 return FALSE;
2211 }
2212 cb->IsValid = TRUE;
2213
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002214 /*
2215 * Allocate a buffer large enough to hold the entire console screen
2216 * buffer. If this ConsoleBuffer structure has already been initialized
2217 * with a buffer of the correct size, then just use that one.
2218 */
2219 if (!cb->IsValid || cb->Buffer == NULL ||
2220 cb->BufferSize.X != cb->Info.dwSize.X ||
2221 cb->BufferSize.Y != cb->Info.dwSize.Y)
2222 {
2223 cb->BufferSize.X = cb->Info.dwSize.X;
2224 cb->BufferSize.Y = cb->Info.dwSize.Y;
2225 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2226 vim_free(cb->Buffer);
2227 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2228 if (cb->Buffer == NULL)
2229 return FALSE;
2230 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231
2232 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002233 * We will now copy the console screen buffer into our buffer.
2234 * ReadConsoleOutput() seems to be limited as far as how much you
2235 * can read at a time. Empirically, this number seems to be about
2236 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2237 * in chunks until it is all copied. The chunks will all have the
2238 * same horizontal characteristics, so initialize them now. The
2239 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002241 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002242 ReadRegion.Left = 0;
2243 ReadRegion.Right = cb->Info.dwSize.X - 1;
2244 Y_incr = 12000 / cb->Info.dwSize.X;
2245 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002247 /*
2248 * Read into position (0, Y) in our buffer.
2249 */
2250 BufferCoord.Y = Y;
2251 /*
2252 * Read the region whose top left corner is (0, Y) and whose bottom
2253 * right corner is (width - 1, Y + Y_incr - 1). This should define
2254 * a region of size width by Y_incr. Don't worry if this region is
2255 * too large for the remaining buffer; it will be cropped.
2256 */
2257 ReadRegion.Top = Y;
2258 ReadRegion.Bottom = Y + Y_incr - 1;
2259 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2260 cb->Buffer, /* our buffer */
2261 cb->BufferSize, /* dimensions of our buffer */
2262 BufferCoord, /* offset in our buffer */
2263 &ReadRegion)) /* region to save */
2264 {
2265 vim_free(cb->Buffer);
2266 cb->Buffer = NULL;
2267 return FALSE;
2268 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002269 }
2270
2271 return TRUE;
2272}
2273
2274/*
2275 * RestoreConsoleBuffer()
2276 * Description:
2277 * Restores important information about the console buffer, including the
2278 * actual buffer contents, if desired. The information to restore is in
2279 * the same format used by SaveConsoleBuffer().
2280 * Returns:
2281 * TRUE on success
2282 */
2283 static BOOL
2284RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002285 ConsoleBuffer *cb,
2286 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002288 COORD BufferCoord;
2289 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290
2291 if (cb == NULL || !cb->IsValid)
2292 return FALSE;
2293
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002294 /*
2295 * Before restoring the buffer contents, clear the current buffer, and
2296 * restore the cursor position and window information. Doing this now
2297 * prevents old buffer contents from "flashing" onto the screen.
2298 */
2299 if (RestoreScreen)
2300 ClearConsoleBuffer(cb->Info.wAttributes);
2301
2302 FitConsoleWindow(cb->Info.dwSize, TRUE);
2303 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2304 return FALSE;
2305 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2306 return FALSE;
2307
2308 if (!RestoreScreen)
2309 {
2310 /*
2311 * No need to restore the screen buffer contents, so we're done.
2312 */
2313 return TRUE;
2314 }
2315
2316 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2317 return FALSE;
2318 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2319 return FALSE;
2320
2321 /*
2322 * Restore the screen buffer contents.
2323 */
2324 if (cb->Buffer != NULL)
2325 {
2326 BufferCoord.X = 0;
2327 BufferCoord.Y = 0;
2328 WriteRegion.Left = 0;
2329 WriteRegion.Top = 0;
2330 WriteRegion.Right = cb->Info.dwSize.X - 1;
2331 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2332 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2333 cb->Buffer, /* our buffer */
2334 cb->BufferSize, /* dimensions of our buffer */
2335 BufferCoord, /* offset in our buffer */
2336 &WriteRegion)) /* region to restore */
2337 {
2338 return FALSE;
2339 }
2340 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341
2342 return TRUE;
2343}
2344
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002345#define FEAT_RESTORE_ORIG_SCREEN
2346#ifdef FEAT_RESTORE_ORIG_SCREEN
2347static ConsoleBuffer g_cbOrig = { 0 };
2348#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349static ConsoleBuffer g_cbNonTermcap = { 0 };
2350static ConsoleBuffer g_cbTermcap = { 0 };
2351
2352#ifdef FEAT_TITLE
2353#ifdef __BORLANDC__
2354typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2355#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002356typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357#endif
2358char g_szOrigTitle[256] = { 0 };
2359HWND g_hWnd = NULL; /* also used in os_mswin.c */
2360static HICON g_hOrigIconSmall = NULL;
2361static HICON g_hOrigIcon = NULL;
2362static HICON g_hVimIcon = NULL;
2363static BOOL g_fCanChangeIcon = FALSE;
2364
2365/* ICON* are not defined in VC++ 4.0 */
2366#ifndef ICON_SMALL
2367#define ICON_SMALL 0
2368#endif
2369#ifndef ICON_BIG
2370#define ICON_BIG 1
2371#endif
2372/*
2373 * GetConsoleIcon()
2374 * Description:
2375 * Attempts to retrieve the small icon and/or the big icon currently in
2376 * use by a given window.
2377 * Returns:
2378 * TRUE on success
2379 */
2380 static BOOL
2381GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002382 HWND hWnd,
2383 HICON *phIconSmall,
2384 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385{
2386 if (hWnd == NULL)
2387 return FALSE;
2388
2389 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002390 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2391 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002393 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2394 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395 return TRUE;
2396}
2397
2398/*
2399 * SetConsoleIcon()
2400 * Description:
2401 * Attempts to change the small icon and/or the big icon currently in
2402 * use by a given window.
2403 * Returns:
2404 * TRUE on success
2405 */
2406 static BOOL
2407SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002408 HWND hWnd,
2409 HICON hIconSmall,
2410 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412 if (hWnd == NULL)
2413 return FALSE;
2414
2415 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002416 SendMessage(hWnd, WM_SETICON,
2417 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002419 SendMessage(hWnd, WM_SETICON,
2420 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421 return TRUE;
2422}
2423
2424/*
2425 * SaveConsoleTitleAndIcon()
2426 * Description:
2427 * Saves the current console window title in g_szOrigTitle, for later
2428 * restoration. Also, attempts to obtain a handle to the console window,
2429 * and use it to save the small and big icons currently in use by the
2430 * console window. This is not always possible on some versions of Windows;
2431 * nor is it possible when running Vim remotely using Telnet (since the
2432 * console window the user sees is owned by a remote process).
2433 */
2434 static void
2435SaveConsoleTitleAndIcon(void)
2436{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 /* Save the original title. */
2438 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2439 return;
2440
2441 /*
2442 * Obtain a handle to the console window using GetConsoleWindow() from
2443 * KERNEL32.DLL; we need to handle in order to change the window icon.
2444 * This function only exists on NT-based Windows, starting with Windows
2445 * 2000. On older operating systems, we can't change the window icon
2446 * anyway.
2447 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002448 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002449 if (g_hWnd == NULL)
2450 return;
2451
2452 /* Save the original console window icon. */
2453 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2454 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2455 return;
2456
2457 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002458 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002459 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002460 if (g_hVimIcon != NULL)
2461 g_fCanChangeIcon = TRUE;
2462}
2463#endif
2464
2465static int g_fWindInitCalled = FALSE;
2466static int g_fTermcapMode = FALSE;
2467static CONSOLE_CURSOR_INFO g_cci;
2468static DWORD g_cmodein = 0;
2469static DWORD g_cmodeout = 0;
2470
2471/*
2472 * non-GUI version of mch_init().
2473 */
2474 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002475mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002476{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002477#ifndef FEAT_RESTORE_ORIG_SCREEN
2478 CONSOLE_SCREEN_BUFFER_INFO csbi;
2479#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480#ifndef __MINGW32__
2481 extern int _fmode;
2482#endif
2483
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002484 /* Silently handle invalid parameters to CRT functions */
2485 SET_INVALID_PARAM_HANDLER;
2486
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487 /* Let critical errors result in a failure, not in a dialog box. Required
2488 * for the timestamp test to work on removed floppies. */
2489 SetErrorMode(SEM_FAILCRITICALERRORS);
2490
2491 _fmode = O_BINARY; /* we do our own CR-LF translation */
2492 out_flush();
2493
2494 /* Obtain handles for the standard Console I/O devices */
2495 if (read_cmd_fd == 0)
2496 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2497 else
2498 create_conin();
2499 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2500
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002501#ifdef FEAT_RESTORE_ORIG_SCREEN
2502 /* Save the initial console buffer for later restoration */
2503 SaveConsoleBuffer(&g_cbOrig);
2504 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2505#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002507 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2508 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2509#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 if (cterm_normal_fg_color == 0)
2511 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2512 if (cterm_normal_bg_color == 0)
2513 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2514
2515 /* set termcap codes to current text attributes */
2516 update_tcap(g_attrCurrent);
2517
2518 GetConsoleCursorInfo(g_hConOut, &g_cci);
2519 GetConsoleMode(g_hConIn, &g_cmodein);
2520 GetConsoleMode(g_hConOut, &g_cmodeout);
2521
2522#ifdef FEAT_TITLE
2523 SaveConsoleTitleAndIcon();
2524 /*
2525 * Set both the small and big icons of the console window to Vim's icon.
2526 * Note that Vim presently only has one size of icon (32x32), but it
2527 * automatically gets scaled down to 16x16 when setting the small icon.
2528 */
2529 if (g_fCanChangeIcon)
2530 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2531#endif
2532
2533 ui_get_shellsize();
2534
2535#ifdef MCH_WRITE_DUMP
2536 fdDump = fopen("dump", "wt");
2537
2538 if (fdDump)
2539 {
2540 time_t t;
2541
2542 time(&t);
2543 fputs(ctime(&t), fdDump);
2544 fflush(fdDump);
2545 }
2546#endif
2547
2548 g_fWindInitCalled = TRUE;
2549
2550#ifdef FEAT_MOUSE
2551 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2552#endif
2553
2554#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002555 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002556#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557}
2558
2559/*
2560 * non-GUI version of mch_exit().
2561 * Shut down and exit with status `r'
2562 * Careful: mch_exit() may be called before mch_init()!
2563 */
2564 void
2565mch_exit(int r)
2566{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002567 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568
Bram Moolenaar955f1982017-02-05 15:10:51 +01002569 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002570 if (g_fWindInitCalled)
2571 settmode(TMODE_COOK);
2572
2573 ml_close_all(TRUE); /* remove all memfiles */
2574
2575 if (g_fWindInitCalled)
2576 {
2577#ifdef FEAT_TITLE
2578 mch_restore_title(3);
2579 /*
2580 * Restore both the small and big icons of the console window to
2581 * what they were at startup. Don't do this when the window is
2582 * closed, Vim would hang here.
2583 */
2584 if (g_fCanChangeIcon && !g_fForceExit)
2585 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2586#endif
2587
2588#ifdef MCH_WRITE_DUMP
2589 if (fdDump)
2590 {
2591 time_t t;
2592
2593 time(&t);
2594 fputs(ctime(&t), fdDump);
2595 fclose(fdDump);
2596 }
2597 fdDump = NULL;
2598#endif
2599 }
2600
2601 SetConsoleCursorInfo(g_hConOut, &g_cci);
2602 SetConsoleMode(g_hConIn, g_cmodein);
2603 SetConsoleMode(g_hConOut, g_cmodeout);
2604
2605#ifdef DYNAMIC_GETTEXT
2606 dyn_libintl_end();
2607#endif
2608
2609 exit(r);
2610}
2611#endif /* !FEAT_GUI_W32 */
2612
Bram Moolenaar071d4272004-06-13 20:20:40 +00002613/*
2614 * Do we have an interactive window?
2615 */
2616 int
2617mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002618 int argc UNUSED,
2619 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002620{
2621 get_exe_name();
2622
2623#ifdef FEAT_GUI_W32
2624 return OK; /* GUI always has a tty */
2625#else
2626 if (isatty(1))
2627 return OK;
2628 return FAIL;
2629#endif
2630}
2631
2632
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002633#ifdef FEAT_MBYTE
2634/*
2635 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2636 * if it already exists. When "len" is > 0, also expand short to long
2637 * filenames.
2638 * Return FAIL if wide functions are not available, OK otherwise.
2639 * NOTE: much of this is identical to fname_case(), keep in sync!
2640 */
2641 static int
2642fname_casew(
2643 WCHAR *name,
2644 int len)
2645{
2646 WCHAR szTrueName[_MAX_PATH + 2];
2647 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2648 WCHAR *ptrue, *ptruePrev;
2649 WCHAR *porig, *porigPrev;
2650 int flen;
2651 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002652 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002653 int c;
2654 int slen;
2655
2656 flen = (int)wcslen(name);
2657 if (flen > _MAX_PATH)
2658 return OK;
2659
2660 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2661
2662 /* Build the new name in szTrueName[] one component at a time. */
2663 porig = name;
2664 ptrue = szTrueName;
2665
2666 if (iswalpha(porig[0]) && porig[1] == L':')
2667 {
2668 /* copy leading drive letter */
2669 *ptrue++ = *porig++;
2670 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002671 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002672 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002673
2674 while (*porig != NUL)
2675 {
2676 /* copy \ characters */
2677 while (*porig == psepc)
2678 *ptrue++ = *porig++;
2679
2680 ptruePrev = ptrue;
2681 porigPrev = porig;
2682 while (*porig != NUL && *porig != psepc)
2683 {
2684 *ptrue++ = *porig++;
2685 }
2686 *ptrue = NUL;
2687
2688 /* To avoid a slow failure append "\*" when searching a directory,
2689 * server or network share. */
2690 wcscpy(szTrueNameTemp, szTrueName);
2691 slen = (int)wcslen(szTrueNameTemp);
2692 if (*porig == psepc && slen + 2 < _MAX_PATH)
2693 wcscpy(szTrueNameTemp + slen, L"\\*");
2694
2695 /* Skip "", "." and "..". */
2696 if (ptrue > ptruePrev
2697 && (ptruePrev[0] != L'.'
2698 || (ptruePrev[1] != NUL
2699 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2700 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2701 != INVALID_HANDLE_VALUE)
2702 {
2703 c = *porig;
2704 *porig = NUL;
2705
2706 /* Only use the match when it's the same name (ignoring case) or
2707 * expansion is allowed and there is a match with the short name
2708 * and there is enough room. */
2709 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2710 || (len > 0
2711 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2712 && (int)(ptruePrev - szTrueName)
2713 + (int)wcslen(fb.cFileName) < len)))
2714 {
2715 wcscpy(ptruePrev, fb.cFileName);
2716
2717 /* Look for exact match and prefer it if found. Must be a
2718 * long name, otherwise there would be only one match. */
2719 while (FindNextFileW(hFind, &fb))
2720 {
2721 if (*fb.cAlternateFileName != NUL
2722 && (wcscoll(porigPrev, fb.cFileName) == 0
2723 || (len > 0
2724 && (_wcsicoll(porigPrev,
2725 fb.cAlternateFileName) == 0
2726 && (int)(ptruePrev - szTrueName)
2727 + (int)wcslen(fb.cFileName) < len))))
2728 {
2729 wcscpy(ptruePrev, fb.cFileName);
2730 break;
2731 }
2732 }
2733 }
2734 FindClose(hFind);
2735 *porig = c;
2736 ptrue = ptruePrev + wcslen(ptruePrev);
2737 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002738 }
2739
2740 wcscpy(name, szTrueName);
2741 return OK;
2742}
2743#endif
2744
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745/*
2746 * fname_case(): Set the case of the file name, if it already exists.
2747 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002748 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749 */
2750 void
2751fname_case(
2752 char_u *name,
2753 int len)
2754{
2755 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002756 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757 char *ptrue, *ptruePrev;
2758 char *porig, *porigPrev;
2759 int flen;
2760 WIN32_FIND_DATA fb;
2761 HANDLE hFind;
2762 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002763 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002765 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002766 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767 return;
2768
2769 slash_adjust(name);
2770
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002771#ifdef FEAT_MBYTE
2772 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2773 {
2774 WCHAR *p = enc_to_utf16(name, NULL);
2775
2776 if (p != NULL)
2777 {
2778 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002779 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002780
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002781 wcsncpy(buf, p, _MAX_PATH);
2782 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002783 vim_free(p);
2784
2785 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2786 {
2787 q = utf16_to_enc(buf, NULL);
2788 if (q != NULL)
2789 {
2790 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2791 vim_free(q);
2792 return;
2793 }
2794 }
2795 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002796 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002797 }
2798#endif
2799
2800 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2801 * So we should check this after calling wide function. */
2802 if (flen > _MAX_PATH)
2803 return;
2804
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002806 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807 ptrue = szTrueName;
2808
2809 if (isalpha(porig[0]) && porig[1] == ':')
2810 {
2811 /* copy leading drive letter */
2812 *ptrue++ = *porig++;
2813 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002815 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002816
2817 while (*porig != NUL)
2818 {
2819 /* copy \ characters */
2820 while (*porig == psepc)
2821 *ptrue++ = *porig++;
2822
2823 ptruePrev = ptrue;
2824 porigPrev = porig;
2825 while (*porig != NUL && *porig != psepc)
2826 {
2827#ifdef FEAT_MBYTE
2828 int l;
2829
2830 if (enc_dbcs)
2831 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002832 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833 while (--l >= 0)
2834 *ptrue++ = *porig++;
2835 }
2836 else
2837#endif
2838 *ptrue++ = *porig++;
2839 }
2840 *ptrue = NUL;
2841
Bram Moolenaar464c9252010-10-13 20:37:41 +02002842 /* To avoid a slow failure append "\*" when searching a directory,
2843 * server or network share. */
2844 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002845 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002846 if (*porig == psepc && slen + 2 < _MAX_PATH)
2847 STRCPY(szTrueNameTemp + slen, "\\*");
2848
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849 /* Skip "", "." and "..". */
2850 if (ptrue > ptruePrev
2851 && (ptruePrev[0] != '.'
2852 || (ptruePrev[1] != NUL
2853 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002854 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002855 != INVALID_HANDLE_VALUE)
2856 {
2857 c = *porig;
2858 *porig = NUL;
2859
2860 /* Only use the match when it's the same name (ignoring case) or
2861 * expansion is allowed and there is a match with the short name
2862 * and there is enough room. */
2863 if (_stricoll(porigPrev, fb.cFileName) == 0
2864 || (len > 0
2865 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2866 && (int)(ptruePrev - szTrueName)
2867 + (int)strlen(fb.cFileName) < len)))
2868 {
2869 STRCPY(ptruePrev, fb.cFileName);
2870
2871 /* Look for exact match and prefer it if found. Must be a
2872 * long name, otherwise there would be only one match. */
2873 while (FindNextFile(hFind, &fb))
2874 {
2875 if (*fb.cAlternateFileName != NUL
2876 && (strcoll(porigPrev, fb.cFileName) == 0
2877 || (len > 0
2878 && (_stricoll(porigPrev,
2879 fb.cAlternateFileName) == 0
2880 && (int)(ptruePrev - szTrueName)
2881 + (int)strlen(fb.cFileName) < len))))
2882 {
2883 STRCPY(ptruePrev, fb.cFileName);
2884 break;
2885 }
2886 }
2887 }
2888 FindClose(hFind);
2889 *porig = c;
2890 ptrue = ptruePrev + strlen(ptruePrev);
2891 }
2892 }
2893
2894 STRCPY(name, szTrueName);
2895}
2896
2897
2898/*
2899 * Insert user name in s[len].
2900 */
2901 int
2902mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002903 char_u *s,
2904 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002906 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 DWORD cch = sizeof szUserName;
2908
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002909#ifdef FEAT_MBYTE
2910 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2911 {
2912 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2913 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2914
2915 if (GetUserNameW(wszUserName, &wcch))
2916 {
2917 char_u *p = utf16_to_enc(wszUserName, NULL);
2918
2919 if (p != NULL)
2920 {
2921 vim_strncpy(s, p, len - 1);
2922 vim_free(p);
2923 return OK;
2924 }
2925 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002926 }
2927#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 if (GetUserName(szUserName, &cch))
2929 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002930 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931 return OK;
2932 }
2933 s[0] = NUL;
2934 return FAIL;
2935}
2936
2937
2938/*
2939 * Insert host name in s[len].
2940 */
2941 void
2942mch_get_host_name(
2943 char_u *s,
2944 int len)
2945{
2946 DWORD cch = len;
2947
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002948#ifdef FEAT_MBYTE
2949 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2950 {
2951 WCHAR wszHostName[256 + 1];
2952 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2953
2954 if (GetComputerNameW(wszHostName, &wcch))
2955 {
2956 char_u *p = utf16_to_enc(wszHostName, NULL);
2957
2958 if (p != NULL)
2959 {
2960 vim_strncpy(s, p, len - 1);
2961 vim_free(p);
2962 return;
2963 }
2964 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002965 }
2966#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002967 if (!GetComputerName((LPSTR)s, &cch))
2968 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969}
2970
2971
2972/*
2973 * return process ID
2974 */
2975 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002976mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977{
2978 return (long)GetCurrentProcessId();
2979}
2980
2981
2982/*
2983 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2984 * Return OK for success, FAIL for failure.
2985 */
2986 int
2987mch_dirname(
2988 char_u *buf,
2989 int len)
2990{
2991 /*
2992 * Originally this was:
2993 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2994 * But the Win32s known bug list says that getcwd() doesn't work
2995 * so use the Win32 system call instead. <Negri>
2996 */
2997#ifdef FEAT_MBYTE
2998 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2999 {
3000 WCHAR wbuf[_MAX_PATH + 1];
3001
3002 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3003 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003004 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005
3006 if (p != NULL)
3007 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003008 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009 vim_free(p);
3010 return OK;
3011 }
3012 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003013 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014 }
3015#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003016 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017}
3018
3019/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003020 * Get file permissions for "name".
3021 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022 */
3023 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003024mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003026 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003027 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003029 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003030 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031}
3032
3033
3034/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003035 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003036 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003037 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 */
3039 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003040mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003042 long n = -1;
3043
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044#ifdef FEAT_MBYTE
3045 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3046 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003047 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048
3049 if (p != NULL)
3050 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003051 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003053 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003054 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 }
3056 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003057 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003059 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003060 if (n == -1)
3061 return FAIL;
3062
3063 win32_set_archive(name);
3064
3065 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066}
3067
3068/*
3069 * Set hidden flag for "name".
3070 */
3071 void
3072mch_hide(char_u *name)
3073{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003074 int attrs = win32_getattrs(name);
3075 if (attrs == -1)
3076 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003078 attrs |= FILE_ATTRIBUTE_HIDDEN;
3079 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080}
3081
3082/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003083 * Return TRUE if file "name" exists and is hidden.
3084 */
3085 int
3086mch_ishidden(char_u *name)
3087{
3088 int f = win32_getattrs(name);
3089
3090 if (f == -1)
3091 return FALSE; /* file does not exist at all */
3092
3093 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3094}
3095
3096/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097 * return TRUE if "name" is a directory
3098 * return FALSE if "name" is not a directory or upon error
3099 */
3100 int
3101mch_isdir(char_u *name)
3102{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003103 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104
3105 if (f == -1)
3106 return FALSE; /* file does not exist at all */
3107
3108 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3109}
3110
3111/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003112 * return TRUE if "name" is a directory, NOT a symlink to a directory
3113 * return FALSE if "name" is not a directory
3114 * return FALSE for error
3115 */
3116 int
3117mch_isrealdir(char_u *name)
3118{
3119 return mch_isdir(name) && !mch_is_symbolic_link(name);
3120}
3121
3122/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003123 * Create directory "name".
3124 * Return 0 on success, -1 on error.
3125 */
3126 int
3127mch_mkdir(char_u *name)
3128{
3129#ifdef FEAT_MBYTE
3130 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3131 {
3132 WCHAR *p;
3133 int retval;
3134
3135 p = enc_to_utf16(name, NULL);
3136 if (p == NULL)
3137 return -1;
3138 retval = _wmkdir(p);
3139 vim_free(p);
3140 return retval;
3141 }
3142#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003143 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003144}
3145
3146/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003147 * Delete directory "name".
3148 * Return 0 on success, -1 on error.
3149 */
3150 int
3151mch_rmdir(char_u *name)
3152{
3153#ifdef FEAT_MBYTE
3154 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3155 {
3156 WCHAR *p;
3157 int retval;
3158
3159 p = enc_to_utf16(name, NULL);
3160 if (p == NULL)
3161 return -1;
3162 retval = _wrmdir(p);
3163 vim_free(p);
3164 return retval;
3165 }
3166#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003167 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003168}
3169
3170/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003171 * Return TRUE if file "fname" has more than one link.
3172 */
3173 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003174mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003175{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003176 BY_HANDLE_FILE_INFORMATION info;
3177
3178 return win32_fileinfo(fname, &info) == FILEINFO_OK
3179 && info.nNumberOfLinks > 1;
3180}
3181
3182/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003183 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003184 */
3185 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003186mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003187{
3188 HANDLE hFind;
3189 int res = FALSE;
3190 WIN32_FIND_DATAA findDataA;
3191 DWORD fileFlags = 0, reparseTag = 0;
3192#ifdef FEAT_MBYTE
3193 WCHAR *wn = NULL;
3194 WIN32_FIND_DATAW findDataW;
3195
3196 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003197 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003198 if (wn != NULL)
3199 {
3200 hFind = FindFirstFileW(wn, &findDataW);
3201 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003202 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003203 {
3204 fileFlags = findDataW.dwFileAttributes;
3205 reparseTag = findDataW.dwReserved0;
3206 }
3207 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003208 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003209#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003210 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003211 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003212 if (hFind != INVALID_HANDLE_VALUE)
3213 {
3214 fileFlags = findDataA.dwFileAttributes;
3215 reparseTag = findDataA.dwReserved0;
3216 }
3217 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003218
3219 if (hFind != INVALID_HANDLE_VALUE)
3220 FindClose(hFind);
3221
3222 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003223 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3224 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003225 res = TRUE;
3226
3227 return res;
3228}
3229
3230/*
3231 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3232 * link.
3233 */
3234 int
3235mch_is_linked(char_u *fname)
3236{
3237 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3238 return TRUE;
3239 return FALSE;
3240}
3241
3242/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003243 * Get the by-handle-file-information for "fname".
3244 * Returns FILEINFO_OK when OK.
3245 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3246 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3247 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3248 */
3249 int
3250win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3251{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003252 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003253 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003254#ifdef FEAT_MBYTE
3255 WCHAR *wn = NULL;
3256
3257 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003258 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003259 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003260 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003261 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003262 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003263 if (wn != NULL)
3264 {
3265 hFile = CreateFileW(wn, /* file name */
3266 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003267 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003268 NULL, /* security descriptor */
3269 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003270 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003271 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003272 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003273 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003274 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003275#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003276 hFile = CreateFile((LPCSTR)fname, /* file name */
3277 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003278 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003279 NULL, /* security descriptor */
3280 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003281 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003282 NULL); /* handle to template file */
3283
3284 if (hFile != INVALID_HANDLE_VALUE)
3285 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003286 if (GetFileInformationByHandle(hFile, info) != 0)
3287 res = FILEINFO_OK;
3288 else
3289 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003290 CloseHandle(hFile);
3291 }
3292
Bram Moolenaar03f48552006-02-28 23:52:23 +00003293 return res;
3294}
3295
3296/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003297 * get file attributes for `name'
3298 * -1 : error
3299 * else FILE_ATTRIBUTE_* defined in winnt.h
3300 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003301 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003302win32_getattrs(char_u *name)
3303{
3304 int attr;
3305#ifdef FEAT_MBYTE
3306 WCHAR *p = NULL;
3307
3308 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3309 p = enc_to_utf16(name, NULL);
3310
3311 if (p != NULL)
3312 {
3313 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003314 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003315 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003316 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003317#endif
3318 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003319
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003320 return attr;
3321}
3322
3323/*
3324 * set file attributes for `name' to `attrs'
3325 *
3326 * return -1 for failure, 0 otherwise
3327 */
3328 static
3329 int
3330win32_setattrs(char_u *name, int attrs)
3331{
3332 int res;
3333#ifdef FEAT_MBYTE
3334 WCHAR *p = NULL;
3335
3336 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3337 p = enc_to_utf16(name, NULL);
3338
3339 if (p != NULL)
3340 {
3341 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003342 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003343 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003344 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003345#endif
3346 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003347
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003348 return res ? 0 : -1;
3349}
3350
3351/*
3352 * Set archive flag for "name".
3353 */
3354 static
3355 int
3356win32_set_archive(char_u *name)
3357{
3358 int attrs = win32_getattrs(name);
3359 if (attrs == -1)
3360 return -1;
3361
3362 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3363 return win32_setattrs(name, attrs);
3364}
3365
3366/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003367 * Return TRUE if file or directory "name" is writable (not readonly).
3368 * Strange semantics of Win32: a readonly directory is writable, but you can't
3369 * delete a file. Let's say this means it is writable.
3370 */
3371 int
3372mch_writable(char_u *name)
3373{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003374 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003375
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003376 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3377 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003378}
3379
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003381 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003382 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003383 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3384 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385 */
3386 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003387mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003389 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003390 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003391 char_u *p;
3392
3393 if (len >= _MAX_PATH) /* safety check */
3394 return FALSE;
3395
3396 /* If there already is an extension try using the name directly. Also do
3397 * this with a Unix-shell like 'shell'. */
3398 if (vim_strchr(gettail(name), '.') != NULL
3399 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003400 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003401 return TRUE;
3402
3403 /*
3404 * Loop over all extensions in $PATHEXT.
3405 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003406 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003407 p = mch_getenv("PATHEXT");
3408 if (p == NULL)
3409 p = (char_u *)".com;.exe;.bat;.cmd";
3410 while (*p)
3411 {
3412 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3413 {
3414 /* A single "." means no extension is added. */
3415 buf[len] = NUL;
3416 ++p;
3417 if (*p)
3418 ++p;
3419 }
3420 else
3421 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003422 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003423 return TRUE;
3424 }
3425 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003426}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427
3428/*
3429 * Check what "name" is:
3430 * NODE_NORMAL: file or directory (or doesn't exist)
3431 * NODE_WRITABLE: writable device, socket, fifo, etc.
3432 * NODE_OTHER: non-writable things
3433 */
3434 int
3435mch_nodetype(char_u *name)
3436{
3437 HANDLE hFile;
3438 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003439#ifdef FEAT_MBYTE
3440 WCHAR *wn = NULL;
3441#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442
Bram Moolenaar043545e2006-10-10 16:44:07 +00003443 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3444 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3445 * here. */
3446 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3447 return NODE_WRITABLE;
3448
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003449#ifdef FEAT_MBYTE
3450 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003451 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003452
3453 if (wn != NULL)
3454 {
3455 hFile = CreateFileW(wn, /* file name */
3456 GENERIC_WRITE, /* access mode */
3457 0, /* share mode */
3458 NULL, /* security descriptor */
3459 OPEN_EXISTING, /* creation disposition */
3460 0, /* file attributes */
3461 NULL); /* handle to template file */
3462 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003463 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003464 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003465#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003466 hFile = CreateFile((LPCSTR)name, /* file name */
3467 GENERIC_WRITE, /* access mode */
3468 0, /* share mode */
3469 NULL, /* security descriptor */
3470 OPEN_EXISTING, /* creation disposition */
3471 0, /* file attributes */
3472 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003473
3474 if (hFile == INVALID_HANDLE_VALUE)
3475 return NODE_NORMAL;
3476
3477 type = GetFileType(hFile);
3478 CloseHandle(hFile);
3479 if (type == FILE_TYPE_CHAR)
3480 return NODE_WRITABLE;
3481 if (type == FILE_TYPE_DISK)
3482 return NODE_NORMAL;
3483 return NODE_OTHER;
3484}
3485
3486#ifdef HAVE_ACL
3487struct my_acl
3488{
3489 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3490 PSID pSidOwner;
3491 PSID pSidGroup;
3492 PACL pDacl;
3493 PACL pSacl;
3494};
3495#endif
3496
3497/*
3498 * Return a pointer to the ACL of file "fname" in allocated memory.
3499 * Return NULL if the ACL is not available for whatever reason.
3500 */
3501 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003502mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503{
3504#ifndef HAVE_ACL
3505 return (vim_acl_T)NULL;
3506#else
3507 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003508 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003510 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3511 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003512 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003513# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003514 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003515
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003516 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3517 wn = enc_to_utf16(fname, NULL);
3518 if (wn != NULL)
3519 {
3520 /* Try to retrieve the entire security descriptor. */
3521 err = GetNamedSecurityInfoW(
3522 wn, // Abstract filename
3523 SE_FILE_OBJECT, // File Object
3524 OWNER_SECURITY_INFORMATION |
3525 GROUP_SECURITY_INFORMATION |
3526 DACL_SECURITY_INFORMATION |
3527 SACL_SECURITY_INFORMATION,
3528 &p->pSidOwner, // Ownership information.
3529 &p->pSidGroup, // Group membership.
3530 &p->pDacl, // Discretionary information.
3531 &p->pSacl, // For auditing purposes.
3532 &p->pSecurityDescriptor);
3533 if (err == ERROR_ACCESS_DENIED ||
3534 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003536 /* Retrieve only DACL. */
3537 (void)GetNamedSecurityInfoW(
3538 wn,
3539 SE_FILE_OBJECT,
3540 DACL_SECURITY_INFORMATION,
3541 NULL,
3542 NULL,
3543 &p->pDacl,
3544 NULL,
3545 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003546 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003547 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003548 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003549 mch_free_acl((vim_acl_T)p);
3550 p = NULL;
3551 }
3552 vim_free(wn);
3553 }
3554 else
3555# endif
3556 {
3557 /* Try to retrieve the entire security descriptor. */
3558 err = GetNamedSecurityInfo(
3559 (LPSTR)fname, // Abstract filename
3560 SE_FILE_OBJECT, // File Object
3561 OWNER_SECURITY_INFORMATION |
3562 GROUP_SECURITY_INFORMATION |
3563 DACL_SECURITY_INFORMATION |
3564 SACL_SECURITY_INFORMATION,
3565 &p->pSidOwner, // Ownership information.
3566 &p->pSidGroup, // Group membership.
3567 &p->pDacl, // Discretionary information.
3568 &p->pSacl, // For auditing purposes.
3569 &p->pSecurityDescriptor);
3570 if (err == ERROR_ACCESS_DENIED ||
3571 err == ERROR_PRIVILEGE_NOT_HELD)
3572 {
3573 /* Retrieve only DACL. */
3574 (void)GetNamedSecurityInfo(
3575 (LPSTR)fname,
3576 SE_FILE_OBJECT,
3577 DACL_SECURITY_INFORMATION,
3578 NULL,
3579 NULL,
3580 &p->pDacl,
3581 NULL,
3582 &p->pSecurityDescriptor);
3583 }
3584 if (p->pSecurityDescriptor == NULL)
3585 {
3586 mch_free_acl((vim_acl_T)p);
3587 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588 }
3589 }
3590 }
3591
3592 return (vim_acl_T)p;
3593#endif
3594}
3595
Bram Moolenaar27515922013-06-29 15:36:26 +02003596#ifdef HAVE_ACL
3597/*
3598 * Check if "acl" contains inherited ACE.
3599 */
3600 static BOOL
3601is_acl_inherited(PACL acl)
3602{
3603 DWORD i;
3604 ACL_SIZE_INFORMATION acl_info;
3605 PACCESS_ALLOWED_ACE ace;
3606
3607 acl_info.AceCount = 0;
3608 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3609 for (i = 0; i < acl_info.AceCount; i++)
3610 {
3611 GetAce(acl, i, (LPVOID *)&ace);
3612 if (ace->Header.AceFlags & INHERITED_ACE)
3613 return TRUE;
3614 }
3615 return FALSE;
3616}
3617#endif
3618
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619/*
3620 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3621 * Errors are ignored.
3622 * This must only be called with "acl" equal to what mch_get_acl() returned.
3623 */
3624 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003625mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626{
3627#ifdef HAVE_ACL
3628 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003629 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003631 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003632 {
3633# ifdef FEAT_MBYTE
3634 WCHAR *wn = NULL;
3635# endif
3636
3637 /* Set security flags */
3638 if (p->pSidOwner)
3639 sec_info |= OWNER_SECURITY_INFORMATION;
3640 if (p->pSidGroup)
3641 sec_info |= GROUP_SECURITY_INFORMATION;
3642 if (p->pDacl)
3643 {
3644 sec_info |= DACL_SECURITY_INFORMATION;
3645 /* Do not inherit its parent's DACL.
3646 * If the DACL is inherited, Cygwin permissions would be changed.
3647 */
3648 if (!is_acl_inherited(p->pDacl))
3649 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3650 }
3651 if (p->pSacl)
3652 sec_info |= SACL_SECURITY_INFORMATION;
3653
3654# ifdef FEAT_MBYTE
3655 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3656 wn = enc_to_utf16(fname, NULL);
3657 if (wn != NULL)
3658 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003659 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003660 wn, // Abstract filename
3661 SE_FILE_OBJECT, // File Object
3662 sec_info,
3663 p->pSidOwner, // Ownership information.
3664 p->pSidGroup, // Group membership.
3665 p->pDacl, // Discretionary information.
3666 p->pSacl // For auditing purposes.
3667 );
3668 vim_free(wn);
3669 }
3670 else
3671# endif
3672 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003673 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003674 (LPSTR)fname, // Abstract filename
3675 SE_FILE_OBJECT, // File Object
3676 sec_info,
3677 p->pSidOwner, // Ownership information.
3678 p->pSidGroup, // Group membership.
3679 p->pDacl, // Discretionary information.
3680 p->pSacl // For auditing purposes.
3681 );
3682 }
3683 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684#endif
3685}
3686
3687 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003688mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689{
3690#ifdef HAVE_ACL
3691 struct my_acl *p = (struct my_acl *)acl;
3692
3693 if (p != NULL)
3694 {
3695 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3696 vim_free(p);
3697 }
3698#endif
3699}
3700
3701#ifndef FEAT_GUI_W32
3702
3703/*
3704 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3705 */
3706 static BOOL WINAPI
3707handler_routine(
3708 DWORD dwCtrlType)
3709{
3710 switch (dwCtrlType)
3711 {
3712 case CTRL_C_EVENT:
3713 if (ctrl_c_interrupts)
3714 g_fCtrlCPressed = TRUE;
3715 return TRUE;
3716
3717 case CTRL_BREAK_EVENT:
3718 g_fCBrkPressed = TRUE;
3719 return TRUE;
3720
3721 /* fatal events: shut down gracefully */
3722 case CTRL_CLOSE_EVENT:
3723 case CTRL_LOGOFF_EVENT:
3724 case CTRL_SHUTDOWN_EVENT:
3725 windgoto((int)Rows - 1, 0);
3726 g_fForceExit = TRUE;
3727
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003728 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 (dwCtrlType == CTRL_CLOSE_EVENT
3730 ? _("close")
3731 : dwCtrlType == CTRL_LOGOFF_EVENT
3732 ? _("logoff")
3733 : _("shutdown")));
3734#ifdef DEBUG
3735 OutputDebugString(IObuff);
3736#endif
3737
3738 preserve_exit(); /* output IObuff, preserve files and exit */
3739
3740 return TRUE; /* not reached */
3741
3742 default:
3743 return FALSE;
3744 }
3745}
3746
3747
3748/*
3749 * set the tty in (raw) ? "raw" : "cooked" mode
3750 */
3751 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003752mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753{
3754 DWORD cmodein;
3755 DWORD cmodeout;
3756 BOOL bEnableHandler;
3757
3758 GetConsoleMode(g_hConIn, &cmodein);
3759 GetConsoleMode(g_hConOut, &cmodeout);
3760 if (tmode == TMODE_RAW)
3761 {
3762 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3763 ENABLE_ECHO_INPUT);
3764#ifdef FEAT_MOUSE
3765 if (g_fMouseActive)
3766 cmodein |= ENABLE_MOUSE_INPUT;
3767#endif
3768 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3769 bEnableHandler = TRUE;
3770 }
3771 else /* cooked */
3772 {
3773 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3774 ENABLE_ECHO_INPUT);
3775 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3776 bEnableHandler = FALSE;
3777 }
3778 SetConsoleMode(g_hConIn, cmodein);
3779 SetConsoleMode(g_hConOut, cmodeout);
3780 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3781
3782#ifdef MCH_WRITE_DUMP
3783 if (fdDump)
3784 {
3785 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3786 tmode == TMODE_RAW ? "raw" :
3787 tmode == TMODE_COOK ? "cooked" : "normal",
3788 cmodein, cmodeout);
3789 fflush(fdDump);
3790 }
3791#endif
3792}
3793
3794
3795/*
3796 * Get the size of the current window in `Rows' and `Columns'
3797 * Return OK when size could be determined, FAIL otherwise.
3798 */
3799 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003800mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801{
3802 CONSOLE_SCREEN_BUFFER_INFO csbi;
3803
3804 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3805 {
3806 /*
3807 * For some reason, we are trying to get the screen dimensions
3808 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3809 * variables are really intended to mean the size of Vim screen
3810 * while in termcap mode.
3811 */
3812 Rows = g_cbTermcap.Info.dwSize.Y;
3813 Columns = g_cbTermcap.Info.dwSize.X;
3814 }
3815 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3816 {
3817 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3818 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3819 }
3820 else
3821 {
3822 Rows = 25;
3823 Columns = 80;
3824 }
3825 return OK;
3826}
3827
3828/*
3829 * Set a console window to `xSize' * `ySize'
3830 */
3831 static void
3832ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003833 HANDLE hConsole,
3834 int xSize,
3835 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836{
3837 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3838 SMALL_RECT srWindowRect; /* hold the new console size */
3839 COORD coordScreen;
3840
3841#ifdef MCH_WRITE_DUMP
3842 if (fdDump)
3843 {
3844 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3845 fflush(fdDump);
3846 }
3847#endif
3848
3849 /* get the largest size we can size the console window to */
3850 coordScreen = GetLargestConsoleWindowSize(hConsole);
3851
3852 /* define the new console window size and scroll position */
3853 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3854 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3855 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3856
3857 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3858 {
3859 int sx, sy;
3860
3861 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3862 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3863 if (sy < ySize || sx < xSize)
3864 {
3865 /*
3866 * Increasing number of lines/columns, do buffer first.
3867 * Use the maximal size in x and y direction.
3868 */
3869 if (sy < ySize)
3870 coordScreen.Y = ySize;
3871 else
3872 coordScreen.Y = sy;
3873 if (sx < xSize)
3874 coordScreen.X = xSize;
3875 else
3876 coordScreen.X = sx;
3877 SetConsoleScreenBufferSize(hConsole, coordScreen);
3878 }
3879 }
3880
3881 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3882 {
3883#ifdef MCH_WRITE_DUMP
3884 if (fdDump)
3885 {
3886 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3887 GetLastError());
3888 fflush(fdDump);
3889 }
3890#endif
3891 }
3892
3893 /* define the new console buffer size */
3894 coordScreen.X = xSize;
3895 coordScreen.Y = ySize;
3896
3897 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3898 {
3899#ifdef MCH_WRITE_DUMP
3900 if (fdDump)
3901 {
3902 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3903 GetLastError());
3904 fflush(fdDump);
3905 }
3906#endif
3907 }
3908}
3909
3910
3911/*
3912 * Set the console window to `Rows' * `Columns'
3913 */
3914 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003915mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916{
3917 COORD coordScreen;
3918
3919 /* Don't change window size while still starting up */
3920 if (suppress_winsize != 0)
3921 {
3922 suppress_winsize = 2;
3923 return;
3924 }
3925
3926 if (term_console)
3927 {
3928 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3929
3930 /* Clamp Rows and Columns to reasonable values */
3931 if (Rows > coordScreen.Y)
3932 Rows = coordScreen.Y;
3933 if (Columns > coordScreen.X)
3934 Columns = coordScreen.X;
3935
3936 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3937 }
3938}
3939
3940/*
3941 * Rows and/or Columns has changed.
3942 */
3943 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003944mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945{
3946 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3947}
3948
3949
3950/*
3951 * Called when started up, to set the winsize that was delayed.
3952 */
3953 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003954mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955{
3956 if (suppress_winsize == 2)
3957 {
3958 suppress_winsize = 0;
3959 mch_set_shellsize();
3960 shell_resized();
3961 }
3962 suppress_winsize = 0;
3963}
3964#endif /* FEAT_GUI_W32 */
3965
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003966 static BOOL
3967vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003968 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003969 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003970 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003971 STARTUPINFO *si,
3972 PROCESS_INFORMATION *pi)
3973{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003974#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003975 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3976 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003977 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003978
3979 if (wcmd != NULL)
3980 {
3981 BOOL ret;
3982 ret = CreateProcessW(
3983 NULL, /* Executable name */
3984 wcmd, /* 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 */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003991 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003992 pi); /* Process information */
3993 vim_free(wcmd);
3994 return ret;
3995 }
3996 }
3997#endif
3998 return CreateProcess(
3999 NULL, /* Executable name */
4000 cmd, /* Command to execute */
4001 NULL, /* Process security attributes */
4002 NULL, /* Thread security attributes */
4003 inherit_handles, /* Inherit handles */
4004 flags, /* Creation flags */
4005 NULL, /* Environment */
4006 NULL, /* Current directory */
4007 si, /* Startup information */
4008 pi); /* Process information */
4009}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004010
4011
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004012 static HINSTANCE
4013vim_shell_execute(
4014 char *cmd,
4015 INT n_show_cmd)
4016{
4017#ifdef FEAT_MBYTE
4018 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4019 {
4020 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4021 if (wcmd != NULL)
4022 {
4023 HINSTANCE ret;
4024 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4025 vim_free(wcmd);
4026 return ret;
4027 }
4028 }
4029#endif
4030 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4031}
4032
4033
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034#if defined(FEAT_GUI_W32) || defined(PROTO)
4035
4036/*
4037 * Specialised version of system() for Win32 GUI mode.
4038 * This version proceeds as follows:
4039 * 1. Create a console window for use by the subprocess
4040 * 2. Run the subprocess (it gets the allocated console by default)
4041 * 3. Wait for the subprocess to terminate and get its exit code
4042 * 4. Prompt the user to press a key to close the console window
4043 */
4044 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004045mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046{
4047 STARTUPINFO si;
4048 PROCESS_INFORMATION pi;
4049 DWORD ret = 0;
4050 HWND hwnd = GetFocus();
4051
4052 si.cb = sizeof(si);
4053 si.lpReserved = NULL;
4054 si.lpDesktop = NULL;
4055 si.lpTitle = NULL;
4056 si.dwFlags = STARTF_USESHOWWINDOW;
4057 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004058 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004059 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004060 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004061 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004062 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004063 else
4064 si.wShowWindow = SW_SHOWNORMAL;
4065 si.cbReserved2 = 0;
4066 si.lpReserved2 = NULL;
4067
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004069 vim_create_process(cmd, FALSE,
4070 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004071
4072 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004073 {
4074#ifdef FEAT_GUI
4075 int delay = 1;
4076
4077 /* Keep updating the window while waiting for the shell to finish. */
4078 for (;;)
4079 {
4080 MSG msg;
4081
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004082 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004083 {
4084 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004085 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004086 delay = 1;
4087 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088 }
4089 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4090 break;
4091
4092 /* We start waiting for a very short time and then increase it, so
4093 * that we respond quickly when the process is quick, and don't
4094 * consume too much overhead when it's slow. */
4095 if (delay < 50)
4096 delay += 10;
4097 }
4098#else
4099 WaitForSingleObject(pi.hProcess, INFINITE);
4100#endif
4101
4102 /* Get the command exit code */
4103 GetExitCodeProcess(pi.hProcess, &ret);
4104 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105
4106 /* Close the handles to the subprocess, so that it goes away */
4107 CloseHandle(pi.hThread);
4108 CloseHandle(pi.hProcess);
4109
4110 /* Try to get input focus back. Doesn't always work though. */
4111 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4112
4113 return ret;
4114}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004115
4116/*
4117 * Thread launched by the gui to send the current buffer data to the
4118 * process. This way avoid to hang up vim totally if the children
4119 * process take a long time to process the lines.
4120 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004121 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004122sub_process_writer(LPVOID param)
4123{
4124 HANDLE g_hChildStd_IN_Wr = param;
4125 linenr_T lnum = curbuf->b_op_start.lnum;
4126 DWORD len = 0;
4127 DWORD l;
4128 char_u *lp = ml_get(lnum);
4129 char_u *s;
4130 int written = 0;
4131
4132 for (;;)
4133 {
4134 l = (DWORD)STRLEN(lp + written);
4135 if (l == 0)
4136 len = 0;
4137 else if (lp[written] == NL)
4138 {
4139 /* NL -> NUL translation */
4140 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4141 }
4142 else
4143 {
4144 s = vim_strchr(lp + written, NL);
4145 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4146 s == NULL ? l : (DWORD)(s - (lp + written)),
4147 &len, NULL);
4148 }
4149 if (len == (int)l)
4150 {
4151 /* Finished a line, add a NL, unless this line should not have
4152 * one. */
4153 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004154 || (!curbuf->b_p_bin
4155 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004156 || (lnum != curbuf->b_no_eol_lnum
4157 && (lnum != curbuf->b_ml.ml_line_count
4158 || curbuf->b_p_eol)))
4159 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004160 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004161 }
4162
4163 ++lnum;
4164 if (lnum > curbuf->b_op_end.lnum)
4165 break;
4166
4167 lp = ml_get(lnum);
4168 written = 0;
4169 }
4170 else if (len > 0)
4171 written += len;
4172 }
4173
4174 /* finished all the lines, close pipe */
4175 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004176 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004177}
4178
4179
4180# define BUFLEN 100 /* length for buffer, stolen from unix version */
4181
4182/*
4183 * This function read from the children's stdout and write the
4184 * data on screen or in the buffer accordingly.
4185 */
4186 static void
4187dump_pipe(int options,
4188 HANDLE g_hChildStd_OUT_Rd,
4189 garray_T *ga,
4190 char_u buffer[],
4191 DWORD *buffer_off)
4192{
4193 DWORD availableBytes = 0;
4194 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004195 int ret;
4196 DWORD len;
4197 DWORD toRead;
4198 int repeatCount;
4199
4200 /* we query the pipe to see if there is any data to read
4201 * to avoid to perform a blocking read */
4202 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4203 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004204 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004205 NULL, /* number of read bytes */
4206 &availableBytes, /* available bytes total */
4207 NULL); /* byteLeft */
4208
4209 repeatCount = 0;
4210 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004211 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004212 {
4213 repeatCount++;
4214 toRead =
4215# ifdef FEAT_MBYTE
4216 (DWORD)(BUFLEN - *buffer_off);
4217# else
4218 (DWORD)BUFLEN;
4219# endif
4220 toRead = availableBytes < toRead ? availableBytes : toRead;
4221 ReadFile(g_hChildStd_OUT_Rd, buffer
4222# ifdef FEAT_MBYTE
4223 + *buffer_off, toRead
4224# else
4225 , toRead
4226# endif
4227 , &len, NULL);
4228
4229 /* If we haven't read anything, there is a problem */
4230 if (len == 0)
4231 break;
4232
4233 availableBytes -= len;
4234
4235 if (options & SHELL_READ)
4236 {
4237 /* Do NUL -> NL translation, append NL separated
4238 * lines to the current buffer. */
4239 for (i = 0; i < len; ++i)
4240 {
4241 if (buffer[i] == NL)
4242 append_ga_line(ga);
4243 else if (buffer[i] == NUL)
4244 ga_append(ga, NL);
4245 else
4246 ga_append(ga, buffer[i]);
4247 }
4248 }
4249# ifdef FEAT_MBYTE
4250 else if (has_mbyte)
4251 {
4252 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004253 int c;
4254 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004255
4256 len += *buffer_off;
4257 buffer[len] = NUL;
4258
4259 /* Check if the last character in buffer[] is
4260 * incomplete, keep these bytes for the next
4261 * round. */
4262 for (p = buffer; p < buffer + len; p += l)
4263 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004264 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004265 if (l == 0)
4266 l = 1; /* NUL byte? */
4267 else if (MB_BYTE2LEN(*p) != l)
4268 break;
4269 }
4270 if (p == buffer) /* no complete character */
4271 {
4272 /* avoid getting stuck at an illegal byte */
4273 if (len >= 12)
4274 ++p;
4275 else
4276 {
4277 *buffer_off = len;
4278 return;
4279 }
4280 }
4281 c = *p;
4282 *p = NUL;
4283 msg_puts(buffer);
4284 if (p < buffer + len)
4285 {
4286 *p = c;
4287 *buffer_off = (DWORD)((buffer + len) - p);
4288 mch_memmove(buffer, p, *buffer_off);
4289 return;
4290 }
4291 *buffer_off = 0;
4292 }
4293# endif /* FEAT_MBYTE */
4294 else
4295 {
4296 buffer[len] = NUL;
4297 msg_puts(buffer);
4298 }
4299
4300 windgoto(msg_row, msg_col);
4301 cursor_on();
4302 out_flush();
4303 }
4304}
4305
4306/*
4307 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4308 * for communication and doesn't open any new window.
4309 */
4310 static int
4311mch_system_piped(char *cmd, int options)
4312{
4313 STARTUPINFO si;
4314 PROCESS_INFORMATION pi;
4315 DWORD ret = 0;
4316
4317 HANDLE g_hChildStd_IN_Rd = NULL;
4318 HANDLE g_hChildStd_IN_Wr = NULL;
4319 HANDLE g_hChildStd_OUT_Rd = NULL;
4320 HANDLE g_hChildStd_OUT_Wr = NULL;
4321
4322 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4323 DWORD len;
4324
4325 /* buffer used to receive keys */
4326 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4327 int ta_len = 0; /* valid bytes in ta_buf[] */
4328
4329 DWORD i;
4330 int c;
4331 int noread_cnt = 0;
4332 garray_T ga;
4333 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004334 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004335 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004336
4337 SECURITY_ATTRIBUTES saAttr;
4338
4339 /* Set the bInheritHandle flag so pipe handles are inherited. */
4340 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4341 saAttr.bInheritHandle = TRUE;
4342 saAttr.lpSecurityDescriptor = NULL;
4343
4344 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4345 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004346 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004347 /* Create a pipe for the child process's STDIN. */
4348 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4349 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004350 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004351 {
4352 CloseHandle(g_hChildStd_IN_Rd);
4353 CloseHandle(g_hChildStd_IN_Wr);
4354 CloseHandle(g_hChildStd_OUT_Rd);
4355 CloseHandle(g_hChildStd_OUT_Wr);
4356 MSG_PUTS(_("\nCannot create pipes\n"));
4357 }
4358
4359 si.cb = sizeof(si);
4360 si.lpReserved = NULL;
4361 si.lpDesktop = NULL;
4362 si.lpTitle = NULL;
4363 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4364
4365 /* set-up our file redirection */
4366 si.hStdError = g_hChildStd_OUT_Wr;
4367 si.hStdOutput = g_hChildStd_OUT_Wr;
4368 si.hStdInput = g_hChildStd_IN_Rd;
4369 si.wShowWindow = SW_HIDE;
4370 si.cbReserved2 = 0;
4371 si.lpReserved2 = NULL;
4372
4373 if (options & SHELL_READ)
4374 ga_init2(&ga, 1, BUFLEN);
4375
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004376 if (cmd != NULL)
4377 {
4378 p = (char *)vim_strsave((char_u *)cmd);
4379 if (p != NULL)
4380 unescape_shellxquote((char_u *)p, p_sxe);
4381 else
4382 p = cmd;
4383 }
4384
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004385 /* Now, run the command.
4386 * About "Inherit handles" being TRUE: this command can be litigious,
4387 * handle inheritance was deactivated for pending temp file, but, if we
4388 * deactivate it, the pipes don't work for some reason. */
4389 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004390
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004391 if (p != cmd)
4392 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004393
4394 /* Close our unused side of the pipes */
4395 CloseHandle(g_hChildStd_IN_Rd);
4396 CloseHandle(g_hChildStd_OUT_Wr);
4397
4398 if (options & SHELL_WRITE)
4399 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004400 HANDLE thread = (HANDLE)
4401 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004402 0, /* default stack size */
4403 sub_process_writer, /* function to be executed */
4404 g_hChildStd_IN_Wr, /* parameter */
4405 0, /* creation flag, start immediately */
4406 NULL); /* we don't care about thread id */
4407 CloseHandle(thread);
4408 g_hChildStd_IN_Wr = NULL;
4409 }
4410
4411 /* Keep updating the window while waiting for the shell to finish. */
4412 for (;;)
4413 {
4414 MSG msg;
4415
Bram Moolenaar175d0702013-12-11 18:36:33 +01004416 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004417 {
4418 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004419 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004420 }
4421
4422 /* write pipe information in the window */
4423 if ((options & (SHELL_READ|SHELL_WRITE))
4424# ifdef FEAT_GUI
4425 || gui.in_use
4426# endif
4427 )
4428 {
4429 len = 0;
4430 if (!(options & SHELL_EXPAND)
4431 && ((options &
4432 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4433 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4434# ifdef FEAT_GUI
4435 || gui.in_use
4436# endif
4437 )
4438 && (ta_len > 0 || noread_cnt > 4))
4439 {
4440 if (ta_len == 0)
4441 {
4442 /* Get extra characters when we don't have any. Reset the
4443 * counter and timer. */
4444 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004445 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4446 }
4447 if (ta_len > 0 || len > 0)
4448 {
4449 /*
4450 * For pipes: Check for CTRL-C: send interrupt signal to
4451 * child. Check for CTRL-D: EOF, close pipe to child.
4452 */
4453 if (len == 1 && cmd != NULL)
4454 {
4455 if (ta_buf[ta_len] == Ctrl_C)
4456 {
4457 /* Learn what exit code is expected, for
4458 * now put 9 as SIGKILL */
4459 TerminateProcess(pi.hProcess, 9);
4460 }
4461 if (ta_buf[ta_len] == Ctrl_D)
4462 {
4463 CloseHandle(g_hChildStd_IN_Wr);
4464 g_hChildStd_IN_Wr = NULL;
4465 }
4466 }
4467
4468 /* replace K_BS by <BS> and K_DEL by <DEL> */
4469 for (i = ta_len; i < ta_len + len; ++i)
4470 {
4471 if (ta_buf[i] == CSI && len - i > 2)
4472 {
4473 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4474 if (c == K_DEL || c == K_KDEL || c == K_BS)
4475 {
4476 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4477 (size_t)(len - i - 2));
4478 if (c == K_DEL || c == K_KDEL)
4479 ta_buf[i] = DEL;
4480 else
4481 ta_buf[i] = Ctrl_H;
4482 len -= 2;
4483 }
4484 }
4485 else if (ta_buf[i] == '\r')
4486 ta_buf[i] = '\n';
4487# ifdef FEAT_MBYTE
4488 if (has_mbyte)
4489 i += (*mb_ptr2len_len)(ta_buf + i,
4490 ta_len + len - i) - 1;
4491# endif
4492 }
4493
4494 /*
4495 * For pipes: echo the typed characters. For a pty this
4496 * does not seem to work.
4497 */
4498 for (i = ta_len; i < ta_len + len; ++i)
4499 {
4500 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4501 msg_putchar(ta_buf[i]);
4502# ifdef FEAT_MBYTE
4503 else if (has_mbyte)
4504 {
4505 int l = (*mb_ptr2len)(ta_buf + i);
4506
4507 msg_outtrans_len(ta_buf + i, l);
4508 i += l - 1;
4509 }
4510# endif
4511 else
4512 msg_outtrans_len(ta_buf + i, 1);
4513 }
4514 windgoto(msg_row, msg_col);
4515 out_flush();
4516
4517 ta_len += len;
4518
4519 /*
4520 * Write the characters to the child, unless EOF has been
4521 * typed for pipes. Write one character at a time, to
4522 * avoid losing too much typeahead. When writing buffer
4523 * lines, drop the typed characters (only check for
4524 * CTRL-C).
4525 */
4526 if (options & SHELL_WRITE)
4527 ta_len = 0;
4528 else if (g_hChildStd_IN_Wr != NULL)
4529 {
4530 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4531 1, &len, NULL);
4532 // if we are typing in, we want to keep things reactive
4533 delay = 1;
4534 if (len > 0)
4535 {
4536 ta_len -= len;
4537 mch_memmove(ta_buf, ta_buf + len, ta_len);
4538 }
4539 }
4540 }
4541 }
4542 }
4543
4544 if (ta_len)
4545 ui_inchar_undo(ta_buf, ta_len);
4546
4547 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4548 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004549 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004550 break;
4551 }
4552
4553 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004554 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004555
4556 /* We start waiting for a very short time and then increase it, so
4557 * that we respond quickly when the process is quick, and don't
4558 * consume too much overhead when it's slow. */
4559 if (delay < 50)
4560 delay += 10;
4561 }
4562
4563 /* Close the pipe */
4564 CloseHandle(g_hChildStd_OUT_Rd);
4565 if (g_hChildStd_IN_Wr != NULL)
4566 CloseHandle(g_hChildStd_IN_Wr);
4567
4568 WaitForSingleObject(pi.hProcess, INFINITE);
4569
4570 /* Get the command exit code */
4571 GetExitCodeProcess(pi.hProcess, &ret);
4572
4573 if (options & SHELL_READ)
4574 {
4575 if (ga.ga_len > 0)
4576 {
4577 append_ga_line(&ga);
4578 /* remember that the NL was missing */
4579 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4580 }
4581 else
4582 curbuf->b_no_eol_lnum = 0;
4583 ga_clear(&ga);
4584 }
4585
4586 /* Close the handles to the subprocess, so that it goes away */
4587 CloseHandle(pi.hThread);
4588 CloseHandle(pi.hProcess);
4589
4590 return ret;
4591}
4592
4593 static int
4594mch_system(char *cmd, int options)
4595{
4596 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004597 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004598 return mch_system_piped(cmd, options);
4599 else
4600 return mch_system_classic(cmd, options);
4601}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004602#else
4603
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004604# ifdef FEAT_MBYTE
4605 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004606mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004607{
4608 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4609 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004610 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004611 if (wcmd != NULL)
4612 {
4613 int ret = _wsystem(wcmd);
4614 vim_free(wcmd);
4615 return ret;
4616 }
4617 }
4618 return system(cmd);
4619}
4620# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004621# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004622# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623
4624#endif
4625
4626/*
4627 * Either execute a command by calling the shell or start a new shell
4628 */
4629 int
4630mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004631 char_u *cmd,
4632 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004633{
4634 int x = 0;
4635 int tmode = cur_tmode;
4636#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004637 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004638# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004639 int did_set_title = FALSE;
4640
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004641 /* Change the title to reflect that we are in a subshell. */
4642 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4643 {
4644 WCHAR szShellTitle[512];
4645
4646 if (GetConsoleTitleW(szShellTitle,
4647 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4648 {
4649 if (cmd == NULL)
4650 wcscat(szShellTitle, L" :sh");
4651 else
4652 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004653 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004654
4655 if (wn != NULL)
4656 {
4657 wcscat(szShellTitle, L" - !");
4658 if ((wcslen(szShellTitle) + wcslen(wn) <
4659 sizeof(szShellTitle)/sizeof(WCHAR)))
4660 wcscat(szShellTitle, wn);
4661 SetConsoleTitleW(szShellTitle);
4662 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004663 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004664 }
4665 }
4666 }
4667 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004668 if (!did_set_title)
4669# endif
4670 /* Change the title to reflect that we are in a subshell. */
4671 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004673 if (cmd == NULL)
4674 strcat(szShellTitle, " :sh");
4675 else
4676 {
4677 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004678 if ((strlen(szShellTitle) + strlen((char *)cmd)
4679 < sizeof(szShellTitle)))
4680 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004681 }
4682 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004684#endif
4685
4686 out_flush();
4687
4688#ifdef MCH_WRITE_DUMP
4689 if (fdDump)
4690 {
4691 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4692 fflush(fdDump);
4693 }
4694#endif
4695
4696 /*
4697 * Catch all deadly signals while running the external command, because a
4698 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4699 */
4700 signal(SIGINT, SIG_IGN);
4701#if defined(__GNUC__) && !defined(__MINGW32__)
4702 signal(SIGKILL, SIG_IGN);
4703#else
4704 signal(SIGBREAK, SIG_IGN);
4705#endif
4706 signal(SIGILL, SIG_IGN);
4707 signal(SIGFPE, SIG_IGN);
4708 signal(SIGSEGV, SIG_IGN);
4709 signal(SIGTERM, SIG_IGN);
4710 signal(SIGABRT, SIG_IGN);
4711
4712 if (options & SHELL_COOKED)
4713 settmode(TMODE_COOK); /* set to normal mode */
4714
4715 if (cmd == NULL)
4716 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004717 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004718 }
4719 else
4720 {
4721 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004722 char_u *newcmd = NULL;
4723 char_u *cmdbase = cmd;
4724 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004725
4726 /* Skip a leading ", ( and "(. */
4727 if (*cmdbase == '"' )
4728 ++cmdbase;
4729 if (*cmdbase == '(')
4730 ++cmdbase;
4731
Bram Moolenaar1c465442017-03-12 20:10:05 +01004732 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004733 {
4734 STARTUPINFO si;
4735 PROCESS_INFORMATION pi;
4736 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004737 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004738 char_u *p;
4739
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004740 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004741 si.cb = sizeof(si);
4742 si.lpReserved = NULL;
4743 si.lpDesktop = NULL;
4744 si.lpTitle = NULL;
4745 si.dwFlags = 0;
4746 si.cbReserved2 = 0;
4747 si.lpReserved2 = NULL;
4748
4749 cmdbase = skipwhite(cmdbase + 5);
4750 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004751 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004752 {
4753 cmdbase = skipwhite(cmdbase + 4);
4754 si.dwFlags = STARTF_USESHOWWINDOW;
4755 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004756 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004757 }
4758 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004759 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004760 {
4761 cmdbase = skipwhite(cmdbase + 2);
4762 flags = CREATE_NO_WINDOW;
4763 si.dwFlags = STARTF_USESTDHANDLES;
4764 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004765 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004766 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004767 NULL, // Security att.
4768 OPEN_EXISTING, // Open flags
4769 FILE_ATTRIBUTE_NORMAL, // File att.
4770 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004771 si.hStdOutput = si.hStdInput;
4772 si.hStdError = si.hStdInput;
4773 }
4774
4775 /* Remove a trailing ", ) and )" if they have a match
4776 * at the start of the command. */
4777 if (cmdbase > cmd)
4778 {
4779 p = cmdbase + STRLEN(cmdbase);
4780 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4781 *--p = NUL;
4782 if (p > cmdbase && p[-1] == ')'
4783 && (*cmd =='(' || cmd[1] == '('))
4784 *--p = NUL;
4785 }
4786
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004787 newcmd = cmdbase;
4788 unescape_shellxquote(cmdbase, p_sxe);
4789
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004790 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004791 * If creating new console, arguments are passed to the
4792 * 'cmd.exe' as-is. If it's not, arguments are not treated
4793 * correctly for current 'cmd.exe'. So unescape characters in
4794 * shellxescape except '|' for avoiding to be treated as
4795 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004796 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004797 if (flags != CREATE_NEW_CONSOLE)
4798 {
4799 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004800 char_u *cmd_shell = mch_getenv("COMSPEC");
4801
4802 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004803 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004804
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004805 subcmd = vim_strsave_escaped_ext(cmdbase,
4806 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004807 if (subcmd != NULL)
4808 {
4809 /* make "cmd.exe /c arguments" */
4810 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004811 newcmd = lalloc(cmdlen, TRUE);
4812 if (newcmd != NULL)
4813 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004814 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004815 else
4816 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004817 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004818 }
4819 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004820
4821 /*
4822 * Now, start the command as a process, so that it doesn't
4823 * inherit our handles which causes unpleasant dangling swap
4824 * files if we exit before the spawned process
4825 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004826 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004827 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004828 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4829 > (HINSTANCE)32)
4830 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004831 else
4832 {
4833 x = -1;
4834#ifdef FEAT_GUI_W32
4835 EMSG(_("E371: Command not found"));
4836#endif
4837 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004838
4839 if (newcmd != cmdbase)
4840 vim_free(newcmd);
4841
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004842 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004843 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004844 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004845 CloseHandle(si.hStdInput);
4846 }
4847 /* Close the handles to the subprocess, so that it goes away */
4848 CloseHandle(pi.hThread);
4849 CloseHandle(pi.hProcess);
4850 }
4851 else
4852 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004853 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004854#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004855 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004856#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004857 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4858
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004859 newcmd = lalloc(cmdlen, TRUE);
4860 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861 {
4862#if defined(FEAT_GUI_W32)
4863 if (need_vimrun_warning)
4864 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004865 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4866 "External commands will not pause after completion.\n"
4867 "See :help win32-vimrun for more information.");
4868 char *title = _("Vim Warning");
4869# ifdef FEAT_MBYTE
4870 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4871 {
4872 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4873 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
4874
4875 if (wmsg != NULL && wtitle != NULL)
4876 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4877 vim_free(wmsg);
4878 vim_free(wtitle);
4879 }
4880 else
4881# endif
4882 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004883 need_vimrun_warning = FALSE;
4884 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004885 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886 /* Use vimrun to execute the command. It opens a console
4887 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004888 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 vimrun_path,
4890 (msg_silent != 0 || (options & SHELL_DOOUT))
4891 ? "-s " : "",
4892 p_sh, p_shcf, cmd);
4893 else
4894#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004895 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004896 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004897 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004898 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004899 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900 }
4901 }
4902
4903 if (tmode == TMODE_RAW)
4904 settmode(TMODE_RAW); /* set to raw mode */
4905
4906 /* Print the return value, unless "vimrun" was used. */
4907 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4908#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004909 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004910#endif
4911 )
4912 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004913 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 msg_putchar('\n');
4915 }
4916#ifdef FEAT_TITLE
4917 resettitle();
4918#endif
4919
4920 signal(SIGINT, SIG_DFL);
4921#if defined(__GNUC__) && !defined(__MINGW32__)
4922 signal(SIGKILL, SIG_DFL);
4923#else
4924 signal(SIGBREAK, SIG_DFL);
4925#endif
4926 signal(SIGILL, SIG_DFL);
4927 signal(SIGFPE, SIG_DFL);
4928 signal(SIGSEGV, SIG_DFL);
4929 signal(SIGTERM, SIG_DFL);
4930 signal(SIGABRT, SIG_DFL);
4931
4932 return x;
4933}
4934
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004935#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004936 static HANDLE
4937job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004938 char_u *fname,
4939 DWORD dwDesiredAccess,
4940 DWORD dwShareMode,
4941 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4942 DWORD dwCreationDisposition,
4943 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004944{
4945 HANDLE h;
4946# ifdef FEAT_MBYTE
4947 WCHAR *wn = NULL;
4948 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4949 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004950 wn = enc_to_utf16(fname, NULL);
4951 if (wn != NULL)
4952 {
4953 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4954 lpSecurityAttributes, dwCreationDisposition,
4955 dwFlagsAndAttributes, NULL);
4956 vim_free(wn);
4957 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004958 }
4959 if (wn == NULL)
4960# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004961 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
4962 lpSecurityAttributes, dwCreationDisposition,
4963 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004964 return h;
4965}
4966
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004967 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004968mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004969{
4970 STARTUPINFO si;
4971 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02004972 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004973 SECURITY_ATTRIBUTES saAttr;
4974 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01004975 HANDLE ifd[2];
4976 HANDLE ofd[2];
4977 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004978
4979 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
4980 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
4981 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
4982 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
4983 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
4984 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
4985 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
4986
4987 if (use_out_for_err && use_null_for_out)
4988 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01004989
4990 ifd[0] = INVALID_HANDLE_VALUE;
4991 ifd[1] = INVALID_HANDLE_VALUE;
4992 ofd[0] = INVALID_HANDLE_VALUE;
4993 ofd[1] = INVALID_HANDLE_VALUE;
4994 efd[0] = INVALID_HANDLE_VALUE;
4995 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004996
Bram Moolenaar14207f42016-10-27 21:13:10 +02004997 jo = CreateJobObject(NULL, NULL);
4998 if (jo == NULL)
4999 {
5000 job->jv_status = JOB_FAILED;
5001 goto failed;
5002 }
5003
Bram Moolenaar76467df2016-02-12 19:30:26 +01005004 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005005 ZeroMemory(&si, sizeof(si));
5006 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005007 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005008 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005009
Bram Moolenaard8070362016-02-15 21:56:54 +01005010 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5011 saAttr.bInheritHandle = TRUE;
5012 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005013
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005014 if (use_file_for_in)
5015 {
5016 char_u *fname = options->jo_io_name[PART_IN];
5017
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005018 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5019 FILE_SHARE_READ | FILE_SHARE_WRITE,
5020 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5021 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005022 {
5023 EMSG2(_(e_notopen), fname);
5024 goto failed;
5025 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005026 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005027 else if (!use_null_for_in &&
5028 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005029 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005030 goto failed;
5031
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005032 if (use_file_for_out)
5033 {
5034 char_u *fname = options->jo_io_name[PART_OUT];
5035
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005036 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5037 FILE_SHARE_READ | FILE_SHARE_WRITE,
5038 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5039 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005040 {
5041 EMSG2(_(e_notopen), fname);
5042 goto failed;
5043 }
5044 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005045 else if (!use_null_for_out &&
5046 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005047 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005048 goto failed;
5049
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005050 if (use_file_for_err)
5051 {
5052 char_u *fname = options->jo_io_name[PART_ERR];
5053
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005054 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5055 FILE_SHARE_READ | FILE_SHARE_WRITE,
5056 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5057 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005058 {
5059 EMSG2(_(e_notopen), fname);
5060 goto failed;
5061 }
5062 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005063 else if (!use_out_for_err && !use_null_for_err &&
5064 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005065 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005066 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005067
Bram Moolenaard8070362016-02-15 21:56:54 +01005068 si.dwFlags |= STARTF_USESTDHANDLES;
5069 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005070 si.hStdOutput = ofd[1];
5071 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5072
5073 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5074 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005075 if (options->jo_set & JO_CHANNEL)
5076 {
5077 channel = options->jo_channel;
5078 if (channel != NULL)
5079 ++channel->ch_refcount;
5080 }
5081 else
5082 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005083 if (channel == NULL)
5084 goto failed;
5085 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005086
5087 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005088 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005089 CREATE_DEFAULT_ERROR_MODE |
5090 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005091 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005092 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005093 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005094 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005095 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005096 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005097 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005098
Bram Moolenaar14207f42016-10-27 21:13:10 +02005099 if (!AssignProcessToJobObject(jo, pi.hProcess))
5100 {
5101 /* if failing, switch the way to terminate
5102 * process with TerminateProcess. */
5103 CloseHandle(jo);
5104 jo = NULL;
5105 }
5106 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005107 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005108 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005109 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005110 job->jv_status = JOB_STARTED;
5111
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005112 CloseHandle(ifd[0]);
5113 CloseHandle(ofd[1]);
5114 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005115 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005116
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005117 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005118 if (channel != NULL)
5119 {
5120 channel_set_pipes(channel,
5121 use_file_for_in || use_null_for_in
5122 ? INVALID_FD : (sock_T)ifd[1],
5123 use_file_for_out || use_null_for_out
5124 ? INVALID_FD : (sock_T)ofd[0],
5125 use_out_for_err || use_file_for_err || use_null_for_err
5126 ? INVALID_FD : (sock_T)efd[0]);
5127 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005128 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005129 return;
5130
5131failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005132 CloseHandle(ifd[0]);
5133 CloseHandle(ofd[0]);
5134 CloseHandle(efd[0]);
5135 CloseHandle(ifd[1]);
5136 CloseHandle(ofd[1]);
5137 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005138 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005139}
5140
5141 char *
5142mch_job_status(job_T *job)
5143{
5144 DWORD dwExitCode = 0;
5145
Bram Moolenaar76467df2016-02-12 19:30:26 +01005146 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5147 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005148 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005149 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005150 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005151 {
5152 ch_log(job->jv_channel, "Job ended");
5153 job->jv_status = JOB_ENDED;
5154 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005155 return "dead";
5156 }
5157 return "run";
5158}
5159
Bram Moolenaar97792de2016-10-15 18:36:49 +02005160 job_T *
5161mch_detect_ended_job(job_T *job_list)
5162{
5163 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5164 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5165 job_T *job = job_list;
5166
5167 while (job != NULL)
5168 {
5169 DWORD n;
5170 DWORD result;
5171
5172 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5173 && job != NULL; job = job->jv_next)
5174 {
5175 if (job->jv_status == JOB_STARTED)
5176 {
5177 jobHandles[n] = job->jv_proc_info.hProcess;
5178 jobArray[n] = job;
5179 ++n;
5180 }
5181 }
5182 if (n == 0)
5183 continue;
5184 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5185 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5186 {
5187 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5188
5189 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5190 return wait_job;
5191 }
5192 }
5193 return NULL;
5194}
5195
Bram Moolenaarfb630902016-10-29 14:55:00 +02005196 static BOOL
5197terminate_all(HANDLE process, int code)
5198{
5199 PROCESSENTRY32 pe;
5200 HANDLE h = INVALID_HANDLE_VALUE;
5201 DWORD pid = GetProcessId(process);
5202
5203 if (pid != 0)
5204 {
5205 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5206 if (h != INVALID_HANDLE_VALUE)
5207 {
5208 pe.dwSize = sizeof(PROCESSENTRY32);
5209 if (!Process32First(h, &pe))
5210 goto theend;
5211
5212 do
5213 {
5214 if (pe.th32ParentProcessID == pid)
5215 {
5216 HANDLE ph = OpenProcess(
5217 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5218 if (ph != NULL)
5219 {
5220 terminate_all(ph, code);
5221 CloseHandle(ph);
5222 }
5223 }
5224 } while (Process32Next(h, &pe));
5225
5226 CloseHandle(h);
5227 }
5228 }
5229
5230theend:
5231 return TerminateProcess(process, code);
5232}
5233
5234/*
5235 * Send a (deadly) signal to "job".
5236 * Return FAIL if it didn't work.
5237 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005238 int
5239mch_stop_job(job_T *job, char_u *how)
5240{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005241 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005242
Bram Moolenaar923d9262016-02-25 20:56:01 +01005243 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005244 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005245 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005246 if (job->jv_job_object != NULL)
5247 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005248 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005249 }
5250
5251 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5252 return FAIL;
5253 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005254 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5255 job->jv_proc_info.dwProcessId)
5256 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005257 FreeConsole();
5258 return ret;
5259}
5260
5261/*
5262 * Clear the data related to "job".
5263 */
5264 void
5265mch_clear_job(job_T *job)
5266{
5267 if (job->jv_status != JOB_FAILED)
5268 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005269 if (job->jv_job_object != NULL)
5270 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005271 CloseHandle(job->jv_proc_info.hProcess);
5272 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005273}
5274#endif
5275
Bram Moolenaar071d4272004-06-13 20:20:40 +00005276
5277#ifndef FEAT_GUI_W32
5278
5279/*
5280 * Start termcap mode
5281 */
5282 static void
5283termcap_mode_start(void)
5284{
5285 DWORD cmodein;
5286
5287 if (g_fTermcapMode)
5288 return;
5289
5290 SaveConsoleBuffer(&g_cbNonTermcap);
5291
5292 if (g_cbTermcap.IsValid)
5293 {
5294 /*
5295 * We've been in termcap mode before. Restore certain screen
5296 * characteristics, including the buffer size and the window
5297 * size. Since we will be redrawing the screen, we don't need
5298 * to restore the actual contents of the buffer.
5299 */
5300 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5301 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5302 Rows = g_cbTermcap.Info.dwSize.Y;
5303 Columns = g_cbTermcap.Info.dwSize.X;
5304 }
5305 else
5306 {
5307 /*
5308 * This is our first time entering termcap mode. Clear the console
5309 * screen buffer, and resize the buffer to match the current window
5310 * size. We will use this as the size of our editing environment.
5311 */
5312 ClearConsoleBuffer(g_attrCurrent);
5313 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5314 }
5315
5316#ifdef FEAT_TITLE
5317 resettitle();
5318#endif
5319
5320 GetConsoleMode(g_hConIn, &cmodein);
5321#ifdef FEAT_MOUSE
5322 if (g_fMouseActive)
5323 cmodein |= ENABLE_MOUSE_INPUT;
5324 else
5325 cmodein &= ~ENABLE_MOUSE_INPUT;
5326#endif
5327 cmodein |= ENABLE_WINDOW_INPUT;
5328 SetConsoleMode(g_hConIn, cmodein);
5329
5330 redraw_later_clear();
5331 g_fTermcapMode = TRUE;
5332}
5333
5334
5335/*
5336 * End termcap mode
5337 */
5338 static void
5339termcap_mode_end(void)
5340{
5341 DWORD cmodein;
5342 ConsoleBuffer *cb;
5343 COORD coord;
5344 DWORD dwDummy;
5345
5346 if (!g_fTermcapMode)
5347 return;
5348
5349 SaveConsoleBuffer(&g_cbTermcap);
5350
5351 GetConsoleMode(g_hConIn, &cmodein);
5352 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5353 SetConsoleMode(g_hConIn, cmodein);
5354
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005355#ifdef FEAT_RESTORE_ORIG_SCREEN
5356 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5357#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005358 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005359#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005360 RestoreConsoleBuffer(cb, p_rs);
5361 SetConsoleCursorInfo(g_hConOut, &g_cci);
5362
5363 if (p_rs || exiting)
5364 {
5365 /*
5366 * Clear anything that happens to be on the current line.
5367 */
5368 coord.X = 0;
5369 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5370 FillConsoleOutputCharacter(g_hConOut, ' ',
5371 cb->Info.dwSize.X, coord, &dwDummy);
5372 /*
5373 * The following is just for aesthetics. If we are exiting without
5374 * restoring the screen, then we want to have a prompt string
5375 * appear at the bottom line. However, the command interpreter
5376 * seems to always advance the cursor one line before displaying
5377 * the prompt string, which causes the screen to scroll. To
5378 * counter this, move the cursor up one line before exiting.
5379 */
5380 if (exiting && !p_rs)
5381 coord.Y--;
5382 /*
5383 * Position the cursor at the leftmost column of the desired row.
5384 */
5385 SetConsoleCursorPosition(g_hConOut, coord);
5386 }
5387
5388 g_fTermcapMode = FALSE;
5389}
5390#endif /* FEAT_GUI_W32 */
5391
5392
5393#ifdef FEAT_GUI_W32
5394 void
5395mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005396 char_u *s UNUSED,
5397 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005398{
5399 /* never used */
5400}
5401
5402#else
5403
5404/*
5405 * clear `n' chars, starting from `coord'
5406 */
5407 static void
5408clear_chars(
5409 COORD coord,
5410 DWORD n)
5411{
5412 DWORD dwDummy;
5413
5414 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5415 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5416}
5417
5418
5419/*
5420 * Clear the screen
5421 */
5422 static void
5423clear_screen(void)
5424{
5425 g_coord.X = g_coord.Y = 0;
5426 clear_chars(g_coord, Rows * Columns);
5427}
5428
5429
5430/*
5431 * Clear to end of display
5432 */
5433 static void
5434clear_to_end_of_display(void)
5435{
5436 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5437 * Columns + (Columns - g_coord.X));
5438}
5439
5440
5441/*
5442 * Clear to end of line
5443 */
5444 static void
5445clear_to_end_of_line(void)
5446{
5447 clear_chars(g_coord, Columns - g_coord.X);
5448}
5449
5450
5451/*
5452 * Scroll the scroll region up by `cLines' lines
5453 */
5454 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005455scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005456{
5457 COORD oldcoord = g_coord;
5458
5459 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5460 delete_lines(cLines);
5461
5462 g_coord = oldcoord;
5463}
5464
5465
5466/*
5467 * Set the scroll region
5468 */
5469 static void
5470set_scroll_region(
5471 unsigned left,
5472 unsigned top,
5473 unsigned right,
5474 unsigned bottom)
5475{
5476 if (left >= right
5477 || top >= bottom
5478 || right > (unsigned) Columns - 1
5479 || bottom > (unsigned) Rows - 1)
5480 return;
5481
5482 g_srScrollRegion.Left = left;
5483 g_srScrollRegion.Top = top;
5484 g_srScrollRegion.Right = right;
5485 g_srScrollRegion.Bottom = bottom;
5486}
5487
5488
5489/*
5490 * Insert `cLines' lines at the current cursor position
5491 */
5492 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005493insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005494{
5495 SMALL_RECT source;
5496 COORD dest;
5497 CHAR_INFO fill;
5498
5499 dest.X = 0;
5500 dest.Y = g_coord.Y + cLines;
5501
5502 source.Left = 0;
5503 source.Top = g_coord.Y;
5504 source.Right = g_srScrollRegion.Right;
5505 source.Bottom = g_srScrollRegion.Bottom - cLines;
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 if (source.Bottom < dest.Y)
5520 {
5521 COORD coord;
5522
5523 coord.X = 0;
5524 coord.Y = source.Bottom;
5525 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5526 }
5527}
5528
5529
5530/*
5531 * Delete `cLines' lines at the current cursor position
5532 */
5533 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005534delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005535{
5536 SMALL_RECT source;
5537 COORD dest;
5538 CHAR_INFO fill;
5539 int nb;
5540
5541 dest.X = 0;
5542 dest.Y = g_coord.Y;
5543
5544 source.Left = 0;
5545 source.Top = g_coord.Y + cLines;
5546 source.Right = g_srScrollRegion.Right;
5547 source.Bottom = g_srScrollRegion.Bottom;
5548
5549 fill.Char.AsciiChar = ' ';
5550 fill.Attributes = g_attrCurrent;
5551
5552 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5553
5554 /* Here we have to deal with a win32 console flake: If the scroll
5555 * region looks like abc and we scroll c to a and fill with d we get
5556 * cbd... if we scroll block c one line at a time to a, we get cdd...
5557 * vim expects cdd consistently... So we have to deal with that
5558 * here... (this also occurs scrolling the same way in the other
5559 * direction). */
5560
5561 nb = dest.Y + (source.Bottom - source.Top) + 1;
5562
5563 if (nb < source.Top)
5564 {
5565 COORD coord;
5566
5567 coord.X = 0;
5568 coord.Y = nb;
5569 clear_chars(coord, Columns * (source.Top - nb));
5570 }
5571}
5572
5573
5574/*
5575 * Set the cursor position
5576 */
5577 static void
5578gotoxy(
5579 unsigned x,
5580 unsigned y)
5581{
5582 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5583 return;
5584
5585 /* external cursor coords are 1-based; internal are 0-based */
5586 g_coord.X = x - 1;
5587 g_coord.Y = y - 1;
5588 SetConsoleCursorPosition(g_hConOut, g_coord);
5589}
5590
5591
5592/*
5593 * Set the current text attribute = (foreground | background)
5594 * See ../doc/os_win32.txt for the numbers.
5595 */
5596 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005597textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005599 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005600
5601 SetConsoleTextAttribute(g_hConOut, wAttr);
5602}
5603
5604
5605 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005606textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005608 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005609
5610 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5611}
5612
5613
5614 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005615textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005617 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618
5619 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5620}
5621
5622
5623/*
5624 * restore the default text attribute (whatever we started with)
5625 */
5626 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005627normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628{
5629 textattr(g_attrDefault);
5630}
5631
5632
5633static WORD g_attrPreStandout = 0;
5634
5635/*
5636 * Make the text standout, by brightening it
5637 */
5638 static void
5639standout(void)
5640{
5641 g_attrPreStandout = g_attrCurrent;
5642 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5643}
5644
5645
5646/*
5647 * Turn off standout mode
5648 */
5649 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005650standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005651{
5652 if (g_attrPreStandout)
5653 {
5654 textattr(g_attrPreStandout);
5655 g_attrPreStandout = 0;
5656 }
5657}
5658
5659
5660/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005661 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005662 */
5663 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005664mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005665{
5666 char_u *p;
5667 int n;
5668
5669 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5670 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5671 if (T_ME[0] == ESC && T_ME[1] == '|')
5672 {
5673 p = T_ME + 2;
5674 n = getdigits(&p);
5675 if (*p == 'm' && n > 0)
5676 {
5677 cterm_normal_fg_color = (n & 0xf) + 1;
5678 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5679 }
5680 }
5681}
5682
5683
5684/*
5685 * visual bell: flash the screen
5686 */
5687 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005688visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689{
5690 COORD coordOrigin = {0, 0};
5691 WORD attrFlash = ~g_attrCurrent & 0xff;
5692
5693 DWORD dwDummy;
5694 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5695
5696 if (oldattrs == NULL)
5697 return;
5698 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5699 coordOrigin, &dwDummy);
5700 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5701 coordOrigin, &dwDummy);
5702
5703 Sleep(15); /* wait for 15 msec */
5704 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5705 coordOrigin, &dwDummy);
5706 vim_free(oldattrs);
5707}
5708
5709
5710/*
5711 * Make the cursor visible or invisible
5712 */
5713 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005714cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715{
5716 s_cursor_visible = fVisible;
5717#ifdef MCH_CURSOR_SHAPE
5718 mch_update_cursor();
5719#endif
5720}
5721
5722
5723/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005724 * write `cbToWrite' bytes in `pchBuf' to the screen
5725 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005726 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005727 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005729 char_u *pchBuf,
5730 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731{
5732 COORD coord = g_coord;
5733 DWORD written;
5734
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005735#ifdef FEAT_MBYTE
5736 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5737 {
5738 static WCHAR *unicodebuf = NULL;
5739 static int unibuflen = 0;
5740 int length;
5741 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005742
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005743 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5744 if (unicodebuf == NULL || length > unibuflen)
5745 {
5746 vim_free(unicodebuf);
5747 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5748 unibuflen = length;
5749 }
5750 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5751 unicodebuf, unibuflen);
5752
5753 cells = mb_string2cells(pchBuf, cbToWrite);
5754 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5755 coord, &written);
5756 /* When writing fails or didn't write a single character, pretend one
5757 * character was written, otherwise we get stuck. */
5758 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5759 coord, &cchwritten) == 0
5760 || cchwritten == 0)
5761 cchwritten = 1;
5762
5763 if (cchwritten == length)
5764 {
5765 written = cbToWrite;
5766 g_coord.X += (SHORT)cells;
5767 }
5768 else
5769 {
5770 char_u *p = pchBuf;
5771 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01005772 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005773 written = p - pchBuf;
5774 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5775 }
5776 }
5777 else
5778#endif
5779 {
5780 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5781 coord, &written);
5782 /* When writing fails or didn't write a single character, pretend one
5783 * character was written, otherwise we get stuck. */
5784 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5785 coord, &written) == 0
5786 || written == 0)
5787 written = 1;
5788
5789 g_coord.X += (SHORT) written;
5790 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791
5792 while (g_coord.X > g_srScrollRegion.Right)
5793 {
5794 g_coord.X -= (SHORT) Columns;
5795 if (g_coord.Y < g_srScrollRegion.Bottom)
5796 g_coord.Y++;
5797 }
5798
5799 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5800
5801 return written;
5802}
5803
5804
5805/*
5806 * mch_write(): write the output buffer to the screen, translating ESC
5807 * sequences into calls to console output routines.
5808 */
5809 void
5810mch_write(
5811 char_u *s,
5812 int len)
5813{
5814 s[len] = NUL;
5815
5816 if (!term_console)
5817 {
5818 write(1, s, (unsigned)len);
5819 return;
5820 }
5821
5822 /* translate ESC | sequences into faked bios calls */
5823 while (len--)
5824 {
5825 /* optimization: use one single write_chars for runs of text,
5826 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005827 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828
5829 if (p_wd)
5830 {
5831 WaitForChar(p_wd);
5832 if (prefix != 0)
5833 prefix = 1;
5834 }
5835
5836 if (prefix != 0)
5837 {
5838 DWORD nWritten;
5839
5840 nWritten = write_chars(s, prefix);
5841#ifdef MCH_WRITE_DUMP
5842 if (fdDump)
5843 {
5844 fputc('>', fdDump);
5845 fwrite(s, sizeof(char_u), nWritten, fdDump);
5846 fputs("<\n", fdDump);
5847 }
5848#endif
5849 len -= (nWritten - 1);
5850 s += nWritten;
5851 }
5852 else if (s[0] == '\n')
5853 {
5854 /* \n, newline: go to the beginning of the next line or scroll */
5855 if (g_coord.Y == g_srScrollRegion.Bottom)
5856 {
5857 scroll(1);
5858 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5859 }
5860 else
5861 {
5862 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5863 }
5864#ifdef MCH_WRITE_DUMP
5865 if (fdDump)
5866 fputs("\\n\n", fdDump);
5867#endif
5868 s++;
5869 }
5870 else if (s[0] == '\r')
5871 {
5872 /* \r, carriage return: go to beginning of line */
5873 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5874#ifdef MCH_WRITE_DUMP
5875 if (fdDump)
5876 fputs("\\r\n", fdDump);
5877#endif
5878 s++;
5879 }
5880 else if (s[0] == '\b')
5881 {
5882 /* \b, backspace: move cursor one position left */
5883 if (g_coord.X > g_srScrollRegion.Left)
5884 g_coord.X--;
5885 else if (g_coord.Y > g_srScrollRegion.Top)
5886 {
5887 g_coord.X = g_srScrollRegion.Right;
5888 g_coord.Y--;
5889 }
5890 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5891#ifdef MCH_WRITE_DUMP
5892 if (fdDump)
5893 fputs("\\b\n", fdDump);
5894#endif
5895 s++;
5896 }
5897 else if (s[0] == '\a')
5898 {
5899 /* \a, bell */
5900 MessageBeep(0xFFFFFFFF);
5901#ifdef MCH_WRITE_DUMP
5902 if (fdDump)
5903 fputs("\\a\n", fdDump);
5904#endif
5905 s++;
5906 }
5907 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5908 {
5909#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005910 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005911#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005912 char_u *p;
5913 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914
5915 switch (s[2])
5916 {
5917 /* one or two numeric arguments, separated by ';' */
5918
5919 case '0': case '1': case '2': case '3': case '4':
5920 case '5': case '6': case '7': case '8': case '9':
5921 p = s + 2;
5922 arg1 = getdigits(&p); /* no check for length! */
5923 if (p > s + len)
5924 break;
5925
5926 if (*p == ';')
5927 {
5928 ++p;
5929 arg2 = getdigits(&p); /* no check for length! */
5930 if (p > s + len)
5931 break;
5932
5933 if (*p == 'H')
5934 gotoxy(arg2, arg1);
5935 else if (*p == 'r')
5936 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5937 }
5938 else if (*p == 'A')
5939 {
5940 /* move cursor up arg1 lines in same column */
5941 gotoxy(g_coord.X + 1,
5942 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5943 }
5944 else if (*p == 'C')
5945 {
5946 /* move cursor right arg1 columns in same line */
5947 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5948 g_coord.Y + 1);
5949 }
5950 else if (*p == 'H')
5951 {
5952 gotoxy(1, arg1);
5953 }
5954 else if (*p == 'L')
5955 {
5956 insert_lines(arg1);
5957 }
5958 else if (*p == 'm')
5959 {
5960 if (arg1 == 0)
5961 normvideo();
5962 else
5963 textattr((WORD) arg1);
5964 }
5965 else if (*p == 'f')
5966 {
5967 textcolor((WORD) arg1);
5968 }
5969 else if (*p == 'b')
5970 {
5971 textbackground((WORD) arg1);
5972 }
5973 else if (*p == 'M')
5974 {
5975 delete_lines(arg1);
5976 }
5977
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005978 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005979 s = p + 1;
5980 break;
5981
5982
5983 /* Three-character escape sequences */
5984
5985 case 'A':
5986 /* move cursor up one line in same column */
5987 gotoxy(g_coord.X + 1,
5988 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5989 goto got3;
5990
5991 case 'B':
5992 visual_bell();
5993 goto got3;
5994
5995 case 'C':
5996 /* move cursor right one column in same line */
5997 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5998 g_coord.Y + 1);
5999 goto got3;
6000
6001 case 'E':
6002 termcap_mode_end();
6003 goto got3;
6004
6005 case 'F':
6006 standout();
6007 goto got3;
6008
6009 case 'f':
6010 standend();
6011 goto got3;
6012
6013 case 'H':
6014 gotoxy(1, 1);
6015 goto got3;
6016
6017 case 'j':
6018 clear_to_end_of_display();
6019 goto got3;
6020
6021 case 'J':
6022 clear_screen();
6023 goto got3;
6024
6025 case 'K':
6026 clear_to_end_of_line();
6027 goto got3;
6028
6029 case 'L':
6030 insert_lines(1);
6031 goto got3;
6032
6033 case 'M':
6034 delete_lines(1);
6035 goto got3;
6036
6037 case 'S':
6038 termcap_mode_start();
6039 goto got3;
6040
6041 case 'V':
6042 cursor_visible(TRUE);
6043 goto got3;
6044
6045 case 'v':
6046 cursor_visible(FALSE);
6047 goto got3;
6048
6049 got3:
6050 s += 3;
6051 len -= 2;
6052 }
6053
6054#ifdef MCH_WRITE_DUMP
6055 if (fdDump)
6056 {
6057 fputs("ESC | ", fdDump);
6058 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6059 fputc('\n', fdDump);
6060 }
6061#endif
6062 }
6063 else
6064 {
6065 /* Write a single character */
6066 DWORD nWritten;
6067
6068 nWritten = write_chars(s, 1);
6069#ifdef MCH_WRITE_DUMP
6070 if (fdDump)
6071 {
6072 fputc('>', fdDump);
6073 fwrite(s, sizeof(char_u), nWritten, fdDump);
6074 fputs("<\n", fdDump);
6075 }
6076#endif
6077
6078 len -= (nWritten - 1);
6079 s += nWritten;
6080 }
6081 }
6082
6083#ifdef MCH_WRITE_DUMP
6084 if (fdDump)
6085 fflush(fdDump);
6086#endif
6087}
6088
6089#endif /* FEAT_GUI_W32 */
6090
6091
6092/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006093 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094 */
6095 void
6096mch_delay(
6097 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006098 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006099{
6100#ifdef FEAT_GUI_W32
6101 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006102#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006104# ifdef FEAT_MZSCHEME
6105 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6106 {
6107 int towait = p_mzq;
6108
6109 /* if msec is large enough, wait by portions in p_mzq */
6110 while (msec > 0)
6111 {
6112 mzvim_check_threads();
6113 if (msec < towait)
6114 towait = msec;
6115 Sleep(towait);
6116 msec -= towait;
6117 }
6118 }
6119 else
6120# endif
6121 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122 else
6123 WaitForChar(msec);
6124#endif
6125}
6126
6127
6128/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006129 * This version of remove is not scared by a readonly (backup) file.
6130 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131 * Return 0 for success, -1 for failure.
6132 */
6133 int
6134mch_remove(char_u *name)
6135{
6136#ifdef FEAT_MBYTE
6137 WCHAR *wn = NULL;
6138 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006139#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006140
Bram Moolenaar203258c2016-01-17 22:15:16 +01006141 /*
6142 * On Windows, deleting a directory's symbolic link is done by
6143 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6144 */
6145 if (mch_isdir(name) && mch_is_symbolic_link(name))
6146 return mch_rmdir(name);
6147
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006148 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6149
6150#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6152 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006153 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 if (wn != NULL)
6155 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156 n = DeleteFileW(wn) ? 0 : -1;
6157 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006158 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159 }
6160 }
6161#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006162 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006163}
6164
6165
6166/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006167 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 */
6169 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006170mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006171{
6172#ifndef FEAT_GUI_W32 /* never used */
6173 if (g_fCtrlCPressed || g_fCBrkPressed)
6174 {
6175 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6176 got_int = TRUE;
6177 }
6178#endif
6179}
6180
Bram Moolenaaree273972016-01-02 21:11:51 +01006181/* physical RAM to leave for the OS */
6182#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006183
6184/*
6185 * How much main memory in KiB that can be used by VIM.
6186 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006187 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006188mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006189{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006190 MEMORYSTATUSEX ms;
6191
Bram Moolenaaree273972016-01-02 21:11:51 +01006192 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006193 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6194 * what fits in 32 bits. But it's not always available. */
6195 ms.dwLength = sizeof(MEMORYSTATUSEX);
6196 GlobalMemoryStatusEx(&ms);
6197 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006198 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006199 /* Process address space fits in physical RAM, use all of it. */
6200 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006201 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006202 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006203 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006204 /* Catch old NT box or perverse hardware setup. */
6205 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006206 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006207 /* Use physical RAM less reserve for OS + data. */
6208 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006209}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211#ifdef FEAT_MBYTE
6212/*
6213 * Same code as below, but with wide functions and no comments.
6214 * Return 0 for success, non-zero for failure.
6215 */
6216 int
6217mch_wrename(WCHAR *wold, WCHAR *wnew)
6218{
6219 WCHAR *p;
6220 int i;
6221 WCHAR szTempFile[_MAX_PATH + 1];
6222 WCHAR szNewPath[_MAX_PATH + 1];
6223 HANDLE hf;
6224
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006225 p = wold;
6226 for (i = 0; wold[i] != NUL; ++i)
6227 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6228 && wold[i + 1] != 0)
6229 p = wold + i + 1;
6230 if ((int)(wold + i - p) < 8 || p[6] != '~')
6231 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232
6233 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6234 return -1;
6235 *p = NUL;
6236
6237 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6238 return -2;
6239
6240 if (!DeleteFileW(szTempFile))
6241 return -3;
6242
6243 if (!MoveFileW(wold, szTempFile))
6244 return -4;
6245
6246 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6247 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6248 return -5;
6249 if (!CloseHandle(hf))
6250 return -6;
6251
6252 if (!MoveFileW(szTempFile, wnew))
6253 {
6254 (void)MoveFileW(szTempFile, wold);
6255 return -7;
6256 }
6257
6258 DeleteFileW(szTempFile);
6259
6260 if (!DeleteFileW(wold))
6261 return -8;
6262
6263 return 0;
6264}
6265#endif
6266
6267
6268/*
6269 * mch_rename() works around a bug in rename (aka MoveFile) in
6270 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6271 * file whose short file name is "FOO.BAR" (its long file name will
6272 * be correct: "foo.bar~"). Because a file can be accessed by
6273 * either its SFN or its LFN, "foo.bar" has effectively been
6274 * renamed to "foo.bar", which is not at all what was wanted. This
6275 * seems to happen only when renaming files with three-character
6276 * extensions by appending a suffix that does not include ".".
6277 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6278 *
6279 * There is another problem, which isn't really a bug but isn't right either:
6280 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6281 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6282 * service pack 6. Doesn't seem to happen on Windows 98.
6283 *
6284 * Like rename(), returns 0 upon success, non-zero upon failure.
6285 * Should probably set errno appropriately when errors occur.
6286 */
6287 int
6288mch_rename(
6289 const char *pszOldFile,
6290 const char *pszNewFile)
6291{
6292 char szTempFile[_MAX_PATH+1];
6293 char szNewPath[_MAX_PATH+1];
6294 char *pszFilePart;
6295 HANDLE hf;
6296#ifdef FEAT_MBYTE
6297 WCHAR *wold = NULL;
6298 WCHAR *wnew = NULL;
6299 int retval = -1;
6300
6301 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6302 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006303 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6304 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 if (wold != NULL && wnew != NULL)
6306 retval = mch_wrename(wold, wnew);
6307 vim_free(wold);
6308 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006309 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310 }
6311#endif
6312
6313 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006314 * No need to play tricks unless the file name contains a "~" as the
6315 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006317 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6318 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6319 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320
6321 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6322 * a directory, no error is returned and pszFilePart will be NULL. */
6323 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6324 || pszFilePart == NULL)
6325 return -1;
6326 *pszFilePart = NUL;
6327
6328 /* Get (and create) a unique temporary file name in directory of new file */
6329 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6330 return -2;
6331
6332 /* blow the temp file away */
6333 if (!DeleteFile(szTempFile))
6334 return -3;
6335
6336 /* rename old file to the temp file */
6337 if (!MoveFile(pszOldFile, szTempFile))
6338 return -4;
6339
6340 /* now create an empty file called pszOldFile; this prevents the operating
6341 * system using pszOldFile as an alias (SFN) if we're renaming within the
6342 * same directory. For example, we're editing a file called
6343 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6344 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6345 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006346 * cause all sorts of problems later in buf_write(). So, we create an
6347 * empty file called filena~1.txt and the system will have to find some
6348 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349 */
6350 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6351 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6352 return -5;
6353 if (!CloseHandle(hf))
6354 return -6;
6355
6356 /* rename the temp file to the new file */
6357 if (!MoveFile(szTempFile, pszNewFile))
6358 {
6359 /* Renaming failed. Rename the file back to its old name, so that it
6360 * looks like nothing happened. */
6361 (void)MoveFile(szTempFile, pszOldFile);
6362
6363 return -7;
6364 }
6365
6366 /* Seems to be left around on Novell filesystems */
6367 DeleteFile(szTempFile);
6368
6369 /* finally, remove the empty old file */
6370 if (!DeleteFile(pszOldFile))
6371 return -8;
6372
6373 return 0; /* success */
6374}
6375
6376/*
6377 * Get the default shell for the current hardware platform
6378 */
6379 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006380default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382 PlatformId();
6383
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006384 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006385}
6386
6387/*
6388 * mch_access() extends access() to do more detailed check on network drives.
6389 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6390 */
6391 int
6392mch_access(char *n, int p)
6393{
6394 HANDLE hFile;
6395 DWORD am;
6396 int retval = -1; /* default: fail */
6397#ifdef FEAT_MBYTE
6398 WCHAR *wn = NULL;
6399
6400 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006401 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402#endif
6403
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006404 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405 {
6406 char TempName[_MAX_PATH + 16] = "";
6407#ifdef FEAT_MBYTE
6408 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6409#endif
6410
6411 if (p & R_OK)
6412 {
6413 /* Read check is performed by seeing if we can do a find file on
6414 * the directory for any file. */
6415#ifdef FEAT_MBYTE
6416 if (wn != NULL)
6417 {
6418 int i;
6419 WIN32_FIND_DATAW d;
6420
6421 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6422 TempNameW[i] = wn[i];
6423 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6424 TempNameW[i++] = '\\';
6425 TempNameW[i++] = '*';
6426 TempNameW[i++] = 0;
6427
6428 hFile = FindFirstFileW(TempNameW, &d);
6429 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006430 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006431 else
6432 (void)FindClose(hFile);
6433 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006434 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006435#endif
6436 {
6437 char *pch;
6438 WIN32_FIND_DATA d;
6439
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006440 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006441 pch = TempName + STRLEN(TempName) - 1;
6442 if (*pch != '\\' && *pch != '/')
6443 *++pch = '\\';
6444 *++pch = '*';
6445 *++pch = NUL;
6446
6447 hFile = FindFirstFile(TempName, &d);
6448 if (hFile == INVALID_HANDLE_VALUE)
6449 goto getout;
6450 (void)FindClose(hFile);
6451 }
6452 }
6453
6454 if (p & W_OK)
6455 {
6456 /* Trying to create a temporary file in the directory should catch
6457 * directories on read-only network shares. However, in
6458 * directories whose ACL allows writes but denies deletes will end
6459 * up keeping the temporary file :-(. */
6460#ifdef FEAT_MBYTE
6461 if (wn != NULL)
6462 {
6463 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006464 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006465 else
6466 DeleteFileW(TempNameW);
6467 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006468 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469#endif
6470 {
6471 if (!GetTempFileName(n, "VIM", 0, TempName))
6472 goto getout;
6473 mch_remove((char_u *)TempName);
6474 }
6475 }
6476 }
6477 else
6478 {
6479 /* Trying to open the file for the required access does ACL, read-only
6480 * network share, and file attribute checks. */
6481 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6482 | ((p & R_OK) ? GENERIC_READ : 0);
6483#ifdef FEAT_MBYTE
6484 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006486 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487#endif
6488 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6489 if (hFile == INVALID_HANDLE_VALUE)
6490 goto getout;
6491 CloseHandle(hFile);
6492 }
6493
6494 retval = 0; /* success */
6495getout:
6496#ifdef FEAT_MBYTE
6497 vim_free(wn);
6498#endif
6499 return retval;
6500}
6501
6502#if defined(FEAT_MBYTE) || defined(PROTO)
6503/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006504 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006505 */
6506 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006507mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006509 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6510# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511 WCHAR *wn;
6512 int f;
6513
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006514 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006516 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 if (wn != NULL)
6518 {
6519 f = _wopen(wn, flags, mode);
6520 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006521 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 }
6523 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006524# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006526 /* open() can open a file which name is longer than _MAX_PATH bytes
6527 * and shorter than _MAX_PATH characters successfully, but sometimes it
6528 * causes unexpected error in another part. We make it an error explicitly
6529 * here. */
6530 if (strlen(name) >= _MAX_PATH)
6531 return -1;
6532
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 return open(name, flags, mode);
6534}
6535
6536/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006537 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538 */
6539 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006540mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541{
6542 WCHAR *wn, *wm;
6543 FILE *f = NULL;
6544
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006545 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006547# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006548 /* Work around an annoying assertion in the Microsoft debug CRT
6549 * when mode's text/binary setting doesn't match _get_fmode(). */
6550 char newMode = mode[strlen(mode) - 1];
6551 int oldMode = 0;
6552
6553 _get_fmode(&oldMode);
6554 if (newMode == 't')
6555 _set_fmode(_O_TEXT);
6556 else if (newMode == 'b')
6557 _set_fmode(_O_BINARY);
6558# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006559 wn = enc_to_utf16((char_u *)name, NULL);
6560 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561 if (wn != NULL && wm != NULL)
6562 f = _wfopen(wn, wm);
6563 vim_free(wn);
6564 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006565
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006566# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006567 _set_fmode(oldMode);
6568# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006569 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 }
6571
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006572 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6573 * and shorter than _MAX_PATH characters successfully, but sometimes it
6574 * causes unexpected error in another part. We make it an error explicitly
6575 * here. */
6576 if (strlen(name) >= _MAX_PATH)
6577 return NULL;
6578
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579 return fopen(name, mode);
6580}
6581#endif
6582
6583#ifdef FEAT_MBYTE
6584/*
6585 * SUB STREAM (aka info stream) handling:
6586 *
6587 * NTFS can have sub streams for each file. Normal contents of file is
6588 * stored in the main stream, and extra contents (author information and
6589 * title and so on) can be stored in sub stream. After Windows 2000, user
6590 * can access and store those informations in sub streams via explorer's
6591 * property menuitem in right click menu. Those informations in sub streams
6592 * were lost when copying only the main stream. So we have to copy sub
6593 * streams.
6594 *
6595 * Incomplete explanation:
6596 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6597 * More useful info and an example:
6598 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6599 */
6600
6601/*
6602 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6603 * and write to stream "substream" of file "to".
6604 * Errors are ignored.
6605 */
6606 static void
6607copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6608{
6609 HANDLE hTo;
6610 WCHAR *to_name;
6611
6612 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6613 wcscpy(to_name, to);
6614 wcscat(to_name, substream);
6615
6616 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6617 FILE_ATTRIBUTE_NORMAL, NULL);
6618 if (hTo != INVALID_HANDLE_VALUE)
6619 {
6620 long done;
6621 DWORD todo;
6622 DWORD readcnt, written;
6623 char buf[4096];
6624
6625 /* Copy block of bytes at a time. Abort when something goes wrong. */
6626 for (done = 0; done < len; done += written)
6627 {
6628 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006629 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6630 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6632 FALSE, FALSE, context)
6633 || readcnt != todo
6634 || !WriteFile(hTo, buf, todo, &written, NULL)
6635 || written != todo)
6636 break;
6637 }
6638 CloseHandle(hTo);
6639 }
6640
6641 free(to_name);
6642}
6643
6644/*
6645 * Copy info streams from file "from" to file "to".
6646 */
6647 static void
6648copy_infostreams(char_u *from, char_u *to)
6649{
6650 WCHAR *fromw;
6651 WCHAR *tow;
6652 HANDLE sh;
6653 WIN32_STREAM_ID sid;
6654 int headersize;
6655 WCHAR streamname[_MAX_PATH];
6656 DWORD readcount;
6657 void *context = NULL;
6658 DWORD lo, hi;
6659 int len;
6660
6661 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006662 fromw = enc_to_utf16(from, NULL);
6663 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664 if (fromw != NULL && tow != NULL)
6665 {
6666 /* Open the file for reading. */
6667 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6668 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6669 if (sh != INVALID_HANDLE_VALUE)
6670 {
6671 /* Use BackupRead() to find the info streams. Repeat until we
6672 * have done them all.*/
6673 for (;;)
6674 {
6675 /* Get the header to find the length of the stream name. If
6676 * the "readcount" is zero we have done all info streams. */
6677 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006678 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6680 &readcount, FALSE, FALSE, &context)
6681 || readcount == 0)
6682 break;
6683
6684 /* We only deal with streams that have a name. The normal
6685 * file data appears to be without a name, even though docs
6686 * suggest it is called "::$DATA". */
6687 if (sid.dwStreamNameSize > 0)
6688 {
6689 /* Read the stream name. */
6690 if (!BackupRead(sh, (LPBYTE)streamname,
6691 sid.dwStreamNameSize,
6692 &readcount, FALSE, FALSE, &context))
6693 break;
6694
6695 /* Copy an info stream with a name ":anything:$DATA".
6696 * Skip "::$DATA", it has no stream name (examples suggest
6697 * it might be used for the normal file contents).
6698 * Note that BackupRead() counts bytes, but the name is in
6699 * wide characters. */
6700 len = readcount / sizeof(WCHAR);
6701 streamname[len] = 0;
6702 if (len > 7 && wcsicmp(streamname + len - 6,
6703 L":$DATA") == 0)
6704 {
6705 streamname[len - 6] = 0;
6706 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006707 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708 }
6709 }
6710
6711 /* Advance to the next stream. We might try seeking too far,
6712 * but BackupSeek() doesn't skip over stream borders, thus
6713 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006714 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 &lo, &hi, &context);
6716 }
6717
6718 /* Clear the context. */
6719 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6720
6721 CloseHandle(sh);
6722 }
6723 }
6724 vim_free(fromw);
6725 vim_free(tow);
6726}
6727#endif
6728
6729/*
6730 * Copy file attributes from file "from" to file "to".
6731 * For Windows NT and later we copy info streams.
6732 * Always returns zero, errors are ignored.
6733 */
6734 int
6735mch_copy_file_attribute(char_u *from, char_u *to)
6736{
6737#ifdef FEAT_MBYTE
6738 /* File streams only work on Windows NT and later. */
6739 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006740 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741#endif
6742 return 0;
6743}
6744
6745#if defined(MYRESETSTKOFLW) || defined(PROTO)
6746/*
6747 * Recreate a destroyed stack guard page in win32.
6748 * Written by Benjamin Peterson.
6749 */
6750
6751/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006752#define MIN_STACK_WINNT 2
6753
6754/*
6755 * This function does the same thing as _resetstkoflw(), which is only
6756 * available in DevStudio .net and later.
6757 * Returns 0 for failure, 1 for success.
6758 */
6759 int
6760myresetstkoflw(void)
6761{
6762 BYTE *pStackPtr;
6763 BYTE *pGuardPage;
6764 BYTE *pStackBase;
6765 BYTE *pLowestPossiblePage;
6766 MEMORY_BASIC_INFORMATION mbi;
6767 SYSTEM_INFO si;
6768 DWORD nPageSize;
6769 DWORD dummy;
6770
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772
6773 /* We need to know the system page size. */
6774 GetSystemInfo(&si);
6775 nPageSize = si.dwPageSize;
6776
6777 /* ...and the current stack pointer */
6778 pStackPtr = (BYTE*)_alloca(1);
6779
6780 /* ...and the base of the stack. */
6781 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6782 return 0;
6783 pStackBase = (BYTE*)mbi.AllocationBase;
6784
6785 /* ...and the page thats min_stack_req pages away from stack base; this is
6786 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006787 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006790 /* We want the first committed page in the stack Start at the stack
6791 * base and move forward through memory until we find a committed block.
6792 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006793 BYTE *pBlock = pStackBase;
6794
Bram Moolenaara466c992005-07-09 21:03:22 +00006795 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006796 {
6797 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6798 return 0;
6799
6800 pBlock += mbi.RegionSize;
6801
6802 if (mbi.State & MEM_COMMIT)
6803 break;
6804 }
6805
6806 /* mbi now describes the first committed block in the stack. */
6807 if (mbi.Protect & PAGE_GUARD)
6808 return 1;
6809
6810 /* decide where the guard page should start */
6811 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6812 pGuardPage = pLowestPossiblePage;
6813 else
6814 pGuardPage = (BYTE*)mbi.BaseAddress;
6815
6816 /* allocate the guard page */
6817 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6818 return 0;
6819
6820 /* apply the guard attribute to the page */
6821 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6822 &dummy))
6823 return 0;
6824 }
6825
6826 return 1;
6827}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006828#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006830
6831#if defined(FEAT_MBYTE) || defined(PROTO)
6832/*
6833 * The command line arguments in UCS2
6834 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006835static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006836static LPWSTR *ArglistW = NULL;
6837static int global_argc = 0;
6838static char **global_argv;
6839
6840static int used_file_argc = 0; /* last argument in global_argv[] used
6841 for the argument list. */
6842static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6843 command line arguments added to
6844 the argument list */
6845static int used_file_count = 0; /* nr of entries in used_file_indexes */
6846static int used_file_literal = FALSE; /* take file names literally */
6847static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006848static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006849static int used_alist_count = 0;
6850
6851
6852/*
6853 * Get the command line arguments. Unicode version.
6854 * Returns argc. Zero when something fails.
6855 */
6856 int
6857get_cmd_argsW(char ***argvp)
6858{
6859 char **argv = NULL;
6860 int argc = 0;
6861 int i;
6862
Bram Moolenaar14993322014-09-09 12:25:33 +02006863 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006864 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6865 if (ArglistW != NULL)
6866 {
6867 argv = malloc((nArgsW + 1) * sizeof(char *));
6868 if (argv != NULL)
6869 {
6870 argc = nArgsW;
6871 argv[argc] = NULL;
6872 for (i = 0; i < argc; ++i)
6873 {
6874 int len;
6875
6876 /* Convert each Unicode argument to the current codepage. */
6877 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006878 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006879 (LPSTR *)&argv[i], &len, 0, 0);
6880 if (argv[i] == NULL)
6881 {
6882 /* Out of memory, clear everything. */
6883 while (i > 0)
6884 free(argv[--i]);
6885 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006886 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006887 argc = 0;
6888 }
6889 }
6890 }
6891 }
6892
6893 global_argc = argc;
6894 global_argv = argv;
6895 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006896 {
6897 if (used_file_indexes != NULL)
6898 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006899 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006900 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006901
6902 if (argvp != NULL)
6903 *argvp = argv;
6904 return argc;
6905}
6906
6907 void
6908free_cmd_argsW(void)
6909{
6910 if (ArglistW != NULL)
6911 {
6912 GlobalFree(ArglistW);
6913 ArglistW = NULL;
6914 }
6915}
6916
6917/*
6918 * Remember "name" is an argument that was added to the argument list.
6919 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6920 * is called.
6921 */
6922 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006923used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006924{
6925 int i;
6926
6927 if (used_file_indexes == NULL)
6928 return;
6929 for (i = used_file_argc + 1; i < global_argc; ++i)
6930 if (STRCMP(global_argv[i], name) == 0)
6931 {
6932 used_file_argc = i;
6933 used_file_indexes[used_file_count++] = i;
6934 break;
6935 }
6936 used_file_literal = literal;
6937 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006938 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006939}
6940
6941/*
6942 * Remember the length of the argument list as it was. If it changes then we
6943 * leave it alone when 'encoding' is set.
6944 */
6945 void
6946set_alist_count(void)
6947{
6948 used_alist_count = GARGCOUNT;
6949}
6950
6951/*
6952 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6953 * has been changed while starting up. Use the UCS-2 command line arguments
6954 * and convert them to 'encoding'.
6955 */
6956 void
6957fix_arg_enc(void)
6958{
6959 int i;
6960 int idx;
6961 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006962 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006963
6964 /* Safety checks:
6965 * - if argument count differs between the wide and non-wide argument
6966 * list, something must be wrong.
6967 * - the file name arguments must have been located.
6968 * - the length of the argument list wasn't changed by the user.
6969 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006970 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006971 || ArglistW == NULL
6972 || used_file_indexes == NULL
6973 || used_file_count == 0
6974 || used_alist_count != GARGCOUNT)
6975 return;
6976
Bram Moolenaar86b68352004-12-27 21:59:20 +00006977 /* Remember the buffer numbers for the arguments. */
6978 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6979 if (fnum_list == NULL)
6980 return; /* out of memory */
6981 for (i = 0; i < GARGCOUNT; ++i)
6982 fnum_list[i] = GARGLIST[i].ae_fnum;
6983
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006984 /* Clear the argument list. Make room for the new arguments. */
6985 alist_clear(&global_alist);
6986 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006987 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006988
6989 for (i = 0; i < used_file_count; ++i)
6990 {
6991 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006992 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006993 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006994 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006995#ifdef FEAT_DIFF
6996 /* When using diff mode may need to concatenate file name to
6997 * directory name. Just like it's done in main(). */
6998 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6999 && !mch_isdir(alist_name(&GARGLIST[0])))
7000 {
7001 char_u *r;
7002
7003 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7004 if (r != NULL)
7005 {
7006 vim_free(str);
7007 str = r;
7008 }
7009 }
7010#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007011 /* Re-use the old buffer by renaming it. When not using literal
7012 * names it's done by alist_expand() below. */
7013 if (used_file_literal)
7014 buf_set_name(fnum_list[i], str);
7015
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007016 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007017 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007018 }
7019
7020 if (!used_file_literal)
7021 {
7022 /* Now expand wildcards in the arguments. */
7023 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7024 * filename characters but are excluded from 'isfname' to make
7025 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7026 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007027 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007028 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7029 }
7030
7031 /* If wildcard expansion failed, we are editing the first file of the
7032 * arglist and there is no file name: Edit the first argument now. */
7033 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7034 {
7035 do_cmdline_cmd((char_u *)":rewind");
7036 if (GARGCOUNT == 1 && used_file_full_path)
7037 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7038 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007039
7040 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007041}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007042#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007043
7044 int
7045mch_setenv(char *var, char *value, int x)
7046{
7047 char_u *envbuf;
7048
7049 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7050 if (envbuf == NULL)
7051 return -1;
7052
7053 sprintf((char *)envbuf, "%s=%s", var, value);
7054
7055#ifdef FEAT_MBYTE
7056 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7057 {
7058 WCHAR *p = enc_to_utf16(envbuf, NULL);
7059
7060 vim_free(envbuf);
7061 if (p == NULL)
7062 return -1;
7063 _wputenv(p);
7064# ifdef libintl_wputenv
7065 libintl_wputenv(p);
7066# endif
7067 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7068 vim_free(p);
7069 }
7070 else
7071#endif
7072 {
7073 _putenv((char *)envbuf);
7074# ifdef libintl_putenv
7075 libintl_putenv((char *)envbuf);
7076# endif
7077 /* Unlike Un*x systems, we can free the string for _putenv(). */
7078 vim_free(envbuf);
7079 }
7080
7081 return 0;
7082}