blob: 91f453f2e9a9b3db2d84cec77dda7770c19a4c09 [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
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100206static int vtp_working = 0;
207static void vtp_init();
208static void vtp_exit();
209static int vtp_printf(char *format, ...);
210static void vtp_sgr_bulk(int arg);
211static void vtp_sgr_bulks(int argc, int *argv);
212
213static guicolor_T save_console_bg_rgb;
214static guicolor_T save_console_fg_rgb;
215
216# ifdef FEAT_TERMGUICOLORS
217# define USE_VTP (vtp_working && p_tgc)
218# else
219# define USE_VTP 0
220# endif
221
222static void set_console_color_rgb(void);
223static void reset_console_color_rgb(void);
224#endif
225
226/* This flag is newly created from Windows 10 */
227#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
228# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
229#endif
230
231#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100239#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100240/* Dynamic loading for portability */
241typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
242{
243 ULONG cbSize;
244 COORD dwSize;
245 COORD dwCursorPosition;
246 WORD wAttributes;
247 SMALL_RECT srWindow;
248 COORD dwMaximumWindowSize;
249 WORD wPopupAttributes;
250 BOOL bFullscreenSupported;
251 COLORREF ColorTable[16];
252} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
253typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
254static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
255typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
256static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
257static BOOL has_csbiex = FALSE;
258
259/*
260 * Get version number including build number
261 */
262typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
263# define MAKE_VER(major, minor, build) \
264 (((major) << 24) | ((minor) << 16) | (build))
265
266 static DWORD
267get_build_number(void)
268{
269 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
270 HMODULE hNtdll;
271 PfnRtlGetVersion pRtlGetVersion;
272 DWORD ver = MAKE_VER(0, 0, 0);
273
274 hNtdll = GetModuleHandle("ntdll.dll");
275 if (hNtdll != NULL)
276 {
277 pRtlGetVersion =
278 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
279 pRtlGetVersion(&osver);
280 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
281 min(osver.dwMinorVersion, 255),
282 min(osver.dwBuildNumber, 32767));
283 }
284 return ver;
285}
286
287
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288/*
289 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100291 */
292 static BOOL
293read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
299 enum
300 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100301 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 static DWORD s_dwIndex = 0;
305 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100306 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100307 int head;
308 int tail;
309 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200311 if (nLength == -2)
312 return (s_dwMax > 0) ? TRUE : FALSE;
313
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100314 if (!win8_or_later)
315 {
316 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200317 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
318 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 }
320
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321 if (s_dwMax == 0)
322 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100323 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200324 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
325 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100327 s_dwIndex = 0;
328 s_dwMax = dwEvents;
329 if (dwEvents == 0)
330 {
331 *lpEvents = 0;
332 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100334
335 if (s_dwMax > 1)
336 {
337 head = 0;
338 tail = s_dwMax - 1;
339 while (head != tail)
340 {
341 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
342 && s_irCache[head + 1].EventType
343 == WINDOW_BUFFER_SIZE_EVENT)
344 {
345 /* Remove duplicate event to avoid flicker. */
346 for (i = head; i < tail; ++i)
347 s_irCache[i] = s_irCache[i + 1];
348 --tail;
349 continue;
350 }
351 head++;
352 }
353 s_dwMax = tail + 1;
354 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100355 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100356
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100357 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200358 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100359 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100360 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100361 return TRUE;
362}
363
364/*
365 * Version of PeekConsoleInput() that works with IME.
366 */
367 static BOOL
368peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 HANDLE hInput,
370 INPUT_RECORD *lpBuffer,
371 DWORD nLength,
372 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100373{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100374 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375}
376
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100377# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200378 static DWORD
379msg_wait_for_multiple_objects(
380 DWORD nCount,
381 LPHANDLE pHandles,
382 BOOL fWaitAll,
383 DWORD dwMilliseconds,
384 DWORD dwWakeMask)
385{
386 if (read_console_input(NULL, NULL, -2, NULL))
387 return WAIT_OBJECT_0;
388 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
389 dwMilliseconds, dwWakeMask);
390}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100391# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200392
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100393# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200394 static DWORD
395wait_for_single_object(
396 HANDLE hHandle,
397 DWORD dwMilliseconds)
398{
399 if (read_console_input(NULL, NULL, -2, NULL))
400 return WAIT_OBJECT_0;
401 return WaitForSingleObject(hHandle, dwMilliseconds);
402}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100403# endif
404#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200405
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 static void
407get_exe_name(void)
408{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100409 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
410 * as the maximum length that works (plus a NUL byte). */
411#define MAX_ENV_PATH_LEN 8192
412 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200413 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414
415 if (exe_name == NULL)
416 {
417 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100418 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 if (*temp != NUL)
420 exe_name = FullName_save((char_u *)temp, FALSE);
421 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000422
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200423 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000424 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200425 exe_path = vim_strnsave(exe_name,
426 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000428 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200429 /* Append our starting directory to $PATH, so that when doing
430 * "!xxd" it's found in our starting directory. Needed because
431 * SearchPath() also looks there. */
432 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100433 if (p == NULL
434 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100436 if (p == NULL || *p == NUL)
437 temp[0] = NUL;
438 else
439 {
440 STRCPY(temp, p);
441 STRCAT(temp, ";");
442 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100444 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200445 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000446 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448}
449
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200450/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100451 * Unescape characters in "p" that appear in "escaped".
452 */
453 static void
454unescape_shellxquote(char_u *p, char_u *escaped)
455{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100456 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100457 int n;
458
459 while (*p != NUL)
460 {
461 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
462 mch_memmove(p, p + 1, l--);
463#ifdef FEAT_MBYTE
464 n = (*mb_ptr2len)(p);
465#else
466 n = 1;
467#endif
468 p += n;
469 l -= n;
470 }
471}
472
473/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 * Load library "name".
475 */
476 HINSTANCE
477vimLoadLib(char *name)
478{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200479 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200481 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
482 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200483 if (exe_path == NULL)
484 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200485 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200486 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 WCHAR old_dirw[MAXPATHL];
488
489 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
490 {
491 /* Change directory to where the executable is, both to make
492 * sure we find a .dll there and to avoid looking for a .dll
493 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100494 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200495 dll = LoadLibrary(name);
496 SetCurrentDirectoryW(old_dirw);
497 return dll;
498 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200499 }
500 return dll;
501}
502
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100503#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
504/*
505 * Get related information about 'funcname' which is imported by 'hInst'.
506 * If 'info' is 0, return the function address.
507 * If 'info' is 1, return the module name which the function is imported from.
508 */
509 static void *
510get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
511{
512 PBYTE pImage = (PBYTE)hInst;
513 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
514 PIMAGE_NT_HEADERS pPE;
515 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
516 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
517 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
518 PIMAGE_IMPORT_BY_NAME pImpName;
519
520 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
521 return NULL;
522 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
523 if (pPE->Signature != IMAGE_NT_SIGNATURE)
524 return NULL;
525 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
526 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
527 .VirtualAddress);
528 for (; pImpDesc->FirstThunk; ++pImpDesc)
529 {
530 if (!pImpDesc->OriginalFirstThunk)
531 continue;
532 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
533 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
534 for (; pIAT->u1.Function; ++pIAT, ++pINT)
535 {
536 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
537 continue;
538 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
539 + (UINT_PTR)(pINT->u1.AddressOfData));
540 if (strcmp((char *)pImpName->Name, funcname) == 0)
541 {
542 switch (info)
543 {
544 case 0:
545 return (void *)pIAT->u1.Function;
546 case 1:
547 return (void *)(pImage + pImpDesc->Name);
548 default:
549 return NULL;
550 }
551 }
552 }
553 }
554 return NULL;
555}
556
557/*
558 * Get the module handle which 'funcname' in 'hInst' is imported from.
559 */
560 HINSTANCE
561find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
562{
563 char *modulename;
564
565 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
566 if (modulename != NULL)
567 return GetModuleHandleA(modulename);
568 return NULL;
569}
570
571/*
572 * Get the address of 'funcname' which is imported by 'hInst' DLL.
573 */
574 void *
575get_dll_import_func(HINSTANCE hInst, const char *funcname)
576{
577 return get_imported_func_info(hInst, funcname, 0);
578}
579#endif
580
Bram Moolenaar071d4272004-06-13 20:20:40 +0000581#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
582# ifndef GETTEXT_DLL
583# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100584# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000585# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200586/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000587static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200588static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000589static char *null_libintl_textdomain(const char *);
590static char *null_libintl_bindtextdomain(const char *, const char *);
591static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100592static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100593static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000594
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200595static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000596char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200597char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
598 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000599char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
600char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000602char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
603 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100604int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100605int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606
607 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100608dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609{
610 int i;
611 static struct
612 {
613 char *name;
614 FARPROC *ptr;
615 } libintl_entry[] =
616 {
617 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200618 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
620 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
621 {NULL, NULL}
622 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100623 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624
625 /* No need to initialize twice. */
626 if (hLibintlDLL)
627 return 1;
628 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100629 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100630#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100631 if (!hLibintlDLL)
632 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100633#endif
634 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000635 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200636 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000637 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200638 verbose_enter();
639 EMSG2(_(e_loadlib), GETTEXT_DLL);
640 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200642 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643 }
644 for (i = 0; libintl_entry[i].name != NULL
645 && libintl_entry[i].ptr != NULL; ++i)
646 {
647 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
648 libintl_entry[i].name)) == NULL)
649 {
650 dyn_libintl_end();
651 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000652 {
653 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000655 verbose_leave();
656 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657 return 0;
658 }
659 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000660
661 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000662 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000663 "bind_textdomain_codeset");
664 if (dyn_libintl_bind_textdomain_codeset == NULL)
665 dyn_libintl_bind_textdomain_codeset =
666 null_libintl_bind_textdomain_codeset;
667
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100668 /* _putenv() function for the libintl.dll is optional. */
669 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
670 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100671 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100672 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100673 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
674 }
675 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100676 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100677 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
678 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100679
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 return 1;
681}
682
683 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100684dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685{
686 if (hLibintlDLL)
687 FreeLibrary(hLibintlDLL);
688 hLibintlDLL = NULL;
689 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200690 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691 dyn_libintl_textdomain = null_libintl_textdomain;
692 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000693 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100694 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100695 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000696}
697
698 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000699null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700{
701 return (char*)msgid;
702}
703
704 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200705null_libintl_ngettext(
706 const char *msgid,
707 const char *msgid_plural,
708 unsigned long n)
709{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200710 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200711}
712
Bram Moolenaaree695f72016-08-03 22:08:45 +0200713 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100714null_libintl_bindtextdomain(
715 const char *domainname UNUSED,
716 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717{
718 return NULL;
719}
720
721 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100722null_libintl_bind_textdomain_codeset(
723 const char *domainname UNUSED,
724 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000725{
726 return NULL;
727}
728
729 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100730null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000731{
732 return NULL;
733}
734
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200735 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100736null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100737{
738 return 0;
739}
740
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200741 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100742null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100743{
744 return 0;
745}
746
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747#endif /* DYNAMIC_GETTEXT */
748
749/* This symbol is not defined in older versions of the SDK or Visual C++ */
750
751#ifndef VER_PLATFORM_WIN32_WINDOWS
752# define VER_PLATFORM_WIN32_WINDOWS 1
753#endif
754
755DWORD g_PlatformId;
756
757#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100758# ifndef PROTO
759# include <aclapi.h>
760# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200761# ifndef PROTECTED_DACL_SECURITY_INFORMATION
762# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
763# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764#endif
765
Bram Moolenaar27515922013-06-29 15:36:26 +0200766#ifdef HAVE_ACL
767/*
768 * Enables or disables the specified privilege.
769 */
770 static BOOL
771win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
772{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100773 BOOL bResult;
774 LUID luid;
775 HANDLE hToken;
776 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200777
778 if (!OpenProcessToken(GetCurrentProcess(),
779 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
780 return FALSE;
781
782 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
783 {
784 CloseHandle(hToken);
785 return FALSE;
786 }
787
Bram Moolenaar45500912014-07-09 20:51:07 +0200788 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200789 tokenPrivileges.Privileges[0].Luid = luid;
790 tokenPrivileges.Privileges[0].Attributes = bEnable ?
791 SE_PRIVILEGE_ENABLED : 0;
792
793 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
794 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
795
796 CloseHandle(hToken);
797
798 return bResult && GetLastError() == ERROR_SUCCESS;
799}
800#endif
801
Bram Moolenaar071d4272004-06-13 20:20:40 +0000802/*
803 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
804 * VER_PLATFORM_WIN32_WINDOWS (Win95).
805 */
806 void
807PlatformId(void)
808{
809 static int done = FALSE;
810
811 if (!done)
812 {
813 OSVERSIONINFO ovi;
814
815 ovi.dwOSVersionInfoSize = sizeof(ovi);
816 GetVersionEx(&ovi);
817
818 g_PlatformId = ovi.dwPlatformId;
819
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100820 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
821 || ovi.dwMajorVersion > 6)
822 win8_or_later = TRUE;
823
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200825 /* Enable privilege for getting or setting SACLs. */
826 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000827#endif
828 done = TRUE;
829 }
830}
831
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832#ifndef FEAT_GUI_W32
833
834#define SHIFT (SHIFT_PRESSED)
835#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
836#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
837#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
838
839
840/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
841 * We map function keys to their ANSI terminal equivalents, as produced
842 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
843 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
844 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
845 * combinations of function/arrow/etc keys.
846 */
847
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000848static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000849{
850 WORD wVirtKey;
851 BOOL fAnsiKey;
852 int chAlone;
853 int chShift;
854 int chCtrl;
855 int chAlt;
856} VirtKeyMap[] =
857{
858
859/* Key ANSI alone shift ctrl alt */
860 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
861
862 { VK_F1, TRUE, ';', 'T', '^', 'h', },
863 { VK_F2, TRUE, '<', 'U', '_', 'i', },
864 { VK_F3, TRUE, '=', 'V', '`', 'j', },
865 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
866 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
867 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
868 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
869 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
870 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
871 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
872 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
873 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
874
875 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
876 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
877 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
878 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
879 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
880 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
881 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
882 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
883 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
884 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
885
886 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
887
888#if 0
889 /* Most people don't have F13-F20, but what the hell... */
890 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
891 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
892 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
893 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
894 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
895 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
896 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
897 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
898#endif
899 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
900 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
901 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
902 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
903
904 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
905 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
906 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
907 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
908 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
909 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
910 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
911 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
912 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
913 /* Sorry, out of number space! <negri>*/
914 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
915
916};
917
918
919#ifdef _MSC_VER
920// The ToAscii bug destroys several registers. Need to turn off optimization
921// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000922# pragma warning(push)
923# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924# pragma optimize("", off)
925#endif
926
927#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200928# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200930# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931#endif
932
933/* The return code indicates key code size. */
934 static int
935#ifdef __BORLANDC__
936 __stdcall
937#endif
938win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000939 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940{
941 UINT uMods = pker->dwControlKeyState;
942 static int s_iIsDead = 0;
943 static WORD awAnsiCode[2];
944 static BYTE abKeystate[256];
945
946
947 if (s_iIsDead == 2)
948 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200949 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 s_iIsDead = 0;
951 return 1;
952 }
953
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200954 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 return 1;
956
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200957 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200960 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961
962 if (uMods & SHIFT_PRESSED)
963 abKeystate[VK_SHIFT] = 0x80;
964 if (uMods & CAPSLOCK_ON)
965 abKeystate[VK_CAPITAL] = 1;
966
967 if ((uMods & ALT_GR) == ALT_GR)
968 {
969 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
970 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
971 }
972
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200973 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
974 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000975
976 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200977 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978
979 return s_iIsDead;
980}
981
982#ifdef _MSC_VER
983/* MUST switch optimization on again here, otherwise a call to
984 * decode_key_event() may crash (e.g. when hitting caps-lock) */
985# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000986# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987
988# if (_MSC_VER < 1100)
989/* MUST turn off global optimisation for this next function, or
990 * pressing ctrl-minus in insert mode crashes Vim when built with
991 * VC4.1. -- negri. */
992# pragma optimize("g", off)
993# endif
994#endif
995
996static BOOL g_fJustGotFocus = FALSE;
997
998/*
999 * Decode a KEY_EVENT into one or two keystrokes
1000 */
1001 static BOOL
1002decode_key_event(
1003 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001004 WCHAR *pch,
1005 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006 int *pmodifiers,
1007 BOOL fDoPost)
1008{
1009 int i;
1010 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1011
1012 *pch = *pch2 = NUL;
1013 g_fJustGotFocus = FALSE;
1014
1015 /* ignore key up events */
1016 if (!pker->bKeyDown)
1017 return FALSE;
1018
1019 /* ignore some keystrokes */
1020 switch (pker->wVirtualKeyCode)
1021 {
1022 /* modifiers */
1023 case VK_SHIFT:
1024 case VK_CONTROL:
1025 case VK_MENU: /* Alt key */
1026 return FALSE;
1027
1028 default:
1029 break;
1030 }
1031
1032 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001033 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 {
1035 /* Ctrl-6 is Ctrl-^ */
1036 if (pker->wVirtualKeyCode == '6')
1037 {
1038 *pch = Ctrl_HAT;
1039 return TRUE;
1040 }
1041 /* Ctrl-2 is Ctrl-@ */
1042 else if (pker->wVirtualKeyCode == '2')
1043 {
1044 *pch = NUL;
1045 return TRUE;
1046 }
1047 /* Ctrl-- is Ctrl-_ */
1048 else if (pker->wVirtualKeyCode == 0xBD)
1049 {
1050 *pch = Ctrl__;
1051 return TRUE;
1052 }
1053 }
1054
1055 /* Shift-TAB */
1056 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1057 {
1058 *pch = K_NUL;
1059 *pch2 = '\017';
1060 return TRUE;
1061 }
1062
1063 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1064 {
1065 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1066 {
1067 if (nModifs == 0)
1068 *pch = VirtKeyMap[i].chAlone;
1069 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1070 *pch = VirtKeyMap[i].chShift;
1071 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1072 *pch = VirtKeyMap[i].chCtrl;
1073 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1074 *pch = VirtKeyMap[i].chAlt;
1075
1076 if (*pch != 0)
1077 {
1078 if (VirtKeyMap[i].fAnsiKey)
1079 {
1080 *pch2 = *pch;
1081 *pch = K_NUL;
1082 }
1083
1084 return TRUE;
1085 }
1086 }
1087 }
1088
1089 i = win32_kbd_patch_key(pker);
1090
1091 if (i < 0)
1092 *pch = NUL;
1093 else
1094 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001095 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001096
1097 if (pmodifiers != NULL)
1098 {
1099 /* Pass on the ALT key as a modifier, but only when not combined
1100 * with CTRL (which is ALTGR). */
1101 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1102 *pmodifiers |= MOD_MASK_ALT;
1103
1104 /* Pass on SHIFT only for special keys, because we don't know when
1105 * it's already included with the character. */
1106 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1107 *pmodifiers |= MOD_MASK_SHIFT;
1108
1109 /* Pass on CTRL only for non-special keys, because we don't know
1110 * when it's already included with the character. And not when
1111 * combined with ALT (which is ALTGR). */
1112 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1113 && *pch >= 0x20 && *pch < 0x80)
1114 *pmodifiers |= MOD_MASK_CTRL;
1115 }
1116 }
1117
1118 return (*pch != NUL);
1119}
1120
1121#ifdef _MSC_VER
1122# pragma optimize("", on)
1123#endif
1124
1125#endif /* FEAT_GUI_W32 */
1126
1127
1128#ifdef FEAT_MOUSE
1129
1130/*
1131 * For the GUI the mouse handling is in gui_w32.c.
1132 */
1133# ifdef FEAT_GUI_W32
1134 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001135mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136{
1137}
1138# else
1139static int g_fMouseAvail = FALSE; /* mouse present */
1140static int g_fMouseActive = FALSE; /* mouse enabled */
1141static int g_nMouseClick = -1; /* mouse status */
1142static int g_xMouse; /* mouse x coordinate */
1143static int g_yMouse; /* mouse y coordinate */
1144
1145/*
1146 * Enable or disable mouse input
1147 */
1148 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001149mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150{
1151 DWORD cmodein;
1152
1153 if (!g_fMouseAvail)
1154 return;
1155
1156 g_fMouseActive = on;
1157 GetConsoleMode(g_hConIn, &cmodein);
1158
1159 if (g_fMouseActive)
1160 cmodein |= ENABLE_MOUSE_INPUT;
1161 else
1162 cmodein &= ~ENABLE_MOUSE_INPUT;
1163
1164 SetConsoleMode(g_hConIn, cmodein);
1165}
1166
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167/*
1168 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1169 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1170 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1171 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1172 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1173 * and we return the mouse position in g_xMouse and g_yMouse.
1174 *
1175 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1176 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1177 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1178 *
1179 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1180 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1181 *
1182 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1183 * moves, even if it stays within the same character cell. We ignore
1184 * all MOUSE_MOVED messages if the position hasn't really changed, and
1185 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1186 * we're only interested in MOUSE_DRAG).
1187 *
1188 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1189 * 2-button mouses by pressing the left & right buttons simultaneously.
1190 * In practice, it's almost impossible to click both at the same time,
1191 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1192 * in such cases, if the user is clicking quickly.
1193 */
1194 static BOOL
1195decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001196 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001197{
1198 static int s_nOldButton = -1;
1199 static int s_nOldMouseClick = -1;
1200 static int s_xOldMouse = -1;
1201 static int s_yOldMouse = -1;
1202 static linenr_T s_old_topline = 0;
1203#ifdef FEAT_DIFF
1204 static int s_old_topfill = 0;
1205#endif
1206 static int s_cClicks = 1;
1207 static BOOL s_fReleased = TRUE;
1208 static DWORD s_dwLastClickTime = 0;
1209 static BOOL s_fNextIsMiddle = FALSE;
1210
1211 static DWORD cButtons = 0; /* number of buttons supported */
1212
1213 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1214 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1215 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1216 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1217
1218 int nButton;
1219
1220 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1221 cButtons = 2;
1222
1223 if (!g_fMouseAvail || !g_fMouseActive)
1224 {
1225 g_nMouseClick = -1;
1226 return FALSE;
1227 }
1228
1229 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1230 if (g_fJustGotFocus)
1231 {
1232 g_fJustGotFocus = FALSE;
1233 return FALSE;
1234 }
1235
1236 /* unprocessed mouse click? */
1237 if (g_nMouseClick != -1)
1238 return TRUE;
1239
1240 nButton = -1;
1241 g_xMouse = pmer->dwMousePosition.X;
1242 g_yMouse = pmer->dwMousePosition.Y;
1243
1244 if (pmer->dwEventFlags == MOUSE_MOVED)
1245 {
1246 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1247 * events even when the mouse moves only within a char cell.) */
1248 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1249 return FALSE;
1250 }
1251
1252 /* If no buttons are pressed... */
1253 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1254 {
1255 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1256 if (s_fReleased)
1257 return FALSE;
1258
1259 nButton = MOUSE_RELEASE;
1260 s_fReleased = TRUE;
1261 }
1262 else /* one or more buttons pressed */
1263 {
1264 /* on a 2-button mouse, hold down left and right buttons
1265 * simultaneously to get MIDDLE. */
1266
1267 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1268 {
1269 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1270
1271 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001272 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001273 if (dwLR == LEFT || dwLR == RIGHT)
1274 {
1275 for (;;)
1276 {
1277 /* wait a short time for next input event */
1278 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1279 != WAIT_OBJECT_0)
1280 break;
1281 else
1282 {
1283 DWORD cRecords = 0;
1284 INPUT_RECORD ir;
1285 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1286
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001287 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001288
1289 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1290 || !(pmer2->dwButtonState & LEFT_RIGHT))
1291 break;
1292 else
1293 {
1294 if (pmer2->dwEventFlags != MOUSE_MOVED)
1295 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001296 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001297
1298 return decode_mouse_event(pmer2);
1299 }
1300 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1301 s_yOldMouse == pmer2->dwMousePosition.Y)
1302 {
1303 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001304 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001305
1306 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001307 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308
1309 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1310 break;
1311 }
1312 else
1313 break;
1314 }
1315 }
1316 }
1317 }
1318 }
1319
1320 if (s_fNextIsMiddle)
1321 {
1322 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1323 ? MOUSE_DRAG : MOUSE_MIDDLE;
1324 s_fNextIsMiddle = FALSE;
1325 }
1326 else if (cButtons == 2 &&
1327 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1328 {
1329 nButton = MOUSE_MIDDLE;
1330
1331 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1332 {
1333 s_fNextIsMiddle = TRUE;
1334 nButton = MOUSE_RELEASE;
1335 }
1336 }
1337 else if ((pmer->dwButtonState & LEFT) == LEFT)
1338 nButton = MOUSE_LEFT;
1339 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1340 nButton = MOUSE_MIDDLE;
1341 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1342 nButton = MOUSE_RIGHT;
1343
1344 if (! s_fReleased && ! s_fNextIsMiddle
1345 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1346 return FALSE;
1347
1348 s_fReleased = s_fNextIsMiddle;
1349 }
1350
1351 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1352 {
1353 /* button pressed or released, without mouse moving */
1354 if (nButton != -1 && nButton != MOUSE_RELEASE)
1355 {
1356 DWORD dwCurrentTime = GetTickCount();
1357
1358 if (s_xOldMouse != g_xMouse
1359 || s_yOldMouse != g_yMouse
1360 || s_nOldButton != nButton
1361 || s_old_topline != curwin->w_topline
1362#ifdef FEAT_DIFF
1363 || s_old_topfill != curwin->w_topfill
1364#endif
1365 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1366 {
1367 s_cClicks = 1;
1368 }
1369 else if (++s_cClicks > 4)
1370 {
1371 s_cClicks = 1;
1372 }
1373
1374 s_dwLastClickTime = dwCurrentTime;
1375 }
1376 }
1377 else if (pmer->dwEventFlags == MOUSE_MOVED)
1378 {
1379 if (nButton != -1 && nButton != MOUSE_RELEASE)
1380 nButton = MOUSE_DRAG;
1381
1382 s_cClicks = 1;
1383 }
1384
1385 if (nButton == -1)
1386 return FALSE;
1387
1388 if (nButton != MOUSE_RELEASE)
1389 s_nOldButton = nButton;
1390
1391 g_nMouseClick = nButton;
1392
1393 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1394 g_nMouseClick |= MOUSE_SHIFT;
1395 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1396 g_nMouseClick |= MOUSE_CTRL;
1397 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1398 g_nMouseClick |= MOUSE_ALT;
1399
1400 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1401 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1402
1403 /* only pass on interesting (i.e., different) mouse events */
1404 if (s_xOldMouse == g_xMouse
1405 && s_yOldMouse == g_yMouse
1406 && s_nOldMouseClick == g_nMouseClick)
1407 {
1408 g_nMouseClick = -1;
1409 return FALSE;
1410 }
1411
1412 s_xOldMouse = g_xMouse;
1413 s_yOldMouse = g_yMouse;
1414 s_old_topline = curwin->w_topline;
1415#ifdef FEAT_DIFF
1416 s_old_topfill = curwin->w_topfill;
1417#endif
1418 s_nOldMouseClick = g_nMouseClick;
1419
1420 return TRUE;
1421}
1422
1423# endif /* FEAT_GUI_W32 */
1424#endif /* FEAT_MOUSE */
1425
1426
1427#ifdef MCH_CURSOR_SHAPE
1428/*
1429 * Set the shape of the cursor.
1430 * 'thickness' can be from 1 (thin) to 99 (block)
1431 */
1432 static void
1433mch_set_cursor_shape(int thickness)
1434{
1435 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1436 ConsoleCursorInfo.dwSize = thickness;
1437 ConsoleCursorInfo.bVisible = s_cursor_visible;
1438
1439 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1440 if (s_cursor_visible)
1441 SetConsoleCursorPosition(g_hConOut, g_coord);
1442}
1443
1444 void
1445mch_update_cursor(void)
1446{
1447 int idx;
1448 int thickness;
1449
1450 /*
1451 * How the cursor is drawn depends on the current mode.
1452 */
1453 idx = get_shape_idx(FALSE);
1454
1455 if (shape_table[idx].shape == SHAPE_BLOCK)
1456 thickness = 99; /* 100 doesn't work on W95 */
1457 else
1458 thickness = shape_table[idx].percentage;
1459 mch_set_cursor_shape(thickness);
1460}
1461#endif
1462
1463#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1464/*
1465 * Handle FOCUS_EVENT.
1466 */
1467 static void
1468handle_focus_event(INPUT_RECORD ir)
1469{
1470 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1471 ui_focus_change((int)g_fJustGotFocus);
1472}
1473
1474/*
1475 * Wait until console input from keyboard or mouse is available,
1476 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001477 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001478 * Return TRUE if something is available FALSE if not.
1479 */
1480 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001481WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482{
1483 DWORD dwNow = 0, dwEndTime = 0;
1484 INPUT_RECORD ir;
1485 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001486 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001487#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001488 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001489#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490
1491 if (msec > 0)
1492 /* Wait until the specified time has elapsed. */
1493 dwEndTime = GetTickCount() + msec;
1494 else if (msec < 0)
1495 /* Wait forever. */
1496 dwEndTime = INFINITE;
1497
1498 /* We need to loop until the end of the time period, because
1499 * we might get multiple unusable mouse events in that time.
1500 */
1501 for (;;)
1502 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001503#ifdef MESSAGE_QUEUE
1504 parse_queued_messages();
1505#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001506#ifdef FEAT_MZSCHEME
1507 mzvim_check_threads();
1508#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509#ifdef FEAT_CLIENTSERVER
1510 serverProcessPendingMessages();
1511#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001512
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513 if (0
1514#ifdef FEAT_MOUSE
1515 || g_nMouseClick != -1
1516#endif
1517#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001518 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519#endif
1520 )
1521 return TRUE;
1522
1523 if (msec > 0)
1524 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001525 /* If the specified wait time has passed, return. Beware that
1526 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001527 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001528 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529 break;
1530 }
1531 if (msec != 0)
1532 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001533 DWORD dwWaitTime = dwEndTime - dwNow;
1534
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001535#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001536 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001537 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001538 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001539 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001540 /* If there is readahead then parse_queued_messages() timed out
1541 * and we should call it again soon. */
1542 if (channel_any_readahead())
1543 dwWaitTime = 10;
1544 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001545#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001546#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001547 if (p_beval && dwWaitTime > 100)
1548 /* The 'balloonexpr' may indirectly invoke a callback while
1549 * waiting for a character, need to check often. */
1550 dwWaitTime = 100;
1551#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001552#ifdef FEAT_MZSCHEME
1553 if (mzthreads_allowed() && p_mzq > 0
1554 && (msec < 0 || (long)dwWaitTime > p_mzq))
1555 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1556#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001557#ifdef FEAT_TIMERS
1558 {
1559 long due_time;
1560
1561 /* When waiting very briefly don't trigger timers. */
1562 if (dwWaitTime > 10)
1563 {
1564 /* Trigger timers and then get the time in msec until the
1565 * next one is due. Wait up to that time. */
1566 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001567 if (typebuf.tb_change_cnt != tb_change_cnt)
1568 {
1569 /* timer may have used feedkeys() */
1570 return FALSE;
1571 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001572 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1573 dwWaitTime = due_time;
1574 }
1575 }
1576#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577#ifdef FEAT_CLIENTSERVER
1578 /* Wait for either an event on the console input or a message in
1579 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001580 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001581 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001583 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584#endif
1585 continue;
1586 }
1587
1588 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001589 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590
1591#ifdef FEAT_MBYTE_IME
1592 if (State & CMDLINE && msg_row == Rows - 1)
1593 {
1594 CONSOLE_SCREEN_BUFFER_INFO csbi;
1595
1596 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1597 {
1598 if (csbi.dwCursorPosition.Y != msg_row)
1599 {
1600 /* The screen is now messed up, must redraw the
1601 * command line and later all the windows. */
1602 redraw_all_later(CLEAR);
1603 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1604 redrawcmd();
1605 }
1606 }
1607 }
1608#endif
1609
1610 if (cRecords > 0)
1611 {
1612 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1613 {
1614#ifdef FEAT_MBYTE_IME
1615 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1616 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001617 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1619 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001620 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621 continue;
1622 }
1623#endif
1624 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1625 NULL, FALSE))
1626 return TRUE;
1627 }
1628
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001629 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630
1631 if (ir.EventType == FOCUS_EVENT)
1632 handle_focus_event(ir);
1633 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001634 {
1635 /* Only call shell_resized() when the size actually change to
1636 * avoid the screen is cleard. */
1637 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1638 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1639 shell_resized();
1640 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641#ifdef FEAT_MOUSE
1642 else if (ir.EventType == MOUSE_EVENT
1643 && decode_mouse_event(&ir.Event.MouseEvent))
1644 return TRUE;
1645#endif
1646 }
1647 else if (msec == 0)
1648 break;
1649 }
1650
1651#ifdef FEAT_CLIENTSERVER
1652 /* Something might have been received while we were waiting. */
1653 if (input_available())
1654 return TRUE;
1655#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001656
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657 return FALSE;
1658}
1659
1660#ifndef FEAT_GUI_MSWIN
1661/*
1662 * return non-zero if a character is available
1663 */
1664 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001665mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001667 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001669
1670# if defined(FEAT_TERMINAL) || defined(PROTO)
1671/*
1672 * Check for any pending input or messages.
1673 */
1674 int
1675mch_check_messages(void)
1676{
1677 return WaitForChar(0L, TRUE);
1678}
1679# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680#endif
1681
1682/*
1683 * Create the console input. Used when reading stdin doesn't work.
1684 */
1685 static void
1686create_conin(void)
1687{
1688 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1689 FILE_SHARE_READ|FILE_SHARE_WRITE,
1690 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001691 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 did_create_conin = TRUE;
1693}
1694
1695/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001696 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001698 static WCHAR
1699tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001701 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702
1703 for (;;)
1704 {
1705 INPUT_RECORD ir;
1706 DWORD cRecords = 0;
1707
1708#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001709 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 if (input_available())
1711 return 0;
1712# ifdef FEAT_MOUSE
1713 if (g_nMouseClick != -1)
1714 return 0;
1715# endif
1716#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001717 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 {
1719 if (did_create_conin)
1720 read_error_exit();
1721 create_conin();
1722 continue;
1723 }
1724
1725 if (ir.EventType == KEY_EVENT)
1726 {
1727 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1728 pmodifiers, TRUE))
1729 return ch;
1730 }
1731 else if (ir.EventType == FOCUS_EVENT)
1732 handle_focus_event(ir);
1733 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1734 shell_resized();
1735#ifdef FEAT_MOUSE
1736 else if (ir.EventType == MOUSE_EVENT)
1737 {
1738 if (decode_mouse_event(&ir.Event.MouseEvent))
1739 return 0;
1740 }
1741#endif
1742 }
1743}
1744#endif /* !FEAT_GUI_W32 */
1745
1746
1747/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001748 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 * Get one or more characters from the keyboard or the mouse.
1750 * If time == 0, do not wait for characters.
1751 * If time == n, wait a short time for characters.
1752 * If time == -1, wait forever for characters.
1753 * Returns the number of characters read into buf.
1754 */
1755 int
1756mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001757 char_u *buf UNUSED,
1758 int maxlen UNUSED,
1759 long time UNUSED,
1760 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001761{
1762#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1763
1764 int len;
1765 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001766#define TYPEAHEADLEN 20
1767 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1768 static int typeaheadlen = 0;
1769
1770 /* First use any typeahead that was kept because "buf" was too small. */
1771 if (typeaheadlen > 0)
1772 goto theend;
1773
Bram Moolenaar071d4272004-06-13 20:20:40 +00001774 if (time >= 0)
1775 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001776 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778 }
1779 else /* time == -1, wait forever */
1780 {
1781 mch_set_winsize_now(); /* Allow winsize changes from now on */
1782
Bram Moolenaar3918c952005-03-15 22:34:55 +00001783 /*
1784 * If there is no character available within 2 seconds (default)
1785 * write the autoscript file to disk. Or cause the CursorHold event
1786 * to be triggered.
1787 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001788 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789 {
1790#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001791 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001793 buf[0] = K_SPECIAL;
1794 buf[1] = KS_EXTRA;
1795 buf[2] = (int)KE_CURSORHOLD;
1796 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 }
1798#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001799 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800 }
1801 }
1802
1803 /*
1804 * Try to read as many characters as there are, until the buffer is full.
1805 */
1806
1807 /* we will get at least one key. Get more if they are available. */
1808 g_fCBrkPressed = FALSE;
1809
1810#ifdef MCH_WRITE_DUMP
1811 if (fdDump)
1812 fputc('[', fdDump);
1813#endif
1814
1815 /* Keep looping until there is something in the typeahead buffer and more
1816 * to get and still room in the buffer (up to two bytes for a char and
1817 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001818 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 && typeaheadlen + 5 <= TYPEAHEADLEN)
1820 {
1821 if (typebuf_changed(tb_change_cnt))
1822 {
1823 /* "buf" may be invalid now if a client put something in the
1824 * typeahead buffer and "buf" is in the typeahead buffer. */
1825 typeaheadlen = 0;
1826 break;
1827 }
1828#ifdef FEAT_MOUSE
1829 if (g_nMouseClick != -1)
1830 {
1831# ifdef MCH_WRITE_DUMP
1832 if (fdDump)
1833 fprintf(fdDump, "{%02x @ %d, %d}",
1834 g_nMouseClick, g_xMouse, g_yMouse);
1835# endif
1836 typeahead[typeaheadlen++] = ESC + 128;
1837 typeahead[typeaheadlen++] = 'M';
1838 typeahead[typeaheadlen++] = g_nMouseClick;
1839 typeahead[typeaheadlen++] = g_xMouse + '!';
1840 typeahead[typeaheadlen++] = g_yMouse + '!';
1841 g_nMouseClick = -1;
1842 }
1843 else
1844#endif
1845 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001846 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 int modifiers = 0;
1848
1849 c = tgetch(&modifiers, &ch2);
1850
1851 if (typebuf_changed(tb_change_cnt))
1852 {
1853 /* "buf" may be invalid now if a client put something in the
1854 * typeahead buffer and "buf" is in the typeahead buffer. */
1855 typeaheadlen = 0;
1856 break;
1857 }
1858
1859 if (c == Ctrl_C && ctrl_c_interrupts)
1860 {
1861#if defined(FEAT_CLIENTSERVER)
1862 trash_input_buf();
1863#endif
1864 got_int = TRUE;
1865 }
1866
1867#ifdef FEAT_MOUSE
1868 if (g_nMouseClick == -1)
1869#endif
1870 {
1871 int n = 1;
1872
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001873#ifdef FEAT_MBYTE
1874 if (ch2 == NUL)
1875 {
1876 int i;
1877 char_u *p;
1878 WCHAR ch[2];
1879
1880 ch[0] = c;
1881 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1882 {
1883 ch[1] = tgetch(&modifiers, &ch2);
1884 n++;
1885 }
1886 p = utf16_to_enc(ch, &n);
1887 if (p != NULL)
1888 {
1889 for (i = 0; i < n; i++)
1890 typeahead[typeaheadlen + i] = p[i];
1891 vim_free(p);
1892 }
1893 }
1894 else
1895#endif
1896 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 if (ch2 != NUL)
1898 {
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001899 if (c == K_NUL && (ch2 & 0xff00) != 0)
1900 {
1901 /* fAnsiKey with modifier keys */
1902 typeahead[typeaheadlen + n] = (char_u)ch2;
1903 n++;
1904 }
1905 else
1906 {
1907 typeahead[typeaheadlen + n] = 3;
1908 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1909 n += 2;
1910 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001911 }
1912
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 /* Use the ALT key to set the 8th bit of the character
1914 * when it's one byte, the 8th bit isn't set yet and not
1915 * using a double-byte encoding (would become a lead
1916 * byte). */
1917 if ((modifiers & MOD_MASK_ALT)
1918 && n == 1
1919 && (typeahead[typeaheadlen] & 0x80) == 0
1920#ifdef FEAT_MBYTE
1921 && !enc_dbcs
1922#endif
1923 )
1924 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001925#ifdef FEAT_MBYTE
1926 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1927 typeahead + typeaheadlen);
1928#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001930#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931 modifiers &= ~MOD_MASK_ALT;
1932 }
1933
1934 if (modifiers != 0)
1935 {
1936 /* Prepend modifiers to the character. */
1937 mch_memmove(typeahead + typeaheadlen + 3,
1938 typeahead + typeaheadlen, n);
1939 typeahead[typeaheadlen++] = K_SPECIAL;
1940 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1941 typeahead[typeaheadlen++] = modifiers;
1942 }
1943
1944 typeaheadlen += n;
1945
1946#ifdef MCH_WRITE_DUMP
1947 if (fdDump)
1948 fputc(c, fdDump);
1949#endif
1950 }
1951 }
1952 }
1953
1954#ifdef MCH_WRITE_DUMP
1955 if (fdDump)
1956 {
1957 fputs("]\n", fdDump);
1958 fflush(fdDump);
1959 }
1960#endif
1961
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962theend:
1963 /* Move typeahead to "buf", as much as fits. */
1964 len = 0;
1965 while (len < maxlen && typeaheadlen > 0)
1966 {
1967 buf[len++] = typeahead[0];
1968 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1969 }
1970 return len;
1971
1972#else /* FEAT_GUI_W32 */
1973 return 0;
1974#endif /* FEAT_GUI_W32 */
1975}
1976
Bram Moolenaar82881492012-11-20 16:53:39 +01001977#ifndef PROTO
1978# ifndef __MINGW32__
1979# include <shellapi.h> /* required for FindExecutable() */
1980# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981#endif
1982
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001983/*
Bram Moolenaar43663192017-03-05 14:29:12 +01001984 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
1985 * If "use_path" is FALSE: Return TRUE if "name" exists.
1986 * When returning TRUE and "path" is not NULL save the path and set "*path" to
1987 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001988 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001989 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01001991executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001993 char *dum;
1994 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001995 char *curpath, *newpath;
1996 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997
Bram Moolenaar43663192017-03-05 14:29:12 +01001998 if (!use_path)
1999 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002000 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002001 {
2002 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002003 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002004 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002005 *path = vim_strsave((char_u *)name);
2006 else
2007 *path = FullName_save((char_u *)name, FALSE);
2008 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002009 return TRUE;
2010 }
2011 return FALSE;
2012 }
2013
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002014#ifdef FEAT_MBYTE
2015 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002017 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002018 WCHAR fnamew[_MAX_PATH];
2019 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002020 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002021
2022 if (p != NULL)
2023 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002024 wcurpath = _wgetenv(L"PATH");
2025 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2026 * sizeof(WCHAR));
2027 if (wnewpath == NULL)
2028 return FALSE;
2029 wcscpy(wnewpath, L".;");
2030 wcscat(wnewpath, wcurpath);
2031 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2032 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002033 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002034 if (n == 0)
2035 return FALSE;
2036 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2037 return FALSE;
2038 if (path != NULL)
2039 *path = utf16_to_enc(fnamew, NULL);
2040 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002041 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002043#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002044
2045 curpath = getenv("PATH");
2046 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2047 if (newpath == NULL)
2048 return FALSE;
2049 STRCPY(newpath, ".;");
2050 STRCAT(newpath, curpath);
2051 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2052 vim_free(newpath);
2053 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002054 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002055 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002056 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002057 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002058 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002059 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060}
2061
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002062#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002063 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002064/*
2065 * Bad parameter handler.
2066 *
2067 * Certain MS CRT functions will intentionally crash when passed invalid
2068 * parameters to highlight possible security holes. Setting this function as
2069 * the bad parameter handler will prevent the crash.
2070 *
2071 * In debug builds the parameters contain CRT information that might help track
2072 * down the source of a problem, but in non-debug builds the arguments are all
2073 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2074 * worth allowing these to make debugging of issues easier.
2075 */
2076 static void
2077bad_param_handler(const wchar_t *expression,
2078 const wchar_t *function,
2079 const wchar_t *file,
2080 unsigned int line,
2081 uintptr_t pReserved)
2082{
2083}
2084
2085# define SET_INVALID_PARAM_HANDLER \
2086 ((void)_set_invalid_parameter_handler(bad_param_handler))
2087#else
2088# define SET_INVALID_PARAM_HANDLER
2089#endif
2090
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091#ifdef FEAT_GUI_W32
2092
2093/*
2094 * GUI version of mch_init().
2095 */
2096 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002097mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002098{
2099#ifndef __MINGW32__
2100 extern int _fmode;
2101#endif
2102
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002103 /* Silently handle invalid parameters to CRT functions */
2104 SET_INVALID_PARAM_HANDLER;
2105
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106 /* Let critical errors result in a failure, not in a dialog box. Required
2107 * for the timestamp test to work on removed floppies. */
2108 SetErrorMode(SEM_FAILCRITICALERRORS);
2109
2110 _fmode = O_BINARY; /* we do our own CR-LF translation */
2111
2112 /* Specify window size. Is there a place to get the default from? */
2113 Rows = 25;
2114 Columns = 80;
2115
2116 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117 {
2118 char_u vimrun_location[_MAX_PATH + 4];
2119
2120 /* First try in same directory as gvim.exe */
2121 STRCPY(vimrun_location, exe_name);
2122 STRCPY(gettail(vimrun_location), "vimrun.exe");
2123 if (mch_getperm(vimrun_location) >= 0)
2124 {
2125 if (*skiptowhite(vimrun_location) != NUL)
2126 {
2127 /* Enclose path with white space in double quotes. */
2128 mch_memmove(vimrun_location + 1, vimrun_location,
2129 STRLEN(vimrun_location) + 1);
2130 *vimrun_location = '"';
2131 STRCPY(gettail(vimrun_location), "vimrun\" ");
2132 }
2133 else
2134 STRCPY(gettail(vimrun_location), "vimrun ");
2135
2136 vimrun_path = (char *)vim_strsave(vimrun_location);
2137 s_dont_use_vimrun = FALSE;
2138 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002139 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 s_dont_use_vimrun = FALSE;
2141
2142 /* Don't give the warning for a missing vimrun.exe right now, but only
2143 * when vimrun was supposed to be used. Don't bother people that do
2144 * not need vimrun.exe. */
2145 if (s_dont_use_vimrun)
2146 need_vimrun_warning = TRUE;
2147 }
2148
2149 /*
2150 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2151 * Otherwise the default "findstr /n" is used.
2152 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002153 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002154 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2155
2156#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002157 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158#endif
2159}
2160
2161
2162#else /* FEAT_GUI_W32 */
2163
2164#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2165#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2166
2167/*
2168 * ClearConsoleBuffer()
2169 * Description:
2170 * Clears the entire contents of the console screen buffer, using the
2171 * specified attribute.
2172 * Returns:
2173 * TRUE on success
2174 */
2175 static BOOL
2176ClearConsoleBuffer(WORD wAttribute)
2177{
2178 CONSOLE_SCREEN_BUFFER_INFO csbi;
2179 COORD coord;
2180 DWORD NumCells, dummy;
2181
2182 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2183 return FALSE;
2184
2185 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2186 coord.X = 0;
2187 coord.Y = 0;
2188 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2189 coord, &dummy))
2190 {
2191 return FALSE;
2192 }
2193 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2194 coord, &dummy))
2195 {
2196 return FALSE;
2197 }
2198
2199 return TRUE;
2200}
2201
2202/*
2203 * FitConsoleWindow()
2204 * Description:
2205 * Checks if the console window will fit within given buffer dimensions.
2206 * Also, if requested, will shrink the window to fit.
2207 * Returns:
2208 * TRUE on success
2209 */
2210 static BOOL
2211FitConsoleWindow(
2212 COORD dwBufferSize,
2213 BOOL WantAdjust)
2214{
2215 CONSOLE_SCREEN_BUFFER_INFO csbi;
2216 COORD dwWindowSize;
2217 BOOL NeedAdjust = FALSE;
2218
2219 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2220 {
2221 /*
2222 * A buffer resize will fail if the current console window does
2223 * not lie completely within that buffer. To avoid this, we might
2224 * have to move and possibly shrink the window.
2225 */
2226 if (csbi.srWindow.Right >= dwBufferSize.X)
2227 {
2228 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2229 if (dwWindowSize.X > dwBufferSize.X)
2230 dwWindowSize.X = dwBufferSize.X;
2231 csbi.srWindow.Right = dwBufferSize.X - 1;
2232 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2233 NeedAdjust = TRUE;
2234 }
2235 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2236 {
2237 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2238 if (dwWindowSize.Y > dwBufferSize.Y)
2239 dwWindowSize.Y = dwBufferSize.Y;
2240 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2241 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2242 NeedAdjust = TRUE;
2243 }
2244 if (NeedAdjust && WantAdjust)
2245 {
2246 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2247 return FALSE;
2248 }
2249 return TRUE;
2250 }
2251
2252 return FALSE;
2253}
2254
2255typedef struct ConsoleBufferStruct
2256{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002257 BOOL IsValid;
2258 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002259 PCHAR_INFO Buffer;
2260 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002261 PSMALL_RECT Regions;
2262 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002263} ConsoleBuffer;
2264
2265/*
2266 * SaveConsoleBuffer()
2267 * Description:
2268 * Saves important information about the console buffer, including the
2269 * actual buffer contents. The saved information is suitable for later
2270 * restoration by RestoreConsoleBuffer().
2271 * Returns:
2272 * TRUE if all information was saved; FALSE otherwise
2273 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2274 */
2275 static BOOL
2276SaveConsoleBuffer(
2277 ConsoleBuffer *cb)
2278{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002279 DWORD NumCells;
2280 COORD BufferCoord;
2281 SMALL_RECT ReadRegion;
2282 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002283 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002284
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 if (cb == NULL)
2286 return FALSE;
2287
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002288 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002289 {
2290 cb->IsValid = FALSE;
2291 return FALSE;
2292 }
2293 cb->IsValid = TRUE;
2294
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002295 /*
2296 * Allocate a buffer large enough to hold the entire console screen
2297 * buffer. If this ConsoleBuffer structure has already been initialized
2298 * with a buffer of the correct size, then just use that one.
2299 */
2300 if (!cb->IsValid || cb->Buffer == NULL ||
2301 cb->BufferSize.X != cb->Info.dwSize.X ||
2302 cb->BufferSize.Y != cb->Info.dwSize.Y)
2303 {
2304 cb->BufferSize.X = cb->Info.dwSize.X;
2305 cb->BufferSize.Y = cb->Info.dwSize.Y;
2306 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2307 vim_free(cb->Buffer);
2308 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2309 if (cb->Buffer == NULL)
2310 return FALSE;
2311 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312
2313 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002314 * We will now copy the console screen buffer into our buffer.
2315 * ReadConsoleOutput() seems to be limited as far as how much you
2316 * can read at a time. Empirically, this number seems to be about
2317 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2318 * in chunks until it is all copied. The chunks will all have the
2319 * same horizontal characteristics, so initialize them now. The
2320 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002322 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002323 ReadRegion.Left = 0;
2324 ReadRegion.Right = cb->Info.dwSize.X - 1;
2325 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002326
2327 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2328 if (cb->Regions == NULL || numregions != cb->NumRegions)
2329 {
2330 cb->NumRegions = numregions;
2331 vim_free(cb->Regions);
2332 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2333 if (cb->Regions == NULL)
2334 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002335 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002336 return FALSE;
2337 }
2338 }
2339
2340 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002342 /*
2343 * Read into position (0, Y) in our buffer.
2344 */
2345 BufferCoord.Y = Y;
2346 /*
2347 * Read the region whose top left corner is (0, Y) and whose bottom
2348 * right corner is (width - 1, Y + Y_incr - 1). This should define
2349 * a region of size width by Y_incr. Don't worry if this region is
2350 * too large for the remaining buffer; it will be cropped.
2351 */
2352 ReadRegion.Top = Y;
2353 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002354 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002355 cb->Buffer, /* our buffer */
2356 cb->BufferSize, /* dimensions of our buffer */
2357 BufferCoord, /* offset in our buffer */
2358 &ReadRegion)) /* region to save */
2359 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002360 VIM_CLEAR(cb->Buffer);
2361 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002362 return FALSE;
2363 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002364 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 }
2366
2367 return TRUE;
2368}
2369
2370/*
2371 * RestoreConsoleBuffer()
2372 * Description:
2373 * Restores important information about the console buffer, including the
2374 * actual buffer contents, if desired. The information to restore is in
2375 * the same format used by SaveConsoleBuffer().
2376 * Returns:
2377 * TRUE on success
2378 */
2379 static BOOL
2380RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002381 ConsoleBuffer *cb,
2382 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002384 COORD BufferCoord;
2385 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002386 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387
2388 if (cb == NULL || !cb->IsValid)
2389 return FALSE;
2390
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002391 /*
2392 * Before restoring the buffer contents, clear the current buffer, and
2393 * restore the cursor position and window information. Doing this now
2394 * prevents old buffer contents from "flashing" onto the screen.
2395 */
2396 if (RestoreScreen)
2397 ClearConsoleBuffer(cb->Info.wAttributes);
2398
2399 FitConsoleWindow(cb->Info.dwSize, TRUE);
2400 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2401 return FALSE;
2402 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2403 return FALSE;
2404
2405 if (!RestoreScreen)
2406 {
2407 /*
2408 * No need to restore the screen buffer contents, so we're done.
2409 */
2410 return TRUE;
2411 }
2412
2413 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2414 return FALSE;
2415 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2416 return FALSE;
2417
2418 /*
2419 * Restore the screen buffer contents.
2420 */
2421 if (cb->Buffer != NULL)
2422 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002423 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002424 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002425 BufferCoord.X = cb->Regions[i].Left;
2426 BufferCoord.Y = cb->Regions[i].Top;
2427 WriteRegion = cb->Regions[i];
2428 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2429 cb->Buffer, /* our buffer */
2430 cb->BufferSize, /* dimensions of our buffer */
2431 BufferCoord, /* offset in our buffer */
2432 &WriteRegion)) /* region to restore */
2433 {
2434 return FALSE;
2435 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002436 }
2437 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438
2439 return TRUE;
2440}
2441
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002442#define FEAT_RESTORE_ORIG_SCREEN
2443#ifdef FEAT_RESTORE_ORIG_SCREEN
2444static ConsoleBuffer g_cbOrig = { 0 };
2445#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446static ConsoleBuffer g_cbNonTermcap = { 0 };
2447static ConsoleBuffer g_cbTermcap = { 0 };
2448
2449#ifdef FEAT_TITLE
2450#ifdef __BORLANDC__
2451typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2452#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002453typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454#endif
2455char g_szOrigTitle[256] = { 0 };
2456HWND g_hWnd = NULL; /* also used in os_mswin.c */
2457static HICON g_hOrigIconSmall = NULL;
2458static HICON g_hOrigIcon = NULL;
2459static HICON g_hVimIcon = NULL;
2460static BOOL g_fCanChangeIcon = FALSE;
2461
2462/* ICON* are not defined in VC++ 4.0 */
2463#ifndef ICON_SMALL
2464#define ICON_SMALL 0
2465#endif
2466#ifndef ICON_BIG
2467#define ICON_BIG 1
2468#endif
2469/*
2470 * GetConsoleIcon()
2471 * Description:
2472 * Attempts to retrieve the small icon and/or the big icon currently in
2473 * use by a given window.
2474 * Returns:
2475 * TRUE on success
2476 */
2477 static BOOL
2478GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002479 HWND hWnd,
2480 HICON *phIconSmall,
2481 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482{
2483 if (hWnd == NULL)
2484 return FALSE;
2485
2486 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002487 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2488 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002489 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002490 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2491 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 return TRUE;
2493}
2494
2495/*
2496 * SetConsoleIcon()
2497 * Description:
2498 * Attempts to change the small icon and/or the big icon currently in
2499 * use by a given window.
2500 * Returns:
2501 * TRUE on success
2502 */
2503 static BOOL
2504SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002505 HWND hWnd,
2506 HICON hIconSmall,
2507 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509 if (hWnd == NULL)
2510 return FALSE;
2511
2512 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002513 SendMessage(hWnd, WM_SETICON,
2514 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002516 SendMessage(hWnd, WM_SETICON,
2517 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 return TRUE;
2519}
2520
2521/*
2522 * SaveConsoleTitleAndIcon()
2523 * Description:
2524 * Saves the current console window title in g_szOrigTitle, for later
2525 * restoration. Also, attempts to obtain a handle to the console window,
2526 * and use it to save the small and big icons currently in use by the
2527 * console window. This is not always possible on some versions of Windows;
2528 * nor is it possible when running Vim remotely using Telnet (since the
2529 * console window the user sees is owned by a remote process).
2530 */
2531 static void
2532SaveConsoleTitleAndIcon(void)
2533{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 /* Save the original title. */
2535 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2536 return;
2537
2538 /*
2539 * Obtain a handle to the console window using GetConsoleWindow() from
2540 * KERNEL32.DLL; we need to handle in order to change the window icon.
2541 * This function only exists on NT-based Windows, starting with Windows
2542 * 2000. On older operating systems, we can't change the window icon
2543 * anyway.
2544 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002545 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 if (g_hWnd == NULL)
2547 return;
2548
2549 /* Save the original console window icon. */
2550 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2551 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2552 return;
2553
2554 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002555 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002556 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557 if (g_hVimIcon != NULL)
2558 g_fCanChangeIcon = TRUE;
2559}
2560#endif
2561
2562static int g_fWindInitCalled = FALSE;
2563static int g_fTermcapMode = FALSE;
2564static CONSOLE_CURSOR_INFO g_cci;
2565static DWORD g_cmodein = 0;
2566static DWORD g_cmodeout = 0;
2567
2568/*
2569 * non-GUI version of mch_init().
2570 */
2571 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002572mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002574#ifndef FEAT_RESTORE_ORIG_SCREEN
2575 CONSOLE_SCREEN_BUFFER_INFO csbi;
2576#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577#ifndef __MINGW32__
2578 extern int _fmode;
2579#endif
2580
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002581 /* Silently handle invalid parameters to CRT functions */
2582 SET_INVALID_PARAM_HANDLER;
2583
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 /* Let critical errors result in a failure, not in a dialog box. Required
2585 * for the timestamp test to work on removed floppies. */
2586 SetErrorMode(SEM_FAILCRITICALERRORS);
2587
2588 _fmode = O_BINARY; /* we do our own CR-LF translation */
2589 out_flush();
2590
2591 /* Obtain handles for the standard Console I/O devices */
2592 if (read_cmd_fd == 0)
2593 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2594 else
2595 create_conin();
2596 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2597
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002598#ifdef FEAT_RESTORE_ORIG_SCREEN
2599 /* Save the initial console buffer for later restoration */
2600 SaveConsoleBuffer(&g_cbOrig);
2601 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2602#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002604 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2605 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2606#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002607 if (cterm_normal_fg_color == 0)
2608 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2609 if (cterm_normal_bg_color == 0)
2610 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2611
2612 /* set termcap codes to current text attributes */
2613 update_tcap(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002614 swap_tcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615
2616 GetConsoleCursorInfo(g_hConOut, &g_cci);
2617 GetConsoleMode(g_hConIn, &g_cmodein);
2618 GetConsoleMode(g_hConOut, &g_cmodeout);
2619
2620#ifdef FEAT_TITLE
2621 SaveConsoleTitleAndIcon();
2622 /*
2623 * Set both the small and big icons of the console window to Vim's icon.
2624 * Note that Vim presently only has one size of icon (32x32), but it
2625 * automatically gets scaled down to 16x16 when setting the small icon.
2626 */
2627 if (g_fCanChangeIcon)
2628 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2629#endif
2630
2631 ui_get_shellsize();
2632
2633#ifdef MCH_WRITE_DUMP
2634 fdDump = fopen("dump", "wt");
2635
2636 if (fdDump)
2637 {
2638 time_t t;
2639
2640 time(&t);
2641 fputs(ctime(&t), fdDump);
2642 fflush(fdDump);
2643 }
2644#endif
2645
2646 g_fWindInitCalled = TRUE;
2647
2648#ifdef FEAT_MOUSE
2649 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2650#endif
2651
2652#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002653 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002654#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002655
2656 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002657}
2658
2659/*
2660 * non-GUI version of mch_exit().
2661 * Shut down and exit with status `r'
2662 * Careful: mch_exit() may be called before mch_init()!
2663 */
2664 void
2665mch_exit(int r)
2666{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002667 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002669 vtp_exit();
2670
Bram Moolenaar955f1982017-02-05 15:10:51 +01002671 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002672 if (g_fWindInitCalled)
2673 settmode(TMODE_COOK);
2674
2675 ml_close_all(TRUE); /* remove all memfiles */
2676
2677 if (g_fWindInitCalled)
2678 {
2679#ifdef FEAT_TITLE
2680 mch_restore_title(3);
2681 /*
2682 * Restore both the small and big icons of the console window to
2683 * what they were at startup. Don't do this when the window is
2684 * closed, Vim would hang here.
2685 */
2686 if (g_fCanChangeIcon && !g_fForceExit)
2687 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2688#endif
2689
2690#ifdef MCH_WRITE_DUMP
2691 if (fdDump)
2692 {
2693 time_t t;
2694
2695 time(&t);
2696 fputs(ctime(&t), fdDump);
2697 fclose(fdDump);
2698 }
2699 fdDump = NULL;
2700#endif
2701 }
2702
2703 SetConsoleCursorInfo(g_hConOut, &g_cci);
2704 SetConsoleMode(g_hConIn, g_cmodein);
2705 SetConsoleMode(g_hConOut, g_cmodeout);
2706
2707#ifdef DYNAMIC_GETTEXT
2708 dyn_libintl_end();
2709#endif
2710
2711 exit(r);
2712}
2713#endif /* !FEAT_GUI_W32 */
2714
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715/*
2716 * Do we have an interactive window?
2717 */
2718 int
2719mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002720 int argc UNUSED,
2721 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002722{
2723 get_exe_name();
2724
2725#ifdef FEAT_GUI_W32
2726 return OK; /* GUI always has a tty */
2727#else
2728 if (isatty(1))
2729 return OK;
2730 return FAIL;
2731#endif
2732}
2733
2734
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002735#ifdef FEAT_MBYTE
2736/*
2737 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2738 * if it already exists. When "len" is > 0, also expand short to long
2739 * filenames.
2740 * Return FAIL if wide functions are not available, OK otherwise.
2741 * NOTE: much of this is identical to fname_case(), keep in sync!
2742 */
2743 static int
2744fname_casew(
2745 WCHAR *name,
2746 int len)
2747{
2748 WCHAR szTrueName[_MAX_PATH + 2];
2749 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2750 WCHAR *ptrue, *ptruePrev;
2751 WCHAR *porig, *porigPrev;
2752 int flen;
2753 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002754 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002755 int c;
2756 int slen;
2757
2758 flen = (int)wcslen(name);
2759 if (flen > _MAX_PATH)
2760 return OK;
2761
2762 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2763
2764 /* Build the new name in szTrueName[] one component at a time. */
2765 porig = name;
2766 ptrue = szTrueName;
2767
2768 if (iswalpha(porig[0]) && porig[1] == L':')
2769 {
2770 /* copy leading drive letter */
2771 *ptrue++ = *porig++;
2772 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002773 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002774 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002775
2776 while (*porig != NUL)
2777 {
2778 /* copy \ characters */
2779 while (*porig == psepc)
2780 *ptrue++ = *porig++;
2781
2782 ptruePrev = ptrue;
2783 porigPrev = porig;
2784 while (*porig != NUL && *porig != psepc)
2785 {
2786 *ptrue++ = *porig++;
2787 }
2788 *ptrue = NUL;
2789
2790 /* To avoid a slow failure append "\*" when searching a directory,
2791 * server or network share. */
2792 wcscpy(szTrueNameTemp, szTrueName);
2793 slen = (int)wcslen(szTrueNameTemp);
2794 if (*porig == psepc && slen + 2 < _MAX_PATH)
2795 wcscpy(szTrueNameTemp + slen, L"\\*");
2796
2797 /* Skip "", "." and "..". */
2798 if (ptrue > ptruePrev
2799 && (ptruePrev[0] != L'.'
2800 || (ptruePrev[1] != NUL
2801 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2802 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2803 != INVALID_HANDLE_VALUE)
2804 {
2805 c = *porig;
2806 *porig = NUL;
2807
2808 /* Only use the match when it's the same name (ignoring case) or
2809 * expansion is allowed and there is a match with the short name
2810 * and there is enough room. */
2811 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2812 || (len > 0
2813 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2814 && (int)(ptruePrev - szTrueName)
2815 + (int)wcslen(fb.cFileName) < len)))
2816 {
2817 wcscpy(ptruePrev, fb.cFileName);
2818
2819 /* Look for exact match and prefer it if found. Must be a
2820 * long name, otherwise there would be only one match. */
2821 while (FindNextFileW(hFind, &fb))
2822 {
2823 if (*fb.cAlternateFileName != NUL
2824 && (wcscoll(porigPrev, fb.cFileName) == 0
2825 || (len > 0
2826 && (_wcsicoll(porigPrev,
2827 fb.cAlternateFileName) == 0
2828 && (int)(ptruePrev - szTrueName)
2829 + (int)wcslen(fb.cFileName) < len))))
2830 {
2831 wcscpy(ptruePrev, fb.cFileName);
2832 break;
2833 }
2834 }
2835 }
2836 FindClose(hFind);
2837 *porig = c;
2838 ptrue = ptruePrev + wcslen(ptruePrev);
2839 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002840 }
2841
2842 wcscpy(name, szTrueName);
2843 return OK;
2844}
2845#endif
2846
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847/*
2848 * fname_case(): Set the case of the file name, if it already exists.
2849 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002850 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851 */
2852 void
2853fname_case(
2854 char_u *name,
2855 int len)
2856{
2857 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002858 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859 char *ptrue, *ptruePrev;
2860 char *porig, *porigPrev;
2861 int flen;
2862 WIN32_FIND_DATA fb;
2863 HANDLE hFind;
2864 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002865 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002867 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002868 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869 return;
2870
2871 slash_adjust(name);
2872
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002873#ifdef FEAT_MBYTE
2874 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2875 {
2876 WCHAR *p = enc_to_utf16(name, NULL);
2877
2878 if (p != NULL)
2879 {
2880 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002881 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002882
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002883 wcsncpy(buf, p, _MAX_PATH);
2884 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002885 vim_free(p);
2886
2887 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2888 {
2889 q = utf16_to_enc(buf, NULL);
2890 if (q != NULL)
2891 {
2892 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2893 vim_free(q);
2894 return;
2895 }
2896 }
2897 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002898 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002899 }
2900#endif
2901
2902 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2903 * So we should check this after calling wide function. */
2904 if (flen > _MAX_PATH)
2905 return;
2906
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002908 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909 ptrue = szTrueName;
2910
2911 if (isalpha(porig[0]) && porig[1] == ':')
2912 {
2913 /* copy leading drive letter */
2914 *ptrue++ = *porig++;
2915 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002917 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918
2919 while (*porig != NUL)
2920 {
2921 /* copy \ characters */
2922 while (*porig == psepc)
2923 *ptrue++ = *porig++;
2924
2925 ptruePrev = ptrue;
2926 porigPrev = porig;
2927 while (*porig != NUL && *porig != psepc)
2928 {
2929#ifdef FEAT_MBYTE
2930 int l;
2931
2932 if (enc_dbcs)
2933 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002934 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 while (--l >= 0)
2936 *ptrue++ = *porig++;
2937 }
2938 else
2939#endif
2940 *ptrue++ = *porig++;
2941 }
2942 *ptrue = NUL;
2943
Bram Moolenaar464c9252010-10-13 20:37:41 +02002944 /* To avoid a slow failure append "\*" when searching a directory,
2945 * server or network share. */
2946 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002947 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002948 if (*porig == psepc && slen + 2 < _MAX_PATH)
2949 STRCPY(szTrueNameTemp + slen, "\\*");
2950
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 /* Skip "", "." and "..". */
2952 if (ptrue > ptruePrev
2953 && (ptruePrev[0] != '.'
2954 || (ptruePrev[1] != NUL
2955 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002956 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957 != INVALID_HANDLE_VALUE)
2958 {
2959 c = *porig;
2960 *porig = NUL;
2961
2962 /* Only use the match when it's the same name (ignoring case) or
2963 * expansion is allowed and there is a match with the short name
2964 * and there is enough room. */
2965 if (_stricoll(porigPrev, fb.cFileName) == 0
2966 || (len > 0
2967 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2968 && (int)(ptruePrev - szTrueName)
2969 + (int)strlen(fb.cFileName) < len)))
2970 {
2971 STRCPY(ptruePrev, fb.cFileName);
2972
2973 /* Look for exact match and prefer it if found. Must be a
2974 * long name, otherwise there would be only one match. */
2975 while (FindNextFile(hFind, &fb))
2976 {
2977 if (*fb.cAlternateFileName != NUL
2978 && (strcoll(porigPrev, fb.cFileName) == 0
2979 || (len > 0
2980 && (_stricoll(porigPrev,
2981 fb.cAlternateFileName) == 0
2982 && (int)(ptruePrev - szTrueName)
2983 + (int)strlen(fb.cFileName) < len))))
2984 {
2985 STRCPY(ptruePrev, fb.cFileName);
2986 break;
2987 }
2988 }
2989 }
2990 FindClose(hFind);
2991 *porig = c;
2992 ptrue = ptruePrev + strlen(ptruePrev);
2993 }
2994 }
2995
2996 STRCPY(name, szTrueName);
2997}
2998
2999
3000/*
3001 * Insert user name in s[len].
3002 */
3003 int
3004mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003005 char_u *s,
3006 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003008 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009 DWORD cch = sizeof szUserName;
3010
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003011#ifdef FEAT_MBYTE
3012 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3013 {
3014 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3015 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3016
3017 if (GetUserNameW(wszUserName, &wcch))
3018 {
3019 char_u *p = utf16_to_enc(wszUserName, NULL);
3020
3021 if (p != NULL)
3022 {
3023 vim_strncpy(s, p, len - 1);
3024 vim_free(p);
3025 return OK;
3026 }
3027 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003028 }
3029#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 if (GetUserName(szUserName, &cch))
3031 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003032 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033 return OK;
3034 }
3035 s[0] = NUL;
3036 return FAIL;
3037}
3038
3039
3040/*
3041 * Insert host name in s[len].
3042 */
3043 void
3044mch_get_host_name(
3045 char_u *s,
3046 int len)
3047{
3048 DWORD cch = len;
3049
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003050#ifdef FEAT_MBYTE
3051 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3052 {
3053 WCHAR wszHostName[256 + 1];
3054 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3055
3056 if (GetComputerNameW(wszHostName, &wcch))
3057 {
3058 char_u *p = utf16_to_enc(wszHostName, NULL);
3059
3060 if (p != NULL)
3061 {
3062 vim_strncpy(s, p, len - 1);
3063 vim_free(p);
3064 return;
3065 }
3066 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003067 }
3068#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003069 if (!GetComputerName((LPSTR)s, &cch))
3070 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071}
3072
3073
3074/*
3075 * return process ID
3076 */
3077 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003078mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079{
3080 return (long)GetCurrentProcessId();
3081}
3082
3083
3084/*
3085 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3086 * Return OK for success, FAIL for failure.
3087 */
3088 int
3089mch_dirname(
3090 char_u *buf,
3091 int len)
3092{
3093 /*
3094 * Originally this was:
3095 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3096 * But the Win32s known bug list says that getcwd() doesn't work
3097 * so use the Win32 system call instead. <Negri>
3098 */
3099#ifdef FEAT_MBYTE
3100 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3101 {
3102 WCHAR wbuf[_MAX_PATH + 1];
3103
3104 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3105 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003106 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107
3108 if (p != NULL)
3109 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003110 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111 vim_free(p);
3112 return OK;
3113 }
3114 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003115 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116 }
3117#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003118 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119}
3120
3121/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003122 * Get file permissions for "name".
3123 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003124 */
3125 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003126mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003128 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003129 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003131 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003132 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133}
3134
3135
3136/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003137 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003138 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003139 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 */
3141 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003142mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003143{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003144 long n = -1;
3145
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146#ifdef FEAT_MBYTE
3147 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3148 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003149 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003150
3151 if (p != NULL)
3152 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003153 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003155 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003156 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157 }
3158 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003159 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003161 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003162 if (n == -1)
3163 return FAIL;
3164
3165 win32_set_archive(name);
3166
3167 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168}
3169
3170/*
3171 * Set hidden flag for "name".
3172 */
3173 void
3174mch_hide(char_u *name)
3175{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003176 int attrs = win32_getattrs(name);
3177 if (attrs == -1)
3178 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003180 attrs |= FILE_ATTRIBUTE_HIDDEN;
3181 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182}
3183
3184/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003185 * Return TRUE if file "name" exists and is hidden.
3186 */
3187 int
3188mch_ishidden(char_u *name)
3189{
3190 int f = win32_getattrs(name);
3191
3192 if (f == -1)
3193 return FALSE; /* file does not exist at all */
3194
3195 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3196}
3197
3198/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 * return TRUE if "name" is a directory
3200 * return FALSE if "name" is not a directory or upon error
3201 */
3202 int
3203mch_isdir(char_u *name)
3204{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003205 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206
3207 if (f == -1)
3208 return FALSE; /* file does not exist at all */
3209
3210 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3211}
3212
3213/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003214 * return TRUE if "name" is a directory, NOT a symlink to a directory
3215 * return FALSE if "name" is not a directory
3216 * return FALSE for error
3217 */
3218 int
3219mch_isrealdir(char_u *name)
3220{
3221 return mch_isdir(name) && !mch_is_symbolic_link(name);
3222}
3223
3224/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003225 * Create directory "name".
3226 * Return 0 on success, -1 on error.
3227 */
3228 int
3229mch_mkdir(char_u *name)
3230{
3231#ifdef FEAT_MBYTE
3232 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3233 {
3234 WCHAR *p;
3235 int retval;
3236
3237 p = enc_to_utf16(name, NULL);
3238 if (p == NULL)
3239 return -1;
3240 retval = _wmkdir(p);
3241 vim_free(p);
3242 return retval;
3243 }
3244#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003245 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003246}
3247
3248/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003249 * Delete directory "name".
3250 * Return 0 on success, -1 on error.
3251 */
3252 int
3253mch_rmdir(char_u *name)
3254{
3255#ifdef FEAT_MBYTE
3256 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3257 {
3258 WCHAR *p;
3259 int retval;
3260
3261 p = enc_to_utf16(name, NULL);
3262 if (p == NULL)
3263 return -1;
3264 retval = _wrmdir(p);
3265 vim_free(p);
3266 return retval;
3267 }
3268#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003269 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003270}
3271
3272/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003273 * Return TRUE if file "fname" has more than one link.
3274 */
3275 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003276mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003277{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003278 BY_HANDLE_FILE_INFORMATION info;
3279
3280 return win32_fileinfo(fname, &info) == FILEINFO_OK
3281 && info.nNumberOfLinks > 1;
3282}
3283
3284/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003285 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003286 */
3287 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003288mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003289{
3290 HANDLE hFind;
3291 int res = FALSE;
3292 WIN32_FIND_DATAA findDataA;
3293 DWORD fileFlags = 0, reparseTag = 0;
3294#ifdef FEAT_MBYTE
3295 WCHAR *wn = NULL;
3296 WIN32_FIND_DATAW findDataW;
3297
3298 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003299 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003300 if (wn != NULL)
3301 {
3302 hFind = FindFirstFileW(wn, &findDataW);
3303 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003304 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003305 {
3306 fileFlags = findDataW.dwFileAttributes;
3307 reparseTag = findDataW.dwReserved0;
3308 }
3309 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003310 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003311#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003312 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003313 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003314 if (hFind != INVALID_HANDLE_VALUE)
3315 {
3316 fileFlags = findDataA.dwFileAttributes;
3317 reparseTag = findDataA.dwReserved0;
3318 }
3319 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003320
3321 if (hFind != INVALID_HANDLE_VALUE)
3322 FindClose(hFind);
3323
3324 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003325 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3326 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003327 res = TRUE;
3328
3329 return res;
3330}
3331
3332/*
3333 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3334 * link.
3335 */
3336 int
3337mch_is_linked(char_u *fname)
3338{
3339 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3340 return TRUE;
3341 return FALSE;
3342}
3343
3344/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003345 * Get the by-handle-file-information for "fname".
3346 * Returns FILEINFO_OK when OK.
3347 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3348 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3349 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3350 */
3351 int
3352win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3353{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003354 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003355 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003356#ifdef FEAT_MBYTE
3357 WCHAR *wn = NULL;
3358
3359 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003360 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003361 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003362 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003363 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003364 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003365 if (wn != NULL)
3366 {
3367 hFile = CreateFileW(wn, /* file name */
3368 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003369 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003370 NULL, /* security descriptor */
3371 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003372 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003373 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003374 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003375 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003376 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003377#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003378 hFile = CreateFile((LPCSTR)fname, /* file name */
3379 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003380 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003381 NULL, /* security descriptor */
3382 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003383 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003384 NULL); /* handle to template file */
3385
3386 if (hFile != INVALID_HANDLE_VALUE)
3387 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003388 if (GetFileInformationByHandle(hFile, info) != 0)
3389 res = FILEINFO_OK;
3390 else
3391 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003392 CloseHandle(hFile);
3393 }
3394
Bram Moolenaar03f48552006-02-28 23:52:23 +00003395 return res;
3396}
3397
3398/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003399 * get file attributes for `name'
3400 * -1 : error
3401 * else FILE_ATTRIBUTE_* defined in winnt.h
3402 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003403 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003404win32_getattrs(char_u *name)
3405{
3406 int attr;
3407#ifdef FEAT_MBYTE
3408 WCHAR *p = NULL;
3409
3410 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3411 p = enc_to_utf16(name, NULL);
3412
3413 if (p != NULL)
3414 {
3415 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003416 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003417 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003418 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003419#endif
3420 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003421
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003422 return attr;
3423}
3424
3425/*
3426 * set file attributes for `name' to `attrs'
3427 *
3428 * return -1 for failure, 0 otherwise
3429 */
3430 static
3431 int
3432win32_setattrs(char_u *name, int attrs)
3433{
3434 int res;
3435#ifdef FEAT_MBYTE
3436 WCHAR *p = NULL;
3437
3438 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3439 p = enc_to_utf16(name, NULL);
3440
3441 if (p != NULL)
3442 {
3443 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003444 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003445 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003446 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003447#endif
3448 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003449
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003450 return res ? 0 : -1;
3451}
3452
3453/*
3454 * Set archive flag for "name".
3455 */
3456 static
3457 int
3458win32_set_archive(char_u *name)
3459{
3460 int attrs = win32_getattrs(name);
3461 if (attrs == -1)
3462 return -1;
3463
3464 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3465 return win32_setattrs(name, attrs);
3466}
3467
3468/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469 * Return TRUE if file or directory "name" is writable (not readonly).
3470 * Strange semantics of Win32: a readonly directory is writable, but you can't
3471 * delete a file. Let's say this means it is writable.
3472 */
3473 int
3474mch_writable(char_u *name)
3475{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003476 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003478 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3479 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003480}
3481
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003483 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003484 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003485 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3486 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487 */
3488 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003489mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003491 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003492 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003493 char_u *p;
3494
3495 if (len >= _MAX_PATH) /* safety check */
3496 return FALSE;
3497
3498 /* If there already is an extension try using the name directly. Also do
3499 * this with a Unix-shell like 'shell'. */
3500 if (vim_strchr(gettail(name), '.') != NULL
3501 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003502 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003503 return TRUE;
3504
3505 /*
3506 * Loop over all extensions in $PATHEXT.
3507 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003508 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003509 p = mch_getenv("PATHEXT");
3510 if (p == NULL)
3511 p = (char_u *)".com;.exe;.bat;.cmd";
3512 while (*p)
3513 {
3514 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3515 {
3516 /* A single "." means no extension is added. */
3517 buf[len] = NUL;
3518 ++p;
3519 if (*p)
3520 ++p;
3521 }
3522 else
3523 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003524 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003525 return TRUE;
3526 }
3527 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529
3530/*
3531 * Check what "name" is:
3532 * NODE_NORMAL: file or directory (or doesn't exist)
3533 * NODE_WRITABLE: writable device, socket, fifo, etc.
3534 * NODE_OTHER: non-writable things
3535 */
3536 int
3537mch_nodetype(char_u *name)
3538{
3539 HANDLE hFile;
3540 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003541#ifdef FEAT_MBYTE
3542 WCHAR *wn = NULL;
3543#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544
Bram Moolenaar043545e2006-10-10 16:44:07 +00003545 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3546 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3547 * here. */
3548 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3549 return NODE_WRITABLE;
3550
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003551#ifdef FEAT_MBYTE
3552 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003553 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003554
3555 if (wn != NULL)
3556 {
3557 hFile = CreateFileW(wn, /* file name */
3558 GENERIC_WRITE, /* access mode */
3559 0, /* share mode */
3560 NULL, /* security descriptor */
3561 OPEN_EXISTING, /* creation disposition */
3562 0, /* file attributes */
3563 NULL); /* handle to template file */
3564 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003565 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003566 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003567#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003568 hFile = CreateFile((LPCSTR)name, /* file name */
3569 GENERIC_WRITE, /* access mode */
3570 0, /* share mode */
3571 NULL, /* security descriptor */
3572 OPEN_EXISTING, /* creation disposition */
3573 0, /* file attributes */
3574 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575
3576 if (hFile == INVALID_HANDLE_VALUE)
3577 return NODE_NORMAL;
3578
3579 type = GetFileType(hFile);
3580 CloseHandle(hFile);
3581 if (type == FILE_TYPE_CHAR)
3582 return NODE_WRITABLE;
3583 if (type == FILE_TYPE_DISK)
3584 return NODE_NORMAL;
3585 return NODE_OTHER;
3586}
3587
3588#ifdef HAVE_ACL
3589struct my_acl
3590{
3591 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3592 PSID pSidOwner;
3593 PSID pSidGroup;
3594 PACL pDacl;
3595 PACL pSacl;
3596};
3597#endif
3598
3599/*
3600 * Return a pointer to the ACL of file "fname" in allocated memory.
3601 * Return NULL if the ACL is not available for whatever reason.
3602 */
3603 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003604mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605{
3606#ifndef HAVE_ACL
3607 return (vim_acl_T)NULL;
3608#else
3609 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003610 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003612 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3613 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003615# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003616 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003617
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003618 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3619 wn = enc_to_utf16(fname, NULL);
3620 if (wn != NULL)
3621 {
3622 /* Try to retrieve the entire security descriptor. */
3623 err = GetNamedSecurityInfoW(
3624 wn, // Abstract filename
3625 SE_FILE_OBJECT, // File Object
3626 OWNER_SECURITY_INFORMATION |
3627 GROUP_SECURITY_INFORMATION |
3628 DACL_SECURITY_INFORMATION |
3629 SACL_SECURITY_INFORMATION,
3630 &p->pSidOwner, // Ownership information.
3631 &p->pSidGroup, // Group membership.
3632 &p->pDacl, // Discretionary information.
3633 &p->pSacl, // For auditing purposes.
3634 &p->pSecurityDescriptor);
3635 if (err == ERROR_ACCESS_DENIED ||
3636 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003638 /* Retrieve only DACL. */
3639 (void)GetNamedSecurityInfoW(
3640 wn,
3641 SE_FILE_OBJECT,
3642 DACL_SECURITY_INFORMATION,
3643 NULL,
3644 NULL,
3645 &p->pDacl,
3646 NULL,
3647 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003648 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003649 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003650 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003651 mch_free_acl((vim_acl_T)p);
3652 p = NULL;
3653 }
3654 vim_free(wn);
3655 }
3656 else
3657# endif
3658 {
3659 /* Try to retrieve the entire security descriptor. */
3660 err = GetNamedSecurityInfo(
3661 (LPSTR)fname, // Abstract filename
3662 SE_FILE_OBJECT, // File Object
3663 OWNER_SECURITY_INFORMATION |
3664 GROUP_SECURITY_INFORMATION |
3665 DACL_SECURITY_INFORMATION |
3666 SACL_SECURITY_INFORMATION,
3667 &p->pSidOwner, // Ownership information.
3668 &p->pSidGroup, // Group membership.
3669 &p->pDacl, // Discretionary information.
3670 &p->pSacl, // For auditing purposes.
3671 &p->pSecurityDescriptor);
3672 if (err == ERROR_ACCESS_DENIED ||
3673 err == ERROR_PRIVILEGE_NOT_HELD)
3674 {
3675 /* Retrieve only DACL. */
3676 (void)GetNamedSecurityInfo(
3677 (LPSTR)fname,
3678 SE_FILE_OBJECT,
3679 DACL_SECURITY_INFORMATION,
3680 NULL,
3681 NULL,
3682 &p->pDacl,
3683 NULL,
3684 &p->pSecurityDescriptor);
3685 }
3686 if (p->pSecurityDescriptor == NULL)
3687 {
3688 mch_free_acl((vim_acl_T)p);
3689 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690 }
3691 }
3692 }
3693
3694 return (vim_acl_T)p;
3695#endif
3696}
3697
Bram Moolenaar27515922013-06-29 15:36:26 +02003698#ifdef HAVE_ACL
3699/*
3700 * Check if "acl" contains inherited ACE.
3701 */
3702 static BOOL
3703is_acl_inherited(PACL acl)
3704{
3705 DWORD i;
3706 ACL_SIZE_INFORMATION acl_info;
3707 PACCESS_ALLOWED_ACE ace;
3708
3709 acl_info.AceCount = 0;
3710 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3711 for (i = 0; i < acl_info.AceCount; i++)
3712 {
3713 GetAce(acl, i, (LPVOID *)&ace);
3714 if (ace->Header.AceFlags & INHERITED_ACE)
3715 return TRUE;
3716 }
3717 return FALSE;
3718}
3719#endif
3720
Bram Moolenaar071d4272004-06-13 20:20:40 +00003721/*
3722 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3723 * Errors are ignored.
3724 * This must only be called with "acl" equal to what mch_get_acl() returned.
3725 */
3726 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003727mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728{
3729#ifdef HAVE_ACL
3730 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003731 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003733 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003734 {
3735# ifdef FEAT_MBYTE
3736 WCHAR *wn = NULL;
3737# endif
3738
3739 /* Set security flags */
3740 if (p->pSidOwner)
3741 sec_info |= OWNER_SECURITY_INFORMATION;
3742 if (p->pSidGroup)
3743 sec_info |= GROUP_SECURITY_INFORMATION;
3744 if (p->pDacl)
3745 {
3746 sec_info |= DACL_SECURITY_INFORMATION;
3747 /* Do not inherit its parent's DACL.
3748 * If the DACL is inherited, Cygwin permissions would be changed.
3749 */
3750 if (!is_acl_inherited(p->pDacl))
3751 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3752 }
3753 if (p->pSacl)
3754 sec_info |= SACL_SECURITY_INFORMATION;
3755
3756# ifdef FEAT_MBYTE
3757 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3758 wn = enc_to_utf16(fname, NULL);
3759 if (wn != NULL)
3760 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003761 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003762 wn, // Abstract filename
3763 SE_FILE_OBJECT, // File Object
3764 sec_info,
3765 p->pSidOwner, // Ownership information.
3766 p->pSidGroup, // Group membership.
3767 p->pDacl, // Discretionary information.
3768 p->pSacl // For auditing purposes.
3769 );
3770 vim_free(wn);
3771 }
3772 else
3773# endif
3774 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003775 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003776 (LPSTR)fname, // Abstract filename
3777 SE_FILE_OBJECT, // File Object
3778 sec_info,
3779 p->pSidOwner, // Ownership information.
3780 p->pSidGroup, // Group membership.
3781 p->pDacl, // Discretionary information.
3782 p->pSacl // For auditing purposes.
3783 );
3784 }
3785 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786#endif
3787}
3788
3789 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003790mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791{
3792#ifdef HAVE_ACL
3793 struct my_acl *p = (struct my_acl *)acl;
3794
3795 if (p != NULL)
3796 {
3797 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3798 vim_free(p);
3799 }
3800#endif
3801}
3802
3803#ifndef FEAT_GUI_W32
3804
3805/*
3806 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3807 */
3808 static BOOL WINAPI
3809handler_routine(
3810 DWORD dwCtrlType)
3811{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003812 INPUT_RECORD ir;
3813 DWORD out;
3814
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815 switch (dwCtrlType)
3816 {
3817 case CTRL_C_EVENT:
3818 if (ctrl_c_interrupts)
3819 g_fCtrlCPressed = TRUE;
3820 return TRUE;
3821
3822 case CTRL_BREAK_EVENT:
3823 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003824 ctrl_break_was_pressed = TRUE;
3825 /* ReadConsoleInput is blocking, send a key event to continue. */
3826 ir.EventType = KEY_EVENT;
3827 ir.Event.KeyEvent.bKeyDown = TRUE;
3828 ir.Event.KeyEvent.wRepeatCount = 1;
3829 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3830 ir.Event.KeyEvent.wVirtualScanCode = 0;
3831 ir.Event.KeyEvent.dwControlKeyState = 0;
3832 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3833 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 return TRUE;
3835
3836 /* fatal events: shut down gracefully */
3837 case CTRL_CLOSE_EVENT:
3838 case CTRL_LOGOFF_EVENT:
3839 case CTRL_SHUTDOWN_EVENT:
3840 windgoto((int)Rows - 1, 0);
3841 g_fForceExit = TRUE;
3842
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003843 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003844 (dwCtrlType == CTRL_CLOSE_EVENT
3845 ? _("close")
3846 : dwCtrlType == CTRL_LOGOFF_EVENT
3847 ? _("logoff")
3848 : _("shutdown")));
3849#ifdef DEBUG
3850 OutputDebugString(IObuff);
3851#endif
3852
3853 preserve_exit(); /* output IObuff, preserve files and exit */
3854
3855 return TRUE; /* not reached */
3856
3857 default:
3858 return FALSE;
3859 }
3860}
3861
3862
3863/*
3864 * set the tty in (raw) ? "raw" : "cooked" mode
3865 */
3866 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003867mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868{
3869 DWORD cmodein;
3870 DWORD cmodeout;
3871 BOOL bEnableHandler;
3872
3873 GetConsoleMode(g_hConIn, &cmodein);
3874 GetConsoleMode(g_hConOut, &cmodeout);
3875 if (tmode == TMODE_RAW)
3876 {
3877 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3878 ENABLE_ECHO_INPUT);
3879#ifdef FEAT_MOUSE
3880 if (g_fMouseActive)
3881 cmodein |= ENABLE_MOUSE_INPUT;
3882#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003883 cmodeout &= ~(
3884#ifdef FEAT_TERMGUICOLORS
3885 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3886 * VTP. */
3887 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3888#else
3889 ENABLE_PROCESSED_OUTPUT |
3890#endif
3891 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892 bEnableHandler = TRUE;
3893 }
3894 else /* cooked */
3895 {
3896 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3897 ENABLE_ECHO_INPUT);
3898 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3899 bEnableHandler = FALSE;
3900 }
3901 SetConsoleMode(g_hConIn, cmodein);
3902 SetConsoleMode(g_hConOut, cmodeout);
3903 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3904
3905#ifdef MCH_WRITE_DUMP
3906 if (fdDump)
3907 {
3908 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3909 tmode == TMODE_RAW ? "raw" :
3910 tmode == TMODE_COOK ? "cooked" : "normal",
3911 cmodein, cmodeout);
3912 fflush(fdDump);
3913 }
3914#endif
3915}
3916
3917
3918/*
3919 * Get the size of the current window in `Rows' and `Columns'
3920 * Return OK when size could be determined, FAIL otherwise.
3921 */
3922 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003923mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924{
3925 CONSOLE_SCREEN_BUFFER_INFO csbi;
3926
3927 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3928 {
3929 /*
3930 * For some reason, we are trying to get the screen dimensions
3931 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3932 * variables are really intended to mean the size of Vim screen
3933 * while in termcap mode.
3934 */
3935 Rows = g_cbTermcap.Info.dwSize.Y;
3936 Columns = g_cbTermcap.Info.dwSize.X;
3937 }
3938 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3939 {
3940 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3941 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3942 }
3943 else
3944 {
3945 Rows = 25;
3946 Columns = 80;
3947 }
3948 return OK;
3949}
3950
3951/*
3952 * Set a console window to `xSize' * `ySize'
3953 */
3954 static void
3955ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003956 HANDLE hConsole,
3957 int xSize,
3958 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003959{
3960 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3961 SMALL_RECT srWindowRect; /* hold the new console size */
3962 COORD coordScreen;
3963
3964#ifdef MCH_WRITE_DUMP
3965 if (fdDump)
3966 {
3967 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3968 fflush(fdDump);
3969 }
3970#endif
3971
3972 /* get the largest size we can size the console window to */
3973 coordScreen = GetLargestConsoleWindowSize(hConsole);
3974
3975 /* define the new console window size and scroll position */
3976 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3977 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3978 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3979
3980 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3981 {
3982 int sx, sy;
3983
3984 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3985 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3986 if (sy < ySize || sx < xSize)
3987 {
3988 /*
3989 * Increasing number of lines/columns, do buffer first.
3990 * Use the maximal size in x and y direction.
3991 */
3992 if (sy < ySize)
3993 coordScreen.Y = ySize;
3994 else
3995 coordScreen.Y = sy;
3996 if (sx < xSize)
3997 coordScreen.X = xSize;
3998 else
3999 coordScreen.X = sx;
4000 SetConsoleScreenBufferSize(hConsole, coordScreen);
4001 }
4002 }
4003
4004 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
4005 {
4006#ifdef MCH_WRITE_DUMP
4007 if (fdDump)
4008 {
4009 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4010 GetLastError());
4011 fflush(fdDump);
4012 }
4013#endif
4014 }
4015
4016 /* define the new console buffer size */
4017 coordScreen.X = xSize;
4018 coordScreen.Y = ySize;
4019
4020 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4021 {
4022#ifdef MCH_WRITE_DUMP
4023 if (fdDump)
4024 {
4025 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4026 GetLastError());
4027 fflush(fdDump);
4028 }
4029#endif
4030 }
4031}
4032
4033
4034/*
4035 * Set the console window to `Rows' * `Columns'
4036 */
4037 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004038mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004039{
4040 COORD coordScreen;
4041
4042 /* Don't change window size while still starting up */
4043 if (suppress_winsize != 0)
4044 {
4045 suppress_winsize = 2;
4046 return;
4047 }
4048
4049 if (term_console)
4050 {
4051 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4052
4053 /* Clamp Rows and Columns to reasonable values */
4054 if (Rows > coordScreen.Y)
4055 Rows = coordScreen.Y;
4056 if (Columns > coordScreen.X)
4057 Columns = coordScreen.X;
4058
4059 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4060 }
4061}
4062
4063/*
4064 * Rows and/or Columns has changed.
4065 */
4066 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004067mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068{
4069 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4070}
4071
4072
4073/*
4074 * Called when started up, to set the winsize that was delayed.
4075 */
4076 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004077mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078{
4079 if (suppress_winsize == 2)
4080 {
4081 suppress_winsize = 0;
4082 mch_set_shellsize();
4083 shell_resized();
4084 }
4085 suppress_winsize = 0;
4086}
4087#endif /* FEAT_GUI_W32 */
4088
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004089 static BOOL
4090vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004091 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004092 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004093 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004094 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004095 PROCESS_INFORMATION *pi,
4096 LPVOID *env,
4097 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004098{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004099#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004100 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4101 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004102 BOOL ret;
4103 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004104
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004105 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4106 if (wcmd == NULL)
4107 goto fallback;
4108 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004109 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004110 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4111 if (wcwd == NULL)
4112 {
4113 vim_free(wcmd);
4114 goto fallback;
4115 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004116 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004117
4118 ret = CreateProcessW(
4119 NULL, /* Executable name */
4120 wcmd, /* Command to execute */
4121 NULL, /* Process security attributes */
4122 NULL, /* Thread security attributes */
4123 inherit_handles, /* Inherit handles */
4124 flags, /* Creation flags */
4125 env, /* Environment */
4126 wcwd, /* Current directory */
4127 (LPSTARTUPINFOW)si, /* Startup information */
4128 pi); /* Process information */
4129 vim_free(wcmd);
4130 if (wcwd != NULL)
4131 vim_free(wcwd);
4132 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004133 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004134fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004135#endif
4136 return CreateProcess(
4137 NULL, /* Executable name */
4138 cmd, /* Command to execute */
4139 NULL, /* Process security attributes */
4140 NULL, /* Thread security attributes */
4141 inherit_handles, /* Inherit handles */
4142 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004143 env, /* Environment */
4144 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004145 si, /* Startup information */
4146 pi); /* Process information */
4147}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148
4149
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004150 static HINSTANCE
4151vim_shell_execute(
4152 char *cmd,
4153 INT n_show_cmd)
4154{
4155#ifdef FEAT_MBYTE
4156 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4157 {
4158 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4159 if (wcmd != NULL)
4160 {
4161 HINSTANCE ret;
4162 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4163 vim_free(wcmd);
4164 return ret;
4165 }
4166 }
4167#endif
4168 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4169}
4170
4171
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172#if defined(FEAT_GUI_W32) || defined(PROTO)
4173
4174/*
4175 * Specialised version of system() for Win32 GUI mode.
4176 * This version proceeds as follows:
4177 * 1. Create a console window for use by the subprocess
4178 * 2. Run the subprocess (it gets the allocated console by default)
4179 * 3. Wait for the subprocess to terminate and get its exit code
4180 * 4. Prompt the user to press a key to close the console window
4181 */
4182 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004183mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004184{
4185 STARTUPINFO si;
4186 PROCESS_INFORMATION pi;
4187 DWORD ret = 0;
4188 HWND hwnd = GetFocus();
4189
4190 si.cb = sizeof(si);
4191 si.lpReserved = NULL;
4192 si.lpDesktop = NULL;
4193 si.lpTitle = NULL;
4194 si.dwFlags = STARTF_USESHOWWINDOW;
4195 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004196 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004197 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004199 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004200 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 else
4202 si.wShowWindow = SW_SHOWNORMAL;
4203 si.cbReserved2 = 0;
4204 si.lpReserved2 = NULL;
4205
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004207 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004208 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4209 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004210
4211 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004212 {
4213#ifdef FEAT_GUI
4214 int delay = 1;
4215
4216 /* Keep updating the window while waiting for the shell to finish. */
4217 for (;;)
4218 {
4219 MSG msg;
4220
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004221 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004222 {
4223 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004224 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004225 delay = 1;
4226 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 }
4228 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4229 break;
4230
4231 /* We start waiting for a very short time and then increase it, so
4232 * that we respond quickly when the process is quick, and don't
4233 * consume too much overhead when it's slow. */
4234 if (delay < 50)
4235 delay += 10;
4236 }
4237#else
4238 WaitForSingleObject(pi.hProcess, INFINITE);
4239#endif
4240
4241 /* Get the command exit code */
4242 GetExitCodeProcess(pi.hProcess, &ret);
4243 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004244
4245 /* Close the handles to the subprocess, so that it goes away */
4246 CloseHandle(pi.hThread);
4247 CloseHandle(pi.hProcess);
4248
4249 /* Try to get input focus back. Doesn't always work though. */
4250 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4251
4252 return ret;
4253}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004254
4255/*
4256 * Thread launched by the gui to send the current buffer data to the
4257 * process. This way avoid to hang up vim totally if the children
4258 * process take a long time to process the lines.
4259 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004260 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004261sub_process_writer(LPVOID param)
4262{
4263 HANDLE g_hChildStd_IN_Wr = param;
4264 linenr_T lnum = curbuf->b_op_start.lnum;
4265 DWORD len = 0;
4266 DWORD l;
4267 char_u *lp = ml_get(lnum);
4268 char_u *s;
4269 int written = 0;
4270
4271 for (;;)
4272 {
4273 l = (DWORD)STRLEN(lp + written);
4274 if (l == 0)
4275 len = 0;
4276 else if (lp[written] == NL)
4277 {
4278 /* NL -> NUL translation */
4279 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4280 }
4281 else
4282 {
4283 s = vim_strchr(lp + written, NL);
4284 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4285 s == NULL ? l : (DWORD)(s - (lp + written)),
4286 &len, NULL);
4287 }
4288 if (len == (int)l)
4289 {
4290 /* Finished a line, add a NL, unless this line should not have
4291 * one. */
4292 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004293 || (!curbuf->b_p_bin
4294 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004295 || (lnum != curbuf->b_no_eol_lnum
4296 && (lnum != curbuf->b_ml.ml_line_count
4297 || curbuf->b_p_eol)))
4298 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004299 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004300 }
4301
4302 ++lnum;
4303 if (lnum > curbuf->b_op_end.lnum)
4304 break;
4305
4306 lp = ml_get(lnum);
4307 written = 0;
4308 }
4309 else if (len > 0)
4310 written += len;
4311 }
4312
4313 /* finished all the lines, close pipe */
4314 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004315 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004316}
4317
4318
4319# define BUFLEN 100 /* length for buffer, stolen from unix version */
4320
4321/*
4322 * This function read from the children's stdout and write the
4323 * data on screen or in the buffer accordingly.
4324 */
4325 static void
4326dump_pipe(int options,
4327 HANDLE g_hChildStd_OUT_Rd,
4328 garray_T *ga,
4329 char_u buffer[],
4330 DWORD *buffer_off)
4331{
4332 DWORD availableBytes = 0;
4333 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004334 int ret;
4335 DWORD len;
4336 DWORD toRead;
4337 int repeatCount;
4338
4339 /* we query the pipe to see if there is any data to read
4340 * to avoid to perform a blocking read */
4341 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4342 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004343 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004344 NULL, /* number of read bytes */
4345 &availableBytes, /* available bytes total */
4346 NULL); /* byteLeft */
4347
4348 repeatCount = 0;
4349 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004350 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004351 {
4352 repeatCount++;
4353 toRead =
4354# ifdef FEAT_MBYTE
4355 (DWORD)(BUFLEN - *buffer_off);
4356# else
4357 (DWORD)BUFLEN;
4358# endif
4359 toRead = availableBytes < toRead ? availableBytes : toRead;
4360 ReadFile(g_hChildStd_OUT_Rd, buffer
4361# ifdef FEAT_MBYTE
4362 + *buffer_off, toRead
4363# else
4364 , toRead
4365# endif
4366 , &len, NULL);
4367
4368 /* If we haven't read anything, there is a problem */
4369 if (len == 0)
4370 break;
4371
4372 availableBytes -= len;
4373
4374 if (options & SHELL_READ)
4375 {
4376 /* Do NUL -> NL translation, append NL separated
4377 * lines to the current buffer. */
4378 for (i = 0; i < len; ++i)
4379 {
4380 if (buffer[i] == NL)
4381 append_ga_line(ga);
4382 else if (buffer[i] == NUL)
4383 ga_append(ga, NL);
4384 else
4385 ga_append(ga, buffer[i]);
4386 }
4387 }
4388# ifdef FEAT_MBYTE
4389 else if (has_mbyte)
4390 {
4391 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004392 int c;
4393 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004394
4395 len += *buffer_off;
4396 buffer[len] = NUL;
4397
4398 /* Check if the last character in buffer[] is
4399 * incomplete, keep these bytes for the next
4400 * round. */
4401 for (p = buffer; p < buffer + len; p += l)
4402 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004403 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004404 if (l == 0)
4405 l = 1; /* NUL byte? */
4406 else if (MB_BYTE2LEN(*p) != l)
4407 break;
4408 }
4409 if (p == buffer) /* no complete character */
4410 {
4411 /* avoid getting stuck at an illegal byte */
4412 if (len >= 12)
4413 ++p;
4414 else
4415 {
4416 *buffer_off = len;
4417 return;
4418 }
4419 }
4420 c = *p;
4421 *p = NUL;
4422 msg_puts(buffer);
4423 if (p < buffer + len)
4424 {
4425 *p = c;
4426 *buffer_off = (DWORD)((buffer + len) - p);
4427 mch_memmove(buffer, p, *buffer_off);
4428 return;
4429 }
4430 *buffer_off = 0;
4431 }
4432# endif /* FEAT_MBYTE */
4433 else
4434 {
4435 buffer[len] = NUL;
4436 msg_puts(buffer);
4437 }
4438
4439 windgoto(msg_row, msg_col);
4440 cursor_on();
4441 out_flush();
4442 }
4443}
4444
4445/*
4446 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4447 * for communication and doesn't open any new window.
4448 */
4449 static int
4450mch_system_piped(char *cmd, int options)
4451{
4452 STARTUPINFO si;
4453 PROCESS_INFORMATION pi;
4454 DWORD ret = 0;
4455
4456 HANDLE g_hChildStd_IN_Rd = NULL;
4457 HANDLE g_hChildStd_IN_Wr = NULL;
4458 HANDLE g_hChildStd_OUT_Rd = NULL;
4459 HANDLE g_hChildStd_OUT_Wr = NULL;
4460
4461 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4462 DWORD len;
4463
4464 /* buffer used to receive keys */
4465 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4466 int ta_len = 0; /* valid bytes in ta_buf[] */
4467
4468 DWORD i;
4469 int c;
4470 int noread_cnt = 0;
4471 garray_T ga;
4472 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004473 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004474 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004475
4476 SECURITY_ATTRIBUTES saAttr;
4477
4478 /* Set the bInheritHandle flag so pipe handles are inherited. */
4479 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4480 saAttr.bInheritHandle = TRUE;
4481 saAttr.lpSecurityDescriptor = NULL;
4482
4483 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4484 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004485 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004486 /* Create a pipe for the child process's STDIN. */
4487 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4488 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004489 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004490 {
4491 CloseHandle(g_hChildStd_IN_Rd);
4492 CloseHandle(g_hChildStd_IN_Wr);
4493 CloseHandle(g_hChildStd_OUT_Rd);
4494 CloseHandle(g_hChildStd_OUT_Wr);
4495 MSG_PUTS(_("\nCannot create pipes\n"));
4496 }
4497
4498 si.cb = sizeof(si);
4499 si.lpReserved = NULL;
4500 si.lpDesktop = NULL;
4501 si.lpTitle = NULL;
4502 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4503
4504 /* set-up our file redirection */
4505 si.hStdError = g_hChildStd_OUT_Wr;
4506 si.hStdOutput = g_hChildStd_OUT_Wr;
4507 si.hStdInput = g_hChildStd_IN_Rd;
4508 si.wShowWindow = SW_HIDE;
4509 si.cbReserved2 = 0;
4510 si.lpReserved2 = NULL;
4511
4512 if (options & SHELL_READ)
4513 ga_init2(&ga, 1, BUFLEN);
4514
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004515 if (cmd != NULL)
4516 {
4517 p = (char *)vim_strsave((char_u *)cmd);
4518 if (p != NULL)
4519 unescape_shellxquote((char_u *)p, p_sxe);
4520 else
4521 p = cmd;
4522 }
4523
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004524 /* Now, run the command.
4525 * About "Inherit handles" being TRUE: this command can be litigious,
4526 * handle inheritance was deactivated for pending temp file, but, if we
4527 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004528 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4529 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004530
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004531 if (p != cmd)
4532 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004533
4534 /* Close our unused side of the pipes */
4535 CloseHandle(g_hChildStd_IN_Rd);
4536 CloseHandle(g_hChildStd_OUT_Wr);
4537
4538 if (options & SHELL_WRITE)
4539 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004540 HANDLE thread = (HANDLE)
4541 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004542 0, /* default stack size */
4543 sub_process_writer, /* function to be executed */
4544 g_hChildStd_IN_Wr, /* parameter */
4545 0, /* creation flag, start immediately */
4546 NULL); /* we don't care about thread id */
4547 CloseHandle(thread);
4548 g_hChildStd_IN_Wr = NULL;
4549 }
4550
4551 /* Keep updating the window while waiting for the shell to finish. */
4552 for (;;)
4553 {
4554 MSG msg;
4555
Bram Moolenaar175d0702013-12-11 18:36:33 +01004556 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004557 {
4558 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004559 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004560 }
4561
4562 /* write pipe information in the window */
4563 if ((options & (SHELL_READ|SHELL_WRITE))
4564# ifdef FEAT_GUI
4565 || gui.in_use
4566# endif
4567 )
4568 {
4569 len = 0;
4570 if (!(options & SHELL_EXPAND)
4571 && ((options &
4572 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4573 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4574# ifdef FEAT_GUI
4575 || gui.in_use
4576# endif
4577 )
4578 && (ta_len > 0 || noread_cnt > 4))
4579 {
4580 if (ta_len == 0)
4581 {
4582 /* Get extra characters when we don't have any. Reset the
4583 * counter and timer. */
4584 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004585 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4586 }
4587 if (ta_len > 0 || len > 0)
4588 {
4589 /*
4590 * For pipes: Check for CTRL-C: send interrupt signal to
4591 * child. Check for CTRL-D: EOF, close pipe to child.
4592 */
4593 if (len == 1 && cmd != NULL)
4594 {
4595 if (ta_buf[ta_len] == Ctrl_C)
4596 {
4597 /* Learn what exit code is expected, for
4598 * now put 9 as SIGKILL */
4599 TerminateProcess(pi.hProcess, 9);
4600 }
4601 if (ta_buf[ta_len] == Ctrl_D)
4602 {
4603 CloseHandle(g_hChildStd_IN_Wr);
4604 g_hChildStd_IN_Wr = NULL;
4605 }
4606 }
4607
4608 /* replace K_BS by <BS> and K_DEL by <DEL> */
4609 for (i = ta_len; i < ta_len + len; ++i)
4610 {
4611 if (ta_buf[i] == CSI && len - i > 2)
4612 {
4613 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4614 if (c == K_DEL || c == K_KDEL || c == K_BS)
4615 {
4616 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4617 (size_t)(len - i - 2));
4618 if (c == K_DEL || c == K_KDEL)
4619 ta_buf[i] = DEL;
4620 else
4621 ta_buf[i] = Ctrl_H;
4622 len -= 2;
4623 }
4624 }
4625 else if (ta_buf[i] == '\r')
4626 ta_buf[i] = '\n';
4627# ifdef FEAT_MBYTE
4628 if (has_mbyte)
4629 i += (*mb_ptr2len_len)(ta_buf + i,
4630 ta_len + len - i) - 1;
4631# endif
4632 }
4633
4634 /*
4635 * For pipes: echo the typed characters. For a pty this
4636 * does not seem to work.
4637 */
4638 for (i = ta_len; i < ta_len + len; ++i)
4639 {
4640 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4641 msg_putchar(ta_buf[i]);
4642# ifdef FEAT_MBYTE
4643 else if (has_mbyte)
4644 {
4645 int l = (*mb_ptr2len)(ta_buf + i);
4646
4647 msg_outtrans_len(ta_buf + i, l);
4648 i += l - 1;
4649 }
4650# endif
4651 else
4652 msg_outtrans_len(ta_buf + i, 1);
4653 }
4654 windgoto(msg_row, msg_col);
4655 out_flush();
4656
4657 ta_len += len;
4658
4659 /*
4660 * Write the characters to the child, unless EOF has been
4661 * typed for pipes. Write one character at a time, to
4662 * avoid losing too much typeahead. When writing buffer
4663 * lines, drop the typed characters (only check for
4664 * CTRL-C).
4665 */
4666 if (options & SHELL_WRITE)
4667 ta_len = 0;
4668 else if (g_hChildStd_IN_Wr != NULL)
4669 {
4670 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4671 1, &len, NULL);
4672 // if we are typing in, we want to keep things reactive
4673 delay = 1;
4674 if (len > 0)
4675 {
4676 ta_len -= len;
4677 mch_memmove(ta_buf, ta_buf + len, ta_len);
4678 }
4679 }
4680 }
4681 }
4682 }
4683
4684 if (ta_len)
4685 ui_inchar_undo(ta_buf, ta_len);
4686
4687 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4688 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004689 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004690 break;
4691 }
4692
4693 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004694 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004695
4696 /* We start waiting for a very short time and then increase it, so
4697 * that we respond quickly when the process is quick, and don't
4698 * consume too much overhead when it's slow. */
4699 if (delay < 50)
4700 delay += 10;
4701 }
4702
4703 /* Close the pipe */
4704 CloseHandle(g_hChildStd_OUT_Rd);
4705 if (g_hChildStd_IN_Wr != NULL)
4706 CloseHandle(g_hChildStd_IN_Wr);
4707
4708 WaitForSingleObject(pi.hProcess, INFINITE);
4709
4710 /* Get the command exit code */
4711 GetExitCodeProcess(pi.hProcess, &ret);
4712
4713 if (options & SHELL_READ)
4714 {
4715 if (ga.ga_len > 0)
4716 {
4717 append_ga_line(&ga);
4718 /* remember that the NL was missing */
4719 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4720 }
4721 else
4722 curbuf->b_no_eol_lnum = 0;
4723 ga_clear(&ga);
4724 }
4725
4726 /* Close the handles to the subprocess, so that it goes away */
4727 CloseHandle(pi.hThread);
4728 CloseHandle(pi.hProcess);
4729
4730 return ret;
4731}
4732
4733 static int
4734mch_system(char *cmd, int options)
4735{
4736 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004737 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004738 return mch_system_piped(cmd, options);
4739 else
4740 return mch_system_classic(cmd, options);
4741}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742#else
4743
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004744# ifdef FEAT_MBYTE
4745 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004746mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004747{
4748 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4749 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004750 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004751 if (wcmd != NULL)
4752 {
4753 int ret = _wsystem(wcmd);
4754 vim_free(wcmd);
4755 return ret;
4756 }
4757 }
4758 return system(cmd);
4759}
4760# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004761# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004762# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763
4764#endif
4765
4766/*
4767 * Either execute a command by calling the shell or start a new shell
4768 */
4769 int
4770mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004771 char_u *cmd,
4772 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773{
4774 int x = 0;
4775 int tmode = cur_tmode;
4776#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004777 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004778# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004779 int did_set_title = FALSE;
4780
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004781 /* Change the title to reflect that we are in a subshell. */
4782 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4783 {
4784 WCHAR szShellTitle[512];
4785
4786 if (GetConsoleTitleW(szShellTitle,
4787 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4788 {
4789 if (cmd == NULL)
4790 wcscat(szShellTitle, L" :sh");
4791 else
4792 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004793 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004794
4795 if (wn != NULL)
4796 {
4797 wcscat(szShellTitle, L" - !");
4798 if ((wcslen(szShellTitle) + wcslen(wn) <
4799 sizeof(szShellTitle)/sizeof(WCHAR)))
4800 wcscat(szShellTitle, wn);
4801 SetConsoleTitleW(szShellTitle);
4802 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004803 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004804 }
4805 }
4806 }
4807 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004808 if (!did_set_title)
4809# endif
4810 /* Change the title to reflect that we are in a subshell. */
4811 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004813 if (cmd == NULL)
4814 strcat(szShellTitle, " :sh");
4815 else
4816 {
4817 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004818 if ((strlen(szShellTitle) + strlen((char *)cmd)
4819 < sizeof(szShellTitle)))
4820 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004821 }
4822 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004823 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824#endif
4825
4826 out_flush();
4827
4828#ifdef MCH_WRITE_DUMP
4829 if (fdDump)
4830 {
4831 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4832 fflush(fdDump);
4833 }
4834#endif
4835
4836 /*
4837 * Catch all deadly signals while running the external command, because a
4838 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4839 */
4840 signal(SIGINT, SIG_IGN);
4841#if defined(__GNUC__) && !defined(__MINGW32__)
4842 signal(SIGKILL, SIG_IGN);
4843#else
4844 signal(SIGBREAK, SIG_IGN);
4845#endif
4846 signal(SIGILL, SIG_IGN);
4847 signal(SIGFPE, SIG_IGN);
4848 signal(SIGSEGV, SIG_IGN);
4849 signal(SIGTERM, SIG_IGN);
4850 signal(SIGABRT, SIG_IGN);
4851
4852 if (options & SHELL_COOKED)
4853 settmode(TMODE_COOK); /* set to normal mode */
4854
4855 if (cmd == NULL)
4856 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004857 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858 }
4859 else
4860 {
4861 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004862 char_u *newcmd = NULL;
4863 char_u *cmdbase = cmd;
4864 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004865
4866 /* Skip a leading ", ( and "(. */
4867 if (*cmdbase == '"' )
4868 ++cmdbase;
4869 if (*cmdbase == '(')
4870 ++cmdbase;
4871
Bram Moolenaar1c465442017-03-12 20:10:05 +01004872 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004873 {
4874 STARTUPINFO si;
4875 PROCESS_INFORMATION pi;
4876 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004877 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004878 char_u *p;
4879
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004880 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004881 si.cb = sizeof(si);
4882 si.lpReserved = NULL;
4883 si.lpDesktop = NULL;
4884 si.lpTitle = NULL;
4885 si.dwFlags = 0;
4886 si.cbReserved2 = 0;
4887 si.lpReserved2 = NULL;
4888
4889 cmdbase = skipwhite(cmdbase + 5);
4890 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004891 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004892 {
4893 cmdbase = skipwhite(cmdbase + 4);
4894 si.dwFlags = STARTF_USESHOWWINDOW;
4895 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004896 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004897 }
4898 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004899 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004900 {
4901 cmdbase = skipwhite(cmdbase + 2);
4902 flags = CREATE_NO_WINDOW;
4903 si.dwFlags = STARTF_USESTDHANDLES;
4904 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004905 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004906 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004907 NULL, // Security att.
4908 OPEN_EXISTING, // Open flags
4909 FILE_ATTRIBUTE_NORMAL, // File att.
4910 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004911 si.hStdOutput = si.hStdInput;
4912 si.hStdError = si.hStdInput;
4913 }
4914
4915 /* Remove a trailing ", ) and )" if they have a match
4916 * at the start of the command. */
4917 if (cmdbase > cmd)
4918 {
4919 p = cmdbase + STRLEN(cmdbase);
4920 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4921 *--p = NUL;
4922 if (p > cmdbase && p[-1] == ')'
4923 && (*cmd =='(' || cmd[1] == '('))
4924 *--p = NUL;
4925 }
4926
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004927 newcmd = cmdbase;
4928 unescape_shellxquote(cmdbase, p_sxe);
4929
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004930 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004931 * If creating new console, arguments are passed to the
4932 * 'cmd.exe' as-is. If it's not, arguments are not treated
4933 * correctly for current 'cmd.exe'. So unescape characters in
4934 * shellxescape except '|' for avoiding to be treated as
4935 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004936 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004937 if (flags != CREATE_NEW_CONSOLE)
4938 {
4939 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004940 char_u *cmd_shell = mch_getenv("COMSPEC");
4941
4942 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004943 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004944
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004945 subcmd = vim_strsave_escaped_ext(cmdbase,
4946 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004947 if (subcmd != NULL)
4948 {
4949 /* make "cmd.exe /c arguments" */
4950 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004951 newcmd = lalloc(cmdlen, TRUE);
4952 if (newcmd != NULL)
4953 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004954 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004955 else
4956 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004957 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004958 }
4959 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004960
4961 /*
4962 * Now, start the command as a process, so that it doesn't
4963 * inherit our handles which causes unpleasant dangling swap
4964 * files if we exit before the spawned process
4965 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004966 if (vim_create_process((char *)newcmd, FALSE, flags,
4967 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004968 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004969 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4970 > (HINSTANCE)32)
4971 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004972 else
4973 {
4974 x = -1;
4975#ifdef FEAT_GUI_W32
4976 EMSG(_("E371: Command not found"));
4977#endif
4978 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004979
4980 if (newcmd != cmdbase)
4981 vim_free(newcmd);
4982
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004983 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004984 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004985 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004986 CloseHandle(si.hStdInput);
4987 }
4988 /* Close the handles to the subprocess, so that it goes away */
4989 CloseHandle(pi.hThread);
4990 CloseHandle(pi.hProcess);
4991 }
4992 else
4993 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004994 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004996 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004998 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4999
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005000 newcmd = lalloc(cmdlen, TRUE);
5001 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002 {
5003#if defined(FEAT_GUI_W32)
5004 if (need_vimrun_warning)
5005 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005006 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5007 "External commands will not pause after completion.\n"
5008 "See :help win32-vimrun for more information.");
5009 char *title = _("Vim Warning");
5010# ifdef FEAT_MBYTE
5011 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5012 {
5013 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5014 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5015
5016 if (wmsg != NULL && wtitle != NULL)
5017 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5018 vim_free(wmsg);
5019 vim_free(wtitle);
5020 }
5021 else
5022# endif
5023 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005024 need_vimrun_warning = FALSE;
5025 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005026 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005027 /* Use vimrun to execute the command. It opens a console
5028 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005029 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030 vimrun_path,
5031 (msg_silent != 0 || (options & SHELL_DOOUT))
5032 ? "-s " : "",
5033 p_sh, p_shcf, cmd);
5034 else
5035#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005036 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005037 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005038 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005039 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005041 }
5042 }
5043
5044 if (tmode == TMODE_RAW)
5045 settmode(TMODE_RAW); /* set to raw mode */
5046
5047 /* Print the return value, unless "vimrun" was used. */
5048 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5049#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005050 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005051#endif
5052 )
5053 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005054 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005055 msg_putchar('\n');
5056 }
5057#ifdef FEAT_TITLE
5058 resettitle();
5059#endif
5060
5061 signal(SIGINT, SIG_DFL);
5062#if defined(__GNUC__) && !defined(__MINGW32__)
5063 signal(SIGKILL, SIG_DFL);
5064#else
5065 signal(SIGBREAK, SIG_DFL);
5066#endif
5067 signal(SIGILL, SIG_DFL);
5068 signal(SIGFPE, SIG_DFL);
5069 signal(SIGSEGV, SIG_DFL);
5070 signal(SIGTERM, SIG_DFL);
5071 signal(SIGABRT, SIG_DFL);
5072
5073 return x;
5074}
5075
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005076#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005077 static HANDLE
5078job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005079 char_u *fname,
5080 DWORD dwDesiredAccess,
5081 DWORD dwShareMode,
5082 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5083 DWORD dwCreationDisposition,
5084 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005085{
5086 HANDLE h;
5087# ifdef FEAT_MBYTE
5088 WCHAR *wn = NULL;
5089 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5090 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005091 wn = enc_to_utf16(fname, NULL);
5092 if (wn != NULL)
5093 {
5094 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5095 lpSecurityAttributes, dwCreationDisposition,
5096 dwFlagsAndAttributes, NULL);
5097 vim_free(wn);
5098 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005099 }
5100 if (wn == NULL)
5101# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005102 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5103 lpSecurityAttributes, dwCreationDisposition,
5104 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005105 return h;
5106}
5107
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005108/*
5109 * Turn the dictionary "env" into a NUL separated list that can be used as the
5110 * environment argument of vim_create_process().
5111 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005112 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005113win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005114{
5115 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005116 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005117 LPVOID base = GetEnvironmentStringsW();
5118
5119 /* for last \0 */
5120 if (ga_grow(gap, 1) == FAIL)
5121 return;
5122
5123 if (base)
5124 {
5125 WCHAR *p = (WCHAR*) base;
5126
5127 /* for last \0 */
5128 if (ga_grow(gap, 1) == FAIL)
5129 return;
5130
5131 while (*p != 0 || *(p + 1) != 0)
5132 {
5133 if (ga_grow(gap, 1) == OK)
5134 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5135 p++;
5136 }
5137 FreeEnvironmentStrings(base);
5138 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5139 }
5140
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005141 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005142 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005143 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005144 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005145 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005146 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005147 typval_T *item = &dict_lookup(hi)->di_tv;
5148 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5149 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5150 --todo;
5151 if (wkey != NULL && wval != NULL)
5152 {
5153 size_t n;
5154 size_t lkey = wcslen(wkey);
5155 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005156
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005157 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5158 continue;
5159 for (n = 0; n < lkey; n++)
5160 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5161 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5162 for (n = 0; n < lval; n++)
5163 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5164 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5165 }
5166 if (wkey != NULL) vim_free(wkey);
5167 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005168 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005169 }
5170 }
5171
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005172# ifdef FEAT_CLIENTSERVER
5173 if (is_terminal)
5174 {
5175 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
5176 size_t lval = STRLEN(servername);
5177 size_t n;
5178
5179 if (ga_grow(gap, (int)(14 + lval + 2)) == OK)
5180 {
5181 for (n = 0; n < 15; n++)
5182 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5183 (WCHAR)"VIM_SERVERNAME="[n];
5184 for (n = 0; n < lval; n++)
5185 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5186 (WCHAR)servername[n];
5187 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5188 }
5189 }
5190# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005191}
5192
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005193 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005194mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005195{
5196 STARTUPINFO si;
5197 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005198 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005199 SECURITY_ATTRIBUTES saAttr;
5200 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005201 HANDLE ifd[2];
5202 HANDLE ofd[2];
5203 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005204 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005205
5206 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5207 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5208 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5209 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5210 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5211 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5212 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5213
5214 if (use_out_for_err && use_null_for_out)
5215 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005216
5217 ifd[0] = INVALID_HANDLE_VALUE;
5218 ifd[1] = INVALID_HANDLE_VALUE;
5219 ofd[0] = INVALID_HANDLE_VALUE;
5220 ofd[1] = INVALID_HANDLE_VALUE;
5221 efd[0] = INVALID_HANDLE_VALUE;
5222 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005223 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005224
Bram Moolenaar14207f42016-10-27 21:13:10 +02005225 jo = CreateJobObject(NULL, NULL);
5226 if (jo == NULL)
5227 {
5228 job->jv_status = JOB_FAILED;
5229 goto failed;
5230 }
5231
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005232 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005233 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005234
Bram Moolenaar76467df2016-02-12 19:30:26 +01005235 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005236 ZeroMemory(&si, sizeof(si));
5237 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005238 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005239 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005240
Bram Moolenaard8070362016-02-15 21:56:54 +01005241 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5242 saAttr.bInheritHandle = TRUE;
5243 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005244
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005245 if (use_file_for_in)
5246 {
5247 char_u *fname = options->jo_io_name[PART_IN];
5248
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005249 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5250 FILE_SHARE_READ | FILE_SHARE_WRITE,
5251 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5252 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005253 {
5254 EMSG2(_(e_notopen), fname);
5255 goto failed;
5256 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005257 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005258 else if (!use_null_for_in &&
5259 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005260 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005261 goto failed;
5262
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005263 if (use_file_for_out)
5264 {
5265 char_u *fname = options->jo_io_name[PART_OUT];
5266
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005267 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5268 FILE_SHARE_READ | FILE_SHARE_WRITE,
5269 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5270 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005271 {
5272 EMSG2(_(e_notopen), fname);
5273 goto failed;
5274 }
5275 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005276 else if (!use_null_for_out &&
5277 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005278 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005279 goto failed;
5280
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005281 if (use_file_for_err)
5282 {
5283 char_u *fname = options->jo_io_name[PART_ERR];
5284
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005285 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5286 FILE_SHARE_READ | FILE_SHARE_WRITE,
5287 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5288 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005289 {
5290 EMSG2(_(e_notopen), fname);
5291 goto failed;
5292 }
5293 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005294 else if (!use_out_for_err && !use_null_for_err &&
5295 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005296 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005297 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005298
Bram Moolenaard8070362016-02-15 21:56:54 +01005299 si.dwFlags |= STARTF_USESTDHANDLES;
5300 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005301 si.hStdOutput = ofd[1];
5302 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5303
5304 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5305 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005306 if (options->jo_set & JO_CHANNEL)
5307 {
5308 channel = options->jo_channel;
5309 if (channel != NULL)
5310 ++channel->ch_refcount;
5311 }
5312 else
5313 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005314 if (channel == NULL)
5315 goto failed;
5316 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005317
5318 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005319 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005320 CREATE_DEFAULT_ERROR_MODE |
5321 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005322 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005323 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005324 &si, &pi,
5325 ga.ga_data,
5326 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005327 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005328 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005329 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005330 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005331 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005332
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005333 ga_clear(&ga);
5334
Bram Moolenaar14207f42016-10-27 21:13:10 +02005335 if (!AssignProcessToJobObject(jo, pi.hProcess))
5336 {
5337 /* if failing, switch the way to terminate
5338 * process with TerminateProcess. */
5339 CloseHandle(jo);
5340 jo = NULL;
5341 }
5342 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005343 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005344 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005345 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005346 job->jv_status = JOB_STARTED;
5347
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005348 CloseHandle(ifd[0]);
5349 CloseHandle(ofd[1]);
5350 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005351 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005352
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005353 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005354 if (channel != NULL)
5355 {
5356 channel_set_pipes(channel,
5357 use_file_for_in || use_null_for_in
5358 ? INVALID_FD : (sock_T)ifd[1],
5359 use_file_for_out || use_null_for_out
5360 ? INVALID_FD : (sock_T)ofd[0],
5361 use_out_for_err || use_file_for_err || use_null_for_err
5362 ? INVALID_FD : (sock_T)efd[0]);
5363 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005364 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005365 return;
5366
5367failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005368 CloseHandle(ifd[0]);
5369 CloseHandle(ofd[0]);
5370 CloseHandle(efd[0]);
5371 CloseHandle(ifd[1]);
5372 CloseHandle(ofd[1]);
5373 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005374 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005375 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005376}
5377
5378 char *
5379mch_job_status(job_T *job)
5380{
5381 DWORD dwExitCode = 0;
5382
Bram Moolenaar76467df2016-02-12 19:30:26 +01005383 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5384 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005385 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005386 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005387 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005388 {
5389 ch_log(job->jv_channel, "Job ended");
5390 job->jv_status = JOB_ENDED;
5391 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005392 return "dead";
5393 }
5394 return "run";
5395}
5396
Bram Moolenaar97792de2016-10-15 18:36:49 +02005397 job_T *
5398mch_detect_ended_job(job_T *job_list)
5399{
5400 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5401 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5402 job_T *job = job_list;
5403
5404 while (job != NULL)
5405 {
5406 DWORD n;
5407 DWORD result;
5408
5409 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5410 && job != NULL; job = job->jv_next)
5411 {
5412 if (job->jv_status == JOB_STARTED)
5413 {
5414 jobHandles[n] = job->jv_proc_info.hProcess;
5415 jobArray[n] = job;
5416 ++n;
5417 }
5418 }
5419 if (n == 0)
5420 continue;
5421 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5422 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5423 {
5424 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5425
5426 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5427 return wait_job;
5428 }
5429 }
5430 return NULL;
5431}
5432
Bram Moolenaarfb630902016-10-29 14:55:00 +02005433 static BOOL
5434terminate_all(HANDLE process, int code)
5435{
5436 PROCESSENTRY32 pe;
5437 HANDLE h = INVALID_HANDLE_VALUE;
5438 DWORD pid = GetProcessId(process);
5439
5440 if (pid != 0)
5441 {
5442 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5443 if (h != INVALID_HANDLE_VALUE)
5444 {
5445 pe.dwSize = sizeof(PROCESSENTRY32);
5446 if (!Process32First(h, &pe))
5447 goto theend;
5448
5449 do
5450 {
5451 if (pe.th32ParentProcessID == pid)
5452 {
5453 HANDLE ph = OpenProcess(
5454 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5455 if (ph != NULL)
5456 {
5457 terminate_all(ph, code);
5458 CloseHandle(ph);
5459 }
5460 }
5461 } while (Process32Next(h, &pe));
5462
5463 CloseHandle(h);
5464 }
5465 }
5466
5467theend:
5468 return TerminateProcess(process, code);
5469}
5470
5471/*
5472 * Send a (deadly) signal to "job".
5473 * Return FAIL if it didn't work.
5474 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005475 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005476mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005477{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005478 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005479
Bram Moolenaar923d9262016-02-25 20:56:01 +01005480 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005481 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005482 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005483 if (job->jv_job_object != NULL)
5484 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005485 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005486 }
5487
5488 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5489 return FAIL;
5490 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005491 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5492 job->jv_proc_info.dwProcessId)
5493 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005494 FreeConsole();
5495 return ret;
5496}
5497
5498/*
5499 * Clear the data related to "job".
5500 */
5501 void
5502mch_clear_job(job_T *job)
5503{
5504 if (job->jv_status != JOB_FAILED)
5505 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005506 if (job->jv_job_object != NULL)
5507 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005508 CloseHandle(job->jv_proc_info.hProcess);
5509 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005510}
5511#endif
5512
Bram Moolenaar071d4272004-06-13 20:20:40 +00005513
5514#ifndef FEAT_GUI_W32
5515
5516/*
5517 * Start termcap mode
5518 */
5519 static void
5520termcap_mode_start(void)
5521{
5522 DWORD cmodein;
5523
5524 if (g_fTermcapMode)
5525 return;
5526
5527 SaveConsoleBuffer(&g_cbNonTermcap);
5528
5529 if (g_cbTermcap.IsValid)
5530 {
5531 /*
5532 * We've been in termcap mode before. Restore certain screen
5533 * characteristics, including the buffer size and the window
5534 * size. Since we will be redrawing the screen, we don't need
5535 * to restore the actual contents of the buffer.
5536 */
5537 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005538 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005539 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5540 Rows = g_cbTermcap.Info.dwSize.Y;
5541 Columns = g_cbTermcap.Info.dwSize.X;
5542 }
5543 else
5544 {
5545 /*
5546 * This is our first time entering termcap mode. Clear the console
5547 * screen buffer, and resize the buffer to match the current window
5548 * size. We will use this as the size of our editing environment.
5549 */
5550 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005551 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005552 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5553 }
5554
5555#ifdef FEAT_TITLE
5556 resettitle();
5557#endif
5558
5559 GetConsoleMode(g_hConIn, &cmodein);
5560#ifdef FEAT_MOUSE
5561 if (g_fMouseActive)
5562 cmodein |= ENABLE_MOUSE_INPUT;
5563 else
5564 cmodein &= ~ENABLE_MOUSE_INPUT;
5565#endif
5566 cmodein |= ENABLE_WINDOW_INPUT;
5567 SetConsoleMode(g_hConIn, cmodein);
5568
5569 redraw_later_clear();
5570 g_fTermcapMode = TRUE;
5571}
5572
5573
5574/*
5575 * End termcap mode
5576 */
5577 static void
5578termcap_mode_end(void)
5579{
5580 DWORD cmodein;
5581 ConsoleBuffer *cb;
5582 COORD coord;
5583 DWORD dwDummy;
5584
5585 if (!g_fTermcapMode)
5586 return;
5587
5588 SaveConsoleBuffer(&g_cbTermcap);
5589
5590 GetConsoleMode(g_hConIn, &cmodein);
5591 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5592 SetConsoleMode(g_hConIn, cmodein);
5593
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005594#ifdef FEAT_RESTORE_ORIG_SCREEN
5595 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5596#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005597 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005598#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005599 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005600 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601 SetConsoleCursorInfo(g_hConOut, &g_cci);
5602
5603 if (p_rs || exiting)
5604 {
5605 /*
5606 * Clear anything that happens to be on the current line.
5607 */
5608 coord.X = 0;
5609 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5610 FillConsoleOutputCharacter(g_hConOut, ' ',
5611 cb->Info.dwSize.X, coord, &dwDummy);
5612 /*
5613 * The following is just for aesthetics. If we are exiting without
5614 * restoring the screen, then we want to have a prompt string
5615 * appear at the bottom line. However, the command interpreter
5616 * seems to always advance the cursor one line before displaying
5617 * the prompt string, which causes the screen to scroll. To
5618 * counter this, move the cursor up one line before exiting.
5619 */
5620 if (exiting && !p_rs)
5621 coord.Y--;
5622 /*
5623 * Position the cursor at the leftmost column of the desired row.
5624 */
5625 SetConsoleCursorPosition(g_hConOut, coord);
5626 }
5627
5628 g_fTermcapMode = FALSE;
5629}
5630#endif /* FEAT_GUI_W32 */
5631
5632
5633#ifdef FEAT_GUI_W32
5634 void
5635mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005636 char_u *s UNUSED,
5637 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638{
5639 /* never used */
5640}
5641
5642#else
5643
5644/*
5645 * clear `n' chars, starting from `coord'
5646 */
5647 static void
5648clear_chars(
5649 COORD coord,
5650 DWORD n)
5651{
5652 DWORD dwDummy;
5653
5654 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005655
5656 if (!USE_VTP)
5657 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5658 else
5659 FillConsoleOutputAttribute(g_hConOut, 0, n, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660}
5661
5662
5663/*
5664 * Clear the screen
5665 */
5666 static void
5667clear_screen(void)
5668{
5669 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005670
5671 if (!USE_VTP)
5672 clear_chars(g_coord, Rows * Columns);
5673 else
5674 {
5675 set_console_color_rgb();
5676 gotoxy(1, 1);
5677 vtp_printf("\033[2J");
5678 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005679}
5680
5681
5682/*
5683 * Clear to end of display
5684 */
5685 static void
5686clear_to_end_of_display(void)
5687{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005688 COORD save = g_coord;
5689
5690 if (!USE_VTP)
5691 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005693 else
5694 {
5695 set_console_color_rgb();
5696 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5697 vtp_printf("\033[0J");
5698
5699 gotoxy(save.X + 1, save.Y + 1);
5700 g_coord = save;
5701 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702}
5703
5704
5705/*
5706 * Clear to end of line
5707 */
5708 static void
5709clear_to_end_of_line(void)
5710{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005711 COORD save = g_coord;
5712
5713 if (!USE_VTP)
5714 clear_chars(g_coord, Columns - g_coord.X);
5715 else
5716 {
5717 set_console_color_rgb();
5718 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5719 vtp_printf("\033[0K");
5720
5721 gotoxy(save.X + 1, save.Y + 1);
5722 g_coord = save;
5723 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724}
5725
5726
5727/*
5728 * Scroll the scroll region up by `cLines' lines
5729 */
5730 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005731scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005732{
5733 COORD oldcoord = g_coord;
5734
5735 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5736 delete_lines(cLines);
5737
5738 g_coord = oldcoord;
5739}
5740
5741
5742/*
5743 * Set the scroll region
5744 */
5745 static void
5746set_scroll_region(
5747 unsigned left,
5748 unsigned top,
5749 unsigned right,
5750 unsigned bottom)
5751{
5752 if (left >= right
5753 || top >= bottom
5754 || right > (unsigned) Columns - 1
5755 || bottom > (unsigned) Rows - 1)
5756 return;
5757
5758 g_srScrollRegion.Left = left;
5759 g_srScrollRegion.Top = top;
5760 g_srScrollRegion.Right = right;
5761 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005762
5763 if (USE_VTP)
5764 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005765}
5766
5767
5768/*
5769 * Insert `cLines' lines at the current cursor position
5770 */
5771 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005772insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773{
5774 SMALL_RECT source;
5775 COORD dest;
5776 CHAR_INFO fill;
5777
5778 dest.X = 0;
5779 dest.Y = g_coord.Y + cLines;
5780
5781 source.Left = 0;
5782 source.Top = g_coord.Y;
5783 source.Right = g_srScrollRegion.Right;
5784 source.Bottom = g_srScrollRegion.Bottom - cLines;
5785
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005786 if (!USE_VTP)
5787 {
5788 fill.Char.AsciiChar = ' ';
5789 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005791 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5792 }
5793 else
5794 {
5795 set_console_color_rgb();
5796
5797 gotoxy(1, source.Top + 1);
5798 vtp_printf("\033[%dT", cLines);
5799 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005800
5801 /* Here we have to deal with a win32 console flake: If the scroll
5802 * region looks like abc and we scroll c to a and fill with d we get
5803 * cbd... if we scroll block c one line at a time to a, we get cdd...
5804 * vim expects cdd consistently... So we have to deal with that
5805 * here... (this also occurs scrolling the same way in the other
5806 * direction). */
5807
5808 if (source.Bottom < dest.Y)
5809 {
5810 COORD coord;
5811
5812 coord.X = 0;
5813 coord.Y = source.Bottom;
5814 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5815 }
5816}
5817
5818
5819/*
5820 * Delete `cLines' lines at the current cursor position
5821 */
5822 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005823delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005824{
5825 SMALL_RECT source;
5826 COORD dest;
5827 CHAR_INFO fill;
5828 int nb;
5829
5830 dest.X = 0;
5831 dest.Y = g_coord.Y;
5832
5833 source.Left = 0;
5834 source.Top = g_coord.Y + cLines;
5835 source.Right = g_srScrollRegion.Right;
5836 source.Bottom = g_srScrollRegion.Bottom;
5837
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005838 if (!USE_VTP)
5839 {
5840 fill.Char.AsciiChar = ' ';
5841 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005843 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5844 }
5845 else
5846 {
5847 set_console_color_rgb();
5848
5849 gotoxy(1, source.Top + 1);
5850 vtp_printf("\033[%dS", cLines);
5851 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005852
5853 /* Here we have to deal with a win32 console flake: If the scroll
5854 * region looks like abc and we scroll c to a and fill with d we get
5855 * cbd... if we scroll block c one line at a time to a, we get cdd...
5856 * vim expects cdd consistently... So we have to deal with that
5857 * here... (this also occurs scrolling the same way in the other
5858 * direction). */
5859
5860 nb = dest.Y + (source.Bottom - source.Top) + 1;
5861
5862 if (nb < source.Top)
5863 {
5864 COORD coord;
5865
5866 coord.X = 0;
5867 coord.Y = nb;
5868 clear_chars(coord, Columns * (source.Top - nb));
5869 }
5870}
5871
5872
5873/*
5874 * Set the cursor position
5875 */
5876 static void
5877gotoxy(
5878 unsigned x,
5879 unsigned y)
5880{
5881 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5882 return;
5883
5884 /* external cursor coords are 1-based; internal are 0-based */
5885 g_coord.X = x - 1;
5886 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005887
5888 if (!USE_VTP)
5889 SetConsoleCursorPosition(g_hConOut, g_coord);
5890 else
5891 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005892}
5893
5894
5895/*
5896 * Set the current text attribute = (foreground | background)
5897 * See ../doc/os_win32.txt for the numbers.
5898 */
5899 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005900textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005901{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005902 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903
5904 SetConsoleTextAttribute(g_hConOut, wAttr);
5905}
5906
5907
5908 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005909textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005911 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005913 if (!USE_VTP)
5914 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5915 else
5916 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917}
5918
5919
5920 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005921textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005922{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005923 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005925 if (!USE_VTP)
5926 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5927 else
5928 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929}
5930
5931
5932/*
5933 * restore the default text attribute (whatever we started with)
5934 */
5935 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005936normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005938 if (!USE_VTP)
5939 textattr(g_attrDefault);
5940 else
5941 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942}
5943
5944
5945static WORD g_attrPreStandout = 0;
5946
5947/*
5948 * Make the text standout, by brightening it
5949 */
5950 static void
5951standout(void)
5952{
5953 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005954
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5956}
5957
5958
5959/*
5960 * Turn off standout mode
5961 */
5962 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005963standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005964{
5965 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005966 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005967
5968 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969}
5970
5971
5972/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005973 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974 */
5975 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005976mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005977{
5978 char_u *p;
5979 int n;
5980
5981 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5982 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005983 if (
5984#ifdef FEAT_TERMGUICOLORS
5985 !p_tgc &&
5986#endif
5987 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005988 {
5989 p = T_ME + 2;
5990 n = getdigits(&p);
5991 if (*p == 'm' && n > 0)
5992 {
5993 cterm_normal_fg_color = (n & 0xf) + 1;
5994 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5995 }
5996 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005997#ifdef FEAT_TERMGUICOLORS
5998 cterm_normal_fg_gui_color = INVALCOLOR;
5999 cterm_normal_bg_gui_color = INVALCOLOR;
6000#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001}
6002
6003
6004/*
6005 * visual bell: flash the screen
6006 */
6007 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006008visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009{
6010 COORD coordOrigin = {0, 0};
6011 WORD attrFlash = ~g_attrCurrent & 0xff;
6012
6013 DWORD dwDummy;
6014 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6015
6016 if (oldattrs == NULL)
6017 return;
6018 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6019 coordOrigin, &dwDummy);
6020 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6021 coordOrigin, &dwDummy);
6022
6023 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006024 if (!USE_VTP)
6025 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026 coordOrigin, &dwDummy);
6027 vim_free(oldattrs);
6028}
6029
6030
6031/*
6032 * Make the cursor visible or invisible
6033 */
6034 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006035cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006036{
6037 s_cursor_visible = fVisible;
6038#ifdef MCH_CURSOR_SHAPE
6039 mch_update_cursor();
6040#endif
6041}
6042
6043
6044/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006045 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006046 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006047 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006048 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006050 char_u *pchBuf,
6051 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052{
6053 COORD coord = g_coord;
6054 DWORD written;
6055
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006056#ifdef FEAT_MBYTE
6057 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6058 {
6059 static WCHAR *unicodebuf = NULL;
6060 static int unibuflen = 0;
6061 int length;
6062 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006063
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006064 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6065 if (unicodebuf == NULL || length > unibuflen)
6066 {
6067 vim_free(unicodebuf);
6068 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6069 unibuflen = length;
6070 }
6071 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6072 unicodebuf, unibuflen);
6073
6074 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006075
6076 if (!USE_VTP)
6077 {
6078 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6079 coord, &written);
6080 /* When writing fails or didn't write a single character, pretend one
6081 * character was written, otherwise we get stuck. */
6082 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6083 coord, &cchwritten) == 0
6084 || cchwritten == 0)
6085 cchwritten = 1;
6086 }
6087 else
6088 {
6089 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6090 NULL) == 0 || cchwritten == 0)
6091 cchwritten = 1;
6092 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006093
6094 if (cchwritten == length)
6095 {
6096 written = cbToWrite;
6097 g_coord.X += (SHORT)cells;
6098 }
6099 else
6100 {
6101 char_u *p = pchBuf;
6102 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006103 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006104 written = p - pchBuf;
6105 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6106 }
6107 }
6108 else
6109#endif
6110 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006111 if (!USE_VTP)
6112 {
6113 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6114 coord, &written);
6115 /* When writing fails or didn't write a single character, pretend one
6116 * character was written, otherwise we get stuck. */
6117 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6118 coord, &written) == 0
6119 || written == 0)
6120 written = 1;
6121 }
6122 else
6123 {
6124 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6125 NULL) == 0 || written == 0)
6126 written = 1;
6127 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006128
6129 g_coord.X += (SHORT) written;
6130 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131
6132 while (g_coord.X > g_srScrollRegion.Right)
6133 {
6134 g_coord.X -= (SHORT) Columns;
6135 if (g_coord.Y < g_srScrollRegion.Bottom)
6136 g_coord.Y++;
6137 }
6138
6139 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6140
6141 return written;
6142}
6143
6144
6145/*
6146 * mch_write(): write the output buffer to the screen, translating ESC
6147 * sequences into calls to console output routines.
6148 */
6149 void
6150mch_write(
6151 char_u *s,
6152 int len)
6153{
6154 s[len] = NUL;
6155
6156 if (!term_console)
6157 {
6158 write(1, s, (unsigned)len);
6159 return;
6160 }
6161
6162 /* translate ESC | sequences into faked bios calls */
6163 while (len--)
6164 {
6165 /* optimization: use one single write_chars for runs of text,
6166 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006167 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168
6169 if (p_wd)
6170 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006171 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 if (prefix != 0)
6173 prefix = 1;
6174 }
6175
6176 if (prefix != 0)
6177 {
6178 DWORD nWritten;
6179
6180 nWritten = write_chars(s, prefix);
6181#ifdef MCH_WRITE_DUMP
6182 if (fdDump)
6183 {
6184 fputc('>', fdDump);
6185 fwrite(s, sizeof(char_u), nWritten, fdDump);
6186 fputs("<\n", fdDump);
6187 }
6188#endif
6189 len -= (nWritten - 1);
6190 s += nWritten;
6191 }
6192 else if (s[0] == '\n')
6193 {
6194 /* \n, newline: go to the beginning of the next line or scroll */
6195 if (g_coord.Y == g_srScrollRegion.Bottom)
6196 {
6197 scroll(1);
6198 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6199 }
6200 else
6201 {
6202 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6203 }
6204#ifdef MCH_WRITE_DUMP
6205 if (fdDump)
6206 fputs("\\n\n", fdDump);
6207#endif
6208 s++;
6209 }
6210 else if (s[0] == '\r')
6211 {
6212 /* \r, carriage return: go to beginning of line */
6213 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6214#ifdef MCH_WRITE_DUMP
6215 if (fdDump)
6216 fputs("\\r\n", fdDump);
6217#endif
6218 s++;
6219 }
6220 else if (s[0] == '\b')
6221 {
6222 /* \b, backspace: move cursor one position left */
6223 if (g_coord.X > g_srScrollRegion.Left)
6224 g_coord.X--;
6225 else if (g_coord.Y > g_srScrollRegion.Top)
6226 {
6227 g_coord.X = g_srScrollRegion.Right;
6228 g_coord.Y--;
6229 }
6230 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6231#ifdef MCH_WRITE_DUMP
6232 if (fdDump)
6233 fputs("\\b\n", fdDump);
6234#endif
6235 s++;
6236 }
6237 else if (s[0] == '\a')
6238 {
6239 /* \a, bell */
6240 MessageBeep(0xFFFFFFFF);
6241#ifdef MCH_WRITE_DUMP
6242 if (fdDump)
6243 fputs("\\a\n", fdDump);
6244#endif
6245 s++;
6246 }
6247 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6248 {
6249#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006250 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006252 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006253 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254
6255 switch (s[2])
6256 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 case '0': case '1': case '2': case '3': case '4':
6258 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006259 p = s + 1;
6260 do
6261 {
6262 ++p;
6263 args[argc] = getdigits(&p);
6264 argc += (argc < 15) ? 1 : 0;
6265 if (p > s + len)
6266 break;
6267 } while (*p == ';');
6268
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269 if (p > s + len)
6270 break;
6271
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006272 arg1 = args[0];
6273 arg2 = args[1];
6274 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006276 if (argc == 1 && args[0] == 0)
6277 normvideo();
6278 else if (argc == 1)
6279 {
6280 if (USE_VTP)
6281 textcolor((WORD) arg1);
6282 else
6283 textattr((WORD) arg1);
6284 }
6285 else if (USE_VTP)
6286 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006288 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006290 gotoxy(arg2, arg1);
6291 }
6292 else if (argc == 2 && *p == 'r')
6293 {
6294 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6295 }
6296 else if (argc == 1 && *p == 'A')
6297 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006298 gotoxy(g_coord.X + 1,
6299 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6300 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006301 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 {
6303 textbackground((WORD) arg1);
6304 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006305 else if (argc == 1 && *p == 'C')
6306 {
6307 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6308 g_coord.Y + 1);
6309 }
6310 else if (argc == 1 && *p == 'f')
6311 {
6312 textcolor((WORD) arg1);
6313 }
6314 else if (argc == 1 && *p == 'H')
6315 {
6316 gotoxy(1, arg1);
6317 }
6318 else if (argc == 1 && *p == 'L')
6319 {
6320 insert_lines(arg1);
6321 }
6322 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323 {
6324 delete_lines(arg1);
6325 }
6326
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006327 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328 s = p + 1;
6329 break;
6330
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 gotoxy(g_coord.X + 1,
6333 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6334 goto got3;
6335
6336 case 'B':
6337 visual_bell();
6338 goto got3;
6339
6340 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6342 g_coord.Y + 1);
6343 goto got3;
6344
6345 case 'E':
6346 termcap_mode_end();
6347 goto got3;
6348
6349 case 'F':
6350 standout();
6351 goto got3;
6352
6353 case 'f':
6354 standend();
6355 goto got3;
6356
6357 case 'H':
6358 gotoxy(1, 1);
6359 goto got3;
6360
6361 case 'j':
6362 clear_to_end_of_display();
6363 goto got3;
6364
6365 case 'J':
6366 clear_screen();
6367 goto got3;
6368
6369 case 'K':
6370 clear_to_end_of_line();
6371 goto got3;
6372
6373 case 'L':
6374 insert_lines(1);
6375 goto got3;
6376
6377 case 'M':
6378 delete_lines(1);
6379 goto got3;
6380
6381 case 'S':
6382 termcap_mode_start();
6383 goto got3;
6384
6385 case 'V':
6386 cursor_visible(TRUE);
6387 goto got3;
6388
6389 case 'v':
6390 cursor_visible(FALSE);
6391 goto got3;
6392
6393 got3:
6394 s += 3;
6395 len -= 2;
6396 }
6397
6398#ifdef MCH_WRITE_DUMP
6399 if (fdDump)
6400 {
6401 fputs("ESC | ", fdDump);
6402 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6403 fputc('\n', fdDump);
6404 }
6405#endif
6406 }
6407 else
6408 {
6409 /* Write a single character */
6410 DWORD nWritten;
6411
6412 nWritten = write_chars(s, 1);
6413#ifdef MCH_WRITE_DUMP
6414 if (fdDump)
6415 {
6416 fputc('>', fdDump);
6417 fwrite(s, sizeof(char_u), nWritten, fdDump);
6418 fputs("<\n", fdDump);
6419 }
6420#endif
6421
6422 len -= (nWritten - 1);
6423 s += nWritten;
6424 }
6425 }
6426
6427#ifdef MCH_WRITE_DUMP
6428 if (fdDump)
6429 fflush(fdDump);
6430#endif
6431}
6432
6433#endif /* FEAT_GUI_W32 */
6434
6435
6436/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006437 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006438 */
6439 void
6440mch_delay(
6441 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006442 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006443{
6444#ifdef FEAT_GUI_W32
6445 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006446#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006447 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006448# ifdef FEAT_MZSCHEME
6449 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6450 {
6451 int towait = p_mzq;
6452
6453 /* if msec is large enough, wait by portions in p_mzq */
6454 while (msec > 0)
6455 {
6456 mzvim_check_threads();
6457 if (msec < towait)
6458 towait = msec;
6459 Sleep(towait);
6460 msec -= towait;
6461 }
6462 }
6463 else
6464# endif
6465 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006467 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468#endif
6469}
6470
6471
6472/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006473 * This version of remove is not scared by a readonly (backup) file.
6474 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475 * Return 0 for success, -1 for failure.
6476 */
6477 int
6478mch_remove(char_u *name)
6479{
6480#ifdef FEAT_MBYTE
6481 WCHAR *wn = NULL;
6482 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006483#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484
Bram Moolenaar203258c2016-01-17 22:15:16 +01006485 /*
6486 * On Windows, deleting a directory's symbolic link is done by
6487 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6488 */
6489 if (mch_isdir(name) && mch_is_symbolic_link(name))
6490 return mch_rmdir(name);
6491
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006492 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6493
6494#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006495 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6496 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006497 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 if (wn != NULL)
6499 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006500 n = DeleteFileW(wn) ? 0 : -1;
6501 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006502 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 }
6504 }
6505#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006506 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507}
6508
6509
6510/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006511 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512 */
6513 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006514mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515{
6516#ifndef FEAT_GUI_W32 /* never used */
6517 if (g_fCtrlCPressed || g_fCBrkPressed)
6518 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006519 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006520 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6521 got_int = TRUE;
6522 }
6523#endif
6524}
6525
Bram Moolenaaree273972016-01-02 21:11:51 +01006526/* physical RAM to leave for the OS */
6527#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006528
6529/*
6530 * How much main memory in KiB that can be used by VIM.
6531 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006532 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006533mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006534{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006535 MEMORYSTATUSEX ms;
6536
Bram Moolenaaree273972016-01-02 21:11:51 +01006537 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006538 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6539 * what fits in 32 bits. But it's not always available. */
6540 ms.dwLength = sizeof(MEMORYSTATUSEX);
6541 GlobalMemoryStatusEx(&ms);
6542 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006543 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006544 /* Process address space fits in physical RAM, use all of it. */
6545 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006546 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006547 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006548 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006549 /* Catch old NT box or perverse hardware setup. */
6550 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006551 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006552 /* Use physical RAM less reserve for OS + data. */
6553 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006554}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556#ifdef FEAT_MBYTE
6557/*
6558 * Same code as below, but with wide functions and no comments.
6559 * Return 0 for success, non-zero for failure.
6560 */
6561 int
6562mch_wrename(WCHAR *wold, WCHAR *wnew)
6563{
6564 WCHAR *p;
6565 int i;
6566 WCHAR szTempFile[_MAX_PATH + 1];
6567 WCHAR szNewPath[_MAX_PATH + 1];
6568 HANDLE hf;
6569
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006570 p = wold;
6571 for (i = 0; wold[i] != NUL; ++i)
6572 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6573 && wold[i + 1] != 0)
6574 p = wold + i + 1;
6575 if ((int)(wold + i - p) < 8 || p[6] != '~')
6576 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577
6578 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6579 return -1;
6580 *p = NUL;
6581
6582 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6583 return -2;
6584
6585 if (!DeleteFileW(szTempFile))
6586 return -3;
6587
6588 if (!MoveFileW(wold, szTempFile))
6589 return -4;
6590
6591 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6592 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6593 return -5;
6594 if (!CloseHandle(hf))
6595 return -6;
6596
6597 if (!MoveFileW(szTempFile, wnew))
6598 {
6599 (void)MoveFileW(szTempFile, wold);
6600 return -7;
6601 }
6602
6603 DeleteFileW(szTempFile);
6604
6605 if (!DeleteFileW(wold))
6606 return -8;
6607
6608 return 0;
6609}
6610#endif
6611
6612
6613/*
6614 * mch_rename() works around a bug in rename (aka MoveFile) in
6615 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6616 * file whose short file name is "FOO.BAR" (its long file name will
6617 * be correct: "foo.bar~"). Because a file can be accessed by
6618 * either its SFN or its LFN, "foo.bar" has effectively been
6619 * renamed to "foo.bar", which is not at all what was wanted. This
6620 * seems to happen only when renaming files with three-character
6621 * extensions by appending a suffix that does not include ".".
6622 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6623 *
6624 * There is another problem, which isn't really a bug but isn't right either:
6625 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6626 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6627 * service pack 6. Doesn't seem to happen on Windows 98.
6628 *
6629 * Like rename(), returns 0 upon success, non-zero upon failure.
6630 * Should probably set errno appropriately when errors occur.
6631 */
6632 int
6633mch_rename(
6634 const char *pszOldFile,
6635 const char *pszNewFile)
6636{
6637 char szTempFile[_MAX_PATH+1];
6638 char szNewPath[_MAX_PATH+1];
6639 char *pszFilePart;
6640 HANDLE hf;
6641#ifdef FEAT_MBYTE
6642 WCHAR *wold = NULL;
6643 WCHAR *wnew = NULL;
6644 int retval = -1;
6645
6646 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6647 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006648 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6649 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650 if (wold != NULL && wnew != NULL)
6651 retval = mch_wrename(wold, wnew);
6652 vim_free(wold);
6653 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006654 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 }
6656#endif
6657
6658 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006659 * No need to play tricks unless the file name contains a "~" as the
6660 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006662 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6663 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6664 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665
6666 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6667 * a directory, no error is returned and pszFilePart will be NULL. */
6668 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6669 || pszFilePart == NULL)
6670 return -1;
6671 *pszFilePart = NUL;
6672
6673 /* Get (and create) a unique temporary file name in directory of new file */
6674 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6675 return -2;
6676
6677 /* blow the temp file away */
6678 if (!DeleteFile(szTempFile))
6679 return -3;
6680
6681 /* rename old file to the temp file */
6682 if (!MoveFile(pszOldFile, szTempFile))
6683 return -4;
6684
6685 /* now create an empty file called pszOldFile; this prevents the operating
6686 * system using pszOldFile as an alias (SFN) if we're renaming within the
6687 * same directory. For example, we're editing a file called
6688 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6689 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6690 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006691 * cause all sorts of problems later in buf_write(). So, we create an
6692 * empty file called filena~1.txt and the system will have to find some
6693 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 */
6695 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6696 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6697 return -5;
6698 if (!CloseHandle(hf))
6699 return -6;
6700
6701 /* rename the temp file to the new file */
6702 if (!MoveFile(szTempFile, pszNewFile))
6703 {
6704 /* Renaming failed. Rename the file back to its old name, so that it
6705 * looks like nothing happened. */
6706 (void)MoveFile(szTempFile, pszOldFile);
6707
6708 return -7;
6709 }
6710
6711 /* Seems to be left around on Novell filesystems */
6712 DeleteFile(szTempFile);
6713
6714 /* finally, remove the empty old file */
6715 if (!DeleteFile(pszOldFile))
6716 return -8;
6717
6718 return 0; /* success */
6719}
6720
6721/*
6722 * Get the default shell for the current hardware platform
6723 */
6724 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006725default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006727 PlatformId();
6728
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006729 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730}
6731
6732/*
6733 * mch_access() extends access() to do more detailed check on network drives.
6734 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6735 */
6736 int
6737mch_access(char *n, int p)
6738{
6739 HANDLE hFile;
6740 DWORD am;
6741 int retval = -1; /* default: fail */
6742#ifdef FEAT_MBYTE
6743 WCHAR *wn = NULL;
6744
6745 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006746 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747#endif
6748
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006749 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750 {
6751 char TempName[_MAX_PATH + 16] = "";
6752#ifdef FEAT_MBYTE
6753 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6754#endif
6755
6756 if (p & R_OK)
6757 {
6758 /* Read check is performed by seeing if we can do a find file on
6759 * the directory for any file. */
6760#ifdef FEAT_MBYTE
6761 if (wn != NULL)
6762 {
6763 int i;
6764 WIN32_FIND_DATAW d;
6765
6766 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6767 TempNameW[i] = wn[i];
6768 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6769 TempNameW[i++] = '\\';
6770 TempNameW[i++] = '*';
6771 TempNameW[i++] = 0;
6772
6773 hFile = FindFirstFileW(TempNameW, &d);
6774 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006775 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776 else
6777 (void)FindClose(hFile);
6778 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006779 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780#endif
6781 {
6782 char *pch;
6783 WIN32_FIND_DATA d;
6784
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006785 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 pch = TempName + STRLEN(TempName) - 1;
6787 if (*pch != '\\' && *pch != '/')
6788 *++pch = '\\';
6789 *++pch = '*';
6790 *++pch = NUL;
6791
6792 hFile = FindFirstFile(TempName, &d);
6793 if (hFile == INVALID_HANDLE_VALUE)
6794 goto getout;
6795 (void)FindClose(hFile);
6796 }
6797 }
6798
6799 if (p & W_OK)
6800 {
6801 /* Trying to create a temporary file in the directory should catch
6802 * directories on read-only network shares. However, in
6803 * directories whose ACL allows writes but denies deletes will end
6804 * up keeping the temporary file :-(. */
6805#ifdef FEAT_MBYTE
6806 if (wn != NULL)
6807 {
6808 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006809 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810 else
6811 DeleteFileW(TempNameW);
6812 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006813 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006814#endif
6815 {
6816 if (!GetTempFileName(n, "VIM", 0, TempName))
6817 goto getout;
6818 mch_remove((char_u *)TempName);
6819 }
6820 }
6821 }
6822 else
6823 {
6824 /* Trying to open the file for the required access does ACL, read-only
6825 * network share, and file attribute checks. */
6826 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6827 | ((p & R_OK) ? GENERIC_READ : 0);
6828#ifdef FEAT_MBYTE
6829 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006830 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006831 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006832#endif
6833 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6834 if (hFile == INVALID_HANDLE_VALUE)
6835 goto getout;
6836 CloseHandle(hFile);
6837 }
6838
6839 retval = 0; /* success */
6840getout:
6841#ifdef FEAT_MBYTE
6842 vim_free(wn);
6843#endif
6844 return retval;
6845}
6846
6847#if defined(FEAT_MBYTE) || defined(PROTO)
6848/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006849 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850 */
6851 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006852mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006854 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6855# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006856 WCHAR *wn;
6857 int f;
6858
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006859 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006861 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862 if (wn != NULL)
6863 {
6864 f = _wopen(wn, flags, mode);
6865 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006866 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867 }
6868 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006869# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006871 /* open() can open a file which name is longer than _MAX_PATH bytes
6872 * and shorter than _MAX_PATH characters successfully, but sometimes it
6873 * causes unexpected error in another part. We make it an error explicitly
6874 * here. */
6875 if (strlen(name) >= _MAX_PATH)
6876 return -1;
6877
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878 return open(name, flags, mode);
6879}
6880
6881/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006882 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006883 */
6884 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006885mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886{
6887 WCHAR *wn, *wm;
6888 FILE *f = NULL;
6889
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006890 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006892# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006893 /* Work around an annoying assertion in the Microsoft debug CRT
6894 * when mode's text/binary setting doesn't match _get_fmode(). */
6895 char newMode = mode[strlen(mode) - 1];
6896 int oldMode = 0;
6897
6898 _get_fmode(&oldMode);
6899 if (newMode == 't')
6900 _set_fmode(_O_TEXT);
6901 else if (newMode == 'b')
6902 _set_fmode(_O_BINARY);
6903# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006904 wn = enc_to_utf16((char_u *)name, NULL);
6905 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906 if (wn != NULL && wm != NULL)
6907 f = _wfopen(wn, wm);
6908 vim_free(wn);
6909 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006910
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006911# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006912 _set_fmode(oldMode);
6913# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006914 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 }
6916
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006917 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6918 * and shorter than _MAX_PATH characters successfully, but sometimes it
6919 * causes unexpected error in another part. We make it an error explicitly
6920 * here. */
6921 if (strlen(name) >= _MAX_PATH)
6922 return NULL;
6923
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924 return fopen(name, mode);
6925}
6926#endif
6927
6928#ifdef FEAT_MBYTE
6929/*
6930 * SUB STREAM (aka info stream) handling:
6931 *
6932 * NTFS can have sub streams for each file. Normal contents of file is
6933 * stored in the main stream, and extra contents (author information and
6934 * title and so on) can be stored in sub stream. After Windows 2000, user
6935 * can access and store those informations in sub streams via explorer's
6936 * property menuitem in right click menu. Those informations in sub streams
6937 * were lost when copying only the main stream. So we have to copy sub
6938 * streams.
6939 *
6940 * Incomplete explanation:
6941 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6942 * More useful info and an example:
6943 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6944 */
6945
6946/*
6947 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6948 * and write to stream "substream" of file "to".
6949 * Errors are ignored.
6950 */
6951 static void
6952copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6953{
6954 HANDLE hTo;
6955 WCHAR *to_name;
6956
6957 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6958 wcscpy(to_name, to);
6959 wcscat(to_name, substream);
6960
6961 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6962 FILE_ATTRIBUTE_NORMAL, NULL);
6963 if (hTo != INVALID_HANDLE_VALUE)
6964 {
6965 long done;
6966 DWORD todo;
6967 DWORD readcnt, written;
6968 char buf[4096];
6969
6970 /* Copy block of bytes at a time. Abort when something goes wrong. */
6971 for (done = 0; done < len; done += written)
6972 {
6973 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006974 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6975 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6977 FALSE, FALSE, context)
6978 || readcnt != todo
6979 || !WriteFile(hTo, buf, todo, &written, NULL)
6980 || written != todo)
6981 break;
6982 }
6983 CloseHandle(hTo);
6984 }
6985
6986 free(to_name);
6987}
6988
6989/*
6990 * Copy info streams from file "from" to file "to".
6991 */
6992 static void
6993copy_infostreams(char_u *from, char_u *to)
6994{
6995 WCHAR *fromw;
6996 WCHAR *tow;
6997 HANDLE sh;
6998 WIN32_STREAM_ID sid;
6999 int headersize;
7000 WCHAR streamname[_MAX_PATH];
7001 DWORD readcount;
7002 void *context = NULL;
7003 DWORD lo, hi;
7004 int len;
7005
7006 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007007 fromw = enc_to_utf16(from, NULL);
7008 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 if (fromw != NULL && tow != NULL)
7010 {
7011 /* Open the file for reading. */
7012 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7013 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7014 if (sh != INVALID_HANDLE_VALUE)
7015 {
7016 /* Use BackupRead() to find the info streams. Repeat until we
7017 * have done them all.*/
7018 for (;;)
7019 {
7020 /* Get the header to find the length of the stream name. If
7021 * the "readcount" is zero we have done all info streams. */
7022 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007023 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7025 &readcount, FALSE, FALSE, &context)
7026 || readcount == 0)
7027 break;
7028
7029 /* We only deal with streams that have a name. The normal
7030 * file data appears to be without a name, even though docs
7031 * suggest it is called "::$DATA". */
7032 if (sid.dwStreamNameSize > 0)
7033 {
7034 /* Read the stream name. */
7035 if (!BackupRead(sh, (LPBYTE)streamname,
7036 sid.dwStreamNameSize,
7037 &readcount, FALSE, FALSE, &context))
7038 break;
7039
7040 /* Copy an info stream with a name ":anything:$DATA".
7041 * Skip "::$DATA", it has no stream name (examples suggest
7042 * it might be used for the normal file contents).
7043 * Note that BackupRead() counts bytes, but the name is in
7044 * wide characters. */
7045 len = readcount / sizeof(WCHAR);
7046 streamname[len] = 0;
7047 if (len > 7 && wcsicmp(streamname + len - 6,
7048 L":$DATA") == 0)
7049 {
7050 streamname[len - 6] = 0;
7051 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007052 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053 }
7054 }
7055
7056 /* Advance to the next stream. We might try seeking too far,
7057 * but BackupSeek() doesn't skip over stream borders, thus
7058 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007059 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 &lo, &hi, &context);
7061 }
7062
7063 /* Clear the context. */
7064 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7065
7066 CloseHandle(sh);
7067 }
7068 }
7069 vim_free(fromw);
7070 vim_free(tow);
7071}
7072#endif
7073
7074/*
7075 * Copy file attributes from file "from" to file "to".
7076 * For Windows NT and later we copy info streams.
7077 * Always returns zero, errors are ignored.
7078 */
7079 int
7080mch_copy_file_attribute(char_u *from, char_u *to)
7081{
7082#ifdef FEAT_MBYTE
7083 /* File streams only work on Windows NT and later. */
7084 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007085 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086#endif
7087 return 0;
7088}
7089
7090#if defined(MYRESETSTKOFLW) || defined(PROTO)
7091/*
7092 * Recreate a destroyed stack guard page in win32.
7093 * Written by Benjamin Peterson.
7094 */
7095
7096/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097#define MIN_STACK_WINNT 2
7098
7099/*
7100 * This function does the same thing as _resetstkoflw(), which is only
7101 * available in DevStudio .net and later.
7102 * Returns 0 for failure, 1 for success.
7103 */
7104 int
7105myresetstkoflw(void)
7106{
7107 BYTE *pStackPtr;
7108 BYTE *pGuardPage;
7109 BYTE *pStackBase;
7110 BYTE *pLowestPossiblePage;
7111 MEMORY_BASIC_INFORMATION mbi;
7112 SYSTEM_INFO si;
7113 DWORD nPageSize;
7114 DWORD dummy;
7115
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117
7118 /* We need to know the system page size. */
7119 GetSystemInfo(&si);
7120 nPageSize = si.dwPageSize;
7121
7122 /* ...and the current stack pointer */
7123 pStackPtr = (BYTE*)_alloca(1);
7124
7125 /* ...and the base of the stack. */
7126 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7127 return 0;
7128 pStackBase = (BYTE*)mbi.AllocationBase;
7129
7130 /* ...and the page thats min_stack_req pages away from stack base; this is
7131 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007132 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007135 /* We want the first committed page in the stack Start at the stack
7136 * base and move forward through memory until we find a committed block.
7137 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138 BYTE *pBlock = pStackBase;
7139
Bram Moolenaara466c992005-07-09 21:03:22 +00007140 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007141 {
7142 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7143 return 0;
7144
7145 pBlock += mbi.RegionSize;
7146
7147 if (mbi.State & MEM_COMMIT)
7148 break;
7149 }
7150
7151 /* mbi now describes the first committed block in the stack. */
7152 if (mbi.Protect & PAGE_GUARD)
7153 return 1;
7154
7155 /* decide where the guard page should start */
7156 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7157 pGuardPage = pLowestPossiblePage;
7158 else
7159 pGuardPage = (BYTE*)mbi.BaseAddress;
7160
7161 /* allocate the guard page */
7162 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7163 return 0;
7164
7165 /* apply the guard attribute to the page */
7166 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7167 &dummy))
7168 return 0;
7169 }
7170
7171 return 1;
7172}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007173#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007174
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007175
7176#if defined(FEAT_MBYTE) || defined(PROTO)
7177/*
7178 * The command line arguments in UCS2
7179 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007180static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007181static LPWSTR *ArglistW = NULL;
7182static int global_argc = 0;
7183static char **global_argv;
7184
7185static int used_file_argc = 0; /* last argument in global_argv[] used
7186 for the argument list. */
7187static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7188 command line arguments added to
7189 the argument list */
7190static int used_file_count = 0; /* nr of entries in used_file_indexes */
7191static int used_file_literal = FALSE; /* take file names literally */
7192static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007193static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007194static int used_alist_count = 0;
7195
7196
7197/*
7198 * Get the command line arguments. Unicode version.
7199 * Returns argc. Zero when something fails.
7200 */
7201 int
7202get_cmd_argsW(char ***argvp)
7203{
7204 char **argv = NULL;
7205 int argc = 0;
7206 int i;
7207
Bram Moolenaar14993322014-09-09 12:25:33 +02007208 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007209 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7210 if (ArglistW != NULL)
7211 {
7212 argv = malloc((nArgsW + 1) * sizeof(char *));
7213 if (argv != NULL)
7214 {
7215 argc = nArgsW;
7216 argv[argc] = NULL;
7217 for (i = 0; i < argc; ++i)
7218 {
7219 int len;
7220
7221 /* Convert each Unicode argument to the current codepage. */
7222 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007223 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007224 (LPSTR *)&argv[i], &len, 0, 0);
7225 if (argv[i] == NULL)
7226 {
7227 /* Out of memory, clear everything. */
7228 while (i > 0)
7229 free(argv[--i]);
7230 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007231 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007232 argc = 0;
7233 }
7234 }
7235 }
7236 }
7237
7238 global_argc = argc;
7239 global_argv = argv;
7240 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007241 {
7242 if (used_file_indexes != NULL)
7243 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007244 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007245 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007246
7247 if (argvp != NULL)
7248 *argvp = argv;
7249 return argc;
7250}
7251
7252 void
7253free_cmd_argsW(void)
7254{
7255 if (ArglistW != NULL)
7256 {
7257 GlobalFree(ArglistW);
7258 ArglistW = NULL;
7259 }
7260}
7261
7262/*
7263 * Remember "name" is an argument that was added to the argument list.
7264 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7265 * is called.
7266 */
7267 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007268used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007269{
7270 int i;
7271
7272 if (used_file_indexes == NULL)
7273 return;
7274 for (i = used_file_argc + 1; i < global_argc; ++i)
7275 if (STRCMP(global_argv[i], name) == 0)
7276 {
7277 used_file_argc = i;
7278 used_file_indexes[used_file_count++] = i;
7279 break;
7280 }
7281 used_file_literal = literal;
7282 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007283 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007284}
7285
7286/*
7287 * Remember the length of the argument list as it was. If it changes then we
7288 * leave it alone when 'encoding' is set.
7289 */
7290 void
7291set_alist_count(void)
7292{
7293 used_alist_count = GARGCOUNT;
7294}
7295
7296/*
7297 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7298 * has been changed while starting up. Use the UCS-2 command line arguments
7299 * and convert them to 'encoding'.
7300 */
7301 void
7302fix_arg_enc(void)
7303{
7304 int i;
7305 int idx;
7306 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007307 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007308
7309 /* Safety checks:
7310 * - if argument count differs between the wide and non-wide argument
7311 * list, something must be wrong.
7312 * - the file name arguments must have been located.
7313 * - the length of the argument list wasn't changed by the user.
7314 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007315 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007316 || ArglistW == NULL
7317 || used_file_indexes == NULL
7318 || used_file_count == 0
7319 || used_alist_count != GARGCOUNT)
7320 return;
7321
Bram Moolenaar86b68352004-12-27 21:59:20 +00007322 /* Remember the buffer numbers for the arguments. */
7323 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7324 if (fnum_list == NULL)
7325 return; /* out of memory */
7326 for (i = 0; i < GARGCOUNT; ++i)
7327 fnum_list[i] = GARGLIST[i].ae_fnum;
7328
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007329 /* Clear the argument list. Make room for the new arguments. */
7330 alist_clear(&global_alist);
7331 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007332 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007333
7334 for (i = 0; i < used_file_count; ++i)
7335 {
7336 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007337 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007338 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007339 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007340 int literal = used_file_literal;
7341
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007342#ifdef FEAT_DIFF
7343 /* When using diff mode may need to concatenate file name to
7344 * directory name. Just like it's done in main(). */
7345 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7346 && !mch_isdir(alist_name(&GARGLIST[0])))
7347 {
7348 char_u *r;
7349
7350 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7351 if (r != NULL)
7352 {
7353 vim_free(str);
7354 str = r;
7355 }
7356 }
7357#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007358 /* Re-use the old buffer by renaming it. When not using literal
7359 * names it's done by alist_expand() below. */
7360 if (used_file_literal)
7361 buf_set_name(fnum_list[i], str);
7362
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007363 /* Check backtick literal. backtick literal is already expanded in
7364 * main.c, so this part add str as literal. */
7365 if (literal == FALSE)
7366 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007367 size_t len = STRLEN(str);
7368
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007369 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7370 literal = TRUE;
7371 }
7372 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007373 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007374 }
7375
7376 if (!used_file_literal)
7377 {
7378 /* Now expand wildcards in the arguments. */
7379 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7380 * filename characters but are excluded from 'isfname' to make
7381 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7382 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007383 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007384 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7385 }
7386
7387 /* If wildcard expansion failed, we are editing the first file of the
7388 * arglist and there is no file name: Edit the first argument now. */
7389 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7390 {
7391 do_cmdline_cmd((char_u *)":rewind");
7392 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007393 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007394 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007395
7396 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007397}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007398#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007399
7400 int
7401mch_setenv(char *var, char *value, int x)
7402{
7403 char_u *envbuf;
7404
7405 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7406 if (envbuf == NULL)
7407 return -1;
7408
7409 sprintf((char *)envbuf, "%s=%s", var, value);
7410
7411#ifdef FEAT_MBYTE
7412 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7413 {
7414 WCHAR *p = enc_to_utf16(envbuf, NULL);
7415
7416 vim_free(envbuf);
7417 if (p == NULL)
7418 return -1;
7419 _wputenv(p);
7420# ifdef libintl_wputenv
7421 libintl_wputenv(p);
7422# endif
7423 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7424 vim_free(p);
7425 }
7426 else
7427#endif
7428 {
7429 _putenv((char *)envbuf);
7430# ifdef libintl_putenv
7431 libintl_putenv((char *)envbuf);
7432# endif
7433 /* Unlike Un*x systems, we can free the string for _putenv(). */
7434 vim_free(envbuf);
7435 }
7436
7437 return 0;
7438}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007439
7440#ifndef FEAT_GUI_W32
7441
7442/*
7443 * Support for 256 colors and 24-bit colors was added in Windows 10
7444 * version 1703 (Creators update).
7445 */
7446# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7447
7448 static void
7449vtp_init(void)
7450{
7451 DWORD ver, mode;
7452 HMODULE hKerneldll;
7453 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7454
7455 ver = get_build_number();
7456 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7457 GetConsoleMode(g_hConOut, &mode);
7458 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7459 if (SetConsoleMode(g_hConOut, mode) == 0)
7460 vtp_working = 0;
7461
7462 /* Use functions supported from Vista */
7463 hKerneldll = GetModuleHandle("kernel32.dll");
7464 if (hKerneldll != NULL)
7465 {
7466 pGetConsoleScreenBufferInfoEx =
7467 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7468 hKerneldll, "GetConsoleScreenBufferInfoEx");
7469 pSetConsoleScreenBufferInfoEx =
7470 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7471 hKerneldll, "SetConsoleScreenBufferInfoEx");
7472 if (pGetConsoleScreenBufferInfoEx != NULL
7473 && pSetConsoleScreenBufferInfoEx != NULL)
7474 has_csbiex = TRUE;
7475 }
7476
7477 csbi.cbSize = sizeof(csbi);
7478 if (has_csbiex)
7479 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7480 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[0];
7481 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[7];
7482
7483 set_console_color_rgb();
7484}
7485
7486 static void
7487vtp_exit(void)
7488{
7489 reset_console_color_rgb();
7490}
7491
7492 static int
7493vtp_printf(
7494 char *format,
7495 ...)
7496{
7497 char_u buf[100];
7498 va_list list;
7499 DWORD result;
7500
7501 va_start(list, format);
7502 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7503 va_end(list);
7504 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7505 return (int)result;
7506}
7507
7508 static void
7509vtp_sgr_bulk(
7510 int arg)
7511{
7512 int args[1];
7513
7514 args[0] = arg;
7515 vtp_sgr_bulks(1, args);
7516}
7517
7518 static void
7519vtp_sgr_bulks(
7520 int argc,
7521 int *args
7522)
7523{
7524 /* 2('\033[') + 4('255.') * 16 + NUL */
7525 char_u buf[2 + (4 * 16) + 1];
7526 char_u *p;
7527 int i;
7528
7529 p = buf;
7530 *p++ = '\033';
7531 *p++ = '[';
7532
7533 for (i = 0; i < argc; ++i)
7534 {
7535 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7536 *p++ = ';';
7537 }
7538 p--;
7539 *p++ = 'm';
7540 *p = NUL;
7541 vtp_printf((char *)buf);
7542}
7543
7544 static void
7545set_console_color_rgb(void)
7546{
7547# ifdef FEAT_TERMGUICOLORS
7548 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7549 int id;
7550 guicolor_T fg = INVALCOLOR;
7551 guicolor_T bg = INVALCOLOR;
7552
7553 if (!USE_VTP)
7554 return;
7555
7556 id = syn_name2id((char_u *)"Normal");
7557 if (id > 0)
7558 syn_id2colors(id, &fg, &bg);
7559 if (fg == INVALCOLOR)
7560 fg = 0xc0c0c0; /* white text */
7561 if (bg == INVALCOLOR)
7562 bg = 0x000000; /* black background */
7563 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7564 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7565
7566 csbi.cbSize = sizeof(csbi);
7567 if (has_csbiex)
7568 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7569
7570 csbi.cbSize = sizeof(csbi);
7571 csbi.srWindow.Right += 1;
7572 csbi.srWindow.Bottom += 1;
7573 csbi.ColorTable[0] = (COLORREF)bg;
7574 csbi.ColorTable[7] = (COLORREF)fg;
7575 if (has_csbiex)
7576 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7577# endif
7578}
7579
7580 static void
7581reset_console_color_rgb(void)
7582{
7583# ifdef FEAT_TERMGUICOLORS
7584 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7585
7586 csbi.cbSize = sizeof(csbi);
7587 if (has_csbiex)
7588 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7589
7590 csbi.cbSize = sizeof(csbi);
7591 csbi.srWindow.Right += 1;
7592 csbi.srWindow.Bottom += 1;
7593 csbi.ColorTable[0] = (COLORREF)save_console_bg_rgb;
7594 csbi.ColorTable[7] = (COLORREF)save_console_fg_rgb;
7595 if (has_csbiex)
7596 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7597# endif
7598}
7599
7600 void
7601control_console_color_rgb(void)
7602{
7603 if (USE_VTP)
7604 set_console_color_rgb();
7605 else
7606 reset_console_color_rgb();
7607}
7608
7609 int
7610has_vtp_working(void)
7611{
7612 return vtp_working;
7613}
7614
7615 int
7616use_vtp(void)
7617{
7618 return USE_VTP;
7619}
7620
7621#endif