blob: b5a6ccebaed77dd979a091b850f11875466cd030 [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
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171static void scroll(unsigned cLines);
172static void set_scroll_region(unsigned left, unsigned top,
173 unsigned right, unsigned bottom);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174static void delete_lines(unsigned cLines);
175static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static int s_cursor_visible = TRUE;
178static int did_create_conin = FALSE;
179#else
180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaar071d4272004-06-13 20:20:40 +0000189#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100190static int vtp_working = 0;
191static void vtp_init();
192static void vtp_exit();
193static int vtp_printf(char *format, ...);
194static void vtp_sgr_bulk(int arg);
195static void vtp_sgr_bulks(int argc, int *argv);
196
197static guicolor_T save_console_bg_rgb;
198static guicolor_T save_console_fg_rgb;
199
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200200static int g_color_index_bg = 0;
201static int g_color_index_fg = 7;
202
203# ifdef FEAT_TERMGUICOLORS
204static int default_console_color_bg = 0x000000; // black
205static int default_console_color_fg = 0xc0c0c0; // white
206# endif
207
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100208# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200209# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100210# else
211# define USE_VTP 0
212# endif
213
214static void set_console_color_rgb(void);
215static void reset_console_color_rgb(void);
216#endif
217
218/* This flag is newly created from Windows 10 */
219#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
220# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
221#endif
222
223#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224static int suppress_winsize = 1; /* don't fiddle with console */
225#endif
226
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200227static char_u *exe_path = NULL;
228
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100229static BOOL win8_or_later = FALSE;
230
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100231#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232/* Dynamic loading for portability */
233typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
234{
235 ULONG cbSize;
236 COORD dwSize;
237 COORD dwCursorPosition;
238 WORD wAttributes;
239 SMALL_RECT srWindow;
240 COORD dwMaximumWindowSize;
241 WORD wPopupAttributes;
242 BOOL bFullscreenSupported;
243 COLORREF ColorTable[16];
244} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
245typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
246static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
247typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
248static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
249static BOOL has_csbiex = FALSE;
250
251/*
252 * Get version number including build number
253 */
254typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
255# define MAKE_VER(major, minor, build) \
256 (((major) << 24) | ((minor) << 16) | (build))
257
258 static DWORD
259get_build_number(void)
260{
261 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
262 HMODULE hNtdll;
263 PfnRtlGetVersion pRtlGetVersion;
264 DWORD ver = MAKE_VER(0, 0, 0);
265
266 hNtdll = GetModuleHandle("ntdll.dll");
267 if (hNtdll != NULL)
268 {
269 pRtlGetVersion =
270 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
271 pRtlGetVersion(&osver);
272 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
273 min(osver.dwMinorVersion, 255),
274 min(osver.dwBuildNumber, 32767));
275 }
276 return ver;
277}
278
279
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280/*
281 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100282 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100283 */
284 static BOOL
285read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100286 HANDLE hInput,
287 INPUT_RECORD *lpBuffer,
288 DWORD nLength,
289 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100290{
291 enum
292 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100293 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100294 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100296 static DWORD s_dwIndex = 0;
297 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100299 int head;
300 int tail;
301 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200303 if (nLength == -2)
304 return (s_dwMax > 0) ? TRUE : FALSE;
305
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100306 if (!win8_or_later)
307 {
308 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200309 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
310 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100311 }
312
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100313 if (s_dwMax == 0)
314 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100315 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200316 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
317 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100318 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 s_dwIndex = 0;
320 s_dwMax = dwEvents;
321 if (dwEvents == 0)
322 {
323 *lpEvents = 0;
324 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100326
327 if (s_dwMax > 1)
328 {
329 head = 0;
330 tail = s_dwMax - 1;
331 while (head != tail)
332 {
333 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
334 && s_irCache[head + 1].EventType
335 == WINDOW_BUFFER_SIZE_EVENT)
336 {
337 /* Remove duplicate event to avoid flicker. */
338 for (i = head; i < tail; ++i)
339 s_irCache[i] = s_irCache[i + 1];
340 --tail;
341 continue;
342 }
343 head++;
344 }
345 s_dwMax = tail + 1;
346 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100347 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100348
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100349 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200350 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100351 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100352 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100353 return TRUE;
354}
355
356/*
357 * Version of PeekConsoleInput() that works with IME.
358 */
359 static BOOL
360peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100361 HANDLE hInput,
362 INPUT_RECORD *lpBuffer,
363 DWORD nLength,
364 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100365{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100366 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367}
368
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100369# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200370 static DWORD
371msg_wait_for_multiple_objects(
372 DWORD nCount,
373 LPHANDLE pHandles,
374 BOOL fWaitAll,
375 DWORD dwMilliseconds,
376 DWORD dwWakeMask)
377{
378 if (read_console_input(NULL, NULL, -2, NULL))
379 return WAIT_OBJECT_0;
380 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
381 dwMilliseconds, dwWakeMask);
382}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100383# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200384
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100385# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200386 static DWORD
387wait_for_single_object(
388 HANDLE hHandle,
389 DWORD dwMilliseconds)
390{
391 if (read_console_input(NULL, NULL, -2, NULL))
392 return WAIT_OBJECT_0;
393 return WaitForSingleObject(hHandle, dwMilliseconds);
394}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100395# endif
396#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200397
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 static void
399get_exe_name(void)
400{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100401 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
402 * as the maximum length that works (plus a NUL byte). */
403#define MAX_ENV_PATH_LEN 8192
404 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200405 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406
407 if (exe_name == NULL)
408 {
409 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100410 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411 if (*temp != NUL)
412 exe_name = FullName_save((char_u *)temp, FALSE);
413 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000414
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200415 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000416 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200417 exe_path = vim_strnsave(exe_name,
418 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200419 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000420 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200421 /* Append our starting directory to $PATH, so that when doing
422 * "!xxd" it's found in our starting directory. Needed because
423 * SearchPath() also looks there. */
424 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100425 if (p == NULL
426 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100428 if (p == NULL || *p == NUL)
429 temp[0] = NUL;
430 else
431 {
432 STRCPY(temp, p);
433 STRCAT(temp, ";");
434 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100436 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200437 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000438 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440}
441
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200442/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100443 * Unescape characters in "p" that appear in "escaped".
444 */
445 static void
446unescape_shellxquote(char_u *p, char_u *escaped)
447{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100448 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100449 int n;
450
451 while (*p != NUL)
452 {
453 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
454 mch_memmove(p, p + 1, l--);
455#ifdef FEAT_MBYTE
456 n = (*mb_ptr2len)(p);
457#else
458 n = 1;
459#endif
460 p += n;
461 l -= n;
462 }
463}
464
465/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200466 * Load library "name".
467 */
468 HINSTANCE
469vimLoadLib(char *name)
470{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200471 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200473 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
474 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 if (exe_path == NULL)
476 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200477 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200479 WCHAR old_dirw[MAXPATHL];
480
481 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
482 {
483 /* Change directory to where the executable is, both to make
484 * sure we find a .dll there and to avoid looking for a .dll
485 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100486 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 dll = LoadLibrary(name);
488 SetCurrentDirectoryW(old_dirw);
489 return dll;
490 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200491 }
492 return dll;
493}
494
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100495#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
496/*
497 * Get related information about 'funcname' which is imported by 'hInst'.
498 * If 'info' is 0, return the function address.
499 * If 'info' is 1, return the module name which the function is imported from.
500 */
501 static void *
502get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
503{
504 PBYTE pImage = (PBYTE)hInst;
505 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
506 PIMAGE_NT_HEADERS pPE;
507 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
508 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
509 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
510 PIMAGE_IMPORT_BY_NAME pImpName;
511
512 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
513 return NULL;
514 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
515 if (pPE->Signature != IMAGE_NT_SIGNATURE)
516 return NULL;
517 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
518 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
519 .VirtualAddress);
520 for (; pImpDesc->FirstThunk; ++pImpDesc)
521 {
522 if (!pImpDesc->OriginalFirstThunk)
523 continue;
524 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
525 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
526 for (; pIAT->u1.Function; ++pIAT, ++pINT)
527 {
528 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
529 continue;
530 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
531 + (UINT_PTR)(pINT->u1.AddressOfData));
532 if (strcmp((char *)pImpName->Name, funcname) == 0)
533 {
534 switch (info)
535 {
536 case 0:
537 return (void *)pIAT->u1.Function;
538 case 1:
539 return (void *)(pImage + pImpDesc->Name);
540 default:
541 return NULL;
542 }
543 }
544 }
545 }
546 return NULL;
547}
548
549/*
550 * Get the module handle which 'funcname' in 'hInst' is imported from.
551 */
552 HINSTANCE
553find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
554{
555 char *modulename;
556
557 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
558 if (modulename != NULL)
559 return GetModuleHandleA(modulename);
560 return NULL;
561}
562
563/*
564 * Get the address of 'funcname' which is imported by 'hInst' DLL.
565 */
566 void *
567get_dll_import_func(HINSTANCE hInst, const char *funcname)
568{
569 return get_imported_func_info(hInst, funcname, 0);
570}
571#endif
572
Bram Moolenaar071d4272004-06-13 20:20:40 +0000573#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
574# ifndef GETTEXT_DLL
575# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200576# define GETTEXT_DLL_ALT1 "libintl-8.dll"
577# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200579/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000580static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200581static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000582static char *null_libintl_textdomain(const char *);
583static char *null_libintl_bindtextdomain(const char *, const char *);
584static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100585static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100586static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200588static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000589char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200590char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
591 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000592char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
593char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000594 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000595char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
596 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100597int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100598int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000599
600 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100601dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602{
603 int i;
604 static struct
605 {
606 char *name;
607 FARPROC *ptr;
608 } libintl_entry[] =
609 {
610 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200611 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
613 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
614 {NULL, NULL}
615 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100616 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617
Bram Moolenaar7554c542018-10-06 15:03:15 +0200618 // No need to initialize twice.
619 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200621 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100622 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200623#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100624 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200625 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
626#endif
627#ifdef GETTEXT_DLL_ALT2
628 if (!hLibintlDLL)
629 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100630#endif
631 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200633 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200635 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100636 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200637 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200639 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640 }
641 for (i = 0; libintl_entry[i].name != NULL
642 && libintl_entry[i].ptr != NULL; ++i)
643 {
644 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
645 libintl_entry[i].name)) == NULL)
646 {
647 dyn_libintl_end();
648 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000649 {
650 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100651 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000652 verbose_leave();
653 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654 return 0;
655 }
656 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000657
658 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000659 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000660 "bind_textdomain_codeset");
661 if (dyn_libintl_bind_textdomain_codeset == NULL)
662 dyn_libintl_bind_textdomain_codeset =
663 null_libintl_bind_textdomain_codeset;
664
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100665 /* _putenv() function for the libintl.dll is optional. */
666 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
667 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100668 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100669 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100670 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
671 }
672 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100673 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100674 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
675 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100676
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 return 1;
678}
679
680 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100681dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682{
683 if (hLibintlDLL)
684 FreeLibrary(hLibintlDLL);
685 hLibintlDLL = NULL;
686 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200687 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 dyn_libintl_textdomain = null_libintl_textdomain;
689 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000690 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100691 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100692 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693}
694
695 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000696null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697{
698 return (char*)msgid;
699}
700
701 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200702null_libintl_ngettext(
703 const char *msgid,
704 const char *msgid_plural,
705 unsigned long n)
706{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200707 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200708}
709
Bram Moolenaaree695f72016-08-03 22:08:45 +0200710 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100711null_libintl_bindtextdomain(
712 const char *domainname UNUSED,
713 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714{
715 return NULL;
716}
717
718 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100719null_libintl_bind_textdomain_codeset(
720 const char *domainname UNUSED,
721 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000722{
723 return NULL;
724}
725
726 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100727null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728{
729 return NULL;
730}
731
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200732 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100733null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100734{
735 return 0;
736}
737
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200738 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100739null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100740{
741 return 0;
742}
743
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744#endif /* DYNAMIC_GETTEXT */
745
746/* This symbol is not defined in older versions of the SDK or Visual C++ */
747
748#ifndef VER_PLATFORM_WIN32_WINDOWS
749# define VER_PLATFORM_WIN32_WINDOWS 1
750#endif
751
752DWORD g_PlatformId;
753
754#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100755# ifndef PROTO
756# include <aclapi.h>
757# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200758# ifndef PROTECTED_DACL_SECURITY_INFORMATION
759# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761#endif
762
Bram Moolenaar27515922013-06-29 15:36:26 +0200763#ifdef HAVE_ACL
764/*
765 * Enables or disables the specified privilege.
766 */
767 static BOOL
768win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
769{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100770 BOOL bResult;
771 LUID luid;
772 HANDLE hToken;
773 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200774
775 if (!OpenProcessToken(GetCurrentProcess(),
776 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
777 return FALSE;
778
779 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
780 {
781 CloseHandle(hToken);
782 return FALSE;
783 }
784
Bram Moolenaar45500912014-07-09 20:51:07 +0200785 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200786 tokenPrivileges.Privileges[0].Luid = luid;
787 tokenPrivileges.Privileges[0].Attributes = bEnable ?
788 SE_PRIVILEGE_ENABLED : 0;
789
790 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
791 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
792
793 CloseHandle(hToken);
794
795 return bResult && GetLastError() == ERROR_SUCCESS;
796}
797#endif
798
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799/*
800 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
801 * VER_PLATFORM_WIN32_WINDOWS (Win95).
802 */
803 void
804PlatformId(void)
805{
806 static int done = FALSE;
807
808 if (!done)
809 {
810 OSVERSIONINFO ovi;
811
812 ovi.dwOSVersionInfoSize = sizeof(ovi);
813 GetVersionEx(&ovi);
814
815 g_PlatformId = ovi.dwPlatformId;
816
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100817 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
818 || ovi.dwMajorVersion > 6)
819 win8_or_later = TRUE;
820
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200822 /* Enable privilege for getting or setting SACLs. */
823 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#endif
825 done = TRUE;
826 }
827}
828
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829#ifndef FEAT_GUI_W32
830
831#define SHIFT (SHIFT_PRESSED)
832#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
833#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
834#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
835
836
837/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
838 * We map function keys to their ANSI terminal equivalents, as produced
839 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
840 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
841 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
842 * combinations of function/arrow/etc keys.
843 */
844
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000845static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846{
847 WORD wVirtKey;
848 BOOL fAnsiKey;
849 int chAlone;
850 int chShift;
851 int chCtrl;
852 int chAlt;
853} VirtKeyMap[] =
854{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200855// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
857
858 { VK_F1, TRUE, ';', 'T', '^', 'h', },
859 { VK_F2, TRUE, '<', 'U', '_', 'i', },
860 { VK_F3, TRUE, '=', 'V', '`', 'j', },
861 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
862 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
863 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
864 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
865 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
866 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
867 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200868 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
869 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000870
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200871 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
872 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
873 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
874 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
875 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
876 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
877 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
878 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
879 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
880 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200882 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883
884#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200885 // Most people don't have F13-F20, but what the hell...
886 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
887 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
888 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
889 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
890 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
891 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
892 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
893 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200895 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
896 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
897 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
898 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200900 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
901 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
902 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
903 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
904 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
905 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
906 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
907 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
908 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
909 // Sorry, out of number space! <negri>
910 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
911
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912};
913
914
915#ifdef _MSC_VER
916// The ToAscii bug destroys several registers. Need to turn off optimization
917// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000918# pragma warning(push)
919# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920# pragma optimize("", off)
921#endif
922
923#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200924# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200926# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927#endif
928
929/* The return code indicates key code size. */
930 static int
931#ifdef __BORLANDC__
932 __stdcall
933#endif
934win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000935 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936{
937 UINT uMods = pker->dwControlKeyState;
938 static int s_iIsDead = 0;
939 static WORD awAnsiCode[2];
940 static BYTE abKeystate[256];
941
942
943 if (s_iIsDead == 2)
944 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200945 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946 s_iIsDead = 0;
947 return 1;
948 }
949
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200950 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951 return 1;
952
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200953 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200956 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957
958 if (uMods & SHIFT_PRESSED)
959 abKeystate[VK_SHIFT] = 0x80;
960 if (uMods & CAPSLOCK_ON)
961 abKeystate[VK_CAPITAL] = 1;
962
963 if ((uMods & ALT_GR) == ALT_GR)
964 {
965 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
966 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
967 }
968
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200969 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
970 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000971
972 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200973 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000974
975 return s_iIsDead;
976}
977
978#ifdef _MSC_VER
979/* MUST switch optimization on again here, otherwise a call to
980 * decode_key_event() may crash (e.g. when hitting caps-lock) */
981# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000982# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983
984# if (_MSC_VER < 1100)
985/* MUST turn off global optimisation for this next function, or
986 * pressing ctrl-minus in insert mode crashes Vim when built with
987 * VC4.1. -- negri. */
988# pragma optimize("g", off)
989# endif
990#endif
991
992static BOOL g_fJustGotFocus = FALSE;
993
994/*
995 * Decode a KEY_EVENT into one or two keystrokes
996 */
997 static BOOL
998decode_key_event(
999 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001000 WCHAR *pch,
1001 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002 int *pmodifiers,
1003 BOOL fDoPost)
1004{
1005 int i;
1006 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1007
1008 *pch = *pch2 = NUL;
1009 g_fJustGotFocus = FALSE;
1010
1011 /* ignore key up events */
1012 if (!pker->bKeyDown)
1013 return FALSE;
1014
1015 /* ignore some keystrokes */
1016 switch (pker->wVirtualKeyCode)
1017 {
1018 /* modifiers */
1019 case VK_SHIFT:
1020 case VK_CONTROL:
1021 case VK_MENU: /* Alt key */
1022 return FALSE;
1023
1024 default:
1025 break;
1026 }
1027
1028 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001029 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030 {
1031 /* Ctrl-6 is Ctrl-^ */
1032 if (pker->wVirtualKeyCode == '6')
1033 {
1034 *pch = Ctrl_HAT;
1035 return TRUE;
1036 }
1037 /* Ctrl-2 is Ctrl-@ */
1038 else if (pker->wVirtualKeyCode == '2')
1039 {
1040 *pch = NUL;
1041 return TRUE;
1042 }
1043 /* Ctrl-- is Ctrl-_ */
1044 else if (pker->wVirtualKeyCode == 0xBD)
1045 {
1046 *pch = Ctrl__;
1047 return TRUE;
1048 }
1049 }
1050
1051 /* Shift-TAB */
1052 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1053 {
1054 *pch = K_NUL;
1055 *pch2 = '\017';
1056 return TRUE;
1057 }
1058
1059 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1060 {
1061 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1062 {
1063 if (nModifs == 0)
1064 *pch = VirtKeyMap[i].chAlone;
1065 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1066 *pch = VirtKeyMap[i].chShift;
1067 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1068 *pch = VirtKeyMap[i].chCtrl;
1069 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1070 *pch = VirtKeyMap[i].chAlt;
1071
1072 if (*pch != 0)
1073 {
1074 if (VirtKeyMap[i].fAnsiKey)
1075 {
1076 *pch2 = *pch;
1077 *pch = K_NUL;
1078 }
1079
1080 return TRUE;
1081 }
1082 }
1083 }
1084
1085 i = win32_kbd_patch_key(pker);
1086
1087 if (i < 0)
1088 *pch = NUL;
1089 else
1090 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001091 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092
1093 if (pmodifiers != NULL)
1094 {
1095 /* Pass on the ALT key as a modifier, but only when not combined
1096 * with CTRL (which is ALTGR). */
1097 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1098 *pmodifiers |= MOD_MASK_ALT;
1099
1100 /* Pass on SHIFT only for special keys, because we don't know when
1101 * it's already included with the character. */
1102 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1103 *pmodifiers |= MOD_MASK_SHIFT;
1104
1105 /* Pass on CTRL only for non-special keys, because we don't know
1106 * when it's already included with the character. And not when
1107 * combined with ALT (which is ALTGR). */
1108 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1109 && *pch >= 0x20 && *pch < 0x80)
1110 *pmodifiers |= MOD_MASK_CTRL;
1111 }
1112 }
1113
1114 return (*pch != NUL);
1115}
1116
1117#ifdef _MSC_VER
1118# pragma optimize("", on)
1119#endif
1120
1121#endif /* FEAT_GUI_W32 */
1122
1123
1124#ifdef FEAT_MOUSE
1125
1126/*
1127 * For the GUI the mouse handling is in gui_w32.c.
1128 */
1129# ifdef FEAT_GUI_W32
1130 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001131mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001132{
1133}
1134# else
1135static int g_fMouseAvail = FALSE; /* mouse present */
1136static int g_fMouseActive = FALSE; /* mouse enabled */
1137static int g_nMouseClick = -1; /* mouse status */
1138static int g_xMouse; /* mouse x coordinate */
1139static int g_yMouse; /* mouse y coordinate */
1140
1141/*
1142 * Enable or disable mouse input
1143 */
1144 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001145mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146{
1147 DWORD cmodein;
1148
1149 if (!g_fMouseAvail)
1150 return;
1151
1152 g_fMouseActive = on;
1153 GetConsoleMode(g_hConIn, &cmodein);
1154
1155 if (g_fMouseActive)
1156 cmodein |= ENABLE_MOUSE_INPUT;
1157 else
1158 cmodein &= ~ENABLE_MOUSE_INPUT;
1159
1160 SetConsoleMode(g_hConIn, cmodein);
1161}
1162
Bram Moolenaar157d8132018-03-06 17:09:20 +01001163
1164#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1165/*
1166 * Called when 'balloonevalterm' changed.
1167 */
1168 void
1169mch_bevalterm_changed(void)
1170{
1171 mch_setmouse(g_fMouseActive);
1172}
1173#endif
1174
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175/*
1176 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1177 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1178 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1179 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1180 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1181 * and we return the mouse position in g_xMouse and g_yMouse.
1182 *
1183 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1184 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1185 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1186 *
1187 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1188 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1189 *
1190 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1191 * moves, even if it stays within the same character cell. We ignore
1192 * all MOUSE_MOVED messages if the position hasn't really changed, and
1193 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1194 * we're only interested in MOUSE_DRAG).
1195 *
1196 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1197 * 2-button mouses by pressing the left & right buttons simultaneously.
1198 * In practice, it's almost impossible to click both at the same time,
1199 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1200 * in such cases, if the user is clicking quickly.
1201 */
1202 static BOOL
1203decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001204 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001205{
1206 static int s_nOldButton = -1;
1207 static int s_nOldMouseClick = -1;
1208 static int s_xOldMouse = -1;
1209 static int s_yOldMouse = -1;
1210 static linenr_T s_old_topline = 0;
1211#ifdef FEAT_DIFF
1212 static int s_old_topfill = 0;
1213#endif
1214 static int s_cClicks = 1;
1215 static BOOL s_fReleased = TRUE;
1216 static DWORD s_dwLastClickTime = 0;
1217 static BOOL s_fNextIsMiddle = FALSE;
1218
1219 static DWORD cButtons = 0; /* number of buttons supported */
1220
1221 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1222 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1223 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1224 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1225
1226 int nButton;
1227
1228 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1229 cButtons = 2;
1230
1231 if (!g_fMouseAvail || !g_fMouseActive)
1232 {
1233 g_nMouseClick = -1;
1234 return FALSE;
1235 }
1236
1237 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1238 if (g_fJustGotFocus)
1239 {
1240 g_fJustGotFocus = FALSE;
1241 return FALSE;
1242 }
1243
1244 /* unprocessed mouse click? */
1245 if (g_nMouseClick != -1)
1246 return TRUE;
1247
1248 nButton = -1;
1249 g_xMouse = pmer->dwMousePosition.X;
1250 g_yMouse = pmer->dwMousePosition.Y;
1251
1252 if (pmer->dwEventFlags == MOUSE_MOVED)
1253 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001254 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255 * events even when the mouse moves only within a char cell.) */
1256 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1257 return FALSE;
1258 }
1259
1260 /* If no buttons are pressed... */
1261 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1262 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001263 nButton = MOUSE_RELEASE;
1264
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1266 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001267 {
1268#ifdef FEAT_BEVAL_TERM
1269 /* do return mouse move events when we want them */
1270 if (p_bevalterm)
1271 nButton = MOUSE_DRAG;
1272 else
1273#endif
1274 return FALSE;
1275 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001276
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277 s_fReleased = TRUE;
1278 }
1279 else /* one or more buttons pressed */
1280 {
1281 /* on a 2-button mouse, hold down left and right buttons
1282 * simultaneously to get MIDDLE. */
1283
1284 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1285 {
1286 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1287
1288 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001289 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001290 if (dwLR == LEFT || dwLR == RIGHT)
1291 {
1292 for (;;)
1293 {
1294 /* wait a short time for next input event */
1295 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1296 != WAIT_OBJECT_0)
1297 break;
1298 else
1299 {
1300 DWORD cRecords = 0;
1301 INPUT_RECORD ir;
1302 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1303
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001304 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001305
1306 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1307 || !(pmer2->dwButtonState & LEFT_RIGHT))
1308 break;
1309 else
1310 {
1311 if (pmer2->dwEventFlags != MOUSE_MOVED)
1312 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001313 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001314
1315 return decode_mouse_event(pmer2);
1316 }
1317 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1318 s_yOldMouse == pmer2->dwMousePosition.Y)
1319 {
1320 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001321 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001322
1323 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001324 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325
1326 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1327 break;
1328 }
1329 else
1330 break;
1331 }
1332 }
1333 }
1334 }
1335 }
1336
1337 if (s_fNextIsMiddle)
1338 {
1339 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1340 ? MOUSE_DRAG : MOUSE_MIDDLE;
1341 s_fNextIsMiddle = FALSE;
1342 }
1343 else if (cButtons == 2 &&
1344 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1345 {
1346 nButton = MOUSE_MIDDLE;
1347
1348 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1349 {
1350 s_fNextIsMiddle = TRUE;
1351 nButton = MOUSE_RELEASE;
1352 }
1353 }
1354 else if ((pmer->dwButtonState & LEFT) == LEFT)
1355 nButton = MOUSE_LEFT;
1356 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1357 nButton = MOUSE_MIDDLE;
1358 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1359 nButton = MOUSE_RIGHT;
1360
1361 if (! s_fReleased && ! s_fNextIsMiddle
1362 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1363 return FALSE;
1364
1365 s_fReleased = s_fNextIsMiddle;
1366 }
1367
1368 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1369 {
1370 /* button pressed or released, without mouse moving */
1371 if (nButton != -1 && nButton != MOUSE_RELEASE)
1372 {
1373 DWORD dwCurrentTime = GetTickCount();
1374
1375 if (s_xOldMouse != g_xMouse
1376 || s_yOldMouse != g_yMouse
1377 || s_nOldButton != nButton
1378 || s_old_topline != curwin->w_topline
1379#ifdef FEAT_DIFF
1380 || s_old_topfill != curwin->w_topfill
1381#endif
1382 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1383 {
1384 s_cClicks = 1;
1385 }
1386 else if (++s_cClicks > 4)
1387 {
1388 s_cClicks = 1;
1389 }
1390
1391 s_dwLastClickTime = dwCurrentTime;
1392 }
1393 }
1394 else if (pmer->dwEventFlags == MOUSE_MOVED)
1395 {
1396 if (nButton != -1 && nButton != MOUSE_RELEASE)
1397 nButton = MOUSE_DRAG;
1398
1399 s_cClicks = 1;
1400 }
1401
1402 if (nButton == -1)
1403 return FALSE;
1404
1405 if (nButton != MOUSE_RELEASE)
1406 s_nOldButton = nButton;
1407
1408 g_nMouseClick = nButton;
1409
1410 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1411 g_nMouseClick |= MOUSE_SHIFT;
1412 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1413 g_nMouseClick |= MOUSE_CTRL;
1414 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1415 g_nMouseClick |= MOUSE_ALT;
1416
1417 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1418 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1419
1420 /* only pass on interesting (i.e., different) mouse events */
1421 if (s_xOldMouse == g_xMouse
1422 && s_yOldMouse == g_yMouse
1423 && s_nOldMouseClick == g_nMouseClick)
1424 {
1425 g_nMouseClick = -1;
1426 return FALSE;
1427 }
1428
1429 s_xOldMouse = g_xMouse;
1430 s_yOldMouse = g_yMouse;
1431 s_old_topline = curwin->w_topline;
1432#ifdef FEAT_DIFF
1433 s_old_topfill = curwin->w_topfill;
1434#endif
1435 s_nOldMouseClick = g_nMouseClick;
1436
1437 return TRUE;
1438}
1439
1440# endif /* FEAT_GUI_W32 */
1441#endif /* FEAT_MOUSE */
1442
1443
1444#ifdef MCH_CURSOR_SHAPE
1445/*
1446 * Set the shape of the cursor.
1447 * 'thickness' can be from 1 (thin) to 99 (block)
1448 */
1449 static void
1450mch_set_cursor_shape(int thickness)
1451{
1452 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1453 ConsoleCursorInfo.dwSize = thickness;
1454 ConsoleCursorInfo.bVisible = s_cursor_visible;
1455
1456 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1457 if (s_cursor_visible)
1458 SetConsoleCursorPosition(g_hConOut, g_coord);
1459}
1460
1461 void
1462mch_update_cursor(void)
1463{
1464 int idx;
1465 int thickness;
1466
1467 /*
1468 * How the cursor is drawn depends on the current mode.
1469 */
1470 idx = get_shape_idx(FALSE);
1471
1472 if (shape_table[idx].shape == SHAPE_BLOCK)
1473 thickness = 99; /* 100 doesn't work on W95 */
1474 else
1475 thickness = shape_table[idx].percentage;
1476 mch_set_cursor_shape(thickness);
1477}
1478#endif
1479
1480#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1481/*
1482 * Handle FOCUS_EVENT.
1483 */
1484 static void
1485handle_focus_event(INPUT_RECORD ir)
1486{
1487 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1488 ui_focus_change((int)g_fJustGotFocus);
1489}
1490
1491/*
1492 * Wait until console input from keyboard or mouse is available,
1493 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001494 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495 * Return TRUE if something is available FALSE if not.
1496 */
1497 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001498WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499{
1500 DWORD dwNow = 0, dwEndTime = 0;
1501 INPUT_RECORD ir;
1502 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001503 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001504#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001505 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001506#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507
1508 if (msec > 0)
1509 /* Wait until the specified time has elapsed. */
1510 dwEndTime = GetTickCount() + msec;
1511 else if (msec < 0)
1512 /* Wait forever. */
1513 dwEndTime = INFINITE;
1514
1515 /* We need to loop until the end of the time period, because
1516 * we might get multiple unusable mouse events in that time.
1517 */
1518 for (;;)
1519 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001520 // Only process messages when waiting.
1521 if (msec != 0)
1522 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001523#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001524 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001525#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001526#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001527 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001528#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001530 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001532 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001533
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 if (0
1535#ifdef FEAT_MOUSE
1536 || g_nMouseClick != -1
1537#endif
1538#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001539 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540#endif
1541 )
1542 return TRUE;
1543
1544 if (msec > 0)
1545 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001546 /* If the specified wait time has passed, return. Beware that
1547 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001549 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 break;
1551 }
1552 if (msec != 0)
1553 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001554 DWORD dwWaitTime = dwEndTime - dwNow;
1555
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001556#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001557 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001558 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001559 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001560 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001561 /* If there is readahead then parse_queued_messages() timed out
1562 * and we should call it again soon. */
1563 if (channel_any_readahead())
1564 dwWaitTime = 10;
1565 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001566#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001567#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001568 if (p_beval && dwWaitTime > 100)
1569 /* The 'balloonexpr' may indirectly invoke a callback while
1570 * waiting for a character, need to check often. */
1571 dwWaitTime = 100;
1572#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001573#ifdef FEAT_MZSCHEME
1574 if (mzthreads_allowed() && p_mzq > 0
1575 && (msec < 0 || (long)dwWaitTime > p_mzq))
1576 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1577#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001578#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001579 // When waiting very briefly don't trigger timers.
1580 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001581 {
1582 long due_time;
1583
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001584 // Trigger timers and then get the time in msec until the next
1585 // one is due. Wait up to that time.
1586 due_time = check_due_timer();
1587 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001588 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001589 // timer may have used feedkeys().
1590 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001591 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001592 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1593 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001594 }
1595#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001596 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001598 // Wait for either an event on the console input or a
1599 // message in the client-server window.
1600 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1601 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001603 wait_for_single_object(g_hConIn, dwWaitTime)
1604 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001606 )
1607 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 }
1609
1610 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001611 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612
1613#ifdef FEAT_MBYTE_IME
1614 if (State & CMDLINE && msg_row == Rows - 1)
1615 {
1616 CONSOLE_SCREEN_BUFFER_INFO csbi;
1617
1618 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1619 {
1620 if (csbi.dwCursorPosition.Y != msg_row)
1621 {
1622 /* The screen is now messed up, must redraw the
1623 * command line and later all the windows. */
1624 redraw_all_later(CLEAR);
1625 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1626 redrawcmd();
1627 }
1628 }
1629 }
1630#endif
1631
1632 if (cRecords > 0)
1633 {
1634 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1635 {
1636#ifdef FEAT_MBYTE_IME
1637 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1638 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001639 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1641 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001642 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643 continue;
1644 }
1645#endif
1646 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1647 NULL, FALSE))
1648 return TRUE;
1649 }
1650
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001651 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652
1653 if (ir.EventType == FOCUS_EVENT)
1654 handle_focus_event(ir);
1655 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001656 {
1657 /* Only call shell_resized() when the size actually change to
1658 * avoid the screen is cleard. */
1659 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1660 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1661 shell_resized();
1662 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663#ifdef FEAT_MOUSE
1664 else if (ir.EventType == MOUSE_EVENT
1665 && decode_mouse_event(&ir.Event.MouseEvent))
1666 return TRUE;
1667#endif
1668 }
1669 else if (msec == 0)
1670 break;
1671 }
1672
1673#ifdef FEAT_CLIENTSERVER
1674 /* Something might have been received while we were waiting. */
1675 if (input_available())
1676 return TRUE;
1677#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001678
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679 return FALSE;
1680}
1681
1682#ifndef FEAT_GUI_MSWIN
1683/*
1684 * return non-zero if a character is available
1685 */
1686 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001687mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001689 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001691
1692# if defined(FEAT_TERMINAL) || defined(PROTO)
1693/*
1694 * Check for any pending input or messages.
1695 */
1696 int
1697mch_check_messages(void)
1698{
1699 return WaitForChar(0L, TRUE);
1700}
1701# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702#endif
1703
1704/*
1705 * Create the console input. Used when reading stdin doesn't work.
1706 */
1707 static void
1708create_conin(void)
1709{
1710 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1711 FILE_SHARE_READ|FILE_SHARE_WRITE,
1712 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001713 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 did_create_conin = TRUE;
1715}
1716
1717/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001718 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001720 static WCHAR
1721tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001723 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724
1725 for (;;)
1726 {
1727 INPUT_RECORD ir;
1728 DWORD cRecords = 0;
1729
1730#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001731 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732 if (input_available())
1733 return 0;
1734# ifdef FEAT_MOUSE
1735 if (g_nMouseClick != -1)
1736 return 0;
1737# endif
1738#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001739 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001740 {
1741 if (did_create_conin)
1742 read_error_exit();
1743 create_conin();
1744 continue;
1745 }
1746
1747 if (ir.EventType == KEY_EVENT)
1748 {
1749 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1750 pmodifiers, TRUE))
1751 return ch;
1752 }
1753 else if (ir.EventType == FOCUS_EVENT)
1754 handle_focus_event(ir);
1755 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1756 shell_resized();
1757#ifdef FEAT_MOUSE
1758 else if (ir.EventType == MOUSE_EVENT)
1759 {
1760 if (decode_mouse_event(&ir.Event.MouseEvent))
1761 return 0;
1762 }
1763#endif
1764 }
1765}
1766#endif /* !FEAT_GUI_W32 */
1767
1768
1769/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001770 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001771 * Get one or more characters from the keyboard or the mouse.
1772 * If time == 0, do not wait for characters.
1773 * If time == n, wait a short time for characters.
1774 * If time == -1, wait forever for characters.
1775 * Returns the number of characters read into buf.
1776 */
1777 int
1778mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001779 char_u *buf UNUSED,
1780 int maxlen UNUSED,
1781 long time UNUSED,
1782 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783{
1784#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1785
1786 int len;
1787 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788#define TYPEAHEADLEN 20
1789 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1790 static int typeaheadlen = 0;
1791
1792 /* First use any typeahead that was kept because "buf" was too small. */
1793 if (typeaheadlen > 0)
1794 goto theend;
1795
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 if (time >= 0)
1797 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001798 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800 }
1801 else /* time == -1, wait forever */
1802 {
1803 mch_set_winsize_now(); /* Allow winsize changes from now on */
1804
Bram Moolenaar3918c952005-03-15 22:34:55 +00001805 /*
1806 * If there is no character available within 2 seconds (default)
1807 * write the autoscript file to disk. Or cause the CursorHold event
1808 * to be triggered.
1809 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001810 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001812 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001814 buf[0] = K_SPECIAL;
1815 buf[1] = KS_EXTRA;
1816 buf[2] = (int)KE_CURSORHOLD;
1817 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001819 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820 }
1821 }
1822
1823 /*
1824 * Try to read as many characters as there are, until the buffer is full.
1825 */
1826
1827 /* we will get at least one key. Get more if they are available. */
1828 g_fCBrkPressed = FALSE;
1829
1830#ifdef MCH_WRITE_DUMP
1831 if (fdDump)
1832 fputc('[', fdDump);
1833#endif
1834
1835 /* Keep looping until there is something in the typeahead buffer and more
1836 * to get and still room in the buffer (up to two bytes for a char and
1837 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001838 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839 && typeaheadlen + 5 <= TYPEAHEADLEN)
1840 {
1841 if (typebuf_changed(tb_change_cnt))
1842 {
1843 /* "buf" may be invalid now if a client put something in the
1844 * typeahead buffer and "buf" is in the typeahead buffer. */
1845 typeaheadlen = 0;
1846 break;
1847 }
1848#ifdef FEAT_MOUSE
1849 if (g_nMouseClick != -1)
1850 {
1851# ifdef MCH_WRITE_DUMP
1852 if (fdDump)
1853 fprintf(fdDump, "{%02x @ %d, %d}",
1854 g_nMouseClick, g_xMouse, g_yMouse);
1855# endif
1856 typeahead[typeaheadlen++] = ESC + 128;
1857 typeahead[typeaheadlen++] = 'M';
1858 typeahead[typeaheadlen++] = g_nMouseClick;
1859 typeahead[typeaheadlen++] = g_xMouse + '!';
1860 typeahead[typeaheadlen++] = g_yMouse + '!';
1861 g_nMouseClick = -1;
1862 }
1863 else
1864#endif
1865 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001866 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867 int modifiers = 0;
1868
1869 c = tgetch(&modifiers, &ch2);
1870
1871 if (typebuf_changed(tb_change_cnt))
1872 {
1873 /* "buf" may be invalid now if a client put something in the
1874 * typeahead buffer and "buf" is in the typeahead buffer. */
1875 typeaheadlen = 0;
1876 break;
1877 }
1878
1879 if (c == Ctrl_C && ctrl_c_interrupts)
1880 {
1881#if defined(FEAT_CLIENTSERVER)
1882 trash_input_buf();
1883#endif
1884 got_int = TRUE;
1885 }
1886
1887#ifdef FEAT_MOUSE
1888 if (g_nMouseClick == -1)
1889#endif
1890 {
1891 int n = 1;
1892
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001893#ifdef FEAT_MBYTE
1894 if (ch2 == NUL)
1895 {
1896 int i;
1897 char_u *p;
1898 WCHAR ch[2];
1899
1900 ch[0] = c;
1901 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1902 {
1903 ch[1] = tgetch(&modifiers, &ch2);
1904 n++;
1905 }
1906 p = utf16_to_enc(ch, &n);
1907 if (p != NULL)
1908 {
1909 for (i = 0; i < n; i++)
1910 typeahead[typeaheadlen + i] = p[i];
1911 vim_free(p);
1912 }
1913 }
1914 else
1915#endif
1916 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917 if (ch2 != NUL)
1918 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001919 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001920 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001921 switch (ch2)
1922 {
1923 case (WCHAR)'\324': // SHIFT+Insert
1924 case (WCHAR)'\325': // CTRL+Insert
1925 case (WCHAR)'\327': // SHIFT+Delete
1926 case (WCHAR)'\330': // CTRL+Delete
1927 typeahead[typeaheadlen + n] = (char_u)ch2;
1928 n++;
1929 break;
1930
1931 default:
1932 typeahead[typeaheadlen + n] = 3;
1933 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1934 n += 2;
1935 break;
1936 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001937 }
1938 else
1939 {
1940 typeahead[typeaheadlen + n] = 3;
1941 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1942 n += 2;
1943 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001944 }
1945
Bram Moolenaar071d4272004-06-13 20:20:40 +00001946 /* Use the ALT key to set the 8th bit of the character
1947 * when it's one byte, the 8th bit isn't set yet and not
1948 * using a double-byte encoding (would become a lead
1949 * byte). */
1950 if ((modifiers & MOD_MASK_ALT)
1951 && n == 1
1952 && (typeahead[typeaheadlen] & 0x80) == 0
1953#ifdef FEAT_MBYTE
1954 && !enc_dbcs
1955#endif
1956 )
1957 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001958#ifdef FEAT_MBYTE
1959 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1960 typeahead + typeaheadlen);
1961#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001963#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 modifiers &= ~MOD_MASK_ALT;
1965 }
1966
1967 if (modifiers != 0)
1968 {
1969 /* Prepend modifiers to the character. */
1970 mch_memmove(typeahead + typeaheadlen + 3,
1971 typeahead + typeaheadlen, n);
1972 typeahead[typeaheadlen++] = K_SPECIAL;
1973 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1974 typeahead[typeaheadlen++] = modifiers;
1975 }
1976
1977 typeaheadlen += n;
1978
1979#ifdef MCH_WRITE_DUMP
1980 if (fdDump)
1981 fputc(c, fdDump);
1982#endif
1983 }
1984 }
1985 }
1986
1987#ifdef MCH_WRITE_DUMP
1988 if (fdDump)
1989 {
1990 fputs("]\n", fdDump);
1991 fflush(fdDump);
1992 }
1993#endif
1994
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995theend:
1996 /* Move typeahead to "buf", as much as fits. */
1997 len = 0;
1998 while (len < maxlen && typeaheadlen > 0)
1999 {
2000 buf[len++] = typeahead[0];
2001 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2002 }
2003 return len;
2004
2005#else /* FEAT_GUI_W32 */
2006 return 0;
2007#endif /* FEAT_GUI_W32 */
2008}
2009
Bram Moolenaar82881492012-11-20 16:53:39 +01002010#ifndef PROTO
2011# ifndef __MINGW32__
2012# include <shellapi.h> /* required for FindExecutable() */
2013# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014#endif
2015
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002016/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002017 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2018 * If "use_path" is FALSE: Return TRUE if "name" exists.
2019 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2020 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002021 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002022 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002024executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002026 char *dum;
2027 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002028 char *curpath, *newpath;
2029 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030
Bram Moolenaar43663192017-03-05 14:29:12 +01002031 if (!use_path)
2032 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002033 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002034 {
2035 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002036 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002037 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002038 *path = vim_strsave((char_u *)name);
2039 else
2040 *path = FullName_save((char_u *)name, FALSE);
2041 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002042 return TRUE;
2043 }
2044 return FALSE;
2045 }
2046
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002047#ifdef FEAT_MBYTE
2048 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002050 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002051 WCHAR fnamew[_MAX_PATH];
2052 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002053 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002054
2055 if (p != NULL)
2056 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002057 wcurpath = _wgetenv(L"PATH");
2058 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2059 * sizeof(WCHAR));
2060 if (wnewpath == NULL)
2061 return FALSE;
2062 wcscpy(wnewpath, L".;");
2063 wcscat(wnewpath, wcurpath);
2064 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2065 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002066 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002067 if (n == 0)
2068 return FALSE;
2069 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2070 return FALSE;
2071 if (path != NULL)
2072 *path = utf16_to_enc(fnamew, NULL);
2073 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002074 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002076#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002077
2078 curpath = getenv("PATH");
2079 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2080 if (newpath == NULL)
2081 return FALSE;
2082 STRCPY(newpath, ".;");
2083 STRCAT(newpath, curpath);
2084 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2085 vim_free(newpath);
2086 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002087 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002088 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002089 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002090 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002091 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002092 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093}
2094
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002095#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002096 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002097/*
2098 * Bad parameter handler.
2099 *
2100 * Certain MS CRT functions will intentionally crash when passed invalid
2101 * parameters to highlight possible security holes. Setting this function as
2102 * the bad parameter handler will prevent the crash.
2103 *
2104 * In debug builds the parameters contain CRT information that might help track
2105 * down the source of a problem, but in non-debug builds the arguments are all
2106 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2107 * worth allowing these to make debugging of issues easier.
2108 */
2109 static void
2110bad_param_handler(const wchar_t *expression,
2111 const wchar_t *function,
2112 const wchar_t *file,
2113 unsigned int line,
2114 uintptr_t pReserved)
2115{
2116}
2117
2118# define SET_INVALID_PARAM_HANDLER \
2119 ((void)_set_invalid_parameter_handler(bad_param_handler))
2120#else
2121# define SET_INVALID_PARAM_HANDLER
2122#endif
2123
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124#ifdef FEAT_GUI_W32
2125
2126/*
2127 * GUI version of mch_init().
2128 */
2129 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002130mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131{
2132#ifndef __MINGW32__
2133 extern int _fmode;
2134#endif
2135
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002136 /* Silently handle invalid parameters to CRT functions */
2137 SET_INVALID_PARAM_HANDLER;
2138
Bram Moolenaar071d4272004-06-13 20:20:40 +00002139 /* Let critical errors result in a failure, not in a dialog box. Required
2140 * for the timestamp test to work on removed floppies. */
2141 SetErrorMode(SEM_FAILCRITICALERRORS);
2142
2143 _fmode = O_BINARY; /* we do our own CR-LF translation */
2144
2145 /* Specify window size. Is there a place to get the default from? */
2146 Rows = 25;
2147 Columns = 80;
2148
2149 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002150 {
2151 char_u vimrun_location[_MAX_PATH + 4];
2152
2153 /* First try in same directory as gvim.exe */
2154 STRCPY(vimrun_location, exe_name);
2155 STRCPY(gettail(vimrun_location), "vimrun.exe");
2156 if (mch_getperm(vimrun_location) >= 0)
2157 {
2158 if (*skiptowhite(vimrun_location) != NUL)
2159 {
2160 /* Enclose path with white space in double quotes. */
2161 mch_memmove(vimrun_location + 1, vimrun_location,
2162 STRLEN(vimrun_location) + 1);
2163 *vimrun_location = '"';
2164 STRCPY(gettail(vimrun_location), "vimrun\" ");
2165 }
2166 else
2167 STRCPY(gettail(vimrun_location), "vimrun ");
2168
2169 vimrun_path = (char *)vim_strsave(vimrun_location);
2170 s_dont_use_vimrun = FALSE;
2171 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002172 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173 s_dont_use_vimrun = FALSE;
2174
2175 /* Don't give the warning for a missing vimrun.exe right now, but only
2176 * when vimrun was supposed to be used. Don't bother people that do
2177 * not need vimrun.exe. */
2178 if (s_dont_use_vimrun)
2179 need_vimrun_warning = TRUE;
2180 }
2181
2182 /*
2183 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2184 * Otherwise the default "findstr /n" is used.
2185 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002186 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002187 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2188
2189#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002190 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002191#endif
2192}
2193
2194
2195#else /* FEAT_GUI_W32 */
2196
2197#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2198#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2199
2200/*
2201 * ClearConsoleBuffer()
2202 * Description:
2203 * Clears the entire contents of the console screen buffer, using the
2204 * specified attribute.
2205 * Returns:
2206 * TRUE on success
2207 */
2208 static BOOL
2209ClearConsoleBuffer(WORD wAttribute)
2210{
2211 CONSOLE_SCREEN_BUFFER_INFO csbi;
2212 COORD coord;
2213 DWORD NumCells, dummy;
2214
2215 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2216 return FALSE;
2217
2218 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2219 coord.X = 0;
2220 coord.Y = 0;
2221 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2222 coord, &dummy))
2223 {
2224 return FALSE;
2225 }
2226 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2227 coord, &dummy))
2228 {
2229 return FALSE;
2230 }
2231
2232 return TRUE;
2233}
2234
2235/*
2236 * FitConsoleWindow()
2237 * Description:
2238 * Checks if the console window will fit within given buffer dimensions.
2239 * Also, if requested, will shrink the window to fit.
2240 * Returns:
2241 * TRUE on success
2242 */
2243 static BOOL
2244FitConsoleWindow(
2245 COORD dwBufferSize,
2246 BOOL WantAdjust)
2247{
2248 CONSOLE_SCREEN_BUFFER_INFO csbi;
2249 COORD dwWindowSize;
2250 BOOL NeedAdjust = FALSE;
2251
2252 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2253 {
2254 /*
2255 * A buffer resize will fail if the current console window does
2256 * not lie completely within that buffer. To avoid this, we might
2257 * have to move and possibly shrink the window.
2258 */
2259 if (csbi.srWindow.Right >= dwBufferSize.X)
2260 {
2261 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2262 if (dwWindowSize.X > dwBufferSize.X)
2263 dwWindowSize.X = dwBufferSize.X;
2264 csbi.srWindow.Right = dwBufferSize.X - 1;
2265 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2266 NeedAdjust = TRUE;
2267 }
2268 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2269 {
2270 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2271 if (dwWindowSize.Y > dwBufferSize.Y)
2272 dwWindowSize.Y = dwBufferSize.Y;
2273 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2274 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2275 NeedAdjust = TRUE;
2276 }
2277 if (NeedAdjust && WantAdjust)
2278 {
2279 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2280 return FALSE;
2281 }
2282 return TRUE;
2283 }
2284
2285 return FALSE;
2286}
2287
2288typedef struct ConsoleBufferStruct
2289{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002290 BOOL IsValid;
2291 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002292 PCHAR_INFO Buffer;
2293 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002294 PSMALL_RECT Regions;
2295 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296} ConsoleBuffer;
2297
2298/*
2299 * SaveConsoleBuffer()
2300 * Description:
2301 * Saves important information about the console buffer, including the
2302 * actual buffer contents. The saved information is suitable for later
2303 * restoration by RestoreConsoleBuffer().
2304 * Returns:
2305 * TRUE if all information was saved; FALSE otherwise
2306 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2307 */
2308 static BOOL
2309SaveConsoleBuffer(
2310 ConsoleBuffer *cb)
2311{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002312 DWORD NumCells;
2313 COORD BufferCoord;
2314 SMALL_RECT ReadRegion;
2315 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002316 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002317
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 if (cb == NULL)
2319 return FALSE;
2320
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002321 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322 {
2323 cb->IsValid = FALSE;
2324 return FALSE;
2325 }
2326 cb->IsValid = TRUE;
2327
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002328 /*
2329 * Allocate a buffer large enough to hold the entire console screen
2330 * buffer. If this ConsoleBuffer structure has already been initialized
2331 * with a buffer of the correct size, then just use that one.
2332 */
2333 if (!cb->IsValid || cb->Buffer == NULL ||
2334 cb->BufferSize.X != cb->Info.dwSize.X ||
2335 cb->BufferSize.Y != cb->Info.dwSize.Y)
2336 {
2337 cb->BufferSize.X = cb->Info.dwSize.X;
2338 cb->BufferSize.Y = cb->Info.dwSize.Y;
2339 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2340 vim_free(cb->Buffer);
2341 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2342 if (cb->Buffer == NULL)
2343 return FALSE;
2344 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345
2346 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002347 * We will now copy the console screen buffer into our buffer.
2348 * ReadConsoleOutput() seems to be limited as far as how much you
2349 * can read at a time. Empirically, this number seems to be about
2350 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2351 * in chunks until it is all copied. The chunks will all have the
2352 * same horizontal characteristics, so initialize them now. The
2353 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002355 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002356 ReadRegion.Left = 0;
2357 ReadRegion.Right = cb->Info.dwSize.X - 1;
2358 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002359
2360 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2361 if (cb->Regions == NULL || numregions != cb->NumRegions)
2362 {
2363 cb->NumRegions = numregions;
2364 vim_free(cb->Regions);
2365 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2366 if (cb->Regions == NULL)
2367 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002368 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002369 return FALSE;
2370 }
2371 }
2372
2373 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002375 /*
2376 * Read into position (0, Y) in our buffer.
2377 */
2378 BufferCoord.Y = Y;
2379 /*
2380 * Read the region whose top left corner is (0, Y) and whose bottom
2381 * right corner is (width - 1, Y + Y_incr - 1). This should define
2382 * a region of size width by Y_incr. Don't worry if this region is
2383 * too large for the remaining buffer; it will be cropped.
2384 */
2385 ReadRegion.Top = Y;
2386 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002387 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002388 cb->Buffer, /* our buffer */
2389 cb->BufferSize, /* dimensions of our buffer */
2390 BufferCoord, /* offset in our buffer */
2391 &ReadRegion)) /* region to save */
2392 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002393 VIM_CLEAR(cb->Buffer);
2394 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002395 return FALSE;
2396 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002397 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 }
2399
2400 return TRUE;
2401}
2402
2403/*
2404 * RestoreConsoleBuffer()
2405 * Description:
2406 * Restores important information about the console buffer, including the
2407 * actual buffer contents, if desired. The information to restore is in
2408 * the same format used by SaveConsoleBuffer().
2409 * Returns:
2410 * TRUE on success
2411 */
2412 static BOOL
2413RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002414 ConsoleBuffer *cb,
2415 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002417 COORD BufferCoord;
2418 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002419 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420
2421 if (cb == NULL || !cb->IsValid)
2422 return FALSE;
2423
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002424 /*
2425 * Before restoring the buffer contents, clear the current buffer, and
2426 * restore the cursor position and window information. Doing this now
2427 * prevents old buffer contents from "flashing" onto the screen.
2428 */
2429 if (RestoreScreen)
2430 ClearConsoleBuffer(cb->Info.wAttributes);
2431
2432 FitConsoleWindow(cb->Info.dwSize, TRUE);
2433 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2434 return FALSE;
2435 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2436 return FALSE;
2437
2438 if (!RestoreScreen)
2439 {
2440 /*
2441 * No need to restore the screen buffer contents, so we're done.
2442 */
2443 return TRUE;
2444 }
2445
2446 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2447 return FALSE;
2448 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2449 return FALSE;
2450
2451 /*
2452 * Restore the screen buffer contents.
2453 */
2454 if (cb->Buffer != NULL)
2455 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002456 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002457 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002458 BufferCoord.X = cb->Regions[i].Left;
2459 BufferCoord.Y = cb->Regions[i].Top;
2460 WriteRegion = cb->Regions[i];
2461 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2462 cb->Buffer, /* our buffer */
2463 cb->BufferSize, /* dimensions of our buffer */
2464 BufferCoord, /* offset in our buffer */
2465 &WriteRegion)) /* region to restore */
2466 {
2467 return FALSE;
2468 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002469 }
2470 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471
2472 return TRUE;
2473}
2474
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002475#define FEAT_RESTORE_ORIG_SCREEN
2476#ifdef FEAT_RESTORE_ORIG_SCREEN
2477static ConsoleBuffer g_cbOrig = { 0 };
2478#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479static ConsoleBuffer g_cbNonTermcap = { 0 };
2480static ConsoleBuffer g_cbTermcap = { 0 };
2481
2482#ifdef FEAT_TITLE
2483#ifdef __BORLANDC__
2484typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2485#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002486typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487#endif
2488char g_szOrigTitle[256] = { 0 };
2489HWND g_hWnd = NULL; /* also used in os_mswin.c */
2490static HICON g_hOrigIconSmall = NULL;
2491static HICON g_hOrigIcon = NULL;
2492static HICON g_hVimIcon = NULL;
2493static BOOL g_fCanChangeIcon = FALSE;
2494
2495/* ICON* are not defined in VC++ 4.0 */
2496#ifndef ICON_SMALL
2497#define ICON_SMALL 0
2498#endif
2499#ifndef ICON_BIG
2500#define ICON_BIG 1
2501#endif
2502/*
2503 * GetConsoleIcon()
2504 * Description:
2505 * Attempts to retrieve the small icon and/or the big icon currently in
2506 * use by a given window.
2507 * Returns:
2508 * TRUE on success
2509 */
2510 static BOOL
2511GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002512 HWND hWnd,
2513 HICON *phIconSmall,
2514 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515{
2516 if (hWnd == NULL)
2517 return FALSE;
2518
2519 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002520 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2521 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002523 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2524 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 return TRUE;
2526}
2527
2528/*
2529 * SetConsoleIcon()
2530 * Description:
2531 * Attempts to change the small icon and/or the big icon currently in
2532 * use by a given window.
2533 * Returns:
2534 * TRUE on success
2535 */
2536 static BOOL
2537SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002538 HWND hWnd,
2539 HICON hIconSmall,
2540 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 if (hWnd == NULL)
2543 return FALSE;
2544
2545 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002546 SendMessage(hWnd, WM_SETICON,
2547 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002549 SendMessage(hWnd, WM_SETICON,
2550 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 return TRUE;
2552}
2553
2554/*
2555 * SaveConsoleTitleAndIcon()
2556 * Description:
2557 * Saves the current console window title in g_szOrigTitle, for later
2558 * restoration. Also, attempts to obtain a handle to the console window,
2559 * and use it to save the small and big icons currently in use by the
2560 * console window. This is not always possible on some versions of Windows;
2561 * nor is it possible when running Vim remotely using Telnet (since the
2562 * console window the user sees is owned by a remote process).
2563 */
2564 static void
2565SaveConsoleTitleAndIcon(void)
2566{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567 /* Save the original title. */
2568 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2569 return;
2570
2571 /*
2572 * Obtain a handle to the console window using GetConsoleWindow() from
2573 * KERNEL32.DLL; we need to handle in order to change the window icon.
2574 * This function only exists on NT-based Windows, starting with Windows
2575 * 2000. On older operating systems, we can't change the window icon
2576 * anyway.
2577 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002578 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002579 if (g_hWnd == NULL)
2580 return;
2581
2582 /* Save the original console window icon. */
2583 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2584 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2585 return;
2586
2587 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002588 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002589 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 if (g_hVimIcon != NULL)
2591 g_fCanChangeIcon = TRUE;
2592}
2593#endif
2594
2595static int g_fWindInitCalled = FALSE;
2596static int g_fTermcapMode = FALSE;
2597static CONSOLE_CURSOR_INFO g_cci;
2598static DWORD g_cmodein = 0;
2599static DWORD g_cmodeout = 0;
2600
2601/*
2602 * non-GUI version of mch_init().
2603 */
2604 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002605mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002607#ifndef FEAT_RESTORE_ORIG_SCREEN
2608 CONSOLE_SCREEN_BUFFER_INFO csbi;
2609#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610#ifndef __MINGW32__
2611 extern int _fmode;
2612#endif
2613
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002614 /* Silently handle invalid parameters to CRT functions */
2615 SET_INVALID_PARAM_HANDLER;
2616
Bram Moolenaar071d4272004-06-13 20:20:40 +00002617 /* Let critical errors result in a failure, not in a dialog box. Required
2618 * for the timestamp test to work on removed floppies. */
2619 SetErrorMode(SEM_FAILCRITICALERRORS);
2620
2621 _fmode = O_BINARY; /* we do our own CR-LF translation */
2622 out_flush();
2623
2624 /* Obtain handles for the standard Console I/O devices */
2625 if (read_cmd_fd == 0)
2626 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2627 else
2628 create_conin();
2629 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2630
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002631#ifdef FEAT_RESTORE_ORIG_SCREEN
2632 /* Save the initial console buffer for later restoration */
2633 SaveConsoleBuffer(&g_cbOrig);
2634 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2635#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002636 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002637 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2638 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2639#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002640 if (cterm_normal_fg_color == 0)
2641 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2642 if (cterm_normal_bg_color == 0)
2643 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2644
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002645 // Fg and Bg color index nunmber at startup
2646 g_color_index_fg = g_attrDefault & 0xf;
2647 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2648
Bram Moolenaar071d4272004-06-13 20:20:40 +00002649 /* set termcap codes to current text attributes */
2650 update_tcap(g_attrCurrent);
2651
2652 GetConsoleCursorInfo(g_hConOut, &g_cci);
2653 GetConsoleMode(g_hConIn, &g_cmodein);
2654 GetConsoleMode(g_hConOut, &g_cmodeout);
2655
2656#ifdef FEAT_TITLE
2657 SaveConsoleTitleAndIcon();
2658 /*
2659 * Set both the small and big icons of the console window to Vim's icon.
2660 * Note that Vim presently only has one size of icon (32x32), but it
2661 * automatically gets scaled down to 16x16 when setting the small icon.
2662 */
2663 if (g_fCanChangeIcon)
2664 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2665#endif
2666
2667 ui_get_shellsize();
2668
2669#ifdef MCH_WRITE_DUMP
2670 fdDump = fopen("dump", "wt");
2671
2672 if (fdDump)
2673 {
2674 time_t t;
2675
2676 time(&t);
2677 fputs(ctime(&t), fdDump);
2678 fflush(fdDump);
2679 }
2680#endif
2681
2682 g_fWindInitCalled = TRUE;
2683
2684#ifdef FEAT_MOUSE
2685 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2686#endif
2687
2688#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002689 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002691
2692 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693}
2694
2695/*
2696 * non-GUI version of mch_exit().
2697 * Shut down and exit with status `r'
2698 * Careful: mch_exit() may be called before mch_init()!
2699 */
2700 void
2701mch_exit(int r)
2702{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002703 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002705 vtp_exit();
2706
Bram Moolenaar955f1982017-02-05 15:10:51 +01002707 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708 if (g_fWindInitCalled)
2709 settmode(TMODE_COOK);
2710
2711 ml_close_all(TRUE); /* remove all memfiles */
2712
2713 if (g_fWindInitCalled)
2714 {
2715#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002716 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 /*
2718 * Restore both the small and big icons of the console window to
2719 * what they were at startup. Don't do this when the window is
2720 * closed, Vim would hang here.
2721 */
2722 if (g_fCanChangeIcon && !g_fForceExit)
2723 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2724#endif
2725
2726#ifdef MCH_WRITE_DUMP
2727 if (fdDump)
2728 {
2729 time_t t;
2730
2731 time(&t);
2732 fputs(ctime(&t), fdDump);
2733 fclose(fdDump);
2734 }
2735 fdDump = NULL;
2736#endif
2737 }
2738
2739 SetConsoleCursorInfo(g_hConOut, &g_cci);
2740 SetConsoleMode(g_hConIn, g_cmodein);
2741 SetConsoleMode(g_hConOut, g_cmodeout);
2742
2743#ifdef DYNAMIC_GETTEXT
2744 dyn_libintl_end();
2745#endif
2746
2747 exit(r);
2748}
2749#endif /* !FEAT_GUI_W32 */
2750
Bram Moolenaar071d4272004-06-13 20:20:40 +00002751/*
2752 * Do we have an interactive window?
2753 */
2754 int
2755mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002756 int argc UNUSED,
2757 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002758{
2759 get_exe_name();
2760
2761#ifdef FEAT_GUI_W32
2762 return OK; /* GUI always has a tty */
2763#else
2764 if (isatty(1))
2765 return OK;
2766 return FAIL;
2767#endif
2768}
2769
2770
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002771#ifdef FEAT_MBYTE
2772/*
2773 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2774 * if it already exists. When "len" is > 0, also expand short to long
2775 * filenames.
2776 * Return FAIL if wide functions are not available, OK otherwise.
2777 * NOTE: much of this is identical to fname_case(), keep in sync!
2778 */
2779 static int
2780fname_casew(
2781 WCHAR *name,
2782 int len)
2783{
2784 WCHAR szTrueName[_MAX_PATH + 2];
2785 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2786 WCHAR *ptrue, *ptruePrev;
2787 WCHAR *porig, *porigPrev;
2788 int flen;
2789 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002790 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002791 int c;
2792 int slen;
2793
2794 flen = (int)wcslen(name);
2795 if (flen > _MAX_PATH)
2796 return OK;
2797
2798 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2799
2800 /* Build the new name in szTrueName[] one component at a time. */
2801 porig = name;
2802 ptrue = szTrueName;
2803
2804 if (iswalpha(porig[0]) && porig[1] == L':')
2805 {
2806 /* copy leading drive letter */
2807 *ptrue++ = *porig++;
2808 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002809 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002810 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002811
2812 while (*porig != NUL)
2813 {
2814 /* copy \ characters */
2815 while (*porig == psepc)
2816 *ptrue++ = *porig++;
2817
2818 ptruePrev = ptrue;
2819 porigPrev = porig;
2820 while (*porig != NUL && *porig != psepc)
2821 {
2822 *ptrue++ = *porig++;
2823 }
2824 *ptrue = NUL;
2825
2826 /* To avoid a slow failure append "\*" when searching a directory,
2827 * server or network share. */
2828 wcscpy(szTrueNameTemp, szTrueName);
2829 slen = (int)wcslen(szTrueNameTemp);
2830 if (*porig == psepc && slen + 2 < _MAX_PATH)
2831 wcscpy(szTrueNameTemp + slen, L"\\*");
2832
2833 /* Skip "", "." and "..". */
2834 if (ptrue > ptruePrev
2835 && (ptruePrev[0] != L'.'
2836 || (ptruePrev[1] != NUL
2837 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2838 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2839 != INVALID_HANDLE_VALUE)
2840 {
2841 c = *porig;
2842 *porig = NUL;
2843
2844 /* Only use the match when it's the same name (ignoring case) or
2845 * expansion is allowed and there is a match with the short name
2846 * and there is enough room. */
2847 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2848 || (len > 0
2849 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2850 && (int)(ptruePrev - szTrueName)
2851 + (int)wcslen(fb.cFileName) < len)))
2852 {
2853 wcscpy(ptruePrev, fb.cFileName);
2854
2855 /* Look for exact match and prefer it if found. Must be a
2856 * long name, otherwise there would be only one match. */
2857 while (FindNextFileW(hFind, &fb))
2858 {
2859 if (*fb.cAlternateFileName != NUL
2860 && (wcscoll(porigPrev, fb.cFileName) == 0
2861 || (len > 0
2862 && (_wcsicoll(porigPrev,
2863 fb.cAlternateFileName) == 0
2864 && (int)(ptruePrev - szTrueName)
2865 + (int)wcslen(fb.cFileName) < len))))
2866 {
2867 wcscpy(ptruePrev, fb.cFileName);
2868 break;
2869 }
2870 }
2871 }
2872 FindClose(hFind);
2873 *porig = c;
2874 ptrue = ptruePrev + wcslen(ptruePrev);
2875 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002876 }
2877
2878 wcscpy(name, szTrueName);
2879 return OK;
2880}
2881#endif
2882
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883/*
2884 * fname_case(): Set the case of the file name, if it already exists.
2885 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002886 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887 */
2888 void
2889fname_case(
2890 char_u *name,
2891 int len)
2892{
2893 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002894 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895 char *ptrue, *ptruePrev;
2896 char *porig, *porigPrev;
2897 int flen;
2898 WIN32_FIND_DATA fb;
2899 HANDLE hFind;
2900 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002901 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002902
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002903 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002904 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905 return;
2906
2907 slash_adjust(name);
2908
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002909#ifdef FEAT_MBYTE
2910 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2911 {
2912 WCHAR *p = enc_to_utf16(name, NULL);
2913
2914 if (p != NULL)
2915 {
2916 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002917 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002918
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002919 wcsncpy(buf, p, _MAX_PATH);
2920 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002921 vim_free(p);
2922
2923 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2924 {
2925 q = utf16_to_enc(buf, NULL);
2926 if (q != NULL)
2927 {
2928 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2929 vim_free(q);
2930 return;
2931 }
2932 }
2933 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002934 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002935 }
2936#endif
2937
2938 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2939 * So we should check this after calling wide function. */
2940 if (flen > _MAX_PATH)
2941 return;
2942
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002944 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945 ptrue = szTrueName;
2946
2947 if (isalpha(porig[0]) && porig[1] == ':')
2948 {
2949 /* copy leading drive letter */
2950 *ptrue++ = *porig++;
2951 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002953 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954
2955 while (*porig != NUL)
2956 {
2957 /* copy \ characters */
2958 while (*porig == psepc)
2959 *ptrue++ = *porig++;
2960
2961 ptruePrev = ptrue;
2962 porigPrev = porig;
2963 while (*porig != NUL && *porig != psepc)
2964 {
2965#ifdef FEAT_MBYTE
2966 int l;
2967
2968 if (enc_dbcs)
2969 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002970 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 while (--l >= 0)
2972 *ptrue++ = *porig++;
2973 }
2974 else
2975#endif
2976 *ptrue++ = *porig++;
2977 }
2978 *ptrue = NUL;
2979
Bram Moolenaar464c9252010-10-13 20:37:41 +02002980 /* To avoid a slow failure append "\*" when searching a directory,
2981 * server or network share. */
2982 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002983 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002984 if (*porig == psepc && slen + 2 < _MAX_PATH)
2985 STRCPY(szTrueNameTemp + slen, "\\*");
2986
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 /* Skip "", "." and "..". */
2988 if (ptrue > ptruePrev
2989 && (ptruePrev[0] != '.'
2990 || (ptruePrev[1] != NUL
2991 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002992 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993 != INVALID_HANDLE_VALUE)
2994 {
2995 c = *porig;
2996 *porig = NUL;
2997
2998 /* Only use the match when it's the same name (ignoring case) or
2999 * expansion is allowed and there is a match with the short name
3000 * and there is enough room. */
3001 if (_stricoll(porigPrev, fb.cFileName) == 0
3002 || (len > 0
3003 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
3004 && (int)(ptruePrev - szTrueName)
3005 + (int)strlen(fb.cFileName) < len)))
3006 {
3007 STRCPY(ptruePrev, fb.cFileName);
3008
3009 /* Look for exact match and prefer it if found. Must be a
3010 * long name, otherwise there would be only one match. */
3011 while (FindNextFile(hFind, &fb))
3012 {
3013 if (*fb.cAlternateFileName != NUL
3014 && (strcoll(porigPrev, fb.cFileName) == 0
3015 || (len > 0
3016 && (_stricoll(porigPrev,
3017 fb.cAlternateFileName) == 0
3018 && (int)(ptruePrev - szTrueName)
3019 + (int)strlen(fb.cFileName) < len))))
3020 {
3021 STRCPY(ptruePrev, fb.cFileName);
3022 break;
3023 }
3024 }
3025 }
3026 FindClose(hFind);
3027 *porig = c;
3028 ptrue = ptruePrev + strlen(ptruePrev);
3029 }
3030 }
3031
3032 STRCPY(name, szTrueName);
3033}
3034
3035
3036/*
3037 * Insert user name in s[len].
3038 */
3039 int
3040mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003041 char_u *s,
3042 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003044 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045 DWORD cch = sizeof szUserName;
3046
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003047#ifdef FEAT_MBYTE
3048 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3049 {
3050 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3051 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3052
3053 if (GetUserNameW(wszUserName, &wcch))
3054 {
3055 char_u *p = utf16_to_enc(wszUserName, NULL);
3056
3057 if (p != NULL)
3058 {
3059 vim_strncpy(s, p, len - 1);
3060 vim_free(p);
3061 return OK;
3062 }
3063 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003064 }
3065#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066 if (GetUserName(szUserName, &cch))
3067 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003068 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069 return OK;
3070 }
3071 s[0] = NUL;
3072 return FAIL;
3073}
3074
3075
3076/*
3077 * Insert host name in s[len].
3078 */
3079 void
3080mch_get_host_name(
3081 char_u *s,
3082 int len)
3083{
3084 DWORD cch = len;
3085
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003086#ifdef FEAT_MBYTE
3087 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3088 {
3089 WCHAR wszHostName[256 + 1];
3090 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3091
3092 if (GetComputerNameW(wszHostName, &wcch))
3093 {
3094 char_u *p = utf16_to_enc(wszHostName, NULL);
3095
3096 if (p != NULL)
3097 {
3098 vim_strncpy(s, p, len - 1);
3099 vim_free(p);
3100 return;
3101 }
3102 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003103 }
3104#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003105 if (!GetComputerName((LPSTR)s, &cch))
3106 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107}
3108
3109
3110/*
3111 * return process ID
3112 */
3113 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003114mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115{
3116 return (long)GetCurrentProcessId();
3117}
3118
3119
3120/*
3121 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3122 * Return OK for success, FAIL for failure.
3123 */
3124 int
3125mch_dirname(
3126 char_u *buf,
3127 int len)
3128{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003129 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003130 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003131
Bram Moolenaar071d4272004-06-13 20:20:40 +00003132 /*
3133 * Originally this was:
3134 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3135 * But the Win32s known bug list says that getcwd() doesn't work
3136 * so use the Win32 system call instead. <Negri>
3137 */
3138#ifdef FEAT_MBYTE
3139 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3140 {
3141 WCHAR wbuf[_MAX_PATH + 1];
3142
3143 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3144 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003145 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003146 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003147
3148 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003149 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003150 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003151 if (STRLEN(p) >= (size_t)len)
3152 {
3153 // long path name is too long, fall back to short one
3154 vim_free(p);
3155 p = NULL;
3156 }
3157 }
3158 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003159 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160
3161 if (p != NULL)
3162 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003163 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003164 vim_free(p);
3165 return OK;
3166 }
3167 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003168 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169 }
3170#endif
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003171 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3172 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003173 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3174 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3175 // Failed to get long path name or it's too long: fall back to the
3176 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003177 return OK;
3178
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003179 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003180 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181}
3182
3183/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003184 * Get file permissions for "name".
3185 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186 */
3187 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003188mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003190 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003191 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003193 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003194 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195}
3196
3197
3198/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003199 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003200 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003201 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202 */
3203 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003204mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003206 long n = -1;
3207
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208#ifdef FEAT_MBYTE
3209 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3210 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003211 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212
3213 if (p != NULL)
3214 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003215 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003216 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003217 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003218 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219 }
3220 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003221 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003223 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003224 if (n == -1)
3225 return FAIL;
3226
3227 win32_set_archive(name);
3228
3229 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003230}
3231
3232/*
3233 * Set hidden flag for "name".
3234 */
3235 void
3236mch_hide(char_u *name)
3237{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003238 int attrs = win32_getattrs(name);
3239 if (attrs == -1)
3240 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003241
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003242 attrs |= FILE_ATTRIBUTE_HIDDEN;
3243 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244}
3245
3246/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003247 * Return TRUE if file "name" exists and is hidden.
3248 */
3249 int
3250mch_ishidden(char_u *name)
3251{
3252 int f = win32_getattrs(name);
3253
3254 if (f == -1)
3255 return FALSE; /* file does not exist at all */
3256
3257 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3258}
3259
3260/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 * return TRUE if "name" is a directory
3262 * return FALSE if "name" is not a directory or upon error
3263 */
3264 int
3265mch_isdir(char_u *name)
3266{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003267 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003268
3269 if (f == -1)
3270 return FALSE; /* file does not exist at all */
3271
3272 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3273}
3274
3275/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003276 * return TRUE if "name" is a directory, NOT a symlink to a directory
3277 * return FALSE if "name" is not a directory
3278 * return FALSE for error
3279 */
3280 int
3281mch_isrealdir(char_u *name)
3282{
3283 return mch_isdir(name) && !mch_is_symbolic_link(name);
3284}
3285
3286/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003287 * Create directory "name".
3288 * Return 0 on success, -1 on error.
3289 */
3290 int
3291mch_mkdir(char_u *name)
3292{
3293#ifdef FEAT_MBYTE
3294 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3295 {
3296 WCHAR *p;
3297 int retval;
3298
3299 p = enc_to_utf16(name, NULL);
3300 if (p == NULL)
3301 return -1;
3302 retval = _wmkdir(p);
3303 vim_free(p);
3304 return retval;
3305 }
3306#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003307 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003308}
3309
3310/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003311 * Delete directory "name".
3312 * Return 0 on success, -1 on error.
3313 */
3314 int
3315mch_rmdir(char_u *name)
3316{
3317#ifdef FEAT_MBYTE
3318 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3319 {
3320 WCHAR *p;
3321 int retval;
3322
3323 p = enc_to_utf16(name, NULL);
3324 if (p == NULL)
3325 return -1;
3326 retval = _wrmdir(p);
3327 vim_free(p);
3328 return retval;
3329 }
3330#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003331 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003332}
3333
3334/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003335 * Return TRUE if file "fname" has more than one link.
3336 */
3337 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003338mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003339{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003340 BY_HANDLE_FILE_INFORMATION info;
3341
3342 return win32_fileinfo(fname, &info) == FILEINFO_OK
3343 && info.nNumberOfLinks > 1;
3344}
3345
3346/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003347 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003348 */
3349 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003350mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003351{
3352 HANDLE hFind;
3353 int res = FALSE;
3354 WIN32_FIND_DATAA findDataA;
3355 DWORD fileFlags = 0, reparseTag = 0;
3356#ifdef FEAT_MBYTE
3357 WCHAR *wn = NULL;
3358 WIN32_FIND_DATAW findDataW;
3359
3360 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003361 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003362 if (wn != NULL)
3363 {
3364 hFind = FindFirstFileW(wn, &findDataW);
3365 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003366 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003367 {
3368 fileFlags = findDataW.dwFileAttributes;
3369 reparseTag = findDataW.dwReserved0;
3370 }
3371 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003372 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003373#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003374 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003375 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003376 if (hFind != INVALID_HANDLE_VALUE)
3377 {
3378 fileFlags = findDataA.dwFileAttributes;
3379 reparseTag = findDataA.dwReserved0;
3380 }
3381 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003382
3383 if (hFind != INVALID_HANDLE_VALUE)
3384 FindClose(hFind);
3385
3386 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003387 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3388 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003389 res = TRUE;
3390
3391 return res;
3392}
3393
3394/*
3395 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3396 * link.
3397 */
3398 int
3399mch_is_linked(char_u *fname)
3400{
3401 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3402 return TRUE;
3403 return FALSE;
3404}
3405
3406/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003407 * Get the by-handle-file-information for "fname".
3408 * Returns FILEINFO_OK when OK.
3409 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3410 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3411 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3412 */
3413 int
3414win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3415{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003416 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003417 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003418#ifdef FEAT_MBYTE
3419 WCHAR *wn = NULL;
3420
3421 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003422 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003423 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003424 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003425 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003426 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003427 if (wn != NULL)
3428 {
3429 hFile = CreateFileW(wn, /* file name */
3430 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003431 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003432 NULL, /* security descriptor */
3433 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003434 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003435 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003436 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003437 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003438 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003439#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003440 hFile = CreateFile((LPCSTR)fname, /* file name */
3441 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003442 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003443 NULL, /* security descriptor */
3444 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003445 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003446 NULL); /* handle to template file */
3447
3448 if (hFile != INVALID_HANDLE_VALUE)
3449 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003450 if (GetFileInformationByHandle(hFile, info) != 0)
3451 res = FILEINFO_OK;
3452 else
3453 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003454 CloseHandle(hFile);
3455 }
3456
Bram Moolenaar03f48552006-02-28 23:52:23 +00003457 return res;
3458}
3459
3460/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003461 * get file attributes for `name'
3462 * -1 : error
3463 * else FILE_ATTRIBUTE_* defined in winnt.h
3464 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003465 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466win32_getattrs(char_u *name)
3467{
3468 int attr;
3469#ifdef FEAT_MBYTE
3470 WCHAR *p = NULL;
3471
3472 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3473 p = enc_to_utf16(name, NULL);
3474
3475 if (p != NULL)
3476 {
3477 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003478 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003479 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003480 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003481#endif
3482 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003483
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003484 return attr;
3485}
3486
3487/*
3488 * set file attributes for `name' to `attrs'
3489 *
3490 * return -1 for failure, 0 otherwise
3491 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003492 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003493win32_setattrs(char_u *name, int attrs)
3494{
3495 int res;
3496#ifdef FEAT_MBYTE
3497 WCHAR *p = NULL;
3498
3499 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3500 p = enc_to_utf16(name, NULL);
3501
3502 if (p != NULL)
3503 {
3504 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003505 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003506 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003507 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003508#endif
3509 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003510
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003511 return res ? 0 : -1;
3512}
3513
3514/*
3515 * Set archive flag for "name".
3516 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003517 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003518win32_set_archive(char_u *name)
3519{
3520 int attrs = win32_getattrs(name);
3521 if (attrs == -1)
3522 return -1;
3523
3524 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3525 return win32_setattrs(name, attrs);
3526}
3527
3528/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529 * Return TRUE if file or directory "name" is writable (not readonly).
3530 * Strange semantics of Win32: a readonly directory is writable, but you can't
3531 * delete a file. Let's say this means it is writable.
3532 */
3533 int
3534mch_writable(char_u *name)
3535{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003536 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003538 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3539 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540}
3541
Bram Moolenaar071d4272004-06-13 20:20:40 +00003542/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003543 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003544 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003545 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3546 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 */
3548 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003549mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003551 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003552 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003553 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003554
3555 if (len >= _MAX_PATH) /* safety check */
3556 return FALSE;
3557
Bram Moolenaar82956662018-10-06 15:18:45 +02003558 /* Ty using the name directly when a Unix-shell like 'shell'. */
3559 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003560 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003561 return TRUE;
3562
3563 /*
3564 * Loop over all extensions in $PATHEXT.
3565 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003566 p = mch_getenv("PATHEXT");
3567 if (p == NULL)
3568 p = (char_u *)".com;.exe;.bat;.cmd";
3569 saved = vim_strsave(p);
3570 if (saved == NULL)
3571 return FALSE;
3572 p = saved;
3573 while (*p)
3574 {
3575 char_u *tmp = vim_strchr(p, ';');
3576
3577 if (tmp != NULL)
3578 *tmp = NUL;
3579 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3580 && executable_exists((char *)name, path, use_path))
3581 {
3582 vim_free(saved);
3583 return TRUE;
3584 }
3585 if (tmp == NULL)
3586 break;
3587 p = tmp + 1;
3588 }
3589 vim_free(saved);
3590
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003591 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003592 p = mch_getenv("PATHEXT");
3593 if (p == NULL)
3594 p = (char_u *)".com;.exe;.bat;.cmd";
3595 while (*p)
3596 {
3597 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3598 {
3599 /* A single "." means no extension is added. */
3600 buf[len] = NUL;
3601 ++p;
3602 if (*p)
3603 ++p;
3604 }
3605 else
3606 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003607 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003608 return TRUE;
3609 }
3610 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612
3613/*
3614 * Check what "name" is:
3615 * NODE_NORMAL: file or directory (or doesn't exist)
3616 * NODE_WRITABLE: writable device, socket, fifo, etc.
3617 * NODE_OTHER: non-writable things
3618 */
3619 int
3620mch_nodetype(char_u *name)
3621{
3622 HANDLE hFile;
3623 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003624#ifdef FEAT_MBYTE
3625 WCHAR *wn = NULL;
3626#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627
Bram Moolenaar043545e2006-10-10 16:44:07 +00003628 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3629 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3630 * here. */
3631 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3632 return NODE_WRITABLE;
3633
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003634#ifdef FEAT_MBYTE
3635 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003636 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003637
3638 if (wn != NULL)
3639 {
3640 hFile = CreateFileW(wn, /* file name */
3641 GENERIC_WRITE, /* access mode */
3642 0, /* share mode */
3643 NULL, /* security descriptor */
3644 OPEN_EXISTING, /* creation disposition */
3645 0, /* file attributes */
3646 NULL); /* handle to template file */
3647 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003648 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003649 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003650#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003651 hFile = CreateFile((LPCSTR)name, /* file name */
3652 GENERIC_WRITE, /* access mode */
3653 0, /* share mode */
3654 NULL, /* security descriptor */
3655 OPEN_EXISTING, /* creation disposition */
3656 0, /* file attributes */
3657 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658
3659 if (hFile == INVALID_HANDLE_VALUE)
3660 return NODE_NORMAL;
3661
3662 type = GetFileType(hFile);
3663 CloseHandle(hFile);
3664 if (type == FILE_TYPE_CHAR)
3665 return NODE_WRITABLE;
3666 if (type == FILE_TYPE_DISK)
3667 return NODE_NORMAL;
3668 return NODE_OTHER;
3669}
3670
3671#ifdef HAVE_ACL
3672struct my_acl
3673{
3674 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3675 PSID pSidOwner;
3676 PSID pSidGroup;
3677 PACL pDacl;
3678 PACL pSacl;
3679};
3680#endif
3681
3682/*
3683 * Return a pointer to the ACL of file "fname" in allocated memory.
3684 * Return NULL if the ACL is not available for whatever reason.
3685 */
3686 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003687mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688{
3689#ifndef HAVE_ACL
3690 return (vim_acl_T)NULL;
3691#else
3692 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003693 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003694
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003695 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3696 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003698# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003699 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003700
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003701 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3702 wn = enc_to_utf16(fname, NULL);
3703 if (wn != NULL)
3704 {
3705 /* Try to retrieve the entire security descriptor. */
3706 err = GetNamedSecurityInfoW(
3707 wn, // Abstract filename
3708 SE_FILE_OBJECT, // File Object
3709 OWNER_SECURITY_INFORMATION |
3710 GROUP_SECURITY_INFORMATION |
3711 DACL_SECURITY_INFORMATION |
3712 SACL_SECURITY_INFORMATION,
3713 &p->pSidOwner, // Ownership information.
3714 &p->pSidGroup, // Group membership.
3715 &p->pDacl, // Discretionary information.
3716 &p->pSacl, // For auditing purposes.
3717 &p->pSecurityDescriptor);
3718 if (err == ERROR_ACCESS_DENIED ||
3719 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003720 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003721 /* Retrieve only DACL. */
3722 (void)GetNamedSecurityInfoW(
3723 wn,
3724 SE_FILE_OBJECT,
3725 DACL_SECURITY_INFORMATION,
3726 NULL,
3727 NULL,
3728 &p->pDacl,
3729 NULL,
3730 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003731 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003732 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003733 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003734 mch_free_acl((vim_acl_T)p);
3735 p = NULL;
3736 }
3737 vim_free(wn);
3738 }
3739 else
3740# endif
3741 {
3742 /* Try to retrieve the entire security descriptor. */
3743 err = GetNamedSecurityInfo(
3744 (LPSTR)fname, // Abstract filename
3745 SE_FILE_OBJECT, // File Object
3746 OWNER_SECURITY_INFORMATION |
3747 GROUP_SECURITY_INFORMATION |
3748 DACL_SECURITY_INFORMATION |
3749 SACL_SECURITY_INFORMATION,
3750 &p->pSidOwner, // Ownership information.
3751 &p->pSidGroup, // Group membership.
3752 &p->pDacl, // Discretionary information.
3753 &p->pSacl, // For auditing purposes.
3754 &p->pSecurityDescriptor);
3755 if (err == ERROR_ACCESS_DENIED ||
3756 err == ERROR_PRIVILEGE_NOT_HELD)
3757 {
3758 /* Retrieve only DACL. */
3759 (void)GetNamedSecurityInfo(
3760 (LPSTR)fname,
3761 SE_FILE_OBJECT,
3762 DACL_SECURITY_INFORMATION,
3763 NULL,
3764 NULL,
3765 &p->pDacl,
3766 NULL,
3767 &p->pSecurityDescriptor);
3768 }
3769 if (p->pSecurityDescriptor == NULL)
3770 {
3771 mch_free_acl((vim_acl_T)p);
3772 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773 }
3774 }
3775 }
3776
3777 return (vim_acl_T)p;
3778#endif
3779}
3780
Bram Moolenaar27515922013-06-29 15:36:26 +02003781#ifdef HAVE_ACL
3782/*
3783 * Check if "acl" contains inherited ACE.
3784 */
3785 static BOOL
3786is_acl_inherited(PACL acl)
3787{
3788 DWORD i;
3789 ACL_SIZE_INFORMATION acl_info;
3790 PACCESS_ALLOWED_ACE ace;
3791
3792 acl_info.AceCount = 0;
3793 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3794 for (i = 0; i < acl_info.AceCount; i++)
3795 {
3796 GetAce(acl, i, (LPVOID *)&ace);
3797 if (ace->Header.AceFlags & INHERITED_ACE)
3798 return TRUE;
3799 }
3800 return FALSE;
3801}
3802#endif
3803
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804/*
3805 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3806 * Errors are ignored.
3807 * This must only be called with "acl" equal to what mch_get_acl() returned.
3808 */
3809 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003810mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811{
3812#ifdef HAVE_ACL
3813 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003814 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003816 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003817 {
3818# ifdef FEAT_MBYTE
3819 WCHAR *wn = NULL;
3820# endif
3821
3822 /* Set security flags */
3823 if (p->pSidOwner)
3824 sec_info |= OWNER_SECURITY_INFORMATION;
3825 if (p->pSidGroup)
3826 sec_info |= GROUP_SECURITY_INFORMATION;
3827 if (p->pDacl)
3828 {
3829 sec_info |= DACL_SECURITY_INFORMATION;
3830 /* Do not inherit its parent's DACL.
3831 * If the DACL is inherited, Cygwin permissions would be changed.
3832 */
3833 if (!is_acl_inherited(p->pDacl))
3834 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3835 }
3836 if (p->pSacl)
3837 sec_info |= SACL_SECURITY_INFORMATION;
3838
3839# ifdef FEAT_MBYTE
3840 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3841 wn = enc_to_utf16(fname, NULL);
3842 if (wn != NULL)
3843 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003844 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003845 wn, // Abstract filename
3846 SE_FILE_OBJECT, // File Object
3847 sec_info,
3848 p->pSidOwner, // Ownership information.
3849 p->pSidGroup, // Group membership.
3850 p->pDacl, // Discretionary information.
3851 p->pSacl // For auditing purposes.
3852 );
3853 vim_free(wn);
3854 }
3855 else
3856# endif
3857 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003858 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003859 (LPSTR)fname, // Abstract filename
3860 SE_FILE_OBJECT, // File Object
3861 sec_info,
3862 p->pSidOwner, // Ownership information.
3863 p->pSidGroup, // Group membership.
3864 p->pDacl, // Discretionary information.
3865 p->pSacl // For auditing purposes.
3866 );
3867 }
3868 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003869#endif
3870}
3871
3872 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003873mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874{
3875#ifdef HAVE_ACL
3876 struct my_acl *p = (struct my_acl *)acl;
3877
3878 if (p != NULL)
3879 {
3880 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3881 vim_free(p);
3882 }
3883#endif
3884}
3885
3886#ifndef FEAT_GUI_W32
3887
3888/*
3889 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3890 */
3891 static BOOL WINAPI
3892handler_routine(
3893 DWORD dwCtrlType)
3894{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003895 INPUT_RECORD ir;
3896 DWORD out;
3897
Bram Moolenaar071d4272004-06-13 20:20:40 +00003898 switch (dwCtrlType)
3899 {
3900 case CTRL_C_EVENT:
3901 if (ctrl_c_interrupts)
3902 g_fCtrlCPressed = TRUE;
3903 return TRUE;
3904
3905 case CTRL_BREAK_EVENT:
3906 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003907 ctrl_break_was_pressed = TRUE;
3908 /* ReadConsoleInput is blocking, send a key event to continue. */
3909 ir.EventType = KEY_EVENT;
3910 ir.Event.KeyEvent.bKeyDown = TRUE;
3911 ir.Event.KeyEvent.wRepeatCount = 1;
3912 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3913 ir.Event.KeyEvent.wVirtualScanCode = 0;
3914 ir.Event.KeyEvent.dwControlKeyState = 0;
3915 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3916 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917 return TRUE;
3918
3919 /* fatal events: shut down gracefully */
3920 case CTRL_CLOSE_EVENT:
3921 case CTRL_LOGOFF_EVENT:
3922 case CTRL_SHUTDOWN_EVENT:
3923 windgoto((int)Rows - 1, 0);
3924 g_fForceExit = TRUE;
3925
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003926 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003927 (dwCtrlType == CTRL_CLOSE_EVENT
3928 ? _("close")
3929 : dwCtrlType == CTRL_LOGOFF_EVENT
3930 ? _("logoff")
3931 : _("shutdown")));
3932#ifdef DEBUG
3933 OutputDebugString(IObuff);
3934#endif
3935
3936 preserve_exit(); /* output IObuff, preserve files and exit */
3937
3938 return TRUE; /* not reached */
3939
3940 default:
3941 return FALSE;
3942 }
3943}
3944
3945
3946/*
3947 * set the tty in (raw) ? "raw" : "cooked" mode
3948 */
3949 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003950mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951{
3952 DWORD cmodein;
3953 DWORD cmodeout;
3954 BOOL bEnableHandler;
3955
3956 GetConsoleMode(g_hConIn, &cmodein);
3957 GetConsoleMode(g_hConOut, &cmodeout);
3958 if (tmode == TMODE_RAW)
3959 {
3960 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3961 ENABLE_ECHO_INPUT);
3962#ifdef FEAT_MOUSE
3963 if (g_fMouseActive)
3964 cmodein |= ENABLE_MOUSE_INPUT;
3965#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003966 cmodeout &= ~(
3967#ifdef FEAT_TERMGUICOLORS
3968 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3969 * VTP. */
3970 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3971#else
3972 ENABLE_PROCESSED_OUTPUT |
3973#endif
3974 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003975 bEnableHandler = TRUE;
3976 }
3977 else /* cooked */
3978 {
3979 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3980 ENABLE_ECHO_INPUT);
3981 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3982 bEnableHandler = FALSE;
3983 }
3984 SetConsoleMode(g_hConIn, cmodein);
3985 SetConsoleMode(g_hConOut, cmodeout);
3986 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3987
3988#ifdef MCH_WRITE_DUMP
3989 if (fdDump)
3990 {
3991 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3992 tmode == TMODE_RAW ? "raw" :
3993 tmode == TMODE_COOK ? "cooked" : "normal",
3994 cmodein, cmodeout);
3995 fflush(fdDump);
3996 }
3997#endif
3998}
3999
4000
4001/*
4002 * Get the size of the current window in `Rows' and `Columns'
4003 * Return OK when size could be determined, FAIL otherwise.
4004 */
4005 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004006mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004007{
4008 CONSOLE_SCREEN_BUFFER_INFO csbi;
4009
4010 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4011 {
4012 /*
4013 * For some reason, we are trying to get the screen dimensions
4014 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4015 * variables are really intended to mean the size of Vim screen
4016 * while in termcap mode.
4017 */
4018 Rows = g_cbTermcap.Info.dwSize.Y;
4019 Columns = g_cbTermcap.Info.dwSize.X;
4020 }
4021 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4022 {
4023 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4024 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4025 }
4026 else
4027 {
4028 Rows = 25;
4029 Columns = 80;
4030 }
4031 return OK;
4032}
4033
4034/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004035 * Resize console buffer to 'COORD'
4036 */
4037 static void
4038ResizeConBuf(
4039 HANDLE hConsole,
4040 COORD coordScreen)
4041{
4042 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4043 {
4044#ifdef MCH_WRITE_DUMP
4045 if (fdDump)
4046 {
4047 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4048 GetLastError());
4049 fflush(fdDump);
4050 }
4051#endif
4052 }
4053}
4054
4055/*
4056 * Resize console window size to 'srWindowRect'
4057 */
4058 static void
4059ResizeWindow(
4060 HANDLE hConsole,
4061 SMALL_RECT srWindowRect)
4062{
4063 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4064 {
4065#ifdef MCH_WRITE_DUMP
4066 if (fdDump)
4067 {
4068 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4069 GetLastError());
4070 fflush(fdDump);
4071 }
4072#endif
4073 }
4074}
4075
4076/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004077 * Set a console window to `xSize' * `ySize'
4078 */
4079 static void
4080ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004081 HANDLE hConsole,
4082 int xSize,
4083 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084{
4085 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4086 SMALL_RECT srWindowRect; /* hold the new console size */
4087 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004088 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004089
4090#ifdef MCH_WRITE_DUMP
4091 if (fdDump)
4092 {
4093 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4094 fflush(fdDump);
4095 }
4096#endif
4097
4098 /* get the largest size we can size the console window to */
4099 coordScreen = GetLargestConsoleWindowSize(hConsole);
4100
4101 /* define the new console window size and scroll position */
4102 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4103 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4104 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4105
4106 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4107 {
4108 int sx, sy;
4109
4110 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4111 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4112 if (sy < ySize || sx < xSize)
4113 {
4114 /*
4115 * Increasing number of lines/columns, do buffer first.
4116 * Use the maximal size in x and y direction.
4117 */
4118 if (sy < ySize)
4119 coordScreen.Y = ySize;
4120 else
4121 coordScreen.Y = sy;
4122 if (sx < xSize)
4123 coordScreen.X = xSize;
4124 else
4125 coordScreen.X = sx;
4126 SetConsoleScreenBufferSize(hConsole, coordScreen);
4127 }
4128 }
4129
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004130 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 coordScreen.X = xSize;
4132 coordScreen.Y = ySize;
4133
Bram Moolenaar2551c032018-08-23 22:38:31 +02004134 // In the new console call API, only the first time in reverse order
4135 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004137 ResizeWindow(hConsole, srWindowRect);
4138 ResizeConBuf(hConsole, coordScreen);
4139 }
4140 else
4141 {
4142 ResizeConBuf(hConsole, coordScreen);
4143 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004144 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145 }
4146}
4147
4148
4149/*
4150 * Set the console window to `Rows' * `Columns'
4151 */
4152 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004153mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154{
4155 COORD coordScreen;
4156
4157 /* Don't change window size while still starting up */
4158 if (suppress_winsize != 0)
4159 {
4160 suppress_winsize = 2;
4161 return;
4162 }
4163
4164 if (term_console)
4165 {
4166 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4167
4168 /* Clamp Rows and Columns to reasonable values */
4169 if (Rows > coordScreen.Y)
4170 Rows = coordScreen.Y;
4171 if (Columns > coordScreen.X)
4172 Columns = coordScreen.X;
4173
4174 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4175 }
4176}
4177
4178/*
4179 * Rows and/or Columns has changed.
4180 */
4181 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004182mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183{
4184 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4185}
4186
4187
4188/*
4189 * Called when started up, to set the winsize that was delayed.
4190 */
4191 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004192mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193{
4194 if (suppress_winsize == 2)
4195 {
4196 suppress_winsize = 0;
4197 mch_set_shellsize();
4198 shell_resized();
4199 }
4200 suppress_winsize = 0;
4201}
4202#endif /* FEAT_GUI_W32 */
4203
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004204 static BOOL
4205vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004206 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004207 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004208 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004209 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004210 PROCESS_INFORMATION *pi,
4211 LPVOID *env,
4212 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004213{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004214#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004215 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4216 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004217 BOOL ret;
4218 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004219
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004220 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4221 if (wcmd == NULL)
4222 goto fallback;
4223 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004224 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004225 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4226 if (wcwd == NULL)
4227 {
4228 vim_free(wcmd);
4229 goto fallback;
4230 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004231 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004232
4233 ret = CreateProcessW(
4234 NULL, /* Executable name */
4235 wcmd, /* Command to execute */
4236 NULL, /* Process security attributes */
4237 NULL, /* Thread security attributes */
4238 inherit_handles, /* Inherit handles */
4239 flags, /* Creation flags */
4240 env, /* Environment */
4241 wcwd, /* Current directory */
4242 (LPSTARTUPINFOW)si, /* Startup information */
4243 pi); /* Process information */
4244 vim_free(wcmd);
4245 if (wcwd != NULL)
4246 vim_free(wcwd);
4247 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004248 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004249fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004250#endif
4251 return CreateProcess(
4252 NULL, /* Executable name */
4253 cmd, /* Command to execute */
4254 NULL, /* Process security attributes */
4255 NULL, /* Thread security attributes */
4256 inherit_handles, /* Inherit handles */
4257 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004258 env, /* Environment */
4259 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004260 si, /* Startup information */
4261 pi); /* Process information */
4262}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263
4264
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004265 static HINSTANCE
4266vim_shell_execute(
4267 char *cmd,
4268 INT n_show_cmd)
4269{
4270#ifdef FEAT_MBYTE
4271 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4272 {
4273 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4274 if (wcmd != NULL)
4275 {
4276 HINSTANCE ret;
4277 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4278 vim_free(wcmd);
4279 return ret;
4280 }
4281 }
4282#endif
4283 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4284}
4285
4286
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287#if defined(FEAT_GUI_W32) || defined(PROTO)
4288
4289/*
4290 * Specialised version of system() for Win32 GUI mode.
4291 * This version proceeds as follows:
4292 * 1. Create a console window for use by the subprocess
4293 * 2. Run the subprocess (it gets the allocated console by default)
4294 * 3. Wait for the subprocess to terminate and get its exit code
4295 * 4. Prompt the user to press a key to close the console window
4296 */
4297 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299{
4300 STARTUPINFO si;
4301 PROCESS_INFORMATION pi;
4302 DWORD ret = 0;
4303 HWND hwnd = GetFocus();
4304
4305 si.cb = sizeof(si);
4306 si.lpReserved = NULL;
4307 si.lpDesktop = NULL;
4308 si.lpTitle = NULL;
4309 si.dwFlags = STARTF_USESHOWWINDOW;
4310 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004311 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004312 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004314 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004315 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316 else
4317 si.wShowWindow = SW_SHOWNORMAL;
4318 si.cbReserved2 = 0;
4319 si.lpReserved2 = NULL;
4320
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004322 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004323 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4324 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004325
4326 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004327 {
4328#ifdef FEAT_GUI
4329 int delay = 1;
4330
4331 /* Keep updating the window while waiting for the shell to finish. */
4332 for (;;)
4333 {
4334 MSG msg;
4335
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004336 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337 {
4338 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004339 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004340 delay = 1;
4341 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004342 }
4343 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4344 break;
4345
4346 /* We start waiting for a very short time and then increase it, so
4347 * that we respond quickly when the process is quick, and don't
4348 * consume too much overhead when it's slow. */
4349 if (delay < 50)
4350 delay += 10;
4351 }
4352#else
4353 WaitForSingleObject(pi.hProcess, INFINITE);
4354#endif
4355
4356 /* Get the command exit code */
4357 GetExitCodeProcess(pi.hProcess, &ret);
4358 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004359
4360 /* Close the handles to the subprocess, so that it goes away */
4361 CloseHandle(pi.hThread);
4362 CloseHandle(pi.hProcess);
4363
4364 /* Try to get input focus back. Doesn't always work though. */
4365 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4366
4367 return ret;
4368}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004369
4370/*
4371 * Thread launched by the gui to send the current buffer data to the
4372 * process. This way avoid to hang up vim totally if the children
4373 * process take a long time to process the lines.
4374 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004375 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004376sub_process_writer(LPVOID param)
4377{
4378 HANDLE g_hChildStd_IN_Wr = param;
4379 linenr_T lnum = curbuf->b_op_start.lnum;
4380 DWORD len = 0;
4381 DWORD l;
4382 char_u *lp = ml_get(lnum);
4383 char_u *s;
4384 int written = 0;
4385
4386 for (;;)
4387 {
4388 l = (DWORD)STRLEN(lp + written);
4389 if (l == 0)
4390 len = 0;
4391 else if (lp[written] == NL)
4392 {
4393 /* NL -> NUL translation */
4394 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4395 }
4396 else
4397 {
4398 s = vim_strchr(lp + written, NL);
4399 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4400 s == NULL ? l : (DWORD)(s - (lp + written)),
4401 &len, NULL);
4402 }
4403 if (len == (int)l)
4404 {
4405 /* Finished a line, add a NL, unless this line should not have
4406 * one. */
4407 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004408 || (!curbuf->b_p_bin
4409 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004410 || (lnum != curbuf->b_no_eol_lnum
4411 && (lnum != curbuf->b_ml.ml_line_count
4412 || curbuf->b_p_eol)))
4413 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004414 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4415 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416 }
4417
4418 ++lnum;
4419 if (lnum > curbuf->b_op_end.lnum)
4420 break;
4421
4422 lp = ml_get(lnum);
4423 written = 0;
4424 }
4425 else if (len > 0)
4426 written += len;
4427 }
4428
4429 /* finished all the lines, close pipe */
4430 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004431 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004432}
4433
4434
4435# define BUFLEN 100 /* length for buffer, stolen from unix version */
4436
4437/*
4438 * This function read from the children's stdout and write the
4439 * data on screen or in the buffer accordingly.
4440 */
4441 static void
4442dump_pipe(int options,
4443 HANDLE g_hChildStd_OUT_Rd,
4444 garray_T *ga,
4445 char_u buffer[],
4446 DWORD *buffer_off)
4447{
4448 DWORD availableBytes = 0;
4449 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004450 int ret;
4451 DWORD len;
4452 DWORD toRead;
4453 int repeatCount;
4454
4455 /* we query the pipe to see if there is any data to read
4456 * to avoid to perform a blocking read */
4457 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4458 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004459 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004460 NULL, /* number of read bytes */
4461 &availableBytes, /* available bytes total */
4462 NULL); /* byteLeft */
4463
4464 repeatCount = 0;
4465 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004466 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004467 {
4468 repeatCount++;
4469 toRead =
4470# ifdef FEAT_MBYTE
4471 (DWORD)(BUFLEN - *buffer_off);
4472# else
4473 (DWORD)BUFLEN;
4474# endif
4475 toRead = availableBytes < toRead ? availableBytes : toRead;
4476 ReadFile(g_hChildStd_OUT_Rd, buffer
4477# ifdef FEAT_MBYTE
4478 + *buffer_off, toRead
4479# else
4480 , toRead
4481# endif
4482 , &len, NULL);
4483
4484 /* If we haven't read anything, there is a problem */
4485 if (len == 0)
4486 break;
4487
4488 availableBytes -= len;
4489
4490 if (options & SHELL_READ)
4491 {
4492 /* Do NUL -> NL translation, append NL separated
4493 * lines to the current buffer. */
4494 for (i = 0; i < len; ++i)
4495 {
4496 if (buffer[i] == NL)
4497 append_ga_line(ga);
4498 else if (buffer[i] == NUL)
4499 ga_append(ga, NL);
4500 else
4501 ga_append(ga, buffer[i]);
4502 }
4503 }
4504# ifdef FEAT_MBYTE
4505 else if (has_mbyte)
4506 {
4507 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004508 int c;
4509 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004510
4511 len += *buffer_off;
4512 buffer[len] = NUL;
4513
4514 /* Check if the last character in buffer[] is
4515 * incomplete, keep these bytes for the next
4516 * round. */
4517 for (p = buffer; p < buffer + len; p += l)
4518 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004519 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004520 if (l == 0)
4521 l = 1; /* NUL byte? */
4522 else if (MB_BYTE2LEN(*p) != l)
4523 break;
4524 }
4525 if (p == buffer) /* no complete character */
4526 {
4527 /* avoid getting stuck at an illegal byte */
4528 if (len >= 12)
4529 ++p;
4530 else
4531 {
4532 *buffer_off = len;
4533 return;
4534 }
4535 }
4536 c = *p;
4537 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004538 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004539 if (p < buffer + len)
4540 {
4541 *p = c;
4542 *buffer_off = (DWORD)((buffer + len) - p);
4543 mch_memmove(buffer, p, *buffer_off);
4544 return;
4545 }
4546 *buffer_off = 0;
4547 }
4548# endif /* FEAT_MBYTE */
4549 else
4550 {
4551 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004552 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004553 }
4554
4555 windgoto(msg_row, msg_col);
4556 cursor_on();
4557 out_flush();
4558 }
4559}
4560
4561/*
4562 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4563 * for communication and doesn't open any new window.
4564 */
4565 static int
4566mch_system_piped(char *cmd, int options)
4567{
4568 STARTUPINFO si;
4569 PROCESS_INFORMATION pi;
4570 DWORD ret = 0;
4571
4572 HANDLE g_hChildStd_IN_Rd = NULL;
4573 HANDLE g_hChildStd_IN_Wr = NULL;
4574 HANDLE g_hChildStd_OUT_Rd = NULL;
4575 HANDLE g_hChildStd_OUT_Wr = NULL;
4576
4577 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4578 DWORD len;
4579
4580 /* buffer used to receive keys */
4581 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4582 int ta_len = 0; /* valid bytes in ta_buf[] */
4583
4584 DWORD i;
4585 int c;
4586 int noread_cnt = 0;
4587 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004588 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004589 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004590 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004591
4592 SECURITY_ATTRIBUTES saAttr;
4593
4594 /* Set the bInheritHandle flag so pipe handles are inherited. */
4595 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4596 saAttr.bInheritHandle = TRUE;
4597 saAttr.lpSecurityDescriptor = NULL;
4598
4599 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4600 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004601 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004602 /* Create a pipe for the child process's STDIN. */
4603 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4604 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004605 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004606 {
4607 CloseHandle(g_hChildStd_IN_Rd);
4608 CloseHandle(g_hChildStd_IN_Wr);
4609 CloseHandle(g_hChildStd_OUT_Rd);
4610 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004611 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004612 }
4613
4614 si.cb = sizeof(si);
4615 si.lpReserved = NULL;
4616 si.lpDesktop = NULL;
4617 si.lpTitle = NULL;
4618 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4619
4620 /* set-up our file redirection */
4621 si.hStdError = g_hChildStd_OUT_Wr;
4622 si.hStdOutput = g_hChildStd_OUT_Wr;
4623 si.hStdInput = g_hChildStd_IN_Rd;
4624 si.wShowWindow = SW_HIDE;
4625 si.cbReserved2 = 0;
4626 si.lpReserved2 = NULL;
4627
4628 if (options & SHELL_READ)
4629 ga_init2(&ga, 1, BUFLEN);
4630
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004631 if (cmd != NULL)
4632 {
4633 p = (char *)vim_strsave((char_u *)cmd);
4634 if (p != NULL)
4635 unescape_shellxquote((char_u *)p, p_sxe);
4636 else
4637 p = cmd;
4638 }
4639
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004640 /* Now, run the command.
4641 * About "Inherit handles" being TRUE: this command can be litigious,
4642 * handle inheritance was deactivated for pending temp file, but, if we
4643 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004644 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4645 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004646
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004647 if (p != cmd)
4648 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004649
4650 /* Close our unused side of the pipes */
4651 CloseHandle(g_hChildStd_IN_Rd);
4652 CloseHandle(g_hChildStd_OUT_Wr);
4653
4654 if (options & SHELL_WRITE)
4655 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004656 HANDLE thread = (HANDLE)
4657 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004658 0, /* default stack size */
4659 sub_process_writer, /* function to be executed */
4660 g_hChildStd_IN_Wr, /* parameter */
4661 0, /* creation flag, start immediately */
4662 NULL); /* we don't care about thread id */
4663 CloseHandle(thread);
4664 g_hChildStd_IN_Wr = NULL;
4665 }
4666
4667 /* Keep updating the window while waiting for the shell to finish. */
4668 for (;;)
4669 {
4670 MSG msg;
4671
Bram Moolenaar175d0702013-12-11 18:36:33 +01004672 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004673 {
4674 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004675 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004676 }
4677
4678 /* write pipe information in the window */
4679 if ((options & (SHELL_READ|SHELL_WRITE))
4680# ifdef FEAT_GUI
4681 || gui.in_use
4682# endif
4683 )
4684 {
4685 len = 0;
4686 if (!(options & SHELL_EXPAND)
4687 && ((options &
4688 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4689 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4690# ifdef FEAT_GUI
4691 || gui.in_use
4692# endif
4693 )
4694 && (ta_len > 0 || noread_cnt > 4))
4695 {
4696 if (ta_len == 0)
4697 {
4698 /* Get extra characters when we don't have any. Reset the
4699 * counter and timer. */
4700 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004701 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4702 }
4703 if (ta_len > 0 || len > 0)
4704 {
4705 /*
4706 * For pipes: Check for CTRL-C: send interrupt signal to
4707 * child. Check for CTRL-D: EOF, close pipe to child.
4708 */
4709 if (len == 1 && cmd != NULL)
4710 {
4711 if (ta_buf[ta_len] == Ctrl_C)
4712 {
4713 /* Learn what exit code is expected, for
4714 * now put 9 as SIGKILL */
4715 TerminateProcess(pi.hProcess, 9);
4716 }
4717 if (ta_buf[ta_len] == Ctrl_D)
4718 {
4719 CloseHandle(g_hChildStd_IN_Wr);
4720 g_hChildStd_IN_Wr = NULL;
4721 }
4722 }
4723
4724 /* replace K_BS by <BS> and K_DEL by <DEL> */
4725 for (i = ta_len; i < ta_len + len; ++i)
4726 {
4727 if (ta_buf[i] == CSI && len - i > 2)
4728 {
4729 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4730 if (c == K_DEL || c == K_KDEL || c == K_BS)
4731 {
4732 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4733 (size_t)(len - i - 2));
4734 if (c == K_DEL || c == K_KDEL)
4735 ta_buf[i] = DEL;
4736 else
4737 ta_buf[i] = Ctrl_H;
4738 len -= 2;
4739 }
4740 }
4741 else if (ta_buf[i] == '\r')
4742 ta_buf[i] = '\n';
4743# ifdef FEAT_MBYTE
4744 if (has_mbyte)
4745 i += (*mb_ptr2len_len)(ta_buf + i,
4746 ta_len + len - i) - 1;
4747# endif
4748 }
4749
4750 /*
4751 * For pipes: echo the typed characters. For a pty this
4752 * does not seem to work.
4753 */
4754 for (i = ta_len; i < ta_len + len; ++i)
4755 {
4756 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4757 msg_putchar(ta_buf[i]);
4758# ifdef FEAT_MBYTE
4759 else if (has_mbyte)
4760 {
4761 int l = (*mb_ptr2len)(ta_buf + i);
4762
4763 msg_outtrans_len(ta_buf + i, l);
4764 i += l - 1;
4765 }
4766# endif
4767 else
4768 msg_outtrans_len(ta_buf + i, 1);
4769 }
4770 windgoto(msg_row, msg_col);
4771 out_flush();
4772
4773 ta_len += len;
4774
4775 /*
4776 * Write the characters to the child, unless EOF has been
4777 * typed for pipes. Write one character at a time, to
4778 * avoid losing too much typeahead. When writing buffer
4779 * lines, drop the typed characters (only check for
4780 * CTRL-C).
4781 */
4782 if (options & SHELL_WRITE)
4783 ta_len = 0;
4784 else if (g_hChildStd_IN_Wr != NULL)
4785 {
4786 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4787 1, &len, NULL);
4788 // if we are typing in, we want to keep things reactive
4789 delay = 1;
4790 if (len > 0)
4791 {
4792 ta_len -= len;
4793 mch_memmove(ta_buf, ta_buf + len, ta_len);
4794 }
4795 }
4796 }
4797 }
4798 }
4799
4800 if (ta_len)
4801 ui_inchar_undo(ta_buf, ta_len);
4802
4803 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4804 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004805 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004806 break;
4807 }
4808
4809 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004810 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004811
4812 /* We start waiting for a very short time and then increase it, so
4813 * that we respond quickly when the process is quick, and don't
4814 * consume too much overhead when it's slow. */
4815 if (delay < 50)
4816 delay += 10;
4817 }
4818
4819 /* Close the pipe */
4820 CloseHandle(g_hChildStd_OUT_Rd);
4821 if (g_hChildStd_IN_Wr != NULL)
4822 CloseHandle(g_hChildStd_IN_Wr);
4823
4824 WaitForSingleObject(pi.hProcess, INFINITE);
4825
4826 /* Get the command exit code */
4827 GetExitCodeProcess(pi.hProcess, &ret);
4828
4829 if (options & SHELL_READ)
4830 {
4831 if (ga.ga_len > 0)
4832 {
4833 append_ga_line(&ga);
4834 /* remember that the NL was missing */
4835 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4836 }
4837 else
4838 curbuf->b_no_eol_lnum = 0;
4839 ga_clear(&ga);
4840 }
4841
4842 /* Close the handles to the subprocess, so that it goes away */
4843 CloseHandle(pi.hThread);
4844 CloseHandle(pi.hProcess);
4845
4846 return ret;
4847}
4848
4849 static int
4850mch_system(char *cmd, int options)
4851{
4852 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004853 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004854 return mch_system_piped(cmd, options);
4855 else
4856 return mch_system_classic(cmd, options);
4857}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858#else
4859
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004860# ifdef FEAT_MBYTE
4861 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004862mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004863{
4864 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4865 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004866 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004867 if (wcmd != NULL)
4868 {
4869 int ret = _wsystem(wcmd);
4870 vim_free(wcmd);
4871 return ret;
4872 }
4873 }
4874 return system(cmd);
4875}
4876# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004877# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004878# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879
4880#endif
4881
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004882#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4883/*
4884 * Use a terminal window to run a shell command in.
4885 */
4886 static int
4887mch_call_shell_terminal(
4888 char_u *cmd,
4889 int options UNUSED) /* SHELL_*, see vim.h */
4890{
4891 jobopt_T opt;
4892 char_u *newcmd = NULL;
4893 typval_T argvar[2];
4894 long_u cmdlen;
4895 int retval = -1;
4896 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004897 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004898 aco_save_T aco;
4899 oparg_T oa; /* operator arguments */
4900
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004901 if (cmd == NULL)
4902 cmdlen = STRLEN(p_sh) + 1;
4903 else
4904 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004905 newcmd = lalloc(cmdlen, TRUE);
4906 if (newcmd == NULL)
4907 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004908 if (cmd == NULL)
4909 {
4910 STRCPY(newcmd, p_sh);
4911 ch_log(NULL, "starting terminal to run a shell");
4912 }
4913 else
4914 {
4915 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4916 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4917 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004918
4919 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004920
4921 argvar[0].v_type = VAR_STRING;
4922 argvar[0].vval.v_string = newcmd;
4923 argvar[1].v_type = VAR_UNKNOWN;
4924 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004925 if (buf == NULL)
4926 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004927
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004928 job = term_getjob(buf->b_term);
4929 ++job->jv_refcount;
4930
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004931 /* Find a window to make "buf" curbuf. */
4932 aucmd_prepbuf(&aco, buf);
4933
4934 clear_oparg(&oa);
4935 while (term_use_loop())
4936 {
4937 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4938 {
4939 /* If terminal_loop() returns OK we got a key that is handled
4940 * in Normal model. We don't do redrawing anyway. */
4941 if (terminal_loop(TRUE) == OK)
4942 normal_cmd(&oa, TRUE);
4943 }
4944 else
4945 normal_cmd(&oa, TRUE);
4946 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004947 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004948 ch_log(NULL, "system command finished");
4949
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004950 job_unref(job);
4951
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004952 /* restore curwin/curbuf and a few other things */
4953 aucmd_restbuf(&aco);
4954
4955 wait_return(TRUE);
4956 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4957
4958 vim_free(newcmd);
4959 return retval;
4960}
4961#endif
4962
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963/*
4964 * Either execute a command by calling the shell or start a new shell
4965 */
4966 int
4967mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004968 char_u *cmd,
4969 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004970{
4971 int x = 0;
4972 int tmode = cur_tmode;
4973#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004974 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004975# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004976 int did_set_title = FALSE;
4977
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004978 /* Change the title to reflect that we are in a subshell. */
4979 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4980 {
4981 WCHAR szShellTitle[512];
4982
4983 if (GetConsoleTitleW(szShellTitle,
4984 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4985 {
4986 if (cmd == NULL)
4987 wcscat(szShellTitle, L" :sh");
4988 else
4989 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004990 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004991
4992 if (wn != NULL)
4993 {
4994 wcscat(szShellTitle, L" - !");
4995 if ((wcslen(szShellTitle) + wcslen(wn) <
4996 sizeof(szShellTitle)/sizeof(WCHAR)))
4997 wcscat(szShellTitle, wn);
4998 SetConsoleTitleW(szShellTitle);
4999 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005000 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005001 }
5002 }
5003 }
5004 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005005 if (!did_set_title)
5006# endif
5007 /* Change the title to reflect that we are in a subshell. */
5008 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005010 if (cmd == NULL)
5011 strcat(szShellTitle, " :sh");
5012 else
5013 {
5014 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005015 if ((strlen(szShellTitle) + strlen((char *)cmd)
5016 < sizeof(szShellTitle)))
5017 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005018 }
5019 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021#endif
5022
5023 out_flush();
5024
5025#ifdef MCH_WRITE_DUMP
5026 if (fdDump)
5027 {
5028 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5029 fflush(fdDump);
5030 }
5031#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005032#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5033 /* TODO: make the terminal window work with input or output redirected. */
5034 if (vim_strchr(p_go, GO_TERMINAL) != NULL
5035 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5036 {
5037 /* Use a terminal window to run the command in. */
5038 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01005039# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005040 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01005041# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005042 return x;
5043 }
5044#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045
5046 /*
5047 * Catch all deadly signals while running the external command, because a
5048 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5049 */
5050 signal(SIGINT, SIG_IGN);
5051#if defined(__GNUC__) && !defined(__MINGW32__)
5052 signal(SIGKILL, SIG_IGN);
5053#else
5054 signal(SIGBREAK, SIG_IGN);
5055#endif
5056 signal(SIGILL, SIG_IGN);
5057 signal(SIGFPE, SIG_IGN);
5058 signal(SIGSEGV, SIG_IGN);
5059 signal(SIGTERM, SIG_IGN);
5060 signal(SIGABRT, SIG_IGN);
5061
5062 if (options & SHELL_COOKED)
5063 settmode(TMODE_COOK); /* set to normal mode */
5064
5065 if (cmd == NULL)
5066 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005067 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005068 }
5069 else
5070 {
5071 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005072 char_u *newcmd = NULL;
5073 char_u *cmdbase = cmd;
5074 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005075
5076 /* Skip a leading ", ( and "(. */
5077 if (*cmdbase == '"' )
5078 ++cmdbase;
5079 if (*cmdbase == '(')
5080 ++cmdbase;
5081
Bram Moolenaar1c465442017-03-12 20:10:05 +01005082 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005083 {
5084 STARTUPINFO si;
5085 PROCESS_INFORMATION pi;
5086 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005087 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005088 char_u *p;
5089
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005090 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005091 si.cb = sizeof(si);
5092 si.lpReserved = NULL;
5093 si.lpDesktop = NULL;
5094 si.lpTitle = NULL;
5095 si.dwFlags = 0;
5096 si.cbReserved2 = 0;
5097 si.lpReserved2 = NULL;
5098
5099 cmdbase = skipwhite(cmdbase + 5);
5100 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005101 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005102 {
5103 cmdbase = skipwhite(cmdbase + 4);
5104 si.dwFlags = STARTF_USESHOWWINDOW;
5105 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005106 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005107 }
5108 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005109 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005110 {
5111 cmdbase = skipwhite(cmdbase + 2);
5112 flags = CREATE_NO_WINDOW;
5113 si.dwFlags = STARTF_USESTDHANDLES;
5114 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005115 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005116 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005117 NULL, // Security att.
5118 OPEN_EXISTING, // Open flags
5119 FILE_ATTRIBUTE_NORMAL, // File att.
5120 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005121 si.hStdOutput = si.hStdInput;
5122 si.hStdError = si.hStdInput;
5123 }
5124
5125 /* Remove a trailing ", ) and )" if they have a match
5126 * at the start of the command. */
5127 if (cmdbase > cmd)
5128 {
5129 p = cmdbase + STRLEN(cmdbase);
5130 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5131 *--p = NUL;
5132 if (p > cmdbase && p[-1] == ')'
5133 && (*cmd =='(' || cmd[1] == '('))
5134 *--p = NUL;
5135 }
5136
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005137 newcmd = cmdbase;
5138 unescape_shellxquote(cmdbase, p_sxe);
5139
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005140 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005141 * If creating new console, arguments are passed to the
5142 * 'cmd.exe' as-is. If it's not, arguments are not treated
5143 * correctly for current 'cmd.exe'. So unescape characters in
5144 * shellxescape except '|' for avoiding to be treated as
5145 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005146 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005147 if (flags != CREATE_NEW_CONSOLE)
5148 {
5149 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005150 char_u *cmd_shell = mch_getenv("COMSPEC");
5151
5152 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005153 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005154
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005155 subcmd = vim_strsave_escaped_ext(cmdbase,
5156 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005157 if (subcmd != NULL)
5158 {
5159 /* make "cmd.exe /c arguments" */
5160 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005161 newcmd = lalloc(cmdlen, TRUE);
5162 if (newcmd != NULL)
5163 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005164 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005165 else
5166 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005167 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005168 }
5169 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005170
5171 /*
5172 * Now, start the command as a process, so that it doesn't
5173 * inherit our handles which causes unpleasant dangling swap
5174 * files if we exit before the spawned process
5175 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005176 if (vim_create_process((char *)newcmd, FALSE, flags,
5177 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005178 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005179 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5180 > (HINSTANCE)32)
5181 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005182 else
5183 {
5184 x = -1;
5185#ifdef FEAT_GUI_W32
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005186 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005187#endif
5188 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005189
5190 if (newcmd != cmdbase)
5191 vim_free(newcmd);
5192
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005193 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005194 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005195 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005196 CloseHandle(si.hStdInput);
5197 }
5198 /* Close the handles to the subprocess, so that it goes away */
5199 CloseHandle(pi.hThread);
5200 CloseHandle(pi.hProcess);
5201 }
5202 else
5203 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005204 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005205#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005206 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005208 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5209
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005210 newcmd = lalloc(cmdlen, TRUE);
5211 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005212 {
5213#if defined(FEAT_GUI_W32)
5214 if (need_vimrun_warning)
5215 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005216 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5217 "External commands will not pause after completion.\n"
5218 "See :help win32-vimrun for more information.");
5219 char *title = _("Vim Warning");
5220# ifdef FEAT_MBYTE
5221 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5222 {
5223 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5224 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5225
5226 if (wmsg != NULL && wtitle != NULL)
5227 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5228 vim_free(wmsg);
5229 vim_free(wtitle);
5230 }
5231 else
5232# endif
5233 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005234 need_vimrun_warning = FALSE;
5235 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005236 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237 /* Use vimrun to execute the command. It opens a console
5238 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005239 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005240 vimrun_path,
5241 (msg_silent != 0 || (options & SHELL_DOOUT))
5242 ? "-s " : "",
5243 p_sh, p_shcf, cmd);
5244 else
5245#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005246 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005247 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005248 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005249 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005250 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005251 }
5252 }
5253
5254 if (tmode == TMODE_RAW)
5255 settmode(TMODE_RAW); /* set to raw mode */
5256
5257 /* Print the return value, unless "vimrun" was used. */
5258 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5259#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005260 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261#endif
5262 )
5263 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005264 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005265 msg_putchar('\n');
5266 }
5267#ifdef FEAT_TITLE
5268 resettitle();
5269#endif
5270
5271 signal(SIGINT, SIG_DFL);
5272#if defined(__GNUC__) && !defined(__MINGW32__)
5273 signal(SIGKILL, SIG_DFL);
5274#else
5275 signal(SIGBREAK, SIG_DFL);
5276#endif
5277 signal(SIGILL, SIG_DFL);
5278 signal(SIGFPE, SIG_DFL);
5279 signal(SIGSEGV, SIG_DFL);
5280 signal(SIGTERM, SIG_DFL);
5281 signal(SIGABRT, SIG_DFL);
5282
5283 return x;
5284}
5285
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005286#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005287 static HANDLE
5288job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005289 char_u *fname,
5290 DWORD dwDesiredAccess,
5291 DWORD dwShareMode,
5292 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5293 DWORD dwCreationDisposition,
5294 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005295{
5296 HANDLE h;
5297# ifdef FEAT_MBYTE
5298 WCHAR *wn = NULL;
5299 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5300 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005301 wn = enc_to_utf16(fname, NULL);
5302 if (wn != NULL)
5303 {
5304 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5305 lpSecurityAttributes, dwCreationDisposition,
5306 dwFlagsAndAttributes, NULL);
5307 vim_free(wn);
5308 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005309 }
5310 if (wn == NULL)
5311# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005312 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5313 lpSecurityAttributes, dwCreationDisposition,
5314 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005315 return h;
5316}
5317
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005318/*
5319 * Turn the dictionary "env" into a NUL separated list that can be used as the
5320 * environment argument of vim_create_process().
5321 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005322 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005323win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005324{
5325 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005326 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005327 LPVOID base = GetEnvironmentStringsW();
5328
5329 /* for last \0 */
5330 if (ga_grow(gap, 1) == FAIL)
5331 return;
5332
5333 if (base)
5334 {
5335 WCHAR *p = (WCHAR*) base;
5336
5337 /* for last \0 */
5338 if (ga_grow(gap, 1) == FAIL)
5339 return;
5340
5341 while (*p != 0 || *(p + 1) != 0)
5342 {
5343 if (ga_grow(gap, 1) == OK)
5344 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5345 p++;
5346 }
5347 FreeEnvironmentStrings(base);
5348 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5349 }
5350
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005351 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005352 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005353 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005354 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005355 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005356 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005357 typval_T *item = &dict_lookup(hi)->di_tv;
5358 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005359 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005360 --todo;
5361 if (wkey != NULL && wval != NULL)
5362 {
5363 size_t n;
5364 size_t lkey = wcslen(wkey);
5365 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005366
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005367 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5368 continue;
5369 for (n = 0; n < lkey; n++)
5370 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5371 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5372 for (n = 0; n < lval; n++)
5373 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5374 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5375 }
5376 if (wkey != NULL) vim_free(wkey);
5377 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005378 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005379 }
5380 }
5381
Bram Moolenaar493359e2018-06-12 20:25:52 +02005382# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005383 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005384# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005385 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005386 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005387# endif
5388# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005389 char_u *version = get_vim_var_str(VV_VERSION);
5390 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005391# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005392 // size of "VIM_SERVERNAME=" and value,
5393 // plus "VIM_TERMINAL=" and value,
5394 // plus two terminating NULs
5395 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005396# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005397 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005398# endif
5399# ifdef FEAT_TERMINAL
5400 + 13 + version_len + 2
5401# endif
5402 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005403
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005404 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005405 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005406# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005407 for (n = 0; n < 15; n++)
5408 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5409 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005410 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005411 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5412 (WCHAR)servername[n];
5413 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005414# endif
5415# ifdef FEAT_TERMINAL
5416 if (is_terminal)
5417 {
5418 for (n = 0; n < 13; n++)
5419 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5420 (WCHAR)"VIM_TERMINAL="[n];
5421 for (n = 0; n < version_len; n++)
5422 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5423 (WCHAR)version[n];
5424 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5425 }
5426# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005427 }
5428 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005429# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005430}
5431
Bram Moolenaarb091f302019-01-19 14:37:00 +01005432/*
5433 * Create a pair of pipes.
5434 * Return TRUE for success, FALSE for failure.
5435 */
5436 static BOOL
5437create_pipe_pair(HANDLE handles[2])
5438{
5439 static LONG s;
5440 char name[64];
5441 SECURITY_ATTRIBUTES sa;
5442
5443 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5444 GetCurrentProcessId(),
5445 InterlockedIncrement(&s));
5446
5447 // Create named pipe. Max size of named pipe is 65535.
5448 handles[1] = CreateNamedPipe(
5449 name,
5450 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5451 PIPE_TYPE_BYTE | PIPE_NOWAIT,
5452 1, 65535, 0, 0, NULL);
5453
5454 if (handles[1] == INVALID_HANDLE_VALUE)
5455 return FALSE;
5456
5457 sa.nLength = sizeof(sa);
5458 sa.bInheritHandle = TRUE;
5459 sa.lpSecurityDescriptor = NULL;
5460
5461 handles[0] = CreateFile(name,
5462 FILE_GENERIC_READ,
5463 FILE_SHARE_READ, &sa,
5464 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5465
5466 if (handles[0] == INVALID_HANDLE_VALUE)
5467 {
5468 CloseHandle(handles[1]);
5469 return FALSE;
5470 }
5471
5472 return TRUE;
5473}
5474
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005475 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005476mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005477{
5478 STARTUPINFO si;
5479 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005480 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005481 SECURITY_ATTRIBUTES saAttr;
5482 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005483 HANDLE ifd[2];
5484 HANDLE ofd[2];
5485 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005486 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005487
5488 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5489 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5490 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5491 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5492 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5493 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5494 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5495
5496 if (use_out_for_err && use_null_for_out)
5497 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005498
5499 ifd[0] = INVALID_HANDLE_VALUE;
5500 ifd[1] = INVALID_HANDLE_VALUE;
5501 ofd[0] = INVALID_HANDLE_VALUE;
5502 ofd[1] = INVALID_HANDLE_VALUE;
5503 efd[0] = INVALID_HANDLE_VALUE;
5504 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005505 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005506
Bram Moolenaar14207f42016-10-27 21:13:10 +02005507 jo = CreateJobObject(NULL, NULL);
5508 if (jo == NULL)
5509 {
5510 job->jv_status = JOB_FAILED;
5511 goto failed;
5512 }
5513
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005514 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005515 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005516
Bram Moolenaar76467df2016-02-12 19:30:26 +01005517 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005518 ZeroMemory(&si, sizeof(si));
5519 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005520 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005521 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005522
Bram Moolenaard8070362016-02-15 21:56:54 +01005523 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5524 saAttr.bInheritHandle = TRUE;
5525 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005526
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005527 if (use_file_for_in)
5528 {
5529 char_u *fname = options->jo_io_name[PART_IN];
5530
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005531 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5532 FILE_SHARE_READ | FILE_SHARE_WRITE,
5533 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5534 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005535 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005536 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005537 goto failed;
5538 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005539 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005540 else if (!use_null_for_in
5541 && (!create_pipe_pair(ifd)
5542 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005543 goto failed;
5544
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005545 if (use_file_for_out)
5546 {
5547 char_u *fname = options->jo_io_name[PART_OUT];
5548
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005549 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5550 FILE_SHARE_READ | FILE_SHARE_WRITE,
5551 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5552 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005553 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005554 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005555 goto failed;
5556 }
5557 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005558 else if (!use_null_for_out &&
5559 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005560 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005561 goto failed;
5562
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005563 if (use_file_for_err)
5564 {
5565 char_u *fname = options->jo_io_name[PART_ERR];
5566
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005567 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5568 FILE_SHARE_READ | FILE_SHARE_WRITE,
5569 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5570 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005571 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005572 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005573 goto failed;
5574 }
5575 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005576 else if (!use_out_for_err && !use_null_for_err &&
5577 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005578 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005579 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005580
Bram Moolenaard8070362016-02-15 21:56:54 +01005581 si.dwFlags |= STARTF_USESTDHANDLES;
5582 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005583 si.hStdOutput = ofd[1];
5584 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5585
5586 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5587 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005588 if (options->jo_set & JO_CHANNEL)
5589 {
5590 channel = options->jo_channel;
5591 if (channel != NULL)
5592 ++channel->ch_refcount;
5593 }
5594 else
5595 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005596 if (channel == NULL)
5597 goto failed;
5598 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005599
5600 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005601 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005602 CREATE_DEFAULT_ERROR_MODE |
5603 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005604 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005605 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005606 &si, &pi,
5607 ga.ga_data,
5608 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005609 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005610 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005611 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005612 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005613 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005614
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005615 ga_clear(&ga);
5616
Bram Moolenaar14207f42016-10-27 21:13:10 +02005617 if (!AssignProcessToJobObject(jo, pi.hProcess))
5618 {
5619 /* if failing, switch the way to terminate
5620 * process with TerminateProcess. */
5621 CloseHandle(jo);
5622 jo = NULL;
5623 }
5624 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005625 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005626 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005627 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005628 job->jv_status = JOB_STARTED;
5629
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005630 CloseHandle(ifd[0]);
5631 CloseHandle(ofd[1]);
5632 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005633 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005634
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005635 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005636 if (channel != NULL)
5637 {
5638 channel_set_pipes(channel,
5639 use_file_for_in || use_null_for_in
5640 ? INVALID_FD : (sock_T)ifd[1],
5641 use_file_for_out || use_null_for_out
5642 ? INVALID_FD : (sock_T)ofd[0],
5643 use_out_for_err || use_file_for_err || use_null_for_err
5644 ? INVALID_FD : (sock_T)efd[0]);
5645 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005646 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005647 return;
5648
5649failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005650 CloseHandle(ifd[0]);
5651 CloseHandle(ofd[0]);
5652 CloseHandle(efd[0]);
5653 CloseHandle(ifd[1]);
5654 CloseHandle(ofd[1]);
5655 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005656 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005657 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005658}
5659
5660 char *
5661mch_job_status(job_T *job)
5662{
5663 DWORD dwExitCode = 0;
5664
Bram Moolenaar76467df2016-02-12 19:30:26 +01005665 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5666 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005667 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005668 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005669 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005670 {
5671 ch_log(job->jv_channel, "Job ended");
5672 job->jv_status = JOB_ENDED;
5673 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005674 return "dead";
5675 }
5676 return "run";
5677}
5678
Bram Moolenaar97792de2016-10-15 18:36:49 +02005679 job_T *
5680mch_detect_ended_job(job_T *job_list)
5681{
5682 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5683 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5684 job_T *job = job_list;
5685
5686 while (job != NULL)
5687 {
5688 DWORD n;
5689 DWORD result;
5690
5691 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5692 && job != NULL; job = job->jv_next)
5693 {
5694 if (job->jv_status == JOB_STARTED)
5695 {
5696 jobHandles[n] = job->jv_proc_info.hProcess;
5697 jobArray[n] = job;
5698 ++n;
5699 }
5700 }
5701 if (n == 0)
5702 continue;
5703 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5704 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5705 {
5706 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5707
5708 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5709 return wait_job;
5710 }
5711 }
5712 return NULL;
5713}
5714
Bram Moolenaarfb630902016-10-29 14:55:00 +02005715 static BOOL
5716terminate_all(HANDLE process, int code)
5717{
5718 PROCESSENTRY32 pe;
5719 HANDLE h = INVALID_HANDLE_VALUE;
5720 DWORD pid = GetProcessId(process);
5721
5722 if (pid != 0)
5723 {
5724 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5725 if (h != INVALID_HANDLE_VALUE)
5726 {
5727 pe.dwSize = sizeof(PROCESSENTRY32);
5728 if (!Process32First(h, &pe))
5729 goto theend;
5730
5731 do
5732 {
5733 if (pe.th32ParentProcessID == pid)
5734 {
5735 HANDLE ph = OpenProcess(
5736 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5737 if (ph != NULL)
5738 {
5739 terminate_all(ph, code);
5740 CloseHandle(ph);
5741 }
5742 }
5743 } while (Process32Next(h, &pe));
5744
5745 CloseHandle(h);
5746 }
5747 }
5748
5749theend:
5750 return TerminateProcess(process, code);
5751}
5752
5753/*
5754 * Send a (deadly) signal to "job".
5755 * Return FAIL if it didn't work.
5756 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005757 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005758mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005759{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005760 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005761
Bram Moolenaar923d9262016-02-25 20:56:01 +01005762 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005763 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005764 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005765 if (job->jv_job_object != NULL)
5766 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005767 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005768 }
5769
5770 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5771 return FAIL;
5772 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005773 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5774 job->jv_proc_info.dwProcessId)
5775 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005776 FreeConsole();
5777 return ret;
5778}
5779
5780/*
5781 * Clear the data related to "job".
5782 */
5783 void
5784mch_clear_job(job_T *job)
5785{
5786 if (job->jv_status != JOB_FAILED)
5787 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005788 if (job->jv_job_object != NULL)
5789 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005790 CloseHandle(job->jv_proc_info.hProcess);
5791 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005792}
5793#endif
5794
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795
5796#ifndef FEAT_GUI_W32
5797
5798/*
5799 * Start termcap mode
5800 */
5801 static void
5802termcap_mode_start(void)
5803{
5804 DWORD cmodein;
5805
5806 if (g_fTermcapMode)
5807 return;
5808
5809 SaveConsoleBuffer(&g_cbNonTermcap);
5810
5811 if (g_cbTermcap.IsValid)
5812 {
5813 /*
5814 * We've been in termcap mode before. Restore certain screen
5815 * characteristics, including the buffer size and the window
5816 * size. Since we will be redrawing the screen, we don't need
5817 * to restore the actual contents of the buffer.
5818 */
5819 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005820 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5822 Rows = g_cbTermcap.Info.dwSize.Y;
5823 Columns = g_cbTermcap.Info.dwSize.X;
5824 }
5825 else
5826 {
5827 /*
5828 * This is our first time entering termcap mode. Clear the console
5829 * screen buffer, and resize the buffer to match the current window
5830 * size. We will use this as the size of our editing environment.
5831 */
5832 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005833 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5835 }
5836
5837#ifdef FEAT_TITLE
5838 resettitle();
5839#endif
5840
5841 GetConsoleMode(g_hConIn, &cmodein);
5842#ifdef FEAT_MOUSE
5843 if (g_fMouseActive)
5844 cmodein |= ENABLE_MOUSE_INPUT;
5845 else
5846 cmodein &= ~ENABLE_MOUSE_INPUT;
5847#endif
5848 cmodein |= ENABLE_WINDOW_INPUT;
5849 SetConsoleMode(g_hConIn, cmodein);
5850
5851 redraw_later_clear();
5852 g_fTermcapMode = TRUE;
5853}
5854
5855
5856/*
5857 * End termcap mode
5858 */
5859 static void
5860termcap_mode_end(void)
5861{
5862 DWORD cmodein;
5863 ConsoleBuffer *cb;
5864 COORD coord;
5865 DWORD dwDummy;
5866
5867 if (!g_fTermcapMode)
5868 return;
5869
5870 SaveConsoleBuffer(&g_cbTermcap);
5871
5872 GetConsoleMode(g_hConIn, &cmodein);
5873 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5874 SetConsoleMode(g_hConIn, cmodein);
5875
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005876#ifdef FEAT_RESTORE_ORIG_SCREEN
5877 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5878#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005880#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005882 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005883 SetConsoleCursorInfo(g_hConOut, &g_cci);
5884
5885 if (p_rs || exiting)
5886 {
5887 /*
5888 * Clear anything that happens to be on the current line.
5889 */
5890 coord.X = 0;
5891 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5892 FillConsoleOutputCharacter(g_hConOut, ' ',
5893 cb->Info.dwSize.X, coord, &dwDummy);
5894 /*
5895 * The following is just for aesthetics. If we are exiting without
5896 * restoring the screen, then we want to have a prompt string
5897 * appear at the bottom line. However, the command interpreter
5898 * seems to always advance the cursor one line before displaying
5899 * the prompt string, which causes the screen to scroll. To
5900 * counter this, move the cursor up one line before exiting.
5901 */
5902 if (exiting && !p_rs)
5903 coord.Y--;
5904 /*
5905 * Position the cursor at the leftmost column of the desired row.
5906 */
5907 SetConsoleCursorPosition(g_hConOut, coord);
5908 }
5909
5910 g_fTermcapMode = FALSE;
5911}
5912#endif /* FEAT_GUI_W32 */
5913
5914
5915#ifdef FEAT_GUI_W32
5916 void
5917mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005918 char_u *s UNUSED,
5919 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920{
5921 /* never used */
5922}
5923
5924#else
5925
5926/*
5927 * clear `n' chars, starting from `coord'
5928 */
5929 static void
5930clear_chars(
5931 COORD coord,
5932 DWORD n)
5933{
5934 DWORD dwDummy;
5935
5936 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005937
5938 if (!USE_VTP)
5939 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5940 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005941 {
5942 set_console_color_rgb();
5943 gotoxy(coord.X + 1, coord.Y + 1);
5944 vtp_printf("\033[%dX", n);
5945 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946}
5947
5948
5949/*
5950 * Clear the screen
5951 */
5952 static void
5953clear_screen(void)
5954{
5955 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005956
5957 if (!USE_VTP)
5958 clear_chars(g_coord, Rows * Columns);
5959 else
5960 {
5961 set_console_color_rgb();
5962 gotoxy(1, 1);
5963 vtp_printf("\033[2J");
5964 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965}
5966
5967
5968/*
5969 * Clear to end of display
5970 */
5971 static void
5972clear_to_end_of_display(void)
5973{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005974 COORD save = g_coord;
5975
5976 if (!USE_VTP)
5977 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005978 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005979 else
5980 {
5981 set_console_color_rgb();
5982 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5983 vtp_printf("\033[0J");
5984
5985 gotoxy(save.X + 1, save.Y + 1);
5986 g_coord = save;
5987 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005988}
5989
5990
5991/*
5992 * Clear to end of line
5993 */
5994 static void
5995clear_to_end_of_line(void)
5996{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005997 COORD save = g_coord;
5998
5999 if (!USE_VTP)
6000 clear_chars(g_coord, Columns - g_coord.X);
6001 else
6002 {
6003 set_console_color_rgb();
6004 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6005 vtp_printf("\033[0K");
6006
6007 gotoxy(save.X + 1, save.Y + 1);
6008 g_coord = save;
6009 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006010}
6011
6012
6013/*
6014 * Scroll the scroll region up by `cLines' lines
6015 */
6016 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006017scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018{
6019 COORD oldcoord = g_coord;
6020
6021 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6022 delete_lines(cLines);
6023
6024 g_coord = oldcoord;
6025}
6026
6027
6028/*
6029 * Set the scroll region
6030 */
6031 static void
6032set_scroll_region(
6033 unsigned left,
6034 unsigned top,
6035 unsigned right,
6036 unsigned bottom)
6037{
6038 if (left >= right
6039 || top >= bottom
6040 || right > (unsigned) Columns - 1
6041 || bottom > (unsigned) Rows - 1)
6042 return;
6043
6044 g_srScrollRegion.Left = left;
6045 g_srScrollRegion.Top = top;
6046 g_srScrollRegion.Right = right;
6047 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006048
6049 if (USE_VTP)
6050 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051}
6052
6053
6054/*
6055 * Insert `cLines' lines at the current cursor position
6056 */
6057 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006058insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006059{
6060 SMALL_RECT source;
6061 COORD dest;
6062 CHAR_INFO fill;
6063
6064 dest.X = 0;
6065 dest.Y = g_coord.Y + cLines;
6066
6067 source.Left = 0;
6068 source.Top = g_coord.Y;
6069 source.Right = g_srScrollRegion.Right;
6070 source.Bottom = g_srScrollRegion.Bottom - cLines;
6071
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006072 if (!USE_VTP)
6073 {
6074 fill.Char.AsciiChar = ' ';
6075 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006076
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006077 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6078 }
6079 else
6080 {
6081 set_console_color_rgb();
6082
6083 gotoxy(1, source.Top + 1);
6084 vtp_printf("\033[%dT", cLines);
6085 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006086
6087 /* Here we have to deal with a win32 console flake: If the scroll
6088 * region looks like abc and we scroll c to a and fill with d we get
6089 * cbd... if we scroll block c one line at a time to a, we get cdd...
6090 * vim expects cdd consistently... So we have to deal with that
6091 * here... (this also occurs scrolling the same way in the other
6092 * direction). */
6093
6094 if (source.Bottom < dest.Y)
6095 {
6096 COORD coord;
6097
6098 coord.X = 0;
6099 coord.Y = source.Bottom;
6100 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6101 }
6102}
6103
6104
6105/*
6106 * Delete `cLines' lines at the current cursor position
6107 */
6108 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006109delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110{
6111 SMALL_RECT source;
6112 COORD dest;
6113 CHAR_INFO fill;
6114 int nb;
6115
6116 dest.X = 0;
6117 dest.Y = g_coord.Y;
6118
6119 source.Left = 0;
6120 source.Top = g_coord.Y + cLines;
6121 source.Right = g_srScrollRegion.Right;
6122 source.Bottom = g_srScrollRegion.Bottom;
6123
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006124 if (!USE_VTP)
6125 {
6126 fill.Char.AsciiChar = ' ';
6127 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006129 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6130 }
6131 else
6132 {
6133 set_console_color_rgb();
6134
6135 gotoxy(1, source.Top + 1);
6136 vtp_printf("\033[%dS", cLines);
6137 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138
6139 /* Here we have to deal with a win32 console flake: If the scroll
6140 * region looks like abc and we scroll c to a and fill with d we get
6141 * cbd... if we scroll block c one line at a time to a, we get cdd...
6142 * vim expects cdd consistently... So we have to deal with that
6143 * here... (this also occurs scrolling the same way in the other
6144 * direction). */
6145
6146 nb = dest.Y + (source.Bottom - source.Top) + 1;
6147
6148 if (nb < source.Top)
6149 {
6150 COORD coord;
6151
6152 coord.X = 0;
6153 coord.Y = nb;
6154 clear_chars(coord, Columns * (source.Top - nb));
6155 }
6156}
6157
6158
6159/*
6160 * Set the cursor position
6161 */
6162 static void
6163gotoxy(
6164 unsigned x,
6165 unsigned y)
6166{
6167 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6168 return;
6169
6170 /* external cursor coords are 1-based; internal are 0-based */
6171 g_coord.X = x - 1;
6172 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006173
6174 if (!USE_VTP)
6175 SetConsoleCursorPosition(g_hConOut, g_coord);
6176 else
6177 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178}
6179
6180
6181/*
6182 * Set the current text attribute = (foreground | background)
6183 * See ../doc/os_win32.txt for the numbers.
6184 */
6185 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006186textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006188 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189
6190 SetConsoleTextAttribute(g_hConOut, wAttr);
6191}
6192
6193
6194 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006195textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006197 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006199 if (!USE_VTP)
6200 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6201 else
6202 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203}
6204
6205
6206 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006207textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006209 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006211 if (!USE_VTP)
6212 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6213 else
6214 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215}
6216
6217
6218/*
6219 * restore the default text attribute (whatever we started with)
6220 */
6221 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006222normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006224 if (!USE_VTP)
6225 textattr(g_attrDefault);
6226 else
6227 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228}
6229
6230
6231static WORD g_attrPreStandout = 0;
6232
6233/*
6234 * Make the text standout, by brightening it
6235 */
6236 static void
6237standout(void)
6238{
6239 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006240
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6242}
6243
6244
6245/*
6246 * Turn off standout mode
6247 */
6248 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006249standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250{
6251 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006253
6254 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255}
6256
6257
6258/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006259 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 */
6261 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006262mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263{
6264 char_u *p;
6265 int n;
6266
6267 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6268 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006269 if (
6270#ifdef FEAT_TERMGUICOLORS
6271 !p_tgc &&
6272#endif
6273 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274 {
6275 p = T_ME + 2;
6276 n = getdigits(&p);
6277 if (*p == 'm' && n > 0)
6278 {
6279 cterm_normal_fg_color = (n & 0xf) + 1;
6280 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6281 }
6282 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006283#ifdef FEAT_TERMGUICOLORS
6284 cterm_normal_fg_gui_color = INVALCOLOR;
6285 cterm_normal_bg_gui_color = INVALCOLOR;
6286#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287}
6288
6289
6290/*
6291 * visual bell: flash the screen
6292 */
6293 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006294visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295{
6296 COORD coordOrigin = {0, 0};
6297 WORD attrFlash = ~g_attrCurrent & 0xff;
6298
6299 DWORD dwDummy;
6300 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6301
6302 if (oldattrs == NULL)
6303 return;
6304 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6305 coordOrigin, &dwDummy);
6306 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6307 coordOrigin, &dwDummy);
6308
6309 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006310 if (!USE_VTP)
6311 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 coordOrigin, &dwDummy);
6313 vim_free(oldattrs);
6314}
6315
6316
6317/*
6318 * Make the cursor visible or invisible
6319 */
6320 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006321cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322{
6323 s_cursor_visible = fVisible;
6324#ifdef MCH_CURSOR_SHAPE
6325 mch_update_cursor();
6326#endif
6327}
6328
6329
6330/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006331 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006332 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006334 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006336 char_u *pchBuf,
6337 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338{
6339 COORD coord = g_coord;
6340 DWORD written;
6341
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006342#ifdef FEAT_MBYTE
6343 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6344 {
6345 static WCHAR *unicodebuf = NULL;
6346 static int unibuflen = 0;
6347 int length;
6348 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006350 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6351 if (unicodebuf == NULL || length > unibuflen)
6352 {
6353 vim_free(unicodebuf);
6354 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6355 unibuflen = length;
6356 }
6357 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6358 unicodebuf, unibuflen);
6359
6360 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006361
6362 if (!USE_VTP)
6363 {
6364 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6365 coord, &written);
6366 /* When writing fails or didn't write a single character, pretend one
6367 * character was written, otherwise we get stuck. */
6368 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6369 coord, &cchwritten) == 0
6370 || cchwritten == 0)
6371 cchwritten = 1;
6372 }
6373 else
6374 {
6375 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6376 NULL) == 0 || cchwritten == 0)
6377 cchwritten = 1;
6378 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006379
6380 if (cchwritten == length)
6381 {
6382 written = cbToWrite;
6383 g_coord.X += (SHORT)cells;
6384 }
6385 else
6386 {
6387 char_u *p = pchBuf;
6388 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006389 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006390 written = p - pchBuf;
6391 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6392 }
6393 }
6394 else
6395#endif
6396 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006397 if (!USE_VTP)
6398 {
6399 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6400 coord, &written);
6401 /* When writing fails or didn't write a single character, pretend one
6402 * character was written, otherwise we get stuck. */
6403 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6404 coord, &written) == 0
6405 || written == 0)
6406 written = 1;
6407 }
6408 else
6409 {
6410 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6411 NULL) == 0 || written == 0)
6412 written = 1;
6413 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006414
6415 g_coord.X += (SHORT) written;
6416 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417
6418 while (g_coord.X > g_srScrollRegion.Right)
6419 {
6420 g_coord.X -= (SHORT) Columns;
6421 if (g_coord.Y < g_srScrollRegion.Bottom)
6422 g_coord.Y++;
6423 }
6424
6425 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6426
6427 return written;
6428}
6429
6430
6431/*
6432 * mch_write(): write the output buffer to the screen, translating ESC
6433 * sequences into calls to console output routines.
6434 */
6435 void
6436mch_write(
6437 char_u *s,
6438 int len)
6439{
6440 s[len] = NUL;
6441
6442 if (!term_console)
6443 {
6444 write(1, s, (unsigned)len);
6445 return;
6446 }
6447
6448 /* translate ESC | sequences into faked bios calls */
6449 while (len--)
6450 {
6451 /* optimization: use one single write_chars for runs of text,
6452 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006453 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454
6455 if (p_wd)
6456 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006457 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458 if (prefix != 0)
6459 prefix = 1;
6460 }
6461
6462 if (prefix != 0)
6463 {
6464 DWORD nWritten;
6465
6466 nWritten = write_chars(s, prefix);
6467#ifdef MCH_WRITE_DUMP
6468 if (fdDump)
6469 {
6470 fputc('>', fdDump);
6471 fwrite(s, sizeof(char_u), nWritten, fdDump);
6472 fputs("<\n", fdDump);
6473 }
6474#endif
6475 len -= (nWritten - 1);
6476 s += nWritten;
6477 }
6478 else if (s[0] == '\n')
6479 {
6480 /* \n, newline: go to the beginning of the next line or scroll */
6481 if (g_coord.Y == g_srScrollRegion.Bottom)
6482 {
6483 scroll(1);
6484 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6485 }
6486 else
6487 {
6488 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6489 }
6490#ifdef MCH_WRITE_DUMP
6491 if (fdDump)
6492 fputs("\\n\n", fdDump);
6493#endif
6494 s++;
6495 }
6496 else if (s[0] == '\r')
6497 {
6498 /* \r, carriage return: go to beginning of line */
6499 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6500#ifdef MCH_WRITE_DUMP
6501 if (fdDump)
6502 fputs("\\r\n", fdDump);
6503#endif
6504 s++;
6505 }
6506 else if (s[0] == '\b')
6507 {
6508 /* \b, backspace: move cursor one position left */
6509 if (g_coord.X > g_srScrollRegion.Left)
6510 g_coord.X--;
6511 else if (g_coord.Y > g_srScrollRegion.Top)
6512 {
6513 g_coord.X = g_srScrollRegion.Right;
6514 g_coord.Y--;
6515 }
6516 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6517#ifdef MCH_WRITE_DUMP
6518 if (fdDump)
6519 fputs("\\b\n", fdDump);
6520#endif
6521 s++;
6522 }
6523 else if (s[0] == '\a')
6524 {
6525 /* \a, bell */
6526 MessageBeep(0xFFFFFFFF);
6527#ifdef MCH_WRITE_DUMP
6528 if (fdDump)
6529 fputs("\\a\n", fdDump);
6530#endif
6531 s++;
6532 }
6533 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6534 {
6535#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006536 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006538 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006539 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540
6541 switch (s[2])
6542 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 case '0': case '1': case '2': case '3': case '4':
6544 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006545 p = s + 1;
6546 do
6547 {
6548 ++p;
6549 args[argc] = getdigits(&p);
6550 argc += (argc < 15) ? 1 : 0;
6551 if (p > s + len)
6552 break;
6553 } while (*p == ';');
6554
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 if (p > s + len)
6556 break;
6557
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006558 arg1 = args[0];
6559 arg2 = args[1];
6560 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006562 if (argc == 1 && args[0] == 0)
6563 normvideo();
6564 else if (argc == 1)
6565 {
6566 if (USE_VTP)
6567 textcolor((WORD) arg1);
6568 else
6569 textattr((WORD) arg1);
6570 }
6571 else if (USE_VTP)
6572 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006573 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006574 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006576 gotoxy(arg2, arg1);
6577 }
6578 else if (argc == 2 && *p == 'r')
6579 {
6580 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6581 }
6582 else if (argc == 1 && *p == 'A')
6583 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584 gotoxy(g_coord.X + 1,
6585 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6586 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006587 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006588 {
6589 textbackground((WORD) arg1);
6590 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006591 else if (argc == 1 && *p == 'C')
6592 {
6593 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6594 g_coord.Y + 1);
6595 }
6596 else if (argc == 1 && *p == 'f')
6597 {
6598 textcolor((WORD) arg1);
6599 }
6600 else if (argc == 1 && *p == 'H')
6601 {
6602 gotoxy(1, arg1);
6603 }
6604 else if (argc == 1 && *p == 'L')
6605 {
6606 insert_lines(arg1);
6607 }
6608 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006609 {
6610 delete_lines(arg1);
6611 }
6612
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006613 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614 s = p + 1;
6615 break;
6616
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006618 gotoxy(g_coord.X + 1,
6619 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6620 goto got3;
6621
6622 case 'B':
6623 visual_bell();
6624 goto got3;
6625
6626 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006627 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6628 g_coord.Y + 1);
6629 goto got3;
6630
6631 case 'E':
6632 termcap_mode_end();
6633 goto got3;
6634
6635 case 'F':
6636 standout();
6637 goto got3;
6638
6639 case 'f':
6640 standend();
6641 goto got3;
6642
6643 case 'H':
6644 gotoxy(1, 1);
6645 goto got3;
6646
6647 case 'j':
6648 clear_to_end_of_display();
6649 goto got3;
6650
6651 case 'J':
6652 clear_screen();
6653 goto got3;
6654
6655 case 'K':
6656 clear_to_end_of_line();
6657 goto got3;
6658
6659 case 'L':
6660 insert_lines(1);
6661 goto got3;
6662
6663 case 'M':
6664 delete_lines(1);
6665 goto got3;
6666
6667 case 'S':
6668 termcap_mode_start();
6669 goto got3;
6670
6671 case 'V':
6672 cursor_visible(TRUE);
6673 goto got3;
6674
6675 case 'v':
6676 cursor_visible(FALSE);
6677 goto got3;
6678
6679 got3:
6680 s += 3;
6681 len -= 2;
6682 }
6683
6684#ifdef MCH_WRITE_DUMP
6685 if (fdDump)
6686 {
6687 fputs("ESC | ", fdDump);
6688 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6689 fputc('\n', fdDump);
6690 }
6691#endif
6692 }
6693 else
6694 {
6695 /* Write a single character */
6696 DWORD nWritten;
6697
6698 nWritten = write_chars(s, 1);
6699#ifdef MCH_WRITE_DUMP
6700 if (fdDump)
6701 {
6702 fputc('>', fdDump);
6703 fwrite(s, sizeof(char_u), nWritten, fdDump);
6704 fputs("<\n", fdDump);
6705 }
6706#endif
6707
6708 len -= (nWritten - 1);
6709 s += nWritten;
6710 }
6711 }
6712
6713#ifdef MCH_WRITE_DUMP
6714 if (fdDump)
6715 fflush(fdDump);
6716#endif
6717}
6718
6719#endif /* FEAT_GUI_W32 */
6720
6721
6722/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006723 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724 */
6725 void
6726mch_delay(
6727 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006728 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729{
6730#ifdef FEAT_GUI_W32
6731 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006732#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006734# ifdef FEAT_MZSCHEME
6735 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6736 {
6737 int towait = p_mzq;
6738
6739 /* if msec is large enough, wait by portions in p_mzq */
6740 while (msec > 0)
6741 {
6742 mzvim_check_threads();
6743 if (msec < towait)
6744 towait = msec;
6745 Sleep(towait);
6746 msec -= towait;
6747 }
6748 }
6749 else
6750# endif
6751 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006752 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006753 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754#endif
6755}
6756
6757
6758/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006759 * This version of remove is not scared by a readonly (backup) file.
6760 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761 * Return 0 for success, -1 for failure.
6762 */
6763 int
6764mch_remove(char_u *name)
6765{
6766#ifdef FEAT_MBYTE
6767 WCHAR *wn = NULL;
6768 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006769#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770
Bram Moolenaar203258c2016-01-17 22:15:16 +01006771 /*
6772 * On Windows, deleting a directory's symbolic link is done by
6773 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6774 */
6775 if (mch_isdir(name) && mch_is_symbolic_link(name))
6776 return mch_rmdir(name);
6777
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006778 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6779
6780#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006781 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6782 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006783 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784 if (wn != NULL)
6785 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 n = DeleteFileW(wn) ? 0 : -1;
6787 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006788 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789 }
6790 }
6791#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006792 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006793}
6794
6795
6796/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006797 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798 */
6799 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006800mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801{
6802#ifndef FEAT_GUI_W32 /* never used */
6803 if (g_fCtrlCPressed || g_fCBrkPressed)
6804 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006805 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006806 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6807 got_int = TRUE;
6808 }
6809#endif
6810}
6811
Bram Moolenaaree273972016-01-02 21:11:51 +01006812/* physical RAM to leave for the OS */
6813#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006814
6815/*
6816 * How much main memory in KiB that can be used by VIM.
6817 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006818 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006819mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006820{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006821 MEMORYSTATUSEX ms;
6822
Bram Moolenaaree273972016-01-02 21:11:51 +01006823 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006824 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6825 * what fits in 32 bits. But it's not always available. */
6826 ms.dwLength = sizeof(MEMORYSTATUSEX);
6827 GlobalMemoryStatusEx(&ms);
6828 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006829 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006830 /* Process address space fits in physical RAM, use all of it. */
6831 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006832 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006833 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006834 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006835 /* Catch old NT box or perverse hardware setup. */
6836 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006837 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006838 /* Use physical RAM less reserve for OS + data. */
6839 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006840}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006841
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842#ifdef FEAT_MBYTE
6843/*
6844 * Same code as below, but with wide functions and no comments.
6845 * Return 0 for success, non-zero for failure.
6846 */
6847 int
6848mch_wrename(WCHAR *wold, WCHAR *wnew)
6849{
6850 WCHAR *p;
6851 int i;
6852 WCHAR szTempFile[_MAX_PATH + 1];
6853 WCHAR szNewPath[_MAX_PATH + 1];
6854 HANDLE hf;
6855
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006856 p = wold;
6857 for (i = 0; wold[i] != NUL; ++i)
6858 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6859 && wold[i + 1] != 0)
6860 p = wold + i + 1;
6861 if ((int)(wold + i - p) < 8 || p[6] != '~')
6862 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863
6864 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6865 return -1;
6866 *p = NUL;
6867
6868 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6869 return -2;
6870
6871 if (!DeleteFileW(szTempFile))
6872 return -3;
6873
6874 if (!MoveFileW(wold, szTempFile))
6875 return -4;
6876
6877 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6878 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6879 return -5;
6880 if (!CloseHandle(hf))
6881 return -6;
6882
6883 if (!MoveFileW(szTempFile, wnew))
6884 {
6885 (void)MoveFileW(szTempFile, wold);
6886 return -7;
6887 }
6888
6889 DeleteFileW(szTempFile);
6890
6891 if (!DeleteFileW(wold))
6892 return -8;
6893
6894 return 0;
6895}
6896#endif
6897
6898
6899/*
6900 * mch_rename() works around a bug in rename (aka MoveFile) in
6901 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6902 * file whose short file name is "FOO.BAR" (its long file name will
6903 * be correct: "foo.bar~"). Because a file can be accessed by
6904 * either its SFN or its LFN, "foo.bar" has effectively been
6905 * renamed to "foo.bar", which is not at all what was wanted. This
6906 * seems to happen only when renaming files with three-character
6907 * extensions by appending a suffix that does not include ".".
6908 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6909 *
6910 * There is another problem, which isn't really a bug but isn't right either:
6911 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6912 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6913 * service pack 6. Doesn't seem to happen on Windows 98.
6914 *
6915 * Like rename(), returns 0 upon success, non-zero upon failure.
6916 * Should probably set errno appropriately when errors occur.
6917 */
6918 int
6919mch_rename(
6920 const char *pszOldFile,
6921 const char *pszNewFile)
6922{
6923 char szTempFile[_MAX_PATH+1];
6924 char szNewPath[_MAX_PATH+1];
6925 char *pszFilePart;
6926 HANDLE hf;
6927#ifdef FEAT_MBYTE
6928 WCHAR *wold = NULL;
6929 WCHAR *wnew = NULL;
6930 int retval = -1;
6931
6932 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6933 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006934 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6935 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936 if (wold != NULL && wnew != NULL)
6937 retval = mch_wrename(wold, wnew);
6938 vim_free(wold);
6939 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006940 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941 }
6942#endif
6943
6944 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006945 * No need to play tricks unless the file name contains a "~" as the
6946 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006948 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6949 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6950 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951
6952 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6953 * a directory, no error is returned and pszFilePart will be NULL. */
6954 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6955 || pszFilePart == NULL)
6956 return -1;
6957 *pszFilePart = NUL;
6958
6959 /* Get (and create) a unique temporary file name in directory of new file */
6960 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6961 return -2;
6962
6963 /* blow the temp file away */
6964 if (!DeleteFile(szTempFile))
6965 return -3;
6966
6967 /* rename old file to the temp file */
6968 if (!MoveFile(pszOldFile, szTempFile))
6969 return -4;
6970
6971 /* now create an empty file called pszOldFile; this prevents the operating
6972 * system using pszOldFile as an alias (SFN) if we're renaming within the
6973 * same directory. For example, we're editing a file called
6974 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6975 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6976 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006977 * cause all sorts of problems later in buf_write(). So, we create an
6978 * empty file called filena~1.txt and the system will have to find some
6979 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006980 */
6981 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6982 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6983 return -5;
6984 if (!CloseHandle(hf))
6985 return -6;
6986
6987 /* rename the temp file to the new file */
6988 if (!MoveFile(szTempFile, pszNewFile))
6989 {
6990 /* Renaming failed. Rename the file back to its old name, so that it
6991 * looks like nothing happened. */
6992 (void)MoveFile(szTempFile, pszOldFile);
6993
6994 return -7;
6995 }
6996
6997 /* Seems to be left around on Novell filesystems */
6998 DeleteFile(szTempFile);
6999
7000 /* finally, remove the empty old file */
7001 if (!DeleteFile(pszOldFile))
7002 return -8;
7003
7004 return 0; /* success */
7005}
7006
7007/*
7008 * Get the default shell for the current hardware platform
7009 */
7010 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007011default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013 PlatformId();
7014
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007015 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007016}
7017
7018/*
7019 * mch_access() extends access() to do more detailed check on network drives.
7020 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7021 */
7022 int
7023mch_access(char *n, int p)
7024{
7025 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026 int retval = -1; /* default: fail */
7027#ifdef FEAT_MBYTE
7028 WCHAR *wn = NULL;
7029
7030 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007031 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032#endif
7033
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007034 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035 {
7036 char TempName[_MAX_PATH + 16] = "";
7037#ifdef FEAT_MBYTE
7038 WCHAR TempNameW[_MAX_PATH + 16] = L"";
7039#endif
7040
7041 if (p & R_OK)
7042 {
7043 /* Read check is performed by seeing if we can do a find file on
7044 * the directory for any file. */
7045#ifdef FEAT_MBYTE
7046 if (wn != NULL)
7047 {
7048 int i;
7049 WIN32_FIND_DATAW d;
7050
7051 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7052 TempNameW[i] = wn[i];
7053 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7054 TempNameW[i++] = '\\';
7055 TempNameW[i++] = '*';
7056 TempNameW[i++] = 0;
7057
7058 hFile = FindFirstFileW(TempNameW, &d);
7059 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007060 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 else
7062 (void)FindClose(hFile);
7063 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007064 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065#endif
7066 {
7067 char *pch;
7068 WIN32_FIND_DATA d;
7069
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007070 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 pch = TempName + STRLEN(TempName) - 1;
7072 if (*pch != '\\' && *pch != '/')
7073 *++pch = '\\';
7074 *++pch = '*';
7075 *++pch = NUL;
7076
7077 hFile = FindFirstFile(TempName, &d);
7078 if (hFile == INVALID_HANDLE_VALUE)
7079 goto getout;
7080 (void)FindClose(hFile);
7081 }
7082 }
7083
7084 if (p & W_OK)
7085 {
7086 /* Trying to create a temporary file in the directory should catch
7087 * directories on read-only network shares. However, in
7088 * directories whose ACL allows writes but denies deletes will end
7089 * up keeping the temporary file :-(. */
7090#ifdef FEAT_MBYTE
7091 if (wn != NULL)
7092 {
7093 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007094 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095 else
7096 DeleteFileW(TempNameW);
7097 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007098 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099#endif
7100 {
7101 if (!GetTempFileName(n, "VIM", 0, TempName))
7102 goto getout;
7103 mch_remove((char_u *)TempName);
7104 }
7105 }
7106 }
7107 else
7108 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007109 // Don't consider a file read-only if another process has opened it.
7110 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7111
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 /* Trying to open the file for the required access does ACL, read-only
7113 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007114 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7115 | ((p & R_OK) ? GENERIC_READ : 0);
7116
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117#ifdef FEAT_MBYTE
7118 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007119 hFile = CreateFileW(wn, access_mode, share_mode,
7120 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007121 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122#endif
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007123 hFile = CreateFile(n, access_mode, share_mode,
7124 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125 if (hFile == INVALID_HANDLE_VALUE)
7126 goto getout;
7127 CloseHandle(hFile);
7128 }
7129
7130 retval = 0; /* success */
7131getout:
7132#ifdef FEAT_MBYTE
7133 vim_free(wn);
7134#endif
7135 return retval;
7136}
7137
7138#if defined(FEAT_MBYTE) || defined(PROTO)
7139/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007140 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007141 */
7142 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007143mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007145 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
7146# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147 WCHAR *wn;
7148 int f;
7149
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007150 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007152 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153 if (wn != NULL)
7154 {
7155 f = _wopen(wn, flags, mode);
7156 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007157 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 }
7159 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007160# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007161
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007162 /* open() can open a file which name is longer than _MAX_PATH bytes
7163 * and shorter than _MAX_PATH characters successfully, but sometimes it
7164 * causes unexpected error in another part. We make it an error explicitly
7165 * here. */
7166 if (strlen(name) >= _MAX_PATH)
7167 return -1;
7168
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169 return open(name, flags, mode);
7170}
7171
7172/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007173 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007174 */
7175 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007176mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007177{
7178 WCHAR *wn, *wm;
7179 FILE *f = NULL;
7180
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007181 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007182 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007183# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007184 /* Work around an annoying assertion in the Microsoft debug CRT
7185 * when mode's text/binary setting doesn't match _get_fmode(). */
7186 char newMode = mode[strlen(mode) - 1];
7187 int oldMode = 0;
7188
7189 _get_fmode(&oldMode);
7190 if (newMode == 't')
7191 _set_fmode(_O_TEXT);
7192 else if (newMode == 'b')
7193 _set_fmode(_O_BINARY);
7194# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007195 wn = enc_to_utf16((char_u *)name, NULL);
7196 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197 if (wn != NULL && wm != NULL)
7198 f = _wfopen(wn, wm);
7199 vim_free(wn);
7200 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007201
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007202# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007203 _set_fmode(oldMode);
7204# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007205 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007206 }
7207
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007208 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7209 * and shorter than _MAX_PATH characters successfully, but sometimes it
7210 * causes unexpected error in another part. We make it an error explicitly
7211 * here. */
7212 if (strlen(name) >= _MAX_PATH)
7213 return NULL;
7214
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 return fopen(name, mode);
7216}
7217#endif
7218
7219#ifdef FEAT_MBYTE
7220/*
7221 * SUB STREAM (aka info stream) handling:
7222 *
7223 * NTFS can have sub streams for each file. Normal contents of file is
7224 * stored in the main stream, and extra contents (author information and
7225 * title and so on) can be stored in sub stream. After Windows 2000, user
7226 * can access and store those informations in sub streams via explorer's
7227 * property menuitem in right click menu. Those informations in sub streams
7228 * were lost when copying only the main stream. So we have to copy sub
7229 * streams.
7230 *
7231 * Incomplete explanation:
7232 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7233 * More useful info and an example:
7234 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7235 */
7236
7237/*
7238 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7239 * and write to stream "substream" of file "to".
7240 * Errors are ignored.
7241 */
7242 static void
7243copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7244{
7245 HANDLE hTo;
7246 WCHAR *to_name;
7247
7248 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7249 wcscpy(to_name, to);
7250 wcscat(to_name, substream);
7251
7252 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7253 FILE_ATTRIBUTE_NORMAL, NULL);
7254 if (hTo != INVALID_HANDLE_VALUE)
7255 {
7256 long done;
7257 DWORD todo;
7258 DWORD readcnt, written;
7259 char buf[4096];
7260
7261 /* Copy block of bytes at a time. Abort when something goes wrong. */
7262 for (done = 0; done < len; done += written)
7263 {
7264 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007265 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7266 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007267 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7268 FALSE, FALSE, context)
7269 || readcnt != todo
7270 || !WriteFile(hTo, buf, todo, &written, NULL)
7271 || written != todo)
7272 break;
7273 }
7274 CloseHandle(hTo);
7275 }
7276
7277 free(to_name);
7278}
7279
7280/*
7281 * Copy info streams from file "from" to file "to".
7282 */
7283 static void
7284copy_infostreams(char_u *from, char_u *to)
7285{
7286 WCHAR *fromw;
7287 WCHAR *tow;
7288 HANDLE sh;
7289 WIN32_STREAM_ID sid;
7290 int headersize;
7291 WCHAR streamname[_MAX_PATH];
7292 DWORD readcount;
7293 void *context = NULL;
7294 DWORD lo, hi;
7295 int len;
7296
7297 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007298 fromw = enc_to_utf16(from, NULL);
7299 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300 if (fromw != NULL && tow != NULL)
7301 {
7302 /* Open the file for reading. */
7303 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7304 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7305 if (sh != INVALID_HANDLE_VALUE)
7306 {
7307 /* Use BackupRead() to find the info streams. Repeat until we
7308 * have done them all.*/
7309 for (;;)
7310 {
7311 /* Get the header to find the length of the stream name. If
7312 * the "readcount" is zero we have done all info streams. */
7313 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007314 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007315 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7316 &readcount, FALSE, FALSE, &context)
7317 || readcount == 0)
7318 break;
7319
7320 /* We only deal with streams that have a name. The normal
7321 * file data appears to be without a name, even though docs
7322 * suggest it is called "::$DATA". */
7323 if (sid.dwStreamNameSize > 0)
7324 {
7325 /* Read the stream name. */
7326 if (!BackupRead(sh, (LPBYTE)streamname,
7327 sid.dwStreamNameSize,
7328 &readcount, FALSE, FALSE, &context))
7329 break;
7330
7331 /* Copy an info stream with a name ":anything:$DATA".
7332 * Skip "::$DATA", it has no stream name (examples suggest
7333 * it might be used for the normal file contents).
7334 * Note that BackupRead() counts bytes, but the name is in
7335 * wide characters. */
7336 len = readcount / sizeof(WCHAR);
7337 streamname[len] = 0;
7338 if (len > 7 && wcsicmp(streamname + len - 6,
7339 L":$DATA") == 0)
7340 {
7341 streamname[len - 6] = 0;
7342 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007343 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344 }
7345 }
7346
7347 /* Advance to the next stream. We might try seeking too far,
7348 * but BackupSeek() doesn't skip over stream borders, thus
7349 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007350 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351 &lo, &hi, &context);
7352 }
7353
7354 /* Clear the context. */
7355 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7356
7357 CloseHandle(sh);
7358 }
7359 }
7360 vim_free(fromw);
7361 vim_free(tow);
7362}
7363#endif
7364
7365/*
7366 * Copy file attributes from file "from" to file "to".
7367 * For Windows NT and later we copy info streams.
7368 * Always returns zero, errors are ignored.
7369 */
7370 int
7371mch_copy_file_attribute(char_u *from, char_u *to)
7372{
7373#ifdef FEAT_MBYTE
7374 /* File streams only work on Windows NT and later. */
7375 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007376 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377#endif
7378 return 0;
7379}
7380
7381#if defined(MYRESETSTKOFLW) || defined(PROTO)
7382/*
7383 * Recreate a destroyed stack guard page in win32.
7384 * Written by Benjamin Peterson.
7385 */
7386
7387/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007388# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389
7390/*
7391 * This function does the same thing as _resetstkoflw(), which is only
7392 * available in DevStudio .net and later.
7393 * Returns 0 for failure, 1 for success.
7394 */
7395 int
7396myresetstkoflw(void)
7397{
7398 BYTE *pStackPtr;
7399 BYTE *pGuardPage;
7400 BYTE *pStackBase;
7401 BYTE *pLowestPossiblePage;
7402 MEMORY_BASIC_INFORMATION mbi;
7403 SYSTEM_INFO si;
7404 DWORD nPageSize;
7405 DWORD dummy;
7406
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007408
7409 /* We need to know the system page size. */
7410 GetSystemInfo(&si);
7411 nPageSize = si.dwPageSize;
7412
7413 /* ...and the current stack pointer */
7414 pStackPtr = (BYTE*)_alloca(1);
7415
7416 /* ...and the base of the stack. */
7417 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7418 return 0;
7419 pStackBase = (BYTE*)mbi.AllocationBase;
7420
7421 /* ...and the page thats min_stack_req pages away from stack base; this is
7422 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007423 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424
Bram Moolenaar071d4272004-06-13 20:20:40 +00007425 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007426 /* We want the first committed page in the stack Start at the stack
7427 * base and move forward through memory until we find a committed block.
7428 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 BYTE *pBlock = pStackBase;
7430
Bram Moolenaara466c992005-07-09 21:03:22 +00007431 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007432 {
7433 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7434 return 0;
7435
7436 pBlock += mbi.RegionSize;
7437
7438 if (mbi.State & MEM_COMMIT)
7439 break;
7440 }
7441
7442 /* mbi now describes the first committed block in the stack. */
7443 if (mbi.Protect & PAGE_GUARD)
7444 return 1;
7445
7446 /* decide where the guard page should start */
7447 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7448 pGuardPage = pLowestPossiblePage;
7449 else
7450 pGuardPage = (BYTE*)mbi.BaseAddress;
7451
7452 /* allocate the guard page */
7453 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7454 return 0;
7455
7456 /* apply the guard attribute to the page */
7457 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7458 &dummy))
7459 return 0;
7460 }
7461
7462 return 1;
7463}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007464#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007465
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007466
7467#if defined(FEAT_MBYTE) || defined(PROTO)
7468/*
7469 * The command line arguments in UCS2
7470 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007471static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007472static LPWSTR *ArglistW = NULL;
7473static int global_argc = 0;
7474static char **global_argv;
7475
7476static int used_file_argc = 0; /* last argument in global_argv[] used
7477 for the argument list. */
7478static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7479 command line arguments added to
7480 the argument list */
7481static int used_file_count = 0; /* nr of entries in used_file_indexes */
7482static int used_file_literal = FALSE; /* take file names literally */
7483static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007484static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007485static int used_alist_count = 0;
7486
7487
7488/*
7489 * Get the command line arguments. Unicode version.
7490 * Returns argc. Zero when something fails.
7491 */
7492 int
7493get_cmd_argsW(char ***argvp)
7494{
7495 char **argv = NULL;
7496 int argc = 0;
7497 int i;
7498
Bram Moolenaar14993322014-09-09 12:25:33 +02007499 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007500 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7501 if (ArglistW != NULL)
7502 {
7503 argv = malloc((nArgsW + 1) * sizeof(char *));
7504 if (argv != NULL)
7505 {
7506 argc = nArgsW;
7507 argv[argc] = NULL;
7508 for (i = 0; i < argc; ++i)
7509 {
7510 int len;
7511
7512 /* Convert each Unicode argument to the current codepage. */
7513 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007514 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007515 (LPSTR *)&argv[i], &len, 0, 0);
7516 if (argv[i] == NULL)
7517 {
7518 /* Out of memory, clear everything. */
7519 while (i > 0)
7520 free(argv[--i]);
7521 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007522 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007523 argc = 0;
7524 }
7525 }
7526 }
7527 }
7528
7529 global_argc = argc;
7530 global_argv = argv;
7531 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007532 {
7533 if (used_file_indexes != NULL)
7534 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007535 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007536 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007537
7538 if (argvp != NULL)
7539 *argvp = argv;
7540 return argc;
7541}
7542
7543 void
7544free_cmd_argsW(void)
7545{
7546 if (ArglistW != NULL)
7547 {
7548 GlobalFree(ArglistW);
7549 ArglistW = NULL;
7550 }
7551}
7552
7553/*
7554 * Remember "name" is an argument that was added to the argument list.
7555 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7556 * is called.
7557 */
7558 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007559used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007560{
7561 int i;
7562
7563 if (used_file_indexes == NULL)
7564 return;
7565 for (i = used_file_argc + 1; i < global_argc; ++i)
7566 if (STRCMP(global_argv[i], name) == 0)
7567 {
7568 used_file_argc = i;
7569 used_file_indexes[used_file_count++] = i;
7570 break;
7571 }
7572 used_file_literal = literal;
7573 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007574 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007575}
7576
7577/*
7578 * Remember the length of the argument list as it was. If it changes then we
7579 * leave it alone when 'encoding' is set.
7580 */
7581 void
7582set_alist_count(void)
7583{
7584 used_alist_count = GARGCOUNT;
7585}
7586
7587/*
7588 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7589 * has been changed while starting up. Use the UCS-2 command line arguments
7590 * and convert them to 'encoding'.
7591 */
7592 void
7593fix_arg_enc(void)
7594{
7595 int i;
7596 int idx;
7597 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007598 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007599
7600 /* Safety checks:
7601 * - if argument count differs between the wide and non-wide argument
7602 * list, something must be wrong.
7603 * - the file name arguments must have been located.
7604 * - the length of the argument list wasn't changed by the user.
7605 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007606 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007607 || ArglistW == NULL
7608 || used_file_indexes == NULL
7609 || used_file_count == 0
7610 || used_alist_count != GARGCOUNT)
7611 return;
7612
Bram Moolenaar86b68352004-12-27 21:59:20 +00007613 /* Remember the buffer numbers for the arguments. */
7614 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7615 if (fnum_list == NULL)
7616 return; /* out of memory */
7617 for (i = 0; i < GARGCOUNT; ++i)
7618 fnum_list[i] = GARGLIST[i].ae_fnum;
7619
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007620 /* Clear the argument list. Make room for the new arguments. */
7621 alist_clear(&global_alist);
7622 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007623 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007624
7625 for (i = 0; i < used_file_count; ++i)
7626 {
7627 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007628 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007629 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007630 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007631 int literal = used_file_literal;
7632
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007633# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007634 /* When using diff mode may need to concatenate file name to
7635 * directory name. Just like it's done in main(). */
7636 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7637 && !mch_isdir(alist_name(&GARGLIST[0])))
7638 {
7639 char_u *r;
7640
7641 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7642 if (r != NULL)
7643 {
7644 vim_free(str);
7645 str = r;
7646 }
7647 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007648# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007649 /* Re-use the old buffer by renaming it. When not using literal
7650 * names it's done by alist_expand() below. */
7651 if (used_file_literal)
7652 buf_set_name(fnum_list[i], str);
7653
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007654 /* Check backtick literal. backtick literal is already expanded in
7655 * main.c, so this part add str as literal. */
7656 if (literal == FALSE)
7657 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007658 size_t len = STRLEN(str);
7659
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007660 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7661 literal = TRUE;
7662 }
7663 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007664 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007665 }
7666
7667 if (!used_file_literal)
7668 {
7669 /* Now expand wildcards in the arguments. */
7670 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7671 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007672 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7673 * Also, unset wildignore to not be influenced by this option.
7674 * The arguments specified in command-line should be kept even if
7675 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007676 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007677 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007678 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007679 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007680 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007681 }
7682
7683 /* If wildcard expansion failed, we are editing the first file of the
7684 * arglist and there is no file name: Edit the first argument now. */
7685 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7686 {
7687 do_cmdline_cmd((char_u *)":rewind");
7688 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007689 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007690 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007691
7692 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007693}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007694#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007695
7696 int
7697mch_setenv(char *var, char *value, int x)
7698{
7699 char_u *envbuf;
7700
7701 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7702 if (envbuf == NULL)
7703 return -1;
7704
7705 sprintf((char *)envbuf, "%s=%s", var, value);
7706
7707#ifdef FEAT_MBYTE
7708 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7709 {
7710 WCHAR *p = enc_to_utf16(envbuf, NULL);
7711
7712 vim_free(envbuf);
7713 if (p == NULL)
7714 return -1;
7715 _wputenv(p);
7716# ifdef libintl_wputenv
7717 libintl_wputenv(p);
7718# endif
7719 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7720 vim_free(p);
7721 }
7722 else
7723#endif
7724 {
7725 _putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007726#ifdef libintl_putenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007727 libintl_putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007728#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007729 /* Unlike Un*x systems, we can free the string for _putenv(). */
7730 vim_free(envbuf);
7731 }
7732
7733 return 0;
7734}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007735
7736#ifndef FEAT_GUI_W32
7737
7738/*
7739 * Support for 256 colors and 24-bit colors was added in Windows 10
7740 * version 1703 (Creators update).
7741 */
7742# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7743
7744 static void
7745vtp_init(void)
7746{
7747 DWORD ver, mode;
7748 HMODULE hKerneldll;
7749 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007750# ifdef FEAT_TERMGUICOLORS
7751 COLORREF fg, bg;
7752# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007753
7754 ver = get_build_number();
7755 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7756 GetConsoleMode(g_hConOut, &mode);
7757 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7758 if (SetConsoleMode(g_hConOut, mode) == 0)
7759 vtp_working = 0;
7760
7761 /* Use functions supported from Vista */
7762 hKerneldll = GetModuleHandle("kernel32.dll");
7763 if (hKerneldll != NULL)
7764 {
7765 pGetConsoleScreenBufferInfoEx =
7766 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7767 hKerneldll, "GetConsoleScreenBufferInfoEx");
7768 pSetConsoleScreenBufferInfoEx =
7769 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7770 hKerneldll, "SetConsoleScreenBufferInfoEx");
7771 if (pGetConsoleScreenBufferInfoEx != NULL
7772 && pSetConsoleScreenBufferInfoEx != NULL)
7773 has_csbiex = TRUE;
7774 }
7775
7776 csbi.cbSize = sizeof(csbi);
7777 if (has_csbiex)
7778 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007779 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7780 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7781
7782# ifdef FEAT_TERMGUICOLORS
7783 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7784 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7785 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7786 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7787 default_console_color_bg = bg;
7788 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007789# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007790
7791 set_console_color_rgb();
7792}
7793
7794 static void
7795vtp_exit(void)
7796{
7797 reset_console_color_rgb();
7798}
7799
7800 static int
7801vtp_printf(
7802 char *format,
7803 ...)
7804{
7805 char_u buf[100];
7806 va_list list;
7807 DWORD result;
7808
7809 va_start(list, format);
7810 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7811 va_end(list);
7812 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7813 return (int)result;
7814}
7815
7816 static void
7817vtp_sgr_bulk(
7818 int arg)
7819{
7820 int args[1];
7821
7822 args[0] = arg;
7823 vtp_sgr_bulks(1, args);
7824}
7825
7826 static void
7827vtp_sgr_bulks(
7828 int argc,
7829 int *args
7830)
7831{
7832 /* 2('\033[') + 4('255.') * 16 + NUL */
7833 char_u buf[2 + (4 * 16) + 1];
7834 char_u *p;
7835 int i;
7836
7837 p = buf;
7838 *p++ = '\033';
7839 *p++ = '[';
7840
7841 for (i = 0; i < argc; ++i)
7842 {
7843 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7844 *p++ = ';';
7845 }
7846 p--;
7847 *p++ = 'm';
7848 *p = NUL;
7849 vtp_printf((char *)buf);
7850}
7851
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007852# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007853 static int
7854ctermtoxterm(
7855 int cterm)
7856{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007857 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007858
7859 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7860 return (((int)r << 16) | ((int)g << 8) | (int)b);
7861}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007862# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007863
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007864 static void
7865set_console_color_rgb(void)
7866{
7867# ifdef FEAT_TERMGUICOLORS
7868 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7869 int id;
7870 guicolor_T fg = INVALCOLOR;
7871 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007872 int ctermfg;
7873 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007874
7875 if (!USE_VTP)
7876 return;
7877
7878 id = syn_name2id((char_u *)"Normal");
7879 if (id > 0)
7880 syn_id2colors(id, &fg, &bg);
7881 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007882 {
7883 ctermfg = -1;
7884 if (id > 0)
7885 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007886 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7887 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007888 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007889 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007890 {
7891 ctermbg = -1;
7892 if (id > 0)
7893 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007894 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7895 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007896 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007897 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7898 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7899
7900 csbi.cbSize = sizeof(csbi);
7901 if (has_csbiex)
7902 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7903
7904 csbi.cbSize = sizeof(csbi);
7905 csbi.srWindow.Right += 1;
7906 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007907 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7908 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007909 if (has_csbiex)
7910 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7911# endif
7912}
7913
7914 static void
7915reset_console_color_rgb(void)
7916{
7917# ifdef FEAT_TERMGUICOLORS
7918 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7919
7920 csbi.cbSize = sizeof(csbi);
7921 if (has_csbiex)
7922 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7923
7924 csbi.cbSize = sizeof(csbi);
7925 csbi.srWindow.Right += 1;
7926 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007927 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7928 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007929 if (has_csbiex)
7930 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7931# endif
7932}
7933
7934 void
7935control_console_color_rgb(void)
7936{
7937 if (USE_VTP)
7938 set_console_color_rgb();
7939 else
7940 reset_console_color_rgb();
7941}
7942
7943 int
7944has_vtp_working(void)
7945{
7946 return vtp_working;
7947}
7948
7949 int
7950use_vtp(void)
7951{
7952 return USE_VTP;
7953}
7954
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007955 int
7956is_term_win32(void)
7957{
7958 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7959}
7960
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007961#endif