blob: 6a127a44a3815be77a06e14bcb0b97a4284f835d [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--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100455 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100456 p += n;
457 l -= n;
458 }
459}
460
461/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200462 * Load library "name".
463 */
464 HINSTANCE
465vimLoadLib(char *name)
466{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200467 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200468
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200469 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
470 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200471 if (exe_path == NULL)
472 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200473 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200475 WCHAR old_dirw[MAXPATHL];
476
477 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
478 {
479 /* Change directory to where the executable is, both to make
480 * sure we find a .dll there and to avoid looking for a .dll
481 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100482 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200483 dll = LoadLibrary(name);
484 SetCurrentDirectoryW(old_dirw);
485 return dll;
486 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200487 }
488 return dll;
489}
490
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100491#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
492/*
493 * Get related information about 'funcname' which is imported by 'hInst'.
494 * If 'info' is 0, return the function address.
495 * If 'info' is 1, return the module name which the function is imported from.
496 */
497 static void *
498get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
499{
500 PBYTE pImage = (PBYTE)hInst;
501 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
502 PIMAGE_NT_HEADERS pPE;
503 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
504 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
505 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
506 PIMAGE_IMPORT_BY_NAME pImpName;
507
508 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
509 return NULL;
510 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
511 if (pPE->Signature != IMAGE_NT_SIGNATURE)
512 return NULL;
513 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
514 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
515 .VirtualAddress);
516 for (; pImpDesc->FirstThunk; ++pImpDesc)
517 {
518 if (!pImpDesc->OriginalFirstThunk)
519 continue;
520 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
521 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
522 for (; pIAT->u1.Function; ++pIAT, ++pINT)
523 {
524 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
525 continue;
526 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
527 + (UINT_PTR)(pINT->u1.AddressOfData));
528 if (strcmp((char *)pImpName->Name, funcname) == 0)
529 {
530 switch (info)
531 {
532 case 0:
533 return (void *)pIAT->u1.Function;
534 case 1:
535 return (void *)(pImage + pImpDesc->Name);
536 default:
537 return NULL;
538 }
539 }
540 }
541 }
542 return NULL;
543}
544
545/*
546 * Get the module handle which 'funcname' in 'hInst' is imported from.
547 */
548 HINSTANCE
549find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
550{
551 char *modulename;
552
553 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
554 if (modulename != NULL)
555 return GetModuleHandleA(modulename);
556 return NULL;
557}
558
559/*
560 * Get the address of 'funcname' which is imported by 'hInst' DLL.
561 */
562 void *
563get_dll_import_func(HINSTANCE hInst, const char *funcname)
564{
565 return get_imported_func_info(hInst, funcname, 0);
566}
567#endif
568
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
570# ifndef GETTEXT_DLL
571# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200572# define GETTEXT_DLL_ALT1 "libintl-8.dll"
573# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000574# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200575/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000576static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200577static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000578static char *null_libintl_textdomain(const char *);
579static char *null_libintl_bindtextdomain(const char *, const char *);
580static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100581static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100582static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000583
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200584static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000585char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200586char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
587 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000588char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
589char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000591char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
592 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100593int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100594int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000595
596 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100597dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598{
599 int i;
600 static struct
601 {
602 char *name;
603 FARPROC *ptr;
604 } libintl_entry[] =
605 {
606 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200607 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
609 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
610 {NULL, NULL}
611 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100612 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000613
Bram Moolenaar7554c542018-10-06 15:03:15 +0200614 // No need to initialize twice.
615 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200617 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100618 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200619#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100620 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200621 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
622#endif
623#ifdef GETTEXT_DLL_ALT2
624 if (!hLibintlDLL)
625 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100626#endif
627 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000628 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200629 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200631 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100632 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200633 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200635 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000636 }
637 for (i = 0; libintl_entry[i].name != NULL
638 && libintl_entry[i].ptr != NULL; ++i)
639 {
640 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
641 libintl_entry[i].name)) == NULL)
642 {
643 dyn_libintl_end();
644 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000645 {
646 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100647 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000648 verbose_leave();
649 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000650 return 0;
651 }
652 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000653
654 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000655 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000656 "bind_textdomain_codeset");
657 if (dyn_libintl_bind_textdomain_codeset == NULL)
658 dyn_libintl_bind_textdomain_codeset =
659 null_libintl_bind_textdomain_codeset;
660
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100661 /* _putenv() function for the libintl.dll is optional. */
662 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
663 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100664 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100665 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100666 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
667 }
668 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100669 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100670 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
671 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100672
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673 return 1;
674}
675
676 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100677dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678{
679 if (hLibintlDLL)
680 FreeLibrary(hLibintlDLL);
681 hLibintlDLL = NULL;
682 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200683 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684 dyn_libintl_textdomain = null_libintl_textdomain;
685 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000686 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100687 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100688 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000689}
690
691 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000692null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693{
694 return (char*)msgid;
695}
696
697 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200698null_libintl_ngettext(
699 const char *msgid,
700 const char *msgid_plural,
701 unsigned long n)
702{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200703 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200704}
705
Bram Moolenaaree695f72016-08-03 22:08:45 +0200706 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100707null_libintl_bindtextdomain(
708 const char *domainname UNUSED,
709 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710{
711 return NULL;
712}
713
714 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100715null_libintl_bind_textdomain_codeset(
716 const char *domainname UNUSED,
717 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000718{
719 return NULL;
720}
721
722 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100723null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724{
725 return NULL;
726}
727
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200728 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100729null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100730{
731 return 0;
732}
733
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200734 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100735null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100736{
737 return 0;
738}
739
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740#endif /* DYNAMIC_GETTEXT */
741
742/* This symbol is not defined in older versions of the SDK or Visual C++ */
743
744#ifndef VER_PLATFORM_WIN32_WINDOWS
745# define VER_PLATFORM_WIN32_WINDOWS 1
746#endif
747
748DWORD g_PlatformId;
749
750#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100751# ifndef PROTO
752# include <aclapi.h>
753# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200754# ifndef PROTECTED_DACL_SECURITY_INFORMATION
755# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
756# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000757#endif
758
Bram Moolenaar27515922013-06-29 15:36:26 +0200759#ifdef HAVE_ACL
760/*
761 * Enables or disables the specified privilege.
762 */
763 static BOOL
764win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
765{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100766 BOOL bResult;
767 LUID luid;
768 HANDLE hToken;
769 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200770
771 if (!OpenProcessToken(GetCurrentProcess(),
772 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
773 return FALSE;
774
775 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
776 {
777 CloseHandle(hToken);
778 return FALSE;
779 }
780
Bram Moolenaar45500912014-07-09 20:51:07 +0200781 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200782 tokenPrivileges.Privileges[0].Luid = luid;
783 tokenPrivileges.Privileges[0].Attributes = bEnable ?
784 SE_PRIVILEGE_ENABLED : 0;
785
786 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
787 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
788
789 CloseHandle(hToken);
790
791 return bResult && GetLastError() == ERROR_SUCCESS;
792}
793#endif
794
Bram Moolenaar071d4272004-06-13 20:20:40 +0000795/*
796 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
797 * VER_PLATFORM_WIN32_WINDOWS (Win95).
798 */
799 void
800PlatformId(void)
801{
802 static int done = FALSE;
803
804 if (!done)
805 {
806 OSVERSIONINFO ovi;
807
808 ovi.dwOSVersionInfoSize = sizeof(ovi);
809 GetVersionEx(&ovi);
810
811 g_PlatformId = ovi.dwPlatformId;
812
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100813 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
814 || ovi.dwMajorVersion > 6)
815 win8_or_later = TRUE;
816
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200818 /* Enable privilege for getting or setting SACLs. */
819 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820#endif
821 done = TRUE;
822 }
823}
824
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825#ifndef FEAT_GUI_W32
826
827#define SHIFT (SHIFT_PRESSED)
828#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
829#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
830#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
831
832
833/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
834 * We map function keys to their ANSI terminal equivalents, as produced
835 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
836 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
837 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
838 * combinations of function/arrow/etc keys.
839 */
840
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000841static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000842{
843 WORD wVirtKey;
844 BOOL fAnsiKey;
845 int chAlone;
846 int chShift;
847 int chCtrl;
848 int chAlt;
849} VirtKeyMap[] =
850{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200851// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000852 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
853
854 { VK_F1, TRUE, ';', 'T', '^', 'h', },
855 { VK_F2, TRUE, '<', 'U', '_', 'i', },
856 { VK_F3, TRUE, '=', 'V', '`', 'j', },
857 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
858 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
859 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
860 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
861 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
862 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
863 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200864 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
865 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200867 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
868 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
869 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
870 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
871 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
872 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
873 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
874 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
875 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
876 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200878 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879
880#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200881 // Most people don't have F13-F20, but what the hell...
882 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
883 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
884 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
885 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
886 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
887 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
888 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
889 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200891 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
892 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
893 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
894 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000895
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200896 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
897 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
898 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
899 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
900 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
901 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
902 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
903 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
904 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
905 // Sorry, out of number space! <negri>
906 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
907
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908};
909
910
911#ifdef _MSC_VER
912// The ToAscii bug destroys several registers. Need to turn off optimization
913// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000914# pragma warning(push)
915# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916# pragma optimize("", off)
917#endif
918
919#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200920# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200922# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923#endif
924
925/* The return code indicates key code size. */
926 static int
927#ifdef __BORLANDC__
928 __stdcall
929#endif
930win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000931 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932{
933 UINT uMods = pker->dwControlKeyState;
934 static int s_iIsDead = 0;
935 static WORD awAnsiCode[2];
936 static BYTE abKeystate[256];
937
938
939 if (s_iIsDead == 2)
940 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200941 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942 s_iIsDead = 0;
943 return 1;
944 }
945
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200946 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000947 return 1;
948
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200949 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200952 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953
954 if (uMods & SHIFT_PRESSED)
955 abKeystate[VK_SHIFT] = 0x80;
956 if (uMods & CAPSLOCK_ON)
957 abKeystate[VK_CAPITAL] = 1;
958
959 if ((uMods & ALT_GR) == ALT_GR)
960 {
961 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
962 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
963 }
964
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200965 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
966 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967
968 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200969 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970
971 return s_iIsDead;
972}
973
974#ifdef _MSC_VER
975/* MUST switch optimization on again here, otherwise a call to
976 * decode_key_event() may crash (e.g. when hitting caps-lock) */
977# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000978# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979
980# if (_MSC_VER < 1100)
981/* MUST turn off global optimisation for this next function, or
982 * pressing ctrl-minus in insert mode crashes Vim when built with
983 * VC4.1. -- negri. */
984# pragma optimize("g", off)
985# endif
986#endif
987
988static BOOL g_fJustGotFocus = FALSE;
989
990/*
991 * Decode a KEY_EVENT into one or two keystrokes
992 */
993 static BOOL
994decode_key_event(
995 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200996 WCHAR *pch,
997 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998 int *pmodifiers,
999 BOOL fDoPost)
1000{
1001 int i;
1002 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1003
1004 *pch = *pch2 = NUL;
1005 g_fJustGotFocus = FALSE;
1006
1007 /* ignore key up events */
1008 if (!pker->bKeyDown)
1009 return FALSE;
1010
1011 /* ignore some keystrokes */
1012 switch (pker->wVirtualKeyCode)
1013 {
1014 /* modifiers */
1015 case VK_SHIFT:
1016 case VK_CONTROL:
1017 case VK_MENU: /* Alt key */
1018 return FALSE;
1019
1020 default:
1021 break;
1022 }
1023
1024 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001025 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026 {
1027 /* Ctrl-6 is Ctrl-^ */
1028 if (pker->wVirtualKeyCode == '6')
1029 {
1030 *pch = Ctrl_HAT;
1031 return TRUE;
1032 }
1033 /* Ctrl-2 is Ctrl-@ */
1034 else if (pker->wVirtualKeyCode == '2')
1035 {
1036 *pch = NUL;
1037 return TRUE;
1038 }
1039 /* Ctrl-- is Ctrl-_ */
1040 else if (pker->wVirtualKeyCode == 0xBD)
1041 {
1042 *pch = Ctrl__;
1043 return TRUE;
1044 }
1045 }
1046
1047 /* Shift-TAB */
1048 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1049 {
1050 *pch = K_NUL;
1051 *pch2 = '\017';
1052 return TRUE;
1053 }
1054
1055 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1056 {
1057 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1058 {
1059 if (nModifs == 0)
1060 *pch = VirtKeyMap[i].chAlone;
1061 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1062 *pch = VirtKeyMap[i].chShift;
1063 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1064 *pch = VirtKeyMap[i].chCtrl;
1065 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1066 *pch = VirtKeyMap[i].chAlt;
1067
1068 if (*pch != 0)
1069 {
1070 if (VirtKeyMap[i].fAnsiKey)
1071 {
1072 *pch2 = *pch;
1073 *pch = K_NUL;
1074 }
1075
1076 return TRUE;
1077 }
1078 }
1079 }
1080
1081 i = win32_kbd_patch_key(pker);
1082
1083 if (i < 0)
1084 *pch = NUL;
1085 else
1086 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001087 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088
1089 if (pmodifiers != NULL)
1090 {
1091 /* Pass on the ALT key as a modifier, but only when not combined
1092 * with CTRL (which is ALTGR). */
1093 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1094 *pmodifiers |= MOD_MASK_ALT;
1095
1096 /* Pass on SHIFT only for special keys, because we don't know when
1097 * it's already included with the character. */
1098 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1099 *pmodifiers |= MOD_MASK_SHIFT;
1100
1101 /* Pass on CTRL only for non-special keys, because we don't know
1102 * when it's already included with the character. And not when
1103 * combined with ALT (which is ALTGR). */
1104 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1105 && *pch >= 0x20 && *pch < 0x80)
1106 *pmodifiers |= MOD_MASK_CTRL;
1107 }
1108 }
1109
1110 return (*pch != NUL);
1111}
1112
1113#ifdef _MSC_VER
1114# pragma optimize("", on)
1115#endif
1116
1117#endif /* FEAT_GUI_W32 */
1118
1119
1120#ifdef FEAT_MOUSE
1121
1122/*
1123 * For the GUI the mouse handling is in gui_w32.c.
1124 */
1125# ifdef FEAT_GUI_W32
1126 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001127mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128{
1129}
1130# else
1131static int g_fMouseAvail = FALSE; /* mouse present */
1132static int g_fMouseActive = FALSE; /* mouse enabled */
1133static int g_nMouseClick = -1; /* mouse status */
1134static int g_xMouse; /* mouse x coordinate */
1135static int g_yMouse; /* mouse y coordinate */
1136
1137/*
1138 * Enable or disable mouse input
1139 */
1140 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001141mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142{
1143 DWORD cmodein;
1144
1145 if (!g_fMouseAvail)
1146 return;
1147
1148 g_fMouseActive = on;
1149 GetConsoleMode(g_hConIn, &cmodein);
1150
1151 if (g_fMouseActive)
1152 cmodein |= ENABLE_MOUSE_INPUT;
1153 else
1154 cmodein &= ~ENABLE_MOUSE_INPUT;
1155
1156 SetConsoleMode(g_hConIn, cmodein);
1157}
1158
Bram Moolenaar157d8132018-03-06 17:09:20 +01001159
1160#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1161/*
1162 * Called when 'balloonevalterm' changed.
1163 */
1164 void
1165mch_bevalterm_changed(void)
1166{
1167 mch_setmouse(g_fMouseActive);
1168}
1169#endif
1170
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171/*
1172 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1173 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1174 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1175 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1176 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1177 * and we return the mouse position in g_xMouse and g_yMouse.
1178 *
1179 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1180 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1181 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1182 *
1183 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1184 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1185 *
1186 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1187 * moves, even if it stays within the same character cell. We ignore
1188 * all MOUSE_MOVED messages if the position hasn't really changed, and
1189 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1190 * we're only interested in MOUSE_DRAG).
1191 *
1192 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1193 * 2-button mouses by pressing the left & right buttons simultaneously.
1194 * In practice, it's almost impossible to click both at the same time,
1195 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1196 * in such cases, if the user is clicking quickly.
1197 */
1198 static BOOL
1199decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001200 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001201{
1202 static int s_nOldButton = -1;
1203 static int s_nOldMouseClick = -1;
1204 static int s_xOldMouse = -1;
1205 static int s_yOldMouse = -1;
1206 static linenr_T s_old_topline = 0;
1207#ifdef FEAT_DIFF
1208 static int s_old_topfill = 0;
1209#endif
1210 static int s_cClicks = 1;
1211 static BOOL s_fReleased = TRUE;
1212 static DWORD s_dwLastClickTime = 0;
1213 static BOOL s_fNextIsMiddle = FALSE;
1214
1215 static DWORD cButtons = 0; /* number of buttons supported */
1216
1217 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1218 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1219 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1220 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1221
1222 int nButton;
1223
1224 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1225 cButtons = 2;
1226
1227 if (!g_fMouseAvail || !g_fMouseActive)
1228 {
1229 g_nMouseClick = -1;
1230 return FALSE;
1231 }
1232
1233 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1234 if (g_fJustGotFocus)
1235 {
1236 g_fJustGotFocus = FALSE;
1237 return FALSE;
1238 }
1239
1240 /* unprocessed mouse click? */
1241 if (g_nMouseClick != -1)
1242 return TRUE;
1243
1244 nButton = -1;
1245 g_xMouse = pmer->dwMousePosition.X;
1246 g_yMouse = pmer->dwMousePosition.Y;
1247
1248 if (pmer->dwEventFlags == MOUSE_MOVED)
1249 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001250 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251 * events even when the mouse moves only within a char cell.) */
1252 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1253 return FALSE;
1254 }
1255
1256 /* If no buttons are pressed... */
1257 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1258 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001259 nButton = MOUSE_RELEASE;
1260
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1262 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001263 {
1264#ifdef FEAT_BEVAL_TERM
1265 /* do return mouse move events when we want them */
1266 if (p_bevalterm)
1267 nButton = MOUSE_DRAG;
1268 else
1269#endif
1270 return FALSE;
1271 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001272
Bram Moolenaar071d4272004-06-13 20:20:40 +00001273 s_fReleased = TRUE;
1274 }
1275 else /* one or more buttons pressed */
1276 {
1277 /* on a 2-button mouse, hold down left and right buttons
1278 * simultaneously to get MIDDLE. */
1279
1280 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1281 {
1282 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1283
1284 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001285 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286 if (dwLR == LEFT || dwLR == RIGHT)
1287 {
1288 for (;;)
1289 {
1290 /* wait a short time for next input event */
1291 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1292 != WAIT_OBJECT_0)
1293 break;
1294 else
1295 {
1296 DWORD cRecords = 0;
1297 INPUT_RECORD ir;
1298 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1299
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001300 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001301
1302 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1303 || !(pmer2->dwButtonState & LEFT_RIGHT))
1304 break;
1305 else
1306 {
1307 if (pmer2->dwEventFlags != MOUSE_MOVED)
1308 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001309 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001310
1311 return decode_mouse_event(pmer2);
1312 }
1313 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1314 s_yOldMouse == pmer2->dwMousePosition.Y)
1315 {
1316 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001317 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318
1319 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001320 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321
1322 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1323 break;
1324 }
1325 else
1326 break;
1327 }
1328 }
1329 }
1330 }
1331 }
1332
1333 if (s_fNextIsMiddle)
1334 {
1335 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1336 ? MOUSE_DRAG : MOUSE_MIDDLE;
1337 s_fNextIsMiddle = FALSE;
1338 }
1339 else if (cButtons == 2 &&
1340 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1341 {
1342 nButton = MOUSE_MIDDLE;
1343
1344 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1345 {
1346 s_fNextIsMiddle = TRUE;
1347 nButton = MOUSE_RELEASE;
1348 }
1349 }
1350 else if ((pmer->dwButtonState & LEFT) == LEFT)
1351 nButton = MOUSE_LEFT;
1352 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1353 nButton = MOUSE_MIDDLE;
1354 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1355 nButton = MOUSE_RIGHT;
1356
1357 if (! s_fReleased && ! s_fNextIsMiddle
1358 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1359 return FALSE;
1360
1361 s_fReleased = s_fNextIsMiddle;
1362 }
1363
1364 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1365 {
1366 /* button pressed or released, without mouse moving */
1367 if (nButton != -1 && nButton != MOUSE_RELEASE)
1368 {
1369 DWORD dwCurrentTime = GetTickCount();
1370
1371 if (s_xOldMouse != g_xMouse
1372 || s_yOldMouse != g_yMouse
1373 || s_nOldButton != nButton
1374 || s_old_topline != curwin->w_topline
1375#ifdef FEAT_DIFF
1376 || s_old_topfill != curwin->w_topfill
1377#endif
1378 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1379 {
1380 s_cClicks = 1;
1381 }
1382 else if (++s_cClicks > 4)
1383 {
1384 s_cClicks = 1;
1385 }
1386
1387 s_dwLastClickTime = dwCurrentTime;
1388 }
1389 }
1390 else if (pmer->dwEventFlags == MOUSE_MOVED)
1391 {
1392 if (nButton != -1 && nButton != MOUSE_RELEASE)
1393 nButton = MOUSE_DRAG;
1394
1395 s_cClicks = 1;
1396 }
1397
1398 if (nButton == -1)
1399 return FALSE;
1400
1401 if (nButton != MOUSE_RELEASE)
1402 s_nOldButton = nButton;
1403
1404 g_nMouseClick = nButton;
1405
1406 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1407 g_nMouseClick |= MOUSE_SHIFT;
1408 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1409 g_nMouseClick |= MOUSE_CTRL;
1410 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1411 g_nMouseClick |= MOUSE_ALT;
1412
1413 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1414 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1415
1416 /* only pass on interesting (i.e., different) mouse events */
1417 if (s_xOldMouse == g_xMouse
1418 && s_yOldMouse == g_yMouse
1419 && s_nOldMouseClick == g_nMouseClick)
1420 {
1421 g_nMouseClick = -1;
1422 return FALSE;
1423 }
1424
1425 s_xOldMouse = g_xMouse;
1426 s_yOldMouse = g_yMouse;
1427 s_old_topline = curwin->w_topline;
1428#ifdef FEAT_DIFF
1429 s_old_topfill = curwin->w_topfill;
1430#endif
1431 s_nOldMouseClick = g_nMouseClick;
1432
1433 return TRUE;
1434}
1435
1436# endif /* FEAT_GUI_W32 */
1437#endif /* FEAT_MOUSE */
1438
1439
1440#ifdef MCH_CURSOR_SHAPE
1441/*
1442 * Set the shape of the cursor.
1443 * 'thickness' can be from 1 (thin) to 99 (block)
1444 */
1445 static void
1446mch_set_cursor_shape(int thickness)
1447{
1448 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1449 ConsoleCursorInfo.dwSize = thickness;
1450 ConsoleCursorInfo.bVisible = s_cursor_visible;
1451
1452 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1453 if (s_cursor_visible)
1454 SetConsoleCursorPosition(g_hConOut, g_coord);
1455}
1456
1457 void
1458mch_update_cursor(void)
1459{
1460 int idx;
1461 int thickness;
1462
1463 /*
1464 * How the cursor is drawn depends on the current mode.
1465 */
1466 idx = get_shape_idx(FALSE);
1467
1468 if (shape_table[idx].shape == SHAPE_BLOCK)
1469 thickness = 99; /* 100 doesn't work on W95 */
1470 else
1471 thickness = shape_table[idx].percentage;
1472 mch_set_cursor_shape(thickness);
1473}
1474#endif
1475
1476#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1477/*
1478 * Handle FOCUS_EVENT.
1479 */
1480 static void
1481handle_focus_event(INPUT_RECORD ir)
1482{
1483 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1484 ui_focus_change((int)g_fJustGotFocus);
1485}
1486
1487/*
1488 * Wait until console input from keyboard or mouse is available,
1489 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001490 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491 * Return TRUE if something is available FALSE if not.
1492 */
1493 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001494WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495{
1496 DWORD dwNow = 0, dwEndTime = 0;
1497 INPUT_RECORD ir;
1498 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001499 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001500#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001501 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001502#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503
1504 if (msec > 0)
1505 /* Wait until the specified time has elapsed. */
1506 dwEndTime = GetTickCount() + msec;
1507 else if (msec < 0)
1508 /* Wait forever. */
1509 dwEndTime = INFINITE;
1510
1511 /* We need to loop until the end of the time period, because
1512 * we might get multiple unusable mouse events in that time.
1513 */
1514 for (;;)
1515 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001516 // Only process messages when waiting.
1517 if (msec != 0)
1518 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001519#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001520 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001521#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001522#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001523 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001524#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001526 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001527#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001528 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001529
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530 if (0
1531#ifdef FEAT_MOUSE
1532 || g_nMouseClick != -1
1533#endif
1534#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001535 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536#endif
1537 )
1538 return TRUE;
1539
1540 if (msec > 0)
1541 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001542 /* If the specified wait time has passed, return. Beware that
1543 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001545 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 break;
1547 }
1548 if (msec != 0)
1549 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001550 DWORD dwWaitTime = dwEndTime - dwNow;
1551
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001552#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001553 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001554 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001555 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001556 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001557 /* If there is readahead then parse_queued_messages() timed out
1558 * and we should call it again soon. */
1559 if (channel_any_readahead())
1560 dwWaitTime = 10;
1561 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001562#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001563#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001564 if (p_beval && dwWaitTime > 100)
1565 /* The 'balloonexpr' may indirectly invoke a callback while
1566 * waiting for a character, need to check often. */
1567 dwWaitTime = 100;
1568#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001569#ifdef FEAT_MZSCHEME
1570 if (mzthreads_allowed() && p_mzq > 0
1571 && (msec < 0 || (long)dwWaitTime > p_mzq))
1572 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1573#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001574#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001575 // When waiting very briefly don't trigger timers.
1576 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001577 {
1578 long due_time;
1579
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001580 // Trigger timers and then get the time in msec until the next
1581 // one is due. Wait up to that time.
1582 due_time = check_due_timer();
1583 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001584 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001585 // timer may have used feedkeys().
1586 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001587 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001588 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1589 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001590 }
1591#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001592 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001594 // Wait for either an event on the console input or a
1595 // message in the client-server window.
1596 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1597 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001599 wait_for_single_object(g_hConIn, dwWaitTime)
1600 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001602 )
1603 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 }
1605
1606 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001607 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608
1609#ifdef FEAT_MBYTE_IME
1610 if (State & CMDLINE && msg_row == Rows - 1)
1611 {
1612 CONSOLE_SCREEN_BUFFER_INFO csbi;
1613
1614 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1615 {
1616 if (csbi.dwCursorPosition.Y != msg_row)
1617 {
1618 /* The screen is now messed up, must redraw the
1619 * command line and later all the windows. */
1620 redraw_all_later(CLEAR);
1621 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1622 redrawcmd();
1623 }
1624 }
1625 }
1626#endif
1627
1628 if (cRecords > 0)
1629 {
1630 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1631 {
1632#ifdef FEAT_MBYTE_IME
1633 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1634 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001635 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001636 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1637 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001638 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639 continue;
1640 }
1641#endif
1642 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1643 NULL, FALSE))
1644 return TRUE;
1645 }
1646
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001647 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648
1649 if (ir.EventType == FOCUS_EVENT)
1650 handle_focus_event(ir);
1651 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001652 {
1653 /* Only call shell_resized() when the size actually change to
1654 * avoid the screen is cleard. */
1655 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1656 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1657 shell_resized();
1658 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659#ifdef FEAT_MOUSE
1660 else if (ir.EventType == MOUSE_EVENT
1661 && decode_mouse_event(&ir.Event.MouseEvent))
1662 return TRUE;
1663#endif
1664 }
1665 else if (msec == 0)
1666 break;
1667 }
1668
1669#ifdef FEAT_CLIENTSERVER
1670 /* Something might have been received while we were waiting. */
1671 if (input_available())
1672 return TRUE;
1673#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001674
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675 return FALSE;
1676}
1677
1678#ifndef FEAT_GUI_MSWIN
1679/*
1680 * return non-zero if a character is available
1681 */
1682 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001683mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001685 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001687
1688# if defined(FEAT_TERMINAL) || defined(PROTO)
1689/*
1690 * Check for any pending input or messages.
1691 */
1692 int
1693mch_check_messages(void)
1694{
1695 return WaitForChar(0L, TRUE);
1696}
1697# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698#endif
1699
1700/*
1701 * Create the console input. Used when reading stdin doesn't work.
1702 */
1703 static void
1704create_conin(void)
1705{
1706 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1707 FILE_SHARE_READ|FILE_SHARE_WRITE,
1708 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001709 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 did_create_conin = TRUE;
1711}
1712
1713/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001714 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001716 static WCHAR
1717tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001719 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720
1721 for (;;)
1722 {
1723 INPUT_RECORD ir;
1724 DWORD cRecords = 0;
1725
1726#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001727 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001728 if (input_available())
1729 return 0;
1730# ifdef FEAT_MOUSE
1731 if (g_nMouseClick != -1)
1732 return 0;
1733# endif
1734#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001735 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001736 {
1737 if (did_create_conin)
1738 read_error_exit();
1739 create_conin();
1740 continue;
1741 }
1742
1743 if (ir.EventType == KEY_EVENT)
1744 {
1745 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1746 pmodifiers, TRUE))
1747 return ch;
1748 }
1749 else if (ir.EventType == FOCUS_EVENT)
1750 handle_focus_event(ir);
1751 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1752 shell_resized();
1753#ifdef FEAT_MOUSE
1754 else if (ir.EventType == MOUSE_EVENT)
1755 {
1756 if (decode_mouse_event(&ir.Event.MouseEvent))
1757 return 0;
1758 }
1759#endif
1760 }
1761}
1762#endif /* !FEAT_GUI_W32 */
1763
1764
1765/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001766 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 * Get one or more characters from the keyboard or the mouse.
1768 * If time == 0, do not wait for characters.
1769 * If time == n, wait a short time for characters.
1770 * If time == -1, wait forever for characters.
1771 * Returns the number of characters read into buf.
1772 */
1773 int
1774mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001775 char_u *buf UNUSED,
1776 int maxlen UNUSED,
1777 long time UNUSED,
1778 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779{
1780#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1781
1782 int len;
1783 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001784#define TYPEAHEADLEN 20
1785 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1786 static int typeaheadlen = 0;
1787
1788 /* First use any typeahead that was kept because "buf" was too small. */
1789 if (typeaheadlen > 0)
1790 goto theend;
1791
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 if (time >= 0)
1793 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001794 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 }
1797 else /* time == -1, wait forever */
1798 {
1799 mch_set_winsize_now(); /* Allow winsize changes from now on */
1800
Bram Moolenaar3918c952005-03-15 22:34:55 +00001801 /*
1802 * If there is no character available within 2 seconds (default)
1803 * write the autoscript file to disk. Or cause the CursorHold event
1804 * to be triggered.
1805 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001806 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001808 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001810 buf[0] = K_SPECIAL;
1811 buf[1] = KS_EXTRA;
1812 buf[2] = (int)KE_CURSORHOLD;
1813 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001815 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
1817 }
1818
1819 /*
1820 * Try to read as many characters as there are, until the buffer is full.
1821 */
1822
1823 /* we will get at least one key. Get more if they are available. */
1824 g_fCBrkPressed = FALSE;
1825
1826#ifdef MCH_WRITE_DUMP
1827 if (fdDump)
1828 fputc('[', fdDump);
1829#endif
1830
1831 /* Keep looping until there is something in the typeahead buffer and more
1832 * to get and still room in the buffer (up to two bytes for a char and
1833 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001834 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 && typeaheadlen + 5 <= TYPEAHEADLEN)
1836 {
1837 if (typebuf_changed(tb_change_cnt))
1838 {
1839 /* "buf" may be invalid now if a client put something in the
1840 * typeahead buffer and "buf" is in the typeahead buffer. */
1841 typeaheadlen = 0;
1842 break;
1843 }
1844#ifdef FEAT_MOUSE
1845 if (g_nMouseClick != -1)
1846 {
1847# ifdef MCH_WRITE_DUMP
1848 if (fdDump)
1849 fprintf(fdDump, "{%02x @ %d, %d}",
1850 g_nMouseClick, g_xMouse, g_yMouse);
1851# endif
1852 typeahead[typeaheadlen++] = ESC + 128;
1853 typeahead[typeaheadlen++] = 'M';
1854 typeahead[typeaheadlen++] = g_nMouseClick;
1855 typeahead[typeaheadlen++] = g_xMouse + '!';
1856 typeahead[typeaheadlen++] = g_yMouse + '!';
1857 g_nMouseClick = -1;
1858 }
1859 else
1860#endif
1861 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001862 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863 int modifiers = 0;
1864
1865 c = tgetch(&modifiers, &ch2);
1866
1867 if (typebuf_changed(tb_change_cnt))
1868 {
1869 /* "buf" may be invalid now if a client put something in the
1870 * typeahead buffer and "buf" is in the typeahead buffer. */
1871 typeaheadlen = 0;
1872 break;
1873 }
1874
1875 if (c == Ctrl_C && ctrl_c_interrupts)
1876 {
1877#if defined(FEAT_CLIENTSERVER)
1878 trash_input_buf();
1879#endif
1880 got_int = TRUE;
1881 }
1882
1883#ifdef FEAT_MOUSE
1884 if (g_nMouseClick == -1)
1885#endif
1886 {
1887 int n = 1;
1888
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001889 if (ch2 == NUL)
1890 {
1891 int i;
1892 char_u *p;
1893 WCHAR ch[2];
1894
1895 ch[0] = c;
1896 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1897 {
1898 ch[1] = tgetch(&modifiers, &ch2);
1899 n++;
1900 }
1901 p = utf16_to_enc(ch, &n);
1902 if (p != NULL)
1903 {
1904 for (i = 0; i < n; i++)
1905 typeahead[typeaheadlen + i] = p[i];
1906 vim_free(p);
1907 }
1908 }
1909 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001910 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001911 if (ch2 != NUL)
1912 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001913 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001914 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001915 switch (ch2)
1916 {
1917 case (WCHAR)'\324': // SHIFT+Insert
1918 case (WCHAR)'\325': // CTRL+Insert
1919 case (WCHAR)'\327': // SHIFT+Delete
1920 case (WCHAR)'\330': // CTRL+Delete
1921 typeahead[typeaheadlen + n] = (char_u)ch2;
1922 n++;
1923 break;
1924
1925 default:
1926 typeahead[typeaheadlen + n] = 3;
1927 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1928 n += 2;
1929 break;
1930 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001931 }
1932 else
1933 {
1934 typeahead[typeaheadlen + n] = 3;
1935 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1936 n += 2;
1937 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001938 }
1939
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940 /* Use the ALT key to set the 8th bit of the character
1941 * when it's one byte, the 8th bit isn't set yet and not
1942 * using a double-byte encoding (would become a lead
1943 * byte). */
1944 if ((modifiers & MOD_MASK_ALT)
1945 && n == 1
1946 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 )
1949 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001950 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1951 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952 modifiers &= ~MOD_MASK_ALT;
1953 }
1954
1955 if (modifiers != 0)
1956 {
1957 /* Prepend modifiers to the character. */
1958 mch_memmove(typeahead + typeaheadlen + 3,
1959 typeahead + typeaheadlen, n);
1960 typeahead[typeaheadlen++] = K_SPECIAL;
1961 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1962 typeahead[typeaheadlen++] = modifiers;
1963 }
1964
1965 typeaheadlen += n;
1966
1967#ifdef MCH_WRITE_DUMP
1968 if (fdDump)
1969 fputc(c, fdDump);
1970#endif
1971 }
1972 }
1973 }
1974
1975#ifdef MCH_WRITE_DUMP
1976 if (fdDump)
1977 {
1978 fputs("]\n", fdDump);
1979 fflush(fdDump);
1980 }
1981#endif
1982
Bram Moolenaar071d4272004-06-13 20:20:40 +00001983theend:
1984 /* Move typeahead to "buf", as much as fits. */
1985 len = 0;
1986 while (len < maxlen && typeaheadlen > 0)
1987 {
1988 buf[len++] = typeahead[0];
1989 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1990 }
1991 return len;
1992
1993#else /* FEAT_GUI_W32 */
1994 return 0;
1995#endif /* FEAT_GUI_W32 */
1996}
1997
Bram Moolenaar82881492012-11-20 16:53:39 +01001998#ifndef PROTO
1999# ifndef __MINGW32__
2000# include <shellapi.h> /* required for FindExecutable() */
2001# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002#endif
2003
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002004/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002005 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2006 * If "use_path" is FALSE: Return TRUE if "name" exists.
2007 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2008 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002009 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002010 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002011 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002012executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002014 char *dum;
2015 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002016 char *curpath, *newpath;
2017 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018
Bram Moolenaar43663192017-03-05 14:29:12 +01002019 if (!use_path)
2020 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002021 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002022 {
2023 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002024 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002025 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002026 *path = vim_strsave((char_u *)name);
2027 else
2028 *path = FullName_save((char_u *)name, FALSE);
2029 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002030 return TRUE;
2031 }
2032 return FALSE;
2033 }
2034
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002035 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002037 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002038 WCHAR fnamew[_MAX_PATH];
2039 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002040 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002041
2042 if (p != NULL)
2043 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002044 wcurpath = _wgetenv(L"PATH");
2045 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2046 * sizeof(WCHAR));
2047 if (wnewpath == NULL)
2048 return FALSE;
2049 wcscpy(wnewpath, L".;");
2050 wcscat(wnewpath, wcurpath);
2051 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2052 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002053 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002054 if (n == 0)
2055 return FALSE;
2056 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2057 return FALSE;
2058 if (path != NULL)
2059 *path = utf16_to_enc(fnamew, NULL);
2060 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002061 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 }
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002063
2064 curpath = getenv("PATH");
2065 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2066 if (newpath == NULL)
2067 return FALSE;
2068 STRCPY(newpath, ".;");
2069 STRCAT(newpath, curpath);
2070 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2071 vim_free(newpath);
2072 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002073 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002074 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002075 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002076 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002077 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002078 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079}
2080
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002081#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002082 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002083/*
2084 * Bad parameter handler.
2085 *
2086 * Certain MS CRT functions will intentionally crash when passed invalid
2087 * parameters to highlight possible security holes. Setting this function as
2088 * the bad parameter handler will prevent the crash.
2089 *
2090 * In debug builds the parameters contain CRT information that might help track
2091 * down the source of a problem, but in non-debug builds the arguments are all
2092 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2093 * worth allowing these to make debugging of issues easier.
2094 */
2095 static void
2096bad_param_handler(const wchar_t *expression,
2097 const wchar_t *function,
2098 const wchar_t *file,
2099 unsigned int line,
2100 uintptr_t pReserved)
2101{
2102}
2103
2104# define SET_INVALID_PARAM_HANDLER \
2105 ((void)_set_invalid_parameter_handler(bad_param_handler))
2106#else
2107# define SET_INVALID_PARAM_HANDLER
2108#endif
2109
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110#ifdef FEAT_GUI_W32
2111
2112/*
2113 * GUI version of mch_init().
2114 */
2115 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002116mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117{
2118#ifndef __MINGW32__
2119 extern int _fmode;
2120#endif
2121
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002122 /* Silently handle invalid parameters to CRT functions */
2123 SET_INVALID_PARAM_HANDLER;
2124
Bram Moolenaar071d4272004-06-13 20:20:40 +00002125 /* Let critical errors result in a failure, not in a dialog box. Required
2126 * for the timestamp test to work on removed floppies. */
2127 SetErrorMode(SEM_FAILCRITICALERRORS);
2128
2129 _fmode = O_BINARY; /* we do our own CR-LF translation */
2130
2131 /* Specify window size. Is there a place to get the default from? */
2132 Rows = 25;
2133 Columns = 80;
2134
2135 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002136 {
2137 char_u vimrun_location[_MAX_PATH + 4];
2138
2139 /* First try in same directory as gvim.exe */
2140 STRCPY(vimrun_location, exe_name);
2141 STRCPY(gettail(vimrun_location), "vimrun.exe");
2142 if (mch_getperm(vimrun_location) >= 0)
2143 {
2144 if (*skiptowhite(vimrun_location) != NUL)
2145 {
2146 /* Enclose path with white space in double quotes. */
2147 mch_memmove(vimrun_location + 1, vimrun_location,
2148 STRLEN(vimrun_location) + 1);
2149 *vimrun_location = '"';
2150 STRCPY(gettail(vimrun_location), "vimrun\" ");
2151 }
2152 else
2153 STRCPY(gettail(vimrun_location), "vimrun ");
2154
2155 vimrun_path = (char *)vim_strsave(vimrun_location);
2156 s_dont_use_vimrun = FALSE;
2157 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002158 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002159 s_dont_use_vimrun = FALSE;
2160
2161 /* Don't give the warning for a missing vimrun.exe right now, but only
2162 * when vimrun was supposed to be used. Don't bother people that do
2163 * not need vimrun.exe. */
2164 if (s_dont_use_vimrun)
2165 need_vimrun_warning = TRUE;
2166 }
2167
2168 /*
2169 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2170 * Otherwise the default "findstr /n" is used.
2171 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002172 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2174
2175#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002176 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177#endif
2178}
2179
2180
2181#else /* FEAT_GUI_W32 */
2182
2183#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2184#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2185
2186/*
2187 * ClearConsoleBuffer()
2188 * Description:
2189 * Clears the entire contents of the console screen buffer, using the
2190 * specified attribute.
2191 * Returns:
2192 * TRUE on success
2193 */
2194 static BOOL
2195ClearConsoleBuffer(WORD wAttribute)
2196{
2197 CONSOLE_SCREEN_BUFFER_INFO csbi;
2198 COORD coord;
2199 DWORD NumCells, dummy;
2200
2201 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2202 return FALSE;
2203
2204 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2205 coord.X = 0;
2206 coord.Y = 0;
2207 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2208 coord, &dummy))
2209 {
2210 return FALSE;
2211 }
2212 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2213 coord, &dummy))
2214 {
2215 return FALSE;
2216 }
2217
2218 return TRUE;
2219}
2220
2221/*
2222 * FitConsoleWindow()
2223 * Description:
2224 * Checks if the console window will fit within given buffer dimensions.
2225 * Also, if requested, will shrink the window to fit.
2226 * Returns:
2227 * TRUE on success
2228 */
2229 static BOOL
2230FitConsoleWindow(
2231 COORD dwBufferSize,
2232 BOOL WantAdjust)
2233{
2234 CONSOLE_SCREEN_BUFFER_INFO csbi;
2235 COORD dwWindowSize;
2236 BOOL NeedAdjust = FALSE;
2237
2238 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2239 {
2240 /*
2241 * A buffer resize will fail if the current console window does
2242 * not lie completely within that buffer. To avoid this, we might
2243 * have to move and possibly shrink the window.
2244 */
2245 if (csbi.srWindow.Right >= dwBufferSize.X)
2246 {
2247 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2248 if (dwWindowSize.X > dwBufferSize.X)
2249 dwWindowSize.X = dwBufferSize.X;
2250 csbi.srWindow.Right = dwBufferSize.X - 1;
2251 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2252 NeedAdjust = TRUE;
2253 }
2254 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2255 {
2256 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2257 if (dwWindowSize.Y > dwBufferSize.Y)
2258 dwWindowSize.Y = dwBufferSize.Y;
2259 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2260 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2261 NeedAdjust = TRUE;
2262 }
2263 if (NeedAdjust && WantAdjust)
2264 {
2265 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2266 return FALSE;
2267 }
2268 return TRUE;
2269 }
2270
2271 return FALSE;
2272}
2273
2274typedef struct ConsoleBufferStruct
2275{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002276 BOOL IsValid;
2277 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002278 PCHAR_INFO Buffer;
2279 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002280 PSMALL_RECT Regions;
2281 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282} ConsoleBuffer;
2283
2284/*
2285 * SaveConsoleBuffer()
2286 * Description:
2287 * Saves important information about the console buffer, including the
2288 * actual buffer contents. The saved information is suitable for later
2289 * restoration by RestoreConsoleBuffer().
2290 * Returns:
2291 * TRUE if all information was saved; FALSE otherwise
2292 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2293 */
2294 static BOOL
2295SaveConsoleBuffer(
2296 ConsoleBuffer *cb)
2297{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002298 DWORD NumCells;
2299 COORD BufferCoord;
2300 SMALL_RECT ReadRegion;
2301 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002302 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002303
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 if (cb == NULL)
2305 return FALSE;
2306
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002307 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 {
2309 cb->IsValid = FALSE;
2310 return FALSE;
2311 }
2312 cb->IsValid = TRUE;
2313
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002314 /*
2315 * Allocate a buffer large enough to hold the entire console screen
2316 * buffer. If this ConsoleBuffer structure has already been initialized
2317 * with a buffer of the correct size, then just use that one.
2318 */
2319 if (!cb->IsValid || cb->Buffer == NULL ||
2320 cb->BufferSize.X != cb->Info.dwSize.X ||
2321 cb->BufferSize.Y != cb->Info.dwSize.Y)
2322 {
2323 cb->BufferSize.X = cb->Info.dwSize.X;
2324 cb->BufferSize.Y = cb->Info.dwSize.Y;
2325 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2326 vim_free(cb->Buffer);
2327 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2328 if (cb->Buffer == NULL)
2329 return FALSE;
2330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331
2332 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002333 * We will now copy the console screen buffer into our buffer.
2334 * ReadConsoleOutput() seems to be limited as far as how much you
2335 * can read at a time. Empirically, this number seems to be about
2336 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2337 * in chunks until it is all copied. The chunks will all have the
2338 * same horizontal characteristics, so initialize them now. The
2339 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002341 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002342 ReadRegion.Left = 0;
2343 ReadRegion.Right = cb->Info.dwSize.X - 1;
2344 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002345
2346 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2347 if (cb->Regions == NULL || numregions != cb->NumRegions)
2348 {
2349 cb->NumRegions = numregions;
2350 vim_free(cb->Regions);
2351 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2352 if (cb->Regions == NULL)
2353 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002354 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002355 return FALSE;
2356 }
2357 }
2358
2359 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002361 /*
2362 * Read into position (0, Y) in our buffer.
2363 */
2364 BufferCoord.Y = Y;
2365 /*
2366 * Read the region whose top left corner is (0, Y) and whose bottom
2367 * right corner is (width - 1, Y + Y_incr - 1). This should define
2368 * a region of size width by Y_incr. Don't worry if this region is
2369 * too large for the remaining buffer; it will be cropped.
2370 */
2371 ReadRegion.Top = Y;
2372 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002373 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002374 cb->Buffer, /* our buffer */
2375 cb->BufferSize, /* dimensions of our buffer */
2376 BufferCoord, /* offset in our buffer */
2377 &ReadRegion)) /* region to save */
2378 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002379 VIM_CLEAR(cb->Buffer);
2380 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002381 return FALSE;
2382 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002383 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384 }
2385
2386 return TRUE;
2387}
2388
2389/*
2390 * RestoreConsoleBuffer()
2391 * Description:
2392 * Restores important information about the console buffer, including the
2393 * actual buffer contents, if desired. The information to restore is in
2394 * the same format used by SaveConsoleBuffer().
2395 * Returns:
2396 * TRUE on success
2397 */
2398 static BOOL
2399RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002400 ConsoleBuffer *cb,
2401 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002403 COORD BufferCoord;
2404 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002405 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406
2407 if (cb == NULL || !cb->IsValid)
2408 return FALSE;
2409
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002410 /*
2411 * Before restoring the buffer contents, clear the current buffer, and
2412 * restore the cursor position and window information. Doing this now
2413 * prevents old buffer contents from "flashing" onto the screen.
2414 */
2415 if (RestoreScreen)
2416 ClearConsoleBuffer(cb->Info.wAttributes);
2417
2418 FitConsoleWindow(cb->Info.dwSize, TRUE);
2419 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2420 return FALSE;
2421 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2422 return FALSE;
2423
2424 if (!RestoreScreen)
2425 {
2426 /*
2427 * No need to restore the screen buffer contents, so we're done.
2428 */
2429 return TRUE;
2430 }
2431
2432 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2433 return FALSE;
2434 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2435 return FALSE;
2436
2437 /*
2438 * Restore the screen buffer contents.
2439 */
2440 if (cb->Buffer != NULL)
2441 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002442 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002443 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002444 BufferCoord.X = cb->Regions[i].Left;
2445 BufferCoord.Y = cb->Regions[i].Top;
2446 WriteRegion = cb->Regions[i];
2447 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2448 cb->Buffer, /* our buffer */
2449 cb->BufferSize, /* dimensions of our buffer */
2450 BufferCoord, /* offset in our buffer */
2451 &WriteRegion)) /* region to restore */
2452 {
2453 return FALSE;
2454 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002455 }
2456 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457
2458 return TRUE;
2459}
2460
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002461#define FEAT_RESTORE_ORIG_SCREEN
2462#ifdef FEAT_RESTORE_ORIG_SCREEN
2463static ConsoleBuffer g_cbOrig = { 0 };
2464#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465static ConsoleBuffer g_cbNonTermcap = { 0 };
2466static ConsoleBuffer g_cbTermcap = { 0 };
2467
2468#ifdef FEAT_TITLE
2469#ifdef __BORLANDC__
2470typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2471#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002472typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473#endif
2474char g_szOrigTitle[256] = { 0 };
2475HWND g_hWnd = NULL; /* also used in os_mswin.c */
2476static HICON g_hOrigIconSmall = NULL;
2477static HICON g_hOrigIcon = NULL;
2478static HICON g_hVimIcon = NULL;
2479static BOOL g_fCanChangeIcon = FALSE;
2480
2481/* ICON* are not defined in VC++ 4.0 */
2482#ifndef ICON_SMALL
2483#define ICON_SMALL 0
2484#endif
2485#ifndef ICON_BIG
2486#define ICON_BIG 1
2487#endif
2488/*
2489 * GetConsoleIcon()
2490 * Description:
2491 * Attempts to retrieve the small icon and/or the big icon currently in
2492 * use by a given window.
2493 * Returns:
2494 * TRUE on success
2495 */
2496 static BOOL
2497GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002498 HWND hWnd,
2499 HICON *phIconSmall,
2500 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501{
2502 if (hWnd == NULL)
2503 return FALSE;
2504
2505 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002506 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2507 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002509 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2510 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 return TRUE;
2512}
2513
2514/*
2515 * SetConsoleIcon()
2516 * Description:
2517 * Attempts to change the small icon and/or the big icon currently in
2518 * use by a given window.
2519 * Returns:
2520 * TRUE on success
2521 */
2522 static BOOL
2523SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002524 HWND hWnd,
2525 HICON hIconSmall,
2526 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 if (hWnd == NULL)
2529 return FALSE;
2530
2531 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002532 SendMessage(hWnd, WM_SETICON,
2533 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002535 SendMessage(hWnd, WM_SETICON,
2536 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537 return TRUE;
2538}
2539
2540/*
2541 * SaveConsoleTitleAndIcon()
2542 * Description:
2543 * Saves the current console window title in g_szOrigTitle, for later
2544 * restoration. Also, attempts to obtain a handle to the console window,
2545 * and use it to save the small and big icons currently in use by the
2546 * console window. This is not always possible on some versions of Windows;
2547 * nor is it possible when running Vim remotely using Telnet (since the
2548 * console window the user sees is owned by a remote process).
2549 */
2550 static void
2551SaveConsoleTitleAndIcon(void)
2552{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553 /* Save the original title. */
2554 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2555 return;
2556
2557 /*
2558 * Obtain a handle to the console window using GetConsoleWindow() from
2559 * KERNEL32.DLL; we need to handle in order to change the window icon.
2560 * This function only exists on NT-based Windows, starting with Windows
2561 * 2000. On older operating systems, we can't change the window icon
2562 * anyway.
2563 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002564 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 if (g_hWnd == NULL)
2566 return;
2567
2568 /* Save the original console window icon. */
2569 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2570 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2571 return;
2572
2573 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002574 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002575 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 if (g_hVimIcon != NULL)
2577 g_fCanChangeIcon = TRUE;
2578}
2579#endif
2580
2581static int g_fWindInitCalled = FALSE;
2582static int g_fTermcapMode = FALSE;
2583static CONSOLE_CURSOR_INFO g_cci;
2584static DWORD g_cmodein = 0;
2585static DWORD g_cmodeout = 0;
2586
2587/*
2588 * non-GUI version of mch_init().
2589 */
2590 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002591mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002593#ifndef FEAT_RESTORE_ORIG_SCREEN
2594 CONSOLE_SCREEN_BUFFER_INFO csbi;
2595#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596#ifndef __MINGW32__
2597 extern int _fmode;
2598#endif
2599
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002600 /* Silently handle invalid parameters to CRT functions */
2601 SET_INVALID_PARAM_HANDLER;
2602
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 /* Let critical errors result in a failure, not in a dialog box. Required
2604 * for the timestamp test to work on removed floppies. */
2605 SetErrorMode(SEM_FAILCRITICALERRORS);
2606
2607 _fmode = O_BINARY; /* we do our own CR-LF translation */
2608 out_flush();
2609
2610 /* Obtain handles for the standard Console I/O devices */
2611 if (read_cmd_fd == 0)
2612 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2613 else
2614 create_conin();
2615 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2616
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002617#ifdef FEAT_RESTORE_ORIG_SCREEN
2618 /* Save the initial console buffer for later restoration */
2619 SaveConsoleBuffer(&g_cbOrig);
2620 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2621#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002623 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2624 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2625#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 if (cterm_normal_fg_color == 0)
2627 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2628 if (cterm_normal_bg_color == 0)
2629 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2630
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002631 // Fg and Bg color index nunmber at startup
2632 g_color_index_fg = g_attrDefault & 0xf;
2633 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2634
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635 /* set termcap codes to current text attributes */
2636 update_tcap(g_attrCurrent);
2637
2638 GetConsoleCursorInfo(g_hConOut, &g_cci);
2639 GetConsoleMode(g_hConIn, &g_cmodein);
2640 GetConsoleMode(g_hConOut, &g_cmodeout);
2641
2642#ifdef FEAT_TITLE
2643 SaveConsoleTitleAndIcon();
2644 /*
2645 * Set both the small and big icons of the console window to Vim's icon.
2646 * Note that Vim presently only has one size of icon (32x32), but it
2647 * automatically gets scaled down to 16x16 when setting the small icon.
2648 */
2649 if (g_fCanChangeIcon)
2650 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2651#endif
2652
2653 ui_get_shellsize();
2654
2655#ifdef MCH_WRITE_DUMP
2656 fdDump = fopen("dump", "wt");
2657
2658 if (fdDump)
2659 {
2660 time_t t;
2661
2662 time(&t);
2663 fputs(ctime(&t), fdDump);
2664 fflush(fdDump);
2665 }
2666#endif
2667
2668 g_fWindInitCalled = TRUE;
2669
2670#ifdef FEAT_MOUSE
2671 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2672#endif
2673
2674#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002675 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002677
2678 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002679}
2680
2681/*
2682 * non-GUI version of mch_exit().
2683 * Shut down and exit with status `r'
2684 * Careful: mch_exit() may be called before mch_init()!
2685 */
2686 void
2687mch_exit(int r)
2688{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002689 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002691 vtp_exit();
2692
Bram Moolenaar955f1982017-02-05 15:10:51 +01002693 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694 if (g_fWindInitCalled)
2695 settmode(TMODE_COOK);
2696
2697 ml_close_all(TRUE); /* remove all memfiles */
2698
2699 if (g_fWindInitCalled)
2700 {
2701#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002702 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703 /*
2704 * Restore both the small and big icons of the console window to
2705 * what they were at startup. Don't do this when the window is
2706 * closed, Vim would hang here.
2707 */
2708 if (g_fCanChangeIcon && !g_fForceExit)
2709 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2710#endif
2711
2712#ifdef MCH_WRITE_DUMP
2713 if (fdDump)
2714 {
2715 time_t t;
2716
2717 time(&t);
2718 fputs(ctime(&t), fdDump);
2719 fclose(fdDump);
2720 }
2721 fdDump = NULL;
2722#endif
2723 }
2724
2725 SetConsoleCursorInfo(g_hConOut, &g_cci);
2726 SetConsoleMode(g_hConIn, g_cmodein);
2727 SetConsoleMode(g_hConOut, g_cmodeout);
2728
2729#ifdef DYNAMIC_GETTEXT
2730 dyn_libintl_end();
2731#endif
2732
2733 exit(r);
2734}
2735#endif /* !FEAT_GUI_W32 */
2736
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737/*
2738 * Do we have an interactive window?
2739 */
2740 int
2741mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002742 int argc UNUSED,
2743 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744{
2745 get_exe_name();
2746
2747#ifdef FEAT_GUI_W32
2748 return OK; /* GUI always has a tty */
2749#else
2750 if (isatty(1))
2751 return OK;
2752 return FAIL;
2753#endif
2754}
2755
2756
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002757/*
2758 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2759 * if it already exists. When "len" is > 0, also expand short to long
2760 * filenames.
2761 * Return FAIL if wide functions are not available, OK otherwise.
2762 * NOTE: much of this is identical to fname_case(), keep in sync!
2763 */
2764 static int
2765fname_casew(
2766 WCHAR *name,
2767 int len)
2768{
2769 WCHAR szTrueName[_MAX_PATH + 2];
2770 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2771 WCHAR *ptrue, *ptruePrev;
2772 WCHAR *porig, *porigPrev;
2773 int flen;
2774 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002775 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002776 int c;
2777 int slen;
2778
2779 flen = (int)wcslen(name);
2780 if (flen > _MAX_PATH)
2781 return OK;
2782
2783 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2784
2785 /* Build the new name in szTrueName[] one component at a time. */
2786 porig = name;
2787 ptrue = szTrueName;
2788
2789 if (iswalpha(porig[0]) && porig[1] == L':')
2790 {
2791 /* copy leading drive letter */
2792 *ptrue++ = *porig++;
2793 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002794 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002795 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002796
2797 while (*porig != NUL)
2798 {
2799 /* copy \ characters */
2800 while (*porig == psepc)
2801 *ptrue++ = *porig++;
2802
2803 ptruePrev = ptrue;
2804 porigPrev = porig;
2805 while (*porig != NUL && *porig != psepc)
2806 {
2807 *ptrue++ = *porig++;
2808 }
2809 *ptrue = NUL;
2810
2811 /* To avoid a slow failure append "\*" when searching a directory,
2812 * server or network share. */
2813 wcscpy(szTrueNameTemp, szTrueName);
2814 slen = (int)wcslen(szTrueNameTemp);
2815 if (*porig == psepc && slen + 2 < _MAX_PATH)
2816 wcscpy(szTrueNameTemp + slen, L"\\*");
2817
2818 /* Skip "", "." and "..". */
2819 if (ptrue > ptruePrev
2820 && (ptruePrev[0] != L'.'
2821 || (ptruePrev[1] != NUL
2822 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2823 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2824 != INVALID_HANDLE_VALUE)
2825 {
2826 c = *porig;
2827 *porig = NUL;
2828
2829 /* Only use the match when it's the same name (ignoring case) or
2830 * expansion is allowed and there is a match with the short name
2831 * and there is enough room. */
2832 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2833 || (len > 0
2834 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2835 && (int)(ptruePrev - szTrueName)
2836 + (int)wcslen(fb.cFileName) < len)))
2837 {
2838 wcscpy(ptruePrev, fb.cFileName);
2839
2840 /* Look for exact match and prefer it if found. Must be a
2841 * long name, otherwise there would be only one match. */
2842 while (FindNextFileW(hFind, &fb))
2843 {
2844 if (*fb.cAlternateFileName != NUL
2845 && (wcscoll(porigPrev, fb.cFileName) == 0
2846 || (len > 0
2847 && (_wcsicoll(porigPrev,
2848 fb.cAlternateFileName) == 0
2849 && (int)(ptruePrev - szTrueName)
2850 + (int)wcslen(fb.cFileName) < len))))
2851 {
2852 wcscpy(ptruePrev, fb.cFileName);
2853 break;
2854 }
2855 }
2856 }
2857 FindClose(hFind);
2858 *porig = c;
2859 ptrue = ptruePrev + wcslen(ptruePrev);
2860 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002861 }
2862
2863 wcscpy(name, szTrueName);
2864 return OK;
2865}
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002866
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867/*
2868 * fname_case(): Set the case of the file name, if it already exists.
2869 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002870 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871 */
2872 void
2873fname_case(
2874 char_u *name,
2875 int len)
2876{
2877 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002878 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002879 char *ptrue, *ptruePrev;
2880 char *porig, *porigPrev;
2881 int flen;
2882 WIN32_FIND_DATA fb;
2883 HANDLE hFind;
2884 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002885 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002887 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002888 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889 return;
2890
2891 slash_adjust(name);
2892
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002893 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2894 {
2895 WCHAR *p = enc_to_utf16(name, NULL);
2896
2897 if (p != NULL)
2898 {
2899 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002900 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002901
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002902 wcsncpy(buf, p, _MAX_PATH);
2903 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002904 vim_free(p);
2905
2906 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2907 {
2908 q = utf16_to_enc(buf, NULL);
2909 if (q != NULL)
2910 {
2911 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2912 vim_free(q);
2913 return;
2914 }
2915 }
2916 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002917 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002918 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002919
2920 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2921 * So we should check this after calling wide function. */
2922 if (flen > _MAX_PATH)
2923 return;
2924
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002926 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 ptrue = szTrueName;
2928
2929 if (isalpha(porig[0]) && porig[1] == ':')
2930 {
2931 /* copy leading drive letter */
2932 *ptrue++ = *porig++;
2933 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002935 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936
2937 while (*porig != NUL)
2938 {
2939 /* copy \ characters */
2940 while (*porig == psepc)
2941 *ptrue++ = *porig++;
2942
2943 ptruePrev = ptrue;
2944 porigPrev = porig;
2945 while (*porig != NUL && *porig != psepc)
2946 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 int l;
2948
2949 if (enc_dbcs)
2950 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002951 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 while (--l >= 0)
2953 *ptrue++ = *porig++;
2954 }
2955 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 *ptrue++ = *porig++;
2957 }
2958 *ptrue = NUL;
2959
Bram Moolenaar464c9252010-10-13 20:37:41 +02002960 /* To avoid a slow failure append "\*" when searching a directory,
2961 * server or network share. */
2962 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002963 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002964 if (*porig == psepc && slen + 2 < _MAX_PATH)
2965 STRCPY(szTrueNameTemp + slen, "\\*");
2966
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967 /* Skip "", "." and "..". */
2968 if (ptrue > ptruePrev
2969 && (ptruePrev[0] != '.'
2970 || (ptruePrev[1] != NUL
2971 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002972 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973 != INVALID_HANDLE_VALUE)
2974 {
2975 c = *porig;
2976 *porig = NUL;
2977
2978 /* Only use the match when it's the same name (ignoring case) or
2979 * expansion is allowed and there is a match with the short name
2980 * and there is enough room. */
2981 if (_stricoll(porigPrev, fb.cFileName) == 0
2982 || (len > 0
2983 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2984 && (int)(ptruePrev - szTrueName)
2985 + (int)strlen(fb.cFileName) < len)))
2986 {
2987 STRCPY(ptruePrev, fb.cFileName);
2988
2989 /* Look for exact match and prefer it if found. Must be a
2990 * long name, otherwise there would be only one match. */
2991 while (FindNextFile(hFind, &fb))
2992 {
2993 if (*fb.cAlternateFileName != NUL
2994 && (strcoll(porigPrev, fb.cFileName) == 0
2995 || (len > 0
2996 && (_stricoll(porigPrev,
2997 fb.cAlternateFileName) == 0
2998 && (int)(ptruePrev - szTrueName)
2999 + (int)strlen(fb.cFileName) < len))))
3000 {
3001 STRCPY(ptruePrev, fb.cFileName);
3002 break;
3003 }
3004 }
3005 }
3006 FindClose(hFind);
3007 *porig = c;
3008 ptrue = ptruePrev + strlen(ptruePrev);
3009 }
3010 }
3011
3012 STRCPY(name, szTrueName);
3013}
3014
3015
3016/*
3017 * Insert user name in s[len].
3018 */
3019 int
3020mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003021 char_u *s,
3022 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003024 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 DWORD cch = sizeof szUserName;
3026
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003027 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3028 {
3029 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3030 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3031
3032 if (GetUserNameW(wszUserName, &wcch))
3033 {
3034 char_u *p = utf16_to_enc(wszUserName, NULL);
3035
3036 if (p != NULL)
3037 {
3038 vim_strncpy(s, p, len - 1);
3039 vim_free(p);
3040 return OK;
3041 }
3042 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003043 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044 if (GetUserName(szUserName, &cch))
3045 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003046 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047 return OK;
3048 }
3049 s[0] = NUL;
3050 return FAIL;
3051}
3052
3053
3054/*
3055 * Insert host name in s[len].
3056 */
3057 void
3058mch_get_host_name(
3059 char_u *s,
3060 int len)
3061{
3062 DWORD cch = len;
3063
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003064 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3065 {
3066 WCHAR wszHostName[256 + 1];
3067 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3068
3069 if (GetComputerNameW(wszHostName, &wcch))
3070 {
3071 char_u *p = utf16_to_enc(wszHostName, NULL);
3072
3073 if (p != NULL)
3074 {
3075 vim_strncpy(s, p, len - 1);
3076 vim_free(p);
3077 return;
3078 }
3079 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003080 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003081 if (!GetComputerName((LPSTR)s, &cch))
3082 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083}
3084
3085
3086/*
3087 * return process ID
3088 */
3089 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003090mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091{
3092 return (long)GetCurrentProcessId();
3093}
3094
3095
3096/*
3097 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3098 * Return OK for success, FAIL for failure.
3099 */
3100 int
3101mch_dirname(
3102 char_u *buf,
3103 int len)
3104{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003105 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003106 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003107
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108 /*
3109 * Originally this was:
3110 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3111 * But the Win32s known bug list says that getcwd() doesn't work
3112 * so use the Win32 system call instead. <Negri>
3113 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003114 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3115 {
3116 WCHAR wbuf[_MAX_PATH + 1];
3117
3118 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3119 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003120 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003121 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003122
3123 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003124 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003125 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003126 if (STRLEN(p) >= (size_t)len)
3127 {
3128 // long path name is too long, fall back to short one
3129 vim_free(p);
3130 p = NULL;
3131 }
3132 }
3133 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003134 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135
3136 if (p != NULL)
3137 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003138 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139 vim_free(p);
3140 return OK;
3141 }
3142 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003143 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003144 }
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003145 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3146 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003147 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3148 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3149 // Failed to get long path name or it's too long: fall back to the
3150 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003151 return OK;
3152
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003153 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003154 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155}
3156
3157/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003158 * Get file permissions for "name".
3159 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 */
3161 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003162mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003164 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003165 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003167 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003168 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169}
3170
3171
3172/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003173 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003174 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003175 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003176 */
3177 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003178mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003180 long n = -1;
3181
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3183 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003184 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185
3186 if (p != NULL)
3187 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003188 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003190 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003191 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192 }
3193 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003194 if (n == -1)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003195 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003196 if (n == -1)
3197 return FAIL;
3198
3199 win32_set_archive(name);
3200
3201 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202}
3203
3204/*
3205 * Set hidden flag for "name".
3206 */
3207 void
3208mch_hide(char_u *name)
3209{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003210 int attrs = win32_getattrs(name);
3211 if (attrs == -1)
3212 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003214 attrs |= FILE_ATTRIBUTE_HIDDEN;
3215 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003216}
3217
3218/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003219 * Return TRUE if file "name" exists and is hidden.
3220 */
3221 int
3222mch_ishidden(char_u *name)
3223{
3224 int f = win32_getattrs(name);
3225
3226 if (f == -1)
3227 return FALSE; /* file does not exist at all */
3228
3229 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3230}
3231
3232/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233 * return TRUE if "name" is a directory
3234 * return FALSE if "name" is not a directory or upon error
3235 */
3236 int
3237mch_isdir(char_u *name)
3238{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003239 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240
3241 if (f == -1)
3242 return FALSE; /* file does not exist at all */
3243
3244 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3245}
3246
3247/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003248 * return TRUE if "name" is a directory, NOT a symlink to a directory
3249 * return FALSE if "name" is not a directory
3250 * return FALSE for error
3251 */
3252 int
3253mch_isrealdir(char_u *name)
3254{
3255 return mch_isdir(name) && !mch_is_symbolic_link(name);
3256}
3257
3258/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003259 * Create directory "name".
3260 * Return 0 on success, -1 on error.
3261 */
3262 int
3263mch_mkdir(char_u *name)
3264{
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003265 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3266 {
3267 WCHAR *p;
3268 int retval;
3269
3270 p = enc_to_utf16(name, NULL);
3271 if (p == NULL)
3272 return -1;
3273 retval = _wmkdir(p);
3274 vim_free(p);
3275 return retval;
3276 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003277 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003278}
3279
3280/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003281 * Delete directory "name".
3282 * Return 0 on success, -1 on error.
3283 */
3284 int
3285mch_rmdir(char_u *name)
3286{
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003287 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3288 {
3289 WCHAR *p;
3290 int retval;
3291
3292 p = enc_to_utf16(name, NULL);
3293 if (p == NULL)
3294 return -1;
3295 retval = _wrmdir(p);
3296 vim_free(p);
3297 return retval;
3298 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003299 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003300}
3301
3302/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003303 * Return TRUE if file "fname" has more than one link.
3304 */
3305 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003306mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003307{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003308 BY_HANDLE_FILE_INFORMATION info;
3309
3310 return win32_fileinfo(fname, &info) == FILEINFO_OK
3311 && info.nNumberOfLinks > 1;
3312}
3313
3314/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003315 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003316 */
3317 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003318mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003319{
3320 HANDLE hFind;
3321 int res = FALSE;
3322 WIN32_FIND_DATAA findDataA;
3323 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003324 WCHAR *wn = NULL;
3325 WIN32_FIND_DATAW findDataW;
3326
3327 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003328 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003329 if (wn != NULL)
3330 {
3331 hFind = FindFirstFileW(wn, &findDataW);
3332 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003333 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003334 {
3335 fileFlags = findDataW.dwFileAttributes;
3336 reparseTag = findDataW.dwReserved0;
3337 }
3338 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003339 else
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003340 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003341 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003342 if (hFind != INVALID_HANDLE_VALUE)
3343 {
3344 fileFlags = findDataA.dwFileAttributes;
3345 reparseTag = findDataA.dwReserved0;
3346 }
3347 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003348
3349 if (hFind != INVALID_HANDLE_VALUE)
3350 FindClose(hFind);
3351
3352 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003353 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3354 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003355 res = TRUE;
3356
3357 return res;
3358}
3359
3360/*
3361 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3362 * link.
3363 */
3364 int
3365mch_is_linked(char_u *fname)
3366{
3367 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3368 return TRUE;
3369 return FALSE;
3370}
3371
3372/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003373 * Get the by-handle-file-information for "fname".
3374 * Returns FILEINFO_OK when OK.
3375 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3376 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3377 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3378 */
3379 int
3380win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3381{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003382 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003383 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003384 WCHAR *wn = NULL;
3385
3386 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003387 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003388 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003389 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003390 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003391 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003392 if (wn != NULL)
3393 {
3394 hFile = CreateFileW(wn, /* file name */
3395 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003396 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003397 NULL, /* security descriptor */
3398 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003399 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003400 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003401 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003402 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003403 else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003404 hFile = CreateFile((LPCSTR)fname, /* file name */
3405 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003406 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003407 NULL, /* security descriptor */
3408 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003409 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003410 NULL); /* handle to template file */
3411
3412 if (hFile != INVALID_HANDLE_VALUE)
3413 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003414 if (GetFileInformationByHandle(hFile, info) != 0)
3415 res = FILEINFO_OK;
3416 else
3417 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003418 CloseHandle(hFile);
3419 }
3420
Bram Moolenaar03f48552006-02-28 23:52:23 +00003421 return res;
3422}
3423
3424/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003425 * get file attributes for `name'
3426 * -1 : error
3427 * else FILE_ATTRIBUTE_* defined in winnt.h
3428 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003429 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003430win32_getattrs(char_u *name)
3431{
3432 int attr;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003433 WCHAR *p = NULL;
3434
3435 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3436 p = enc_to_utf16(name, NULL);
3437
3438 if (p != NULL)
3439 {
3440 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003441 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003442 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003443 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003444 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003445
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003446 return attr;
3447}
3448
3449/*
3450 * set file attributes for `name' to `attrs'
3451 *
3452 * return -1 for failure, 0 otherwise
3453 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003454 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003455win32_setattrs(char_u *name, int attrs)
3456{
3457 int res;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003458 WCHAR *p = NULL;
3459
3460 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3461 p = enc_to_utf16(name, NULL);
3462
3463 if (p != NULL)
3464 {
3465 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003466 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003467 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003468 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003469 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003470
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003471 return res ? 0 : -1;
3472}
3473
3474/*
3475 * Set archive flag for "name".
3476 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003477 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003478win32_set_archive(char_u *name)
3479{
3480 int attrs = win32_getattrs(name);
3481 if (attrs == -1)
3482 return -1;
3483
3484 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3485 return win32_setattrs(name, attrs);
3486}
3487
3488/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489 * Return TRUE if file or directory "name" is writable (not readonly).
3490 * Strange semantics of Win32: a readonly directory is writable, but you can't
3491 * delete a file. Let's say this means it is writable.
3492 */
3493 int
3494mch_writable(char_u *name)
3495{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003496 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003498 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3499 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500}
3501
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003503 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003504 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003505 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3506 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003507 */
3508 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003509mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003511 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003512 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003513 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003514
3515 if (len >= _MAX_PATH) /* safety check */
3516 return FALSE;
3517
Bram Moolenaar82956662018-10-06 15:18:45 +02003518 /* Ty using the name directly when a Unix-shell like 'shell'. */
3519 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003520 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003521 return TRUE;
3522
3523 /*
3524 * Loop over all extensions in $PATHEXT.
3525 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003526 p = mch_getenv("PATHEXT");
3527 if (p == NULL)
3528 p = (char_u *)".com;.exe;.bat;.cmd";
3529 saved = vim_strsave(p);
3530 if (saved == NULL)
3531 return FALSE;
3532 p = saved;
3533 while (*p)
3534 {
3535 char_u *tmp = vim_strchr(p, ';');
3536
3537 if (tmp != NULL)
3538 *tmp = NUL;
3539 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3540 && executable_exists((char *)name, path, use_path))
3541 {
3542 vim_free(saved);
3543 return TRUE;
3544 }
3545 if (tmp == NULL)
3546 break;
3547 p = tmp + 1;
3548 }
3549 vim_free(saved);
3550
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003551 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003552 p = mch_getenv("PATHEXT");
3553 if (p == NULL)
3554 p = (char_u *)".com;.exe;.bat;.cmd";
3555 while (*p)
3556 {
3557 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3558 {
3559 /* A single "." means no extension is added. */
3560 buf[len] = NUL;
3561 ++p;
3562 if (*p)
3563 ++p;
3564 }
3565 else
3566 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003567 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003568 return TRUE;
3569 }
3570 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003571}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572
3573/*
3574 * Check what "name" is:
3575 * NODE_NORMAL: file or directory (or doesn't exist)
3576 * NODE_WRITABLE: writable device, socket, fifo, etc.
3577 * NODE_OTHER: non-writable things
3578 */
3579 int
3580mch_nodetype(char_u *name)
3581{
3582 HANDLE hFile;
3583 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003584 WCHAR *wn = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585
Bram Moolenaar043545e2006-10-10 16:44:07 +00003586 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3587 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3588 * here. */
3589 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3590 return NODE_WRITABLE;
3591
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003592 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003593 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003594
3595 if (wn != NULL)
3596 {
3597 hFile = CreateFileW(wn, /* file name */
3598 GENERIC_WRITE, /* access mode */
3599 0, /* share mode */
3600 NULL, /* security descriptor */
3601 OPEN_EXISTING, /* creation disposition */
3602 0, /* file attributes */
3603 NULL); /* handle to template file */
3604 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003605 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003606 else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003607 hFile = CreateFile((LPCSTR)name, /* file name */
3608 GENERIC_WRITE, /* access mode */
3609 0, /* share mode */
3610 NULL, /* security descriptor */
3611 OPEN_EXISTING, /* creation disposition */
3612 0, /* file attributes */
3613 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614
3615 if (hFile == INVALID_HANDLE_VALUE)
3616 return NODE_NORMAL;
3617
3618 type = GetFileType(hFile);
3619 CloseHandle(hFile);
3620 if (type == FILE_TYPE_CHAR)
3621 return NODE_WRITABLE;
3622 if (type == FILE_TYPE_DISK)
3623 return NODE_NORMAL;
3624 return NODE_OTHER;
3625}
3626
3627#ifdef HAVE_ACL
3628struct my_acl
3629{
3630 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3631 PSID pSidOwner;
3632 PSID pSidGroup;
3633 PACL pDacl;
3634 PACL pSacl;
3635};
3636#endif
3637
3638/*
3639 * Return a pointer to the ACL of file "fname" in allocated memory.
3640 * Return NULL if the ACL is not available for whatever reason.
3641 */
3642 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003643mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644{
3645#ifndef HAVE_ACL
3646 return (vim_acl_T)NULL;
3647#else
3648 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003649 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003651 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3652 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003653 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003654 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003655
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003656 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3657 wn = enc_to_utf16(fname, NULL);
3658 if (wn != NULL)
3659 {
3660 /* Try to retrieve the entire security descriptor. */
3661 err = GetNamedSecurityInfoW(
3662 wn, // Abstract filename
3663 SE_FILE_OBJECT, // File Object
3664 OWNER_SECURITY_INFORMATION |
3665 GROUP_SECURITY_INFORMATION |
3666 DACL_SECURITY_INFORMATION |
3667 SACL_SECURITY_INFORMATION,
3668 &p->pSidOwner, // Ownership information.
3669 &p->pSidGroup, // Group membership.
3670 &p->pDacl, // Discretionary information.
3671 &p->pSacl, // For auditing purposes.
3672 &p->pSecurityDescriptor);
3673 if (err == ERROR_ACCESS_DENIED ||
3674 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003676 /* Retrieve only DACL. */
3677 (void)GetNamedSecurityInfoW(
3678 wn,
3679 SE_FILE_OBJECT,
3680 DACL_SECURITY_INFORMATION,
3681 NULL,
3682 NULL,
3683 &p->pDacl,
3684 NULL,
3685 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003686 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003687 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003688 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003689 mch_free_acl((vim_acl_T)p);
3690 p = NULL;
3691 }
3692 vim_free(wn);
3693 }
3694 else
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003695 {
3696 /* Try to retrieve the entire security descriptor. */
3697 err = GetNamedSecurityInfo(
3698 (LPSTR)fname, // Abstract filename
3699 SE_FILE_OBJECT, // File Object
3700 OWNER_SECURITY_INFORMATION |
3701 GROUP_SECURITY_INFORMATION |
3702 DACL_SECURITY_INFORMATION |
3703 SACL_SECURITY_INFORMATION,
3704 &p->pSidOwner, // Ownership information.
3705 &p->pSidGroup, // Group membership.
3706 &p->pDacl, // Discretionary information.
3707 &p->pSacl, // For auditing purposes.
3708 &p->pSecurityDescriptor);
3709 if (err == ERROR_ACCESS_DENIED ||
3710 err == ERROR_PRIVILEGE_NOT_HELD)
3711 {
3712 /* Retrieve only DACL. */
3713 (void)GetNamedSecurityInfo(
3714 (LPSTR)fname,
3715 SE_FILE_OBJECT,
3716 DACL_SECURITY_INFORMATION,
3717 NULL,
3718 NULL,
3719 &p->pDacl,
3720 NULL,
3721 &p->pSecurityDescriptor);
3722 }
3723 if (p->pSecurityDescriptor == NULL)
3724 {
3725 mch_free_acl((vim_acl_T)p);
3726 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 }
3728 }
3729 }
3730
3731 return (vim_acl_T)p;
3732#endif
3733}
3734
Bram Moolenaar27515922013-06-29 15:36:26 +02003735#ifdef HAVE_ACL
3736/*
3737 * Check if "acl" contains inherited ACE.
3738 */
3739 static BOOL
3740is_acl_inherited(PACL acl)
3741{
3742 DWORD i;
3743 ACL_SIZE_INFORMATION acl_info;
3744 PACCESS_ALLOWED_ACE ace;
3745
3746 acl_info.AceCount = 0;
3747 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3748 for (i = 0; i < acl_info.AceCount; i++)
3749 {
3750 GetAce(acl, i, (LPVOID *)&ace);
3751 if (ace->Header.AceFlags & INHERITED_ACE)
3752 return TRUE;
3753 }
3754 return FALSE;
3755}
3756#endif
3757
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758/*
3759 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3760 * Errors are ignored.
3761 * This must only be called with "acl" equal to what mch_get_acl() returned.
3762 */
3763 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003764mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765{
3766#ifdef HAVE_ACL
3767 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003768 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003770 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003771 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003772 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003773
3774 /* Set security flags */
3775 if (p->pSidOwner)
3776 sec_info |= OWNER_SECURITY_INFORMATION;
3777 if (p->pSidGroup)
3778 sec_info |= GROUP_SECURITY_INFORMATION;
3779 if (p->pDacl)
3780 {
3781 sec_info |= DACL_SECURITY_INFORMATION;
3782 /* Do not inherit its parent's DACL.
3783 * If the DACL is inherited, Cygwin permissions would be changed.
3784 */
3785 if (!is_acl_inherited(p->pDacl))
3786 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3787 }
3788 if (p->pSacl)
3789 sec_info |= SACL_SECURITY_INFORMATION;
3790
Bram Moolenaar27515922013-06-29 15:36:26 +02003791 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3792 wn = enc_to_utf16(fname, NULL);
3793 if (wn != NULL)
3794 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003795 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003796 wn, // Abstract filename
3797 SE_FILE_OBJECT, // File Object
3798 sec_info,
3799 p->pSidOwner, // Ownership information.
3800 p->pSidGroup, // Group membership.
3801 p->pDacl, // Discretionary information.
3802 p->pSacl // For auditing purposes.
3803 );
3804 vim_free(wn);
3805 }
3806 else
Bram Moolenaar27515922013-06-29 15:36:26 +02003807 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003808 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003809 (LPSTR)fname, // Abstract filename
3810 SE_FILE_OBJECT, // File Object
3811 sec_info,
3812 p->pSidOwner, // Ownership information.
3813 p->pSidGroup, // Group membership.
3814 p->pDacl, // Discretionary information.
3815 p->pSacl // For auditing purposes.
3816 );
3817 }
3818 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003819#endif
3820}
3821
3822 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003823mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824{
3825#ifdef HAVE_ACL
3826 struct my_acl *p = (struct my_acl *)acl;
3827
3828 if (p != NULL)
3829 {
3830 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3831 vim_free(p);
3832 }
3833#endif
3834}
3835
3836#ifndef FEAT_GUI_W32
3837
3838/*
3839 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3840 */
3841 static BOOL WINAPI
3842handler_routine(
3843 DWORD dwCtrlType)
3844{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003845 INPUT_RECORD ir;
3846 DWORD out;
3847
Bram Moolenaar071d4272004-06-13 20:20:40 +00003848 switch (dwCtrlType)
3849 {
3850 case CTRL_C_EVENT:
3851 if (ctrl_c_interrupts)
3852 g_fCtrlCPressed = TRUE;
3853 return TRUE;
3854
3855 case CTRL_BREAK_EVENT:
3856 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003857 ctrl_break_was_pressed = TRUE;
3858 /* ReadConsoleInput is blocking, send a key event to continue. */
3859 ir.EventType = KEY_EVENT;
3860 ir.Event.KeyEvent.bKeyDown = TRUE;
3861 ir.Event.KeyEvent.wRepeatCount = 1;
3862 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3863 ir.Event.KeyEvent.wVirtualScanCode = 0;
3864 ir.Event.KeyEvent.dwControlKeyState = 0;
3865 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3866 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867 return TRUE;
3868
3869 /* fatal events: shut down gracefully */
3870 case CTRL_CLOSE_EVENT:
3871 case CTRL_LOGOFF_EVENT:
3872 case CTRL_SHUTDOWN_EVENT:
3873 windgoto((int)Rows - 1, 0);
3874 g_fForceExit = TRUE;
3875
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003876 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877 (dwCtrlType == CTRL_CLOSE_EVENT
3878 ? _("close")
3879 : dwCtrlType == CTRL_LOGOFF_EVENT
3880 ? _("logoff")
3881 : _("shutdown")));
3882#ifdef DEBUG
3883 OutputDebugString(IObuff);
3884#endif
3885
3886 preserve_exit(); /* output IObuff, preserve files and exit */
3887
3888 return TRUE; /* not reached */
3889
3890 default:
3891 return FALSE;
3892 }
3893}
3894
3895
3896/*
3897 * set the tty in (raw) ? "raw" : "cooked" mode
3898 */
3899 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003900mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901{
3902 DWORD cmodein;
3903 DWORD cmodeout;
3904 BOOL bEnableHandler;
3905
3906 GetConsoleMode(g_hConIn, &cmodein);
3907 GetConsoleMode(g_hConOut, &cmodeout);
3908 if (tmode == TMODE_RAW)
3909 {
3910 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3911 ENABLE_ECHO_INPUT);
3912#ifdef FEAT_MOUSE
3913 if (g_fMouseActive)
3914 cmodein |= ENABLE_MOUSE_INPUT;
3915#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003916 cmodeout &= ~(
3917#ifdef FEAT_TERMGUICOLORS
3918 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3919 * VTP. */
3920 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3921#else
3922 ENABLE_PROCESSED_OUTPUT |
3923#endif
3924 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925 bEnableHandler = TRUE;
3926 }
3927 else /* cooked */
3928 {
3929 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3930 ENABLE_ECHO_INPUT);
3931 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3932 bEnableHandler = FALSE;
3933 }
3934 SetConsoleMode(g_hConIn, cmodein);
3935 SetConsoleMode(g_hConOut, cmodeout);
3936 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3937
3938#ifdef MCH_WRITE_DUMP
3939 if (fdDump)
3940 {
3941 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3942 tmode == TMODE_RAW ? "raw" :
3943 tmode == TMODE_COOK ? "cooked" : "normal",
3944 cmodein, cmodeout);
3945 fflush(fdDump);
3946 }
3947#endif
3948}
3949
3950
3951/*
3952 * Get the size of the current window in `Rows' and `Columns'
3953 * Return OK when size could be determined, FAIL otherwise.
3954 */
3955 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003956mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957{
3958 CONSOLE_SCREEN_BUFFER_INFO csbi;
3959
3960 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3961 {
3962 /*
3963 * For some reason, we are trying to get the screen dimensions
3964 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3965 * variables are really intended to mean the size of Vim screen
3966 * while in termcap mode.
3967 */
3968 Rows = g_cbTermcap.Info.dwSize.Y;
3969 Columns = g_cbTermcap.Info.dwSize.X;
3970 }
3971 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3972 {
3973 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3974 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3975 }
3976 else
3977 {
3978 Rows = 25;
3979 Columns = 80;
3980 }
3981 return OK;
3982}
3983
3984/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003985 * Resize console buffer to 'COORD'
3986 */
3987 static void
3988ResizeConBuf(
3989 HANDLE hConsole,
3990 COORD coordScreen)
3991{
3992 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3993 {
3994#ifdef MCH_WRITE_DUMP
3995 if (fdDump)
3996 {
3997 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3998 GetLastError());
3999 fflush(fdDump);
4000 }
4001#endif
4002 }
4003}
4004
4005/*
4006 * Resize console window size to 'srWindowRect'
4007 */
4008 static void
4009ResizeWindow(
4010 HANDLE hConsole,
4011 SMALL_RECT srWindowRect)
4012{
4013 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4014 {
4015#ifdef MCH_WRITE_DUMP
4016 if (fdDump)
4017 {
4018 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4019 GetLastError());
4020 fflush(fdDump);
4021 }
4022#endif
4023 }
4024}
4025
4026/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004027 * Set a console window to `xSize' * `ySize'
4028 */
4029 static void
4030ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004031 HANDLE hConsole,
4032 int xSize,
4033 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034{
4035 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4036 SMALL_RECT srWindowRect; /* hold the new console size */
4037 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004038 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004039
4040#ifdef MCH_WRITE_DUMP
4041 if (fdDump)
4042 {
4043 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4044 fflush(fdDump);
4045 }
4046#endif
4047
4048 /* get the largest size we can size the console window to */
4049 coordScreen = GetLargestConsoleWindowSize(hConsole);
4050
4051 /* define the new console window size and scroll position */
4052 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4053 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4054 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4055
4056 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4057 {
4058 int sx, sy;
4059
4060 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4061 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4062 if (sy < ySize || sx < xSize)
4063 {
4064 /*
4065 * Increasing number of lines/columns, do buffer first.
4066 * Use the maximal size in x and y direction.
4067 */
4068 if (sy < ySize)
4069 coordScreen.Y = ySize;
4070 else
4071 coordScreen.Y = sy;
4072 if (sx < xSize)
4073 coordScreen.X = xSize;
4074 else
4075 coordScreen.X = sx;
4076 SetConsoleScreenBufferSize(hConsole, coordScreen);
4077 }
4078 }
4079
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004080 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081 coordScreen.X = xSize;
4082 coordScreen.Y = ySize;
4083
Bram Moolenaar2551c032018-08-23 22:38:31 +02004084 // In the new console call API, only the first time in reverse order
4085 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004087 ResizeWindow(hConsole, srWindowRect);
4088 ResizeConBuf(hConsole, coordScreen);
4089 }
4090 else
4091 {
4092 ResizeConBuf(hConsole, coordScreen);
4093 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004094 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 }
4096}
4097
4098
4099/*
4100 * Set the console window to `Rows' * `Columns'
4101 */
4102 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004103mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104{
4105 COORD coordScreen;
4106
4107 /* Don't change window size while still starting up */
4108 if (suppress_winsize != 0)
4109 {
4110 suppress_winsize = 2;
4111 return;
4112 }
4113
4114 if (term_console)
4115 {
4116 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4117
4118 /* Clamp Rows and Columns to reasonable values */
4119 if (Rows > coordScreen.Y)
4120 Rows = coordScreen.Y;
4121 if (Columns > coordScreen.X)
4122 Columns = coordScreen.X;
4123
4124 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4125 }
4126}
4127
4128/*
4129 * Rows and/or Columns has changed.
4130 */
4131 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004132mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133{
4134 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4135}
4136
4137
4138/*
4139 * Called when started up, to set the winsize that was delayed.
4140 */
4141 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004142mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143{
4144 if (suppress_winsize == 2)
4145 {
4146 suppress_winsize = 0;
4147 mch_set_shellsize();
4148 shell_resized();
4149 }
4150 suppress_winsize = 0;
4151}
4152#endif /* FEAT_GUI_W32 */
4153
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004154 static BOOL
4155vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004156 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004157 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004158 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004159 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004160 PROCESS_INFORMATION *pi,
4161 LPVOID *env,
4162 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004163{
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004164 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4165 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004166 BOOL ret;
4167 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004168
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004169 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4170 if (wcmd == NULL)
4171 goto fallback;
4172 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004173 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004174 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4175 if (wcwd == NULL)
4176 {
4177 vim_free(wcmd);
4178 goto fallback;
4179 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004180 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004181
4182 ret = CreateProcessW(
4183 NULL, /* Executable name */
4184 wcmd, /* Command to execute */
4185 NULL, /* Process security attributes */
4186 NULL, /* Thread security attributes */
4187 inherit_handles, /* Inherit handles */
4188 flags, /* Creation flags */
4189 env, /* Environment */
4190 wcwd, /* Current directory */
4191 (LPSTARTUPINFOW)si, /* Startup information */
4192 pi); /* Process information */
4193 vim_free(wcmd);
4194 if (wcwd != NULL)
4195 vim_free(wcwd);
4196 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004197 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004198fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004199 return CreateProcess(
4200 NULL, /* Executable name */
4201 cmd, /* Command to execute */
4202 NULL, /* Process security attributes */
4203 NULL, /* Thread security attributes */
4204 inherit_handles, /* Inherit handles */
4205 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004206 env, /* Environment */
4207 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004208 si, /* Startup information */
4209 pi); /* Process information */
4210}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211
4212
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004213 static HINSTANCE
4214vim_shell_execute(
4215 char *cmd,
4216 INT n_show_cmd)
4217{
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004218 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4219 {
4220 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4221 if (wcmd != NULL)
4222 {
4223 HINSTANCE ret;
4224 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4225 vim_free(wcmd);
4226 return ret;
4227 }
4228 }
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004229 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4230}
4231
4232
Bram Moolenaar071d4272004-06-13 20:20:40 +00004233#if defined(FEAT_GUI_W32) || defined(PROTO)
4234
4235/*
4236 * Specialised version of system() for Win32 GUI mode.
4237 * This version proceeds as follows:
4238 * 1. Create a console window for use by the subprocess
4239 * 2. Run the subprocess (it gets the allocated console by default)
4240 * 3. Wait for the subprocess to terminate and get its exit code
4241 * 4. Prompt the user to press a key to close the console window
4242 */
4243 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004244mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245{
4246 STARTUPINFO si;
4247 PROCESS_INFORMATION pi;
4248 DWORD ret = 0;
4249 HWND hwnd = GetFocus();
4250
4251 si.cb = sizeof(si);
4252 si.lpReserved = NULL;
4253 si.lpDesktop = NULL;
4254 si.lpTitle = NULL;
4255 si.dwFlags = STARTF_USESHOWWINDOW;
4256 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004257 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004258 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004260 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004261 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004262 else
4263 si.wShowWindow = SW_SHOWNORMAL;
4264 si.cbReserved2 = 0;
4265 si.lpReserved2 = NULL;
4266
Bram Moolenaar071d4272004-06-13 20:20:40 +00004267 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004268 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004269 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4270 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004271
4272 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 {
4274#ifdef FEAT_GUI
4275 int delay = 1;
4276
4277 /* Keep updating the window while waiting for the shell to finish. */
4278 for (;;)
4279 {
4280 MSG msg;
4281
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004282 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283 {
4284 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004285 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004286 delay = 1;
4287 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004288 }
4289 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4290 break;
4291
4292 /* We start waiting for a very short time and then increase it, so
4293 * that we respond quickly when the process is quick, and don't
4294 * consume too much overhead when it's slow. */
4295 if (delay < 50)
4296 delay += 10;
4297 }
4298#else
4299 WaitForSingleObject(pi.hProcess, INFINITE);
4300#endif
4301
4302 /* Get the command exit code */
4303 GetExitCodeProcess(pi.hProcess, &ret);
4304 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305
4306 /* Close the handles to the subprocess, so that it goes away */
4307 CloseHandle(pi.hThread);
4308 CloseHandle(pi.hProcess);
4309
4310 /* Try to get input focus back. Doesn't always work though. */
4311 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4312
4313 return ret;
4314}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004315
4316/*
4317 * Thread launched by the gui to send the current buffer data to the
4318 * process. This way avoid to hang up vim totally if the children
4319 * process take a long time to process the lines.
4320 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004321 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004322sub_process_writer(LPVOID param)
4323{
4324 HANDLE g_hChildStd_IN_Wr = param;
4325 linenr_T lnum = curbuf->b_op_start.lnum;
4326 DWORD len = 0;
4327 DWORD l;
4328 char_u *lp = ml_get(lnum);
4329 char_u *s;
4330 int written = 0;
4331
4332 for (;;)
4333 {
4334 l = (DWORD)STRLEN(lp + written);
4335 if (l == 0)
4336 len = 0;
4337 else if (lp[written] == NL)
4338 {
4339 /* NL -> NUL translation */
4340 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4341 }
4342 else
4343 {
4344 s = vim_strchr(lp + written, NL);
4345 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4346 s == NULL ? l : (DWORD)(s - (lp + written)),
4347 &len, NULL);
4348 }
4349 if (len == (int)l)
4350 {
4351 /* Finished a line, add a NL, unless this line should not have
4352 * one. */
4353 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004354 || (!curbuf->b_p_bin
4355 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004356 || (lnum != curbuf->b_no_eol_lnum
4357 && (lnum != curbuf->b_ml.ml_line_count
4358 || curbuf->b_p_eol)))
4359 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004360 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4361 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004362 }
4363
4364 ++lnum;
4365 if (lnum > curbuf->b_op_end.lnum)
4366 break;
4367
4368 lp = ml_get(lnum);
4369 written = 0;
4370 }
4371 else if (len > 0)
4372 written += len;
4373 }
4374
4375 /* finished all the lines, close pipe */
4376 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004377 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004378}
4379
4380
4381# define BUFLEN 100 /* length for buffer, stolen from unix version */
4382
4383/*
4384 * This function read from the children's stdout and write the
4385 * data on screen or in the buffer accordingly.
4386 */
4387 static void
4388dump_pipe(int options,
4389 HANDLE g_hChildStd_OUT_Rd,
4390 garray_T *ga,
4391 char_u buffer[],
4392 DWORD *buffer_off)
4393{
4394 DWORD availableBytes = 0;
4395 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396 int ret;
4397 DWORD len;
4398 DWORD toRead;
4399 int repeatCount;
4400
4401 /* we query the pipe to see if there is any data to read
4402 * to avoid to perform a blocking read */
4403 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4404 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004405 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004406 NULL, /* number of read bytes */
4407 &availableBytes, /* available bytes total */
4408 NULL); /* byteLeft */
4409
4410 repeatCount = 0;
4411 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004412 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004413 {
4414 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004415 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004417 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418
4419 /* If we haven't read anything, there is a problem */
4420 if (len == 0)
4421 break;
4422
4423 availableBytes -= len;
4424
4425 if (options & SHELL_READ)
4426 {
4427 /* Do NUL -> NL translation, append NL separated
4428 * lines to the current buffer. */
4429 for (i = 0; i < len; ++i)
4430 {
4431 if (buffer[i] == NL)
4432 append_ga_line(ga);
4433 else if (buffer[i] == NUL)
4434 ga_append(ga, NL);
4435 else
4436 ga_append(ga, buffer[i]);
4437 }
4438 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004439 else if (has_mbyte)
4440 {
4441 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004442 int c;
4443 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004444
4445 len += *buffer_off;
4446 buffer[len] = NUL;
4447
4448 /* Check if the last character in buffer[] is
4449 * incomplete, keep these bytes for the next
4450 * round. */
4451 for (p = buffer; p < buffer + len; p += l)
4452 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004453 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004454 if (l == 0)
4455 l = 1; /* NUL byte? */
4456 else if (MB_BYTE2LEN(*p) != l)
4457 break;
4458 }
4459 if (p == buffer) /* no complete character */
4460 {
4461 /* avoid getting stuck at an illegal byte */
4462 if (len >= 12)
4463 ++p;
4464 else
4465 {
4466 *buffer_off = len;
4467 return;
4468 }
4469 }
4470 c = *p;
4471 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004472 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004473 if (p < buffer + len)
4474 {
4475 *p = c;
4476 *buffer_off = (DWORD)((buffer + len) - p);
4477 mch_memmove(buffer, p, *buffer_off);
4478 return;
4479 }
4480 *buffer_off = 0;
4481 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004482 else
4483 {
4484 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004485 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004486 }
4487
4488 windgoto(msg_row, msg_col);
4489 cursor_on();
4490 out_flush();
4491 }
4492}
4493
4494/*
4495 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4496 * for communication and doesn't open any new window.
4497 */
4498 static int
4499mch_system_piped(char *cmd, int options)
4500{
4501 STARTUPINFO si;
4502 PROCESS_INFORMATION pi;
4503 DWORD ret = 0;
4504
4505 HANDLE g_hChildStd_IN_Rd = NULL;
4506 HANDLE g_hChildStd_IN_Wr = NULL;
4507 HANDLE g_hChildStd_OUT_Rd = NULL;
4508 HANDLE g_hChildStd_OUT_Wr = NULL;
4509
4510 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4511 DWORD len;
4512
4513 /* buffer used to receive keys */
4514 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4515 int ta_len = 0; /* valid bytes in ta_buf[] */
4516
4517 DWORD i;
4518 int c;
4519 int noread_cnt = 0;
4520 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004521 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004522 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004523 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004524
4525 SECURITY_ATTRIBUTES saAttr;
4526
4527 /* Set the bInheritHandle flag so pipe handles are inherited. */
4528 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4529 saAttr.bInheritHandle = TRUE;
4530 saAttr.lpSecurityDescriptor = NULL;
4531
4532 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4533 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004534 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004535 /* Create a pipe for the child process's STDIN. */
4536 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4537 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004538 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004539 {
4540 CloseHandle(g_hChildStd_IN_Rd);
4541 CloseHandle(g_hChildStd_IN_Wr);
4542 CloseHandle(g_hChildStd_OUT_Rd);
4543 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004544 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004545 }
4546
4547 si.cb = sizeof(si);
4548 si.lpReserved = NULL;
4549 si.lpDesktop = NULL;
4550 si.lpTitle = NULL;
4551 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4552
4553 /* set-up our file redirection */
4554 si.hStdError = g_hChildStd_OUT_Wr;
4555 si.hStdOutput = g_hChildStd_OUT_Wr;
4556 si.hStdInput = g_hChildStd_IN_Rd;
4557 si.wShowWindow = SW_HIDE;
4558 si.cbReserved2 = 0;
4559 si.lpReserved2 = NULL;
4560
4561 if (options & SHELL_READ)
4562 ga_init2(&ga, 1, BUFLEN);
4563
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004564 if (cmd != NULL)
4565 {
4566 p = (char *)vim_strsave((char_u *)cmd);
4567 if (p != NULL)
4568 unescape_shellxquote((char_u *)p, p_sxe);
4569 else
4570 p = cmd;
4571 }
4572
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004573 /* Now, run the command.
4574 * About "Inherit handles" being TRUE: this command can be litigious,
4575 * handle inheritance was deactivated for pending temp file, but, if we
4576 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004577 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4578 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004579
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004580 if (p != cmd)
4581 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004582
4583 /* Close our unused side of the pipes */
4584 CloseHandle(g_hChildStd_IN_Rd);
4585 CloseHandle(g_hChildStd_OUT_Wr);
4586
4587 if (options & SHELL_WRITE)
4588 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004589 HANDLE thread = (HANDLE)
4590 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004591 0, /* default stack size */
4592 sub_process_writer, /* function to be executed */
4593 g_hChildStd_IN_Wr, /* parameter */
4594 0, /* creation flag, start immediately */
4595 NULL); /* we don't care about thread id */
4596 CloseHandle(thread);
4597 g_hChildStd_IN_Wr = NULL;
4598 }
4599
4600 /* Keep updating the window while waiting for the shell to finish. */
4601 for (;;)
4602 {
4603 MSG msg;
4604
Bram Moolenaar175d0702013-12-11 18:36:33 +01004605 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004606 {
4607 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004608 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004609 }
4610
4611 /* write pipe information in the window */
4612 if ((options & (SHELL_READ|SHELL_WRITE))
4613# ifdef FEAT_GUI
4614 || gui.in_use
4615# endif
4616 )
4617 {
4618 len = 0;
4619 if (!(options & SHELL_EXPAND)
4620 && ((options &
4621 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4622 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4623# ifdef FEAT_GUI
4624 || gui.in_use
4625# endif
4626 )
4627 && (ta_len > 0 || noread_cnt > 4))
4628 {
4629 if (ta_len == 0)
4630 {
4631 /* Get extra characters when we don't have any. Reset the
4632 * counter and timer. */
4633 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004634 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4635 }
4636 if (ta_len > 0 || len > 0)
4637 {
4638 /*
4639 * For pipes: Check for CTRL-C: send interrupt signal to
4640 * child. Check for CTRL-D: EOF, close pipe to child.
4641 */
4642 if (len == 1 && cmd != NULL)
4643 {
4644 if (ta_buf[ta_len] == Ctrl_C)
4645 {
4646 /* Learn what exit code is expected, for
4647 * now put 9 as SIGKILL */
4648 TerminateProcess(pi.hProcess, 9);
4649 }
4650 if (ta_buf[ta_len] == Ctrl_D)
4651 {
4652 CloseHandle(g_hChildStd_IN_Wr);
4653 g_hChildStd_IN_Wr = NULL;
4654 }
4655 }
4656
4657 /* replace K_BS by <BS> and K_DEL by <DEL> */
4658 for (i = ta_len; i < ta_len + len; ++i)
4659 {
4660 if (ta_buf[i] == CSI && len - i > 2)
4661 {
4662 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4663 if (c == K_DEL || c == K_KDEL || c == K_BS)
4664 {
4665 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4666 (size_t)(len - i - 2));
4667 if (c == K_DEL || c == K_KDEL)
4668 ta_buf[i] = DEL;
4669 else
4670 ta_buf[i] = Ctrl_H;
4671 len -= 2;
4672 }
4673 }
4674 else if (ta_buf[i] == '\r')
4675 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004676 if (has_mbyte)
4677 i += (*mb_ptr2len_len)(ta_buf + i,
4678 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004679 }
4680
4681 /*
4682 * For pipes: echo the typed characters. For a pty this
4683 * does not seem to work.
4684 */
4685 for (i = ta_len; i < ta_len + len; ++i)
4686 {
4687 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4688 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004689 else if (has_mbyte)
4690 {
4691 int l = (*mb_ptr2len)(ta_buf + i);
4692
4693 msg_outtrans_len(ta_buf + i, l);
4694 i += l - 1;
4695 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004696 else
4697 msg_outtrans_len(ta_buf + i, 1);
4698 }
4699 windgoto(msg_row, msg_col);
4700 out_flush();
4701
4702 ta_len += len;
4703
4704 /*
4705 * Write the characters to the child, unless EOF has been
4706 * typed for pipes. Write one character at a time, to
4707 * avoid losing too much typeahead. When writing buffer
4708 * lines, drop the typed characters (only check for
4709 * CTRL-C).
4710 */
4711 if (options & SHELL_WRITE)
4712 ta_len = 0;
4713 else if (g_hChildStd_IN_Wr != NULL)
4714 {
4715 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4716 1, &len, NULL);
4717 // if we are typing in, we want to keep things reactive
4718 delay = 1;
4719 if (len > 0)
4720 {
4721 ta_len -= len;
4722 mch_memmove(ta_buf, ta_buf + len, ta_len);
4723 }
4724 }
4725 }
4726 }
4727 }
4728
4729 if (ta_len)
4730 ui_inchar_undo(ta_buf, ta_len);
4731
4732 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4733 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004734 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004735 break;
4736 }
4737
4738 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004739 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004740
4741 /* We start waiting for a very short time and then increase it, so
4742 * that we respond quickly when the process is quick, and don't
4743 * consume too much overhead when it's slow. */
4744 if (delay < 50)
4745 delay += 10;
4746 }
4747
4748 /* Close the pipe */
4749 CloseHandle(g_hChildStd_OUT_Rd);
4750 if (g_hChildStd_IN_Wr != NULL)
4751 CloseHandle(g_hChildStd_IN_Wr);
4752
4753 WaitForSingleObject(pi.hProcess, INFINITE);
4754
4755 /* Get the command exit code */
4756 GetExitCodeProcess(pi.hProcess, &ret);
4757
4758 if (options & SHELL_READ)
4759 {
4760 if (ga.ga_len > 0)
4761 {
4762 append_ga_line(&ga);
4763 /* remember that the NL was missing */
4764 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4765 }
4766 else
4767 curbuf->b_no_eol_lnum = 0;
4768 ga_clear(&ga);
4769 }
4770
4771 /* Close the handles to the subprocess, so that it goes away */
4772 CloseHandle(pi.hThread);
4773 CloseHandle(pi.hProcess);
4774
4775 return ret;
4776}
4777
4778 static int
4779mch_system(char *cmd, int options)
4780{
4781 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004782 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004783 return mch_system_piped(cmd, options);
4784 else
4785 return mch_system_classic(cmd, options);
4786}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787#else
4788
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004789 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004790mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004791{
4792 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4793 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004794 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004795 if (wcmd != NULL)
4796 {
4797 int ret = _wsystem(wcmd);
4798 vim_free(wcmd);
4799 return ret;
4800 }
4801 }
4802 return system(cmd);
4803}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804
4805#endif
4806
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004807#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4808/*
4809 * Use a terminal window to run a shell command in.
4810 */
4811 static int
4812mch_call_shell_terminal(
4813 char_u *cmd,
4814 int options UNUSED) /* SHELL_*, see vim.h */
4815{
4816 jobopt_T opt;
4817 char_u *newcmd = NULL;
4818 typval_T argvar[2];
4819 long_u cmdlen;
4820 int retval = -1;
4821 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004822 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004823 aco_save_T aco;
4824 oparg_T oa; /* operator arguments */
4825
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004826 if (cmd == NULL)
4827 cmdlen = STRLEN(p_sh) + 1;
4828 else
4829 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004830 newcmd = lalloc(cmdlen, TRUE);
4831 if (newcmd == NULL)
4832 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004833 if (cmd == NULL)
4834 {
4835 STRCPY(newcmd, p_sh);
4836 ch_log(NULL, "starting terminal to run a shell");
4837 }
4838 else
4839 {
4840 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4841 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4842 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004843
4844 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004845
4846 argvar[0].v_type = VAR_STRING;
4847 argvar[0].vval.v_string = newcmd;
4848 argvar[1].v_type = VAR_UNKNOWN;
4849 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004850 if (buf == NULL)
4851 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004852
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004853 job = term_getjob(buf->b_term);
4854 ++job->jv_refcount;
4855
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004856 /* Find a window to make "buf" curbuf. */
4857 aucmd_prepbuf(&aco, buf);
4858
4859 clear_oparg(&oa);
4860 while (term_use_loop())
4861 {
4862 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4863 {
4864 /* If terminal_loop() returns OK we got a key that is handled
4865 * in Normal model. We don't do redrawing anyway. */
4866 if (terminal_loop(TRUE) == OK)
4867 normal_cmd(&oa, TRUE);
4868 }
4869 else
4870 normal_cmd(&oa, TRUE);
4871 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004872 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004873 ch_log(NULL, "system command finished");
4874
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004875 job_unref(job);
4876
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004877 /* restore curwin/curbuf and a few other things */
4878 aucmd_restbuf(&aco);
4879
4880 wait_return(TRUE);
4881 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4882
4883 vim_free(newcmd);
4884 return retval;
4885}
4886#endif
4887
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888/*
4889 * Either execute a command by calling the shell or start a new shell
4890 */
4891 int
4892mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004893 char_u *cmd,
4894 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895{
4896 int x = 0;
4897 int tmode = cur_tmode;
4898#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004899 char szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004900 int did_set_title = FALSE;
4901
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004902 /* Change the title to reflect that we are in a subshell. */
4903 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4904 {
4905 WCHAR szShellTitle[512];
4906
4907 if (GetConsoleTitleW(szShellTitle,
4908 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4909 {
4910 if (cmd == NULL)
4911 wcscat(szShellTitle, L" :sh");
4912 else
4913 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004914 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004915
4916 if (wn != NULL)
4917 {
4918 wcscat(szShellTitle, L" - !");
4919 if ((wcslen(szShellTitle) + wcslen(wn) <
4920 sizeof(szShellTitle)/sizeof(WCHAR)))
4921 wcscat(szShellTitle, wn);
4922 SetConsoleTitleW(szShellTitle);
4923 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004924 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004925 }
4926 }
4927 }
4928 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004929 if (!did_set_title)
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004930 /* Change the title to reflect that we are in a subshell. */
4931 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004933 if (cmd == NULL)
4934 strcat(szShellTitle, " :sh");
4935 else
4936 {
4937 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004938 if ((strlen(szShellTitle) + strlen((char *)cmd)
4939 < sizeof(szShellTitle)))
4940 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004941 }
4942 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004943 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944#endif
4945
4946 out_flush();
4947
4948#ifdef MCH_WRITE_DUMP
4949 if (fdDump)
4950 {
4951 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4952 fflush(fdDump);
4953 }
4954#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004955#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4956 /* TODO: make the terminal window work with input or output redirected. */
4957 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4958 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4959 {
4960 /* Use a terminal window to run the command in. */
4961 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004962# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004963 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004964# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004965 return x;
4966 }
4967#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004968
4969 /*
4970 * Catch all deadly signals while running the external command, because a
4971 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4972 */
4973 signal(SIGINT, SIG_IGN);
4974#if defined(__GNUC__) && !defined(__MINGW32__)
4975 signal(SIGKILL, SIG_IGN);
4976#else
4977 signal(SIGBREAK, SIG_IGN);
4978#endif
4979 signal(SIGILL, SIG_IGN);
4980 signal(SIGFPE, SIG_IGN);
4981 signal(SIGSEGV, SIG_IGN);
4982 signal(SIGTERM, SIG_IGN);
4983 signal(SIGABRT, SIG_IGN);
4984
4985 if (options & SHELL_COOKED)
4986 settmode(TMODE_COOK); /* set to normal mode */
4987
4988 if (cmd == NULL)
4989 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004990 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004991 }
4992 else
4993 {
4994 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004995 char_u *newcmd = NULL;
4996 char_u *cmdbase = cmd;
4997 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004998
4999 /* Skip a leading ", ( and "(. */
5000 if (*cmdbase == '"' )
5001 ++cmdbase;
5002 if (*cmdbase == '(')
5003 ++cmdbase;
5004
Bram Moolenaar1c465442017-03-12 20:10:05 +01005005 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005006 {
5007 STARTUPINFO si;
5008 PROCESS_INFORMATION pi;
5009 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005010 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005011 char_u *p;
5012
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005013 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005014 si.cb = sizeof(si);
5015 si.lpReserved = NULL;
5016 si.lpDesktop = NULL;
5017 si.lpTitle = NULL;
5018 si.dwFlags = 0;
5019 si.cbReserved2 = 0;
5020 si.lpReserved2 = NULL;
5021
5022 cmdbase = skipwhite(cmdbase + 5);
5023 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005024 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005025 {
5026 cmdbase = skipwhite(cmdbase + 4);
5027 si.dwFlags = STARTF_USESHOWWINDOW;
5028 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005029 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005030 }
5031 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005032 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005033 {
5034 cmdbase = skipwhite(cmdbase + 2);
5035 flags = CREATE_NO_WINDOW;
5036 si.dwFlags = STARTF_USESTDHANDLES;
5037 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005038 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005039 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005040 NULL, // Security att.
5041 OPEN_EXISTING, // Open flags
5042 FILE_ATTRIBUTE_NORMAL, // File att.
5043 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005044 si.hStdOutput = si.hStdInput;
5045 si.hStdError = si.hStdInput;
5046 }
5047
5048 /* Remove a trailing ", ) and )" if they have a match
5049 * at the start of the command. */
5050 if (cmdbase > cmd)
5051 {
5052 p = cmdbase + STRLEN(cmdbase);
5053 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5054 *--p = NUL;
5055 if (p > cmdbase && p[-1] == ')'
5056 && (*cmd =='(' || cmd[1] == '('))
5057 *--p = NUL;
5058 }
5059
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005060 newcmd = cmdbase;
5061 unescape_shellxquote(cmdbase, p_sxe);
5062
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005063 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005064 * If creating new console, arguments are passed to the
5065 * 'cmd.exe' as-is. If it's not, arguments are not treated
5066 * correctly for current 'cmd.exe'. So unescape characters in
5067 * shellxescape except '|' for avoiding to be treated as
5068 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005069 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005070 if (flags != CREATE_NEW_CONSOLE)
5071 {
5072 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005073 char_u *cmd_shell = mch_getenv("COMSPEC");
5074
5075 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005076 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005077
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005078 subcmd = vim_strsave_escaped_ext(cmdbase,
5079 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005080 if (subcmd != NULL)
5081 {
5082 /* make "cmd.exe /c arguments" */
5083 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005084 newcmd = lalloc(cmdlen, TRUE);
5085 if (newcmd != NULL)
5086 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005087 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005088 else
5089 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005090 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005091 }
5092 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005093
5094 /*
5095 * Now, start the command as a process, so that it doesn't
5096 * inherit our handles which causes unpleasant dangling swap
5097 * files if we exit before the spawned process
5098 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005099 if (vim_create_process((char *)newcmd, FALSE, flags,
5100 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005101 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005102 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5103 > (HINSTANCE)32)
5104 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005105 else
5106 {
5107 x = -1;
5108#ifdef FEAT_GUI_W32
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005109 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005110#endif
5111 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005112
5113 if (newcmd != cmdbase)
5114 vim_free(newcmd);
5115
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005116 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005117 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005118 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005119 CloseHandle(si.hStdInput);
5120 }
5121 /* Close the handles to the subprocess, so that it goes away */
5122 CloseHandle(pi.hThread);
5123 CloseHandle(pi.hProcess);
5124 }
5125 else
5126 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005127 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005128#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005129 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005130#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005131 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5132
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005133 newcmd = lalloc(cmdlen, TRUE);
5134 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005135 {
5136#if defined(FEAT_GUI_W32)
5137 if (need_vimrun_warning)
5138 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005139 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5140 "External commands will not pause after completion.\n"
5141 "See :help win32-vimrun for more information.");
5142 char *title = _("Vim Warning");
Bram Moolenaar63e43442016-11-19 17:28:44 +01005143 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5144 {
5145 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5146 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5147
5148 if (wmsg != NULL && wtitle != NULL)
5149 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5150 vim_free(wmsg);
5151 vim_free(wtitle);
5152 }
5153 else
Bram Moolenaar63e43442016-11-19 17:28:44 +01005154 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005155 need_vimrun_warning = FALSE;
5156 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005157 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005158 /* Use vimrun to execute the command. It opens a console
5159 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005160 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005161 vimrun_path,
5162 (msg_silent != 0 || (options & SHELL_DOOUT))
5163 ? "-s " : "",
5164 p_sh, p_shcf, cmd);
5165 else
5166#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005167 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005168 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005169 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005170 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005171 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005172 }
5173 }
5174
5175 if (tmode == TMODE_RAW)
5176 settmode(TMODE_RAW); /* set to raw mode */
5177
5178 /* Print the return value, unless "vimrun" was used. */
5179 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5180#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005181 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182#endif
5183 )
5184 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005185 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186 msg_putchar('\n');
5187 }
5188#ifdef FEAT_TITLE
5189 resettitle();
5190#endif
5191
5192 signal(SIGINT, SIG_DFL);
5193#if defined(__GNUC__) && !defined(__MINGW32__)
5194 signal(SIGKILL, SIG_DFL);
5195#else
5196 signal(SIGBREAK, SIG_DFL);
5197#endif
5198 signal(SIGILL, SIG_DFL);
5199 signal(SIGFPE, SIG_DFL);
5200 signal(SIGSEGV, SIG_DFL);
5201 signal(SIGTERM, SIG_DFL);
5202 signal(SIGABRT, SIG_DFL);
5203
5204 return x;
5205}
5206
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005207#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005208 static HANDLE
5209job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005210 char_u *fname,
5211 DWORD dwDesiredAccess,
5212 DWORD dwShareMode,
5213 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5214 DWORD dwCreationDisposition,
5215 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005216{
5217 HANDLE h;
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005218 WCHAR *wn = NULL;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005219
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005220 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5221 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005222 wn = enc_to_utf16(fname, NULL);
5223 if (wn != NULL)
5224 {
5225 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5226 lpSecurityAttributes, dwCreationDisposition,
5227 dwFlagsAndAttributes, NULL);
5228 vim_free(wn);
5229 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005230 }
5231 if (wn == NULL)
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005232 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5233 lpSecurityAttributes, dwCreationDisposition,
5234 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005235 return h;
5236}
5237
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005238/*
5239 * Turn the dictionary "env" into a NUL separated list that can be used as the
5240 * environment argument of vim_create_process().
5241 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005242 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005243win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005244{
5245 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005246 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005247 LPVOID base = GetEnvironmentStringsW();
5248
5249 /* for last \0 */
5250 if (ga_grow(gap, 1) == FAIL)
5251 return;
5252
5253 if (base)
5254 {
5255 WCHAR *p = (WCHAR*) base;
5256
5257 /* for last \0 */
5258 if (ga_grow(gap, 1) == FAIL)
5259 return;
5260
5261 while (*p != 0 || *(p + 1) != 0)
5262 {
5263 if (ga_grow(gap, 1) == OK)
5264 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5265 p++;
5266 }
5267 FreeEnvironmentStrings(base);
5268 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5269 }
5270
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005271 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005272 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005273 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005274 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005275 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005276 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005277 typval_T *item = &dict_lookup(hi)->di_tv;
5278 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005279 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005280 --todo;
5281 if (wkey != NULL && wval != NULL)
5282 {
5283 size_t n;
5284 size_t lkey = wcslen(wkey);
5285 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005286
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005287 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5288 continue;
5289 for (n = 0; n < lkey; n++)
5290 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5291 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5292 for (n = 0; n < lval; n++)
5293 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5294 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5295 }
5296 if (wkey != NULL) vim_free(wkey);
5297 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005298 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005299 }
5300 }
5301
Bram Moolenaar493359e2018-06-12 20:25:52 +02005302# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005303 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005304# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005305 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005306 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005307# endif
5308# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005309 char_u *version = get_vim_var_str(VV_VERSION);
5310 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005311# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005312 // size of "VIM_SERVERNAME=" and value,
5313 // plus "VIM_TERMINAL=" and value,
5314 // plus two terminating NULs
5315 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005316# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005317 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005318# endif
5319# ifdef FEAT_TERMINAL
5320 + 13 + version_len + 2
5321# endif
5322 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005323
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005324 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005325 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005326# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005327 for (n = 0; n < 15; n++)
5328 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5329 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005330 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005331 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5332 (WCHAR)servername[n];
5333 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005334# endif
5335# ifdef FEAT_TERMINAL
5336 if (is_terminal)
5337 {
5338 for (n = 0; n < 13; n++)
5339 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5340 (WCHAR)"VIM_TERMINAL="[n];
5341 for (n = 0; n < version_len; n++)
5342 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5343 (WCHAR)version[n];
5344 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5345 }
5346# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005347 }
5348 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005349# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005350}
5351
Bram Moolenaarb091f302019-01-19 14:37:00 +01005352/*
5353 * Create a pair of pipes.
5354 * Return TRUE for success, FALSE for failure.
5355 */
5356 static BOOL
5357create_pipe_pair(HANDLE handles[2])
5358{
5359 static LONG s;
5360 char name[64];
5361 SECURITY_ATTRIBUTES sa;
5362
5363 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5364 GetCurrentProcessId(),
5365 InterlockedIncrement(&s));
5366
5367 // Create named pipe. Max size of named pipe is 65535.
5368 handles[1] = CreateNamedPipe(
5369 name,
5370 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5371 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005372 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005373
5374 if (handles[1] == INVALID_HANDLE_VALUE)
5375 return FALSE;
5376
5377 sa.nLength = sizeof(sa);
5378 sa.bInheritHandle = TRUE;
5379 sa.lpSecurityDescriptor = NULL;
5380
5381 handles[0] = CreateFile(name,
5382 FILE_GENERIC_READ,
5383 FILE_SHARE_READ, &sa,
5384 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5385
5386 if (handles[0] == INVALID_HANDLE_VALUE)
5387 {
5388 CloseHandle(handles[1]);
5389 return FALSE;
5390 }
5391
5392 return TRUE;
5393}
5394
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005395 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005396mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005397{
5398 STARTUPINFO si;
5399 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005400 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005401 SECURITY_ATTRIBUTES saAttr;
5402 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005403 HANDLE ifd[2];
5404 HANDLE ofd[2];
5405 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005406 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005407
5408 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5409 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5410 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5411 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5412 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5413 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5414 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5415
5416 if (use_out_for_err && use_null_for_out)
5417 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005418
5419 ifd[0] = INVALID_HANDLE_VALUE;
5420 ifd[1] = INVALID_HANDLE_VALUE;
5421 ofd[0] = INVALID_HANDLE_VALUE;
5422 ofd[1] = INVALID_HANDLE_VALUE;
5423 efd[0] = INVALID_HANDLE_VALUE;
5424 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005425 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005426
Bram Moolenaar14207f42016-10-27 21:13:10 +02005427 jo = CreateJobObject(NULL, NULL);
5428 if (jo == NULL)
5429 {
5430 job->jv_status = JOB_FAILED;
5431 goto failed;
5432 }
5433
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005434 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005435 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005436
Bram Moolenaar76467df2016-02-12 19:30:26 +01005437 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005438 ZeroMemory(&si, sizeof(si));
5439 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005440 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005441 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005442
Bram Moolenaard8070362016-02-15 21:56:54 +01005443 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5444 saAttr.bInheritHandle = TRUE;
5445 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005446
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005447 if (use_file_for_in)
5448 {
5449 char_u *fname = options->jo_io_name[PART_IN];
5450
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005451 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5452 FILE_SHARE_READ | FILE_SHARE_WRITE,
5453 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5454 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005455 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005456 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005457 goto failed;
5458 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005459 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005460 else if (!use_null_for_in
5461 && (!create_pipe_pair(ifd)
5462 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005463 goto failed;
5464
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005465 if (use_file_for_out)
5466 {
5467 char_u *fname = options->jo_io_name[PART_OUT];
5468
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005469 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5470 FILE_SHARE_READ | FILE_SHARE_WRITE,
5471 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5472 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005473 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005474 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005475 goto failed;
5476 }
5477 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005478 else if (!use_null_for_out &&
5479 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005480 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005481 goto failed;
5482
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005483 if (use_file_for_err)
5484 {
5485 char_u *fname = options->jo_io_name[PART_ERR];
5486
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005487 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5488 FILE_SHARE_READ | FILE_SHARE_WRITE,
5489 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5490 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005491 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005492 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005493 goto failed;
5494 }
5495 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005496 else if (!use_out_for_err && !use_null_for_err &&
5497 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005498 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005499 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005500
Bram Moolenaard8070362016-02-15 21:56:54 +01005501 si.dwFlags |= STARTF_USESTDHANDLES;
5502 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005503 si.hStdOutput = ofd[1];
5504 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5505
5506 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5507 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005508 if (options->jo_set & JO_CHANNEL)
5509 {
5510 channel = options->jo_channel;
5511 if (channel != NULL)
5512 ++channel->ch_refcount;
5513 }
5514 else
5515 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005516 if (channel == NULL)
5517 goto failed;
5518 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005519
5520 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005521 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005522 CREATE_DEFAULT_ERROR_MODE |
5523 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005524 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005525 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005526 &si, &pi,
5527 ga.ga_data,
5528 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005529 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005530 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005531 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005532 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005533 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005534
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005535 ga_clear(&ga);
5536
Bram Moolenaar14207f42016-10-27 21:13:10 +02005537 if (!AssignProcessToJobObject(jo, pi.hProcess))
5538 {
5539 /* if failing, switch the way to terminate
5540 * process with TerminateProcess. */
5541 CloseHandle(jo);
5542 jo = NULL;
5543 }
5544 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005545 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005546 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005547 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005548 job->jv_status = JOB_STARTED;
5549
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005550 CloseHandle(ifd[0]);
5551 CloseHandle(ofd[1]);
5552 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005553 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005554
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005555 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005556 if (channel != NULL)
5557 {
5558 channel_set_pipes(channel,
5559 use_file_for_in || use_null_for_in
5560 ? INVALID_FD : (sock_T)ifd[1],
5561 use_file_for_out || use_null_for_out
5562 ? INVALID_FD : (sock_T)ofd[0],
5563 use_out_for_err || use_file_for_err || use_null_for_err
5564 ? INVALID_FD : (sock_T)efd[0]);
5565 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005566 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005567 return;
5568
5569failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005570 CloseHandle(ifd[0]);
5571 CloseHandle(ofd[0]);
5572 CloseHandle(efd[0]);
5573 CloseHandle(ifd[1]);
5574 CloseHandle(ofd[1]);
5575 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005576 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005577 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005578}
5579
5580 char *
5581mch_job_status(job_T *job)
5582{
5583 DWORD dwExitCode = 0;
5584
Bram Moolenaar76467df2016-02-12 19:30:26 +01005585 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5586 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005587 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005588 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005589 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005590 {
5591 ch_log(job->jv_channel, "Job ended");
5592 job->jv_status = JOB_ENDED;
5593 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005594 return "dead";
5595 }
5596 return "run";
5597}
5598
Bram Moolenaar97792de2016-10-15 18:36:49 +02005599 job_T *
5600mch_detect_ended_job(job_T *job_list)
5601{
5602 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5603 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5604 job_T *job = job_list;
5605
5606 while (job != NULL)
5607 {
5608 DWORD n;
5609 DWORD result;
5610
5611 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5612 && job != NULL; job = job->jv_next)
5613 {
5614 if (job->jv_status == JOB_STARTED)
5615 {
5616 jobHandles[n] = job->jv_proc_info.hProcess;
5617 jobArray[n] = job;
5618 ++n;
5619 }
5620 }
5621 if (n == 0)
5622 continue;
5623 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5624 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5625 {
5626 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5627
5628 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5629 return wait_job;
5630 }
5631 }
5632 return NULL;
5633}
5634
Bram Moolenaarfb630902016-10-29 14:55:00 +02005635 static BOOL
5636terminate_all(HANDLE process, int code)
5637{
5638 PROCESSENTRY32 pe;
5639 HANDLE h = INVALID_HANDLE_VALUE;
5640 DWORD pid = GetProcessId(process);
5641
5642 if (pid != 0)
5643 {
5644 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5645 if (h != INVALID_HANDLE_VALUE)
5646 {
5647 pe.dwSize = sizeof(PROCESSENTRY32);
5648 if (!Process32First(h, &pe))
5649 goto theend;
5650
5651 do
5652 {
5653 if (pe.th32ParentProcessID == pid)
5654 {
5655 HANDLE ph = OpenProcess(
5656 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5657 if (ph != NULL)
5658 {
5659 terminate_all(ph, code);
5660 CloseHandle(ph);
5661 }
5662 }
5663 } while (Process32Next(h, &pe));
5664
5665 CloseHandle(h);
5666 }
5667 }
5668
5669theend:
5670 return TerminateProcess(process, code);
5671}
5672
5673/*
5674 * Send a (deadly) signal to "job".
5675 * Return FAIL if it didn't work.
5676 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005677 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005678mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005679{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005680 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005681
Bram Moolenaar923d9262016-02-25 20:56:01 +01005682 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005683 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005684 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005685 if (job->jv_job_object != NULL)
5686 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005687 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005688 }
5689
5690 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5691 return FAIL;
5692 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005693 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5694 job->jv_proc_info.dwProcessId)
5695 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005696 FreeConsole();
5697 return ret;
5698}
5699
5700/*
5701 * Clear the data related to "job".
5702 */
5703 void
5704mch_clear_job(job_T *job)
5705{
5706 if (job->jv_status != JOB_FAILED)
5707 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005708 if (job->jv_job_object != NULL)
5709 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005710 CloseHandle(job->jv_proc_info.hProcess);
5711 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005712}
5713#endif
5714
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715
5716#ifndef FEAT_GUI_W32
5717
5718/*
5719 * Start termcap mode
5720 */
5721 static void
5722termcap_mode_start(void)
5723{
5724 DWORD cmodein;
5725
5726 if (g_fTermcapMode)
5727 return;
5728
5729 SaveConsoleBuffer(&g_cbNonTermcap);
5730
5731 if (g_cbTermcap.IsValid)
5732 {
5733 /*
5734 * We've been in termcap mode before. Restore certain screen
5735 * characteristics, including the buffer size and the window
5736 * size. Since we will be redrawing the screen, we don't need
5737 * to restore the actual contents of the buffer.
5738 */
5739 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005740 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5742 Rows = g_cbTermcap.Info.dwSize.Y;
5743 Columns = g_cbTermcap.Info.dwSize.X;
5744 }
5745 else
5746 {
5747 /*
5748 * This is our first time entering termcap mode. Clear the console
5749 * screen buffer, and resize the buffer to match the current window
5750 * size. We will use this as the size of our editing environment.
5751 */
5752 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005753 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005754 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5755 }
5756
5757#ifdef FEAT_TITLE
5758 resettitle();
5759#endif
5760
5761 GetConsoleMode(g_hConIn, &cmodein);
5762#ifdef FEAT_MOUSE
5763 if (g_fMouseActive)
5764 cmodein |= ENABLE_MOUSE_INPUT;
5765 else
5766 cmodein &= ~ENABLE_MOUSE_INPUT;
5767#endif
5768 cmodein |= ENABLE_WINDOW_INPUT;
5769 SetConsoleMode(g_hConIn, cmodein);
5770
5771 redraw_later_clear();
5772 g_fTermcapMode = TRUE;
5773}
5774
5775
5776/*
5777 * End termcap mode
5778 */
5779 static void
5780termcap_mode_end(void)
5781{
5782 DWORD cmodein;
5783 ConsoleBuffer *cb;
5784 COORD coord;
5785 DWORD dwDummy;
5786
5787 if (!g_fTermcapMode)
5788 return;
5789
5790 SaveConsoleBuffer(&g_cbTermcap);
5791
5792 GetConsoleMode(g_hConIn, &cmodein);
5793 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5794 SetConsoleMode(g_hConIn, cmodein);
5795
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005796#ifdef FEAT_RESTORE_ORIG_SCREEN
5797 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5798#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005800#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005801 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005802 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803 SetConsoleCursorInfo(g_hConOut, &g_cci);
5804
5805 if (p_rs || exiting)
5806 {
5807 /*
5808 * Clear anything that happens to be on the current line.
5809 */
5810 coord.X = 0;
5811 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5812 FillConsoleOutputCharacter(g_hConOut, ' ',
5813 cb->Info.dwSize.X, coord, &dwDummy);
5814 /*
5815 * The following is just for aesthetics. If we are exiting without
5816 * restoring the screen, then we want to have a prompt string
5817 * appear at the bottom line. However, the command interpreter
5818 * seems to always advance the cursor one line before displaying
5819 * the prompt string, which causes the screen to scroll. To
5820 * counter this, move the cursor up one line before exiting.
5821 */
5822 if (exiting && !p_rs)
5823 coord.Y--;
5824 /*
5825 * Position the cursor at the leftmost column of the desired row.
5826 */
5827 SetConsoleCursorPosition(g_hConOut, coord);
5828 }
5829
5830 g_fTermcapMode = FALSE;
5831}
5832#endif /* FEAT_GUI_W32 */
5833
5834
5835#ifdef FEAT_GUI_W32
5836 void
5837mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005838 char_u *s UNUSED,
5839 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840{
5841 /* never used */
5842}
5843
5844#else
5845
5846/*
5847 * clear `n' chars, starting from `coord'
5848 */
5849 static void
5850clear_chars(
5851 COORD coord,
5852 DWORD n)
5853{
5854 DWORD dwDummy;
5855
5856 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005857
5858 if (!USE_VTP)
5859 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5860 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005861 {
5862 set_console_color_rgb();
5863 gotoxy(coord.X + 1, coord.Y + 1);
5864 vtp_printf("\033[%dX", n);
5865 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005866}
5867
5868
5869/*
5870 * Clear the screen
5871 */
5872 static void
5873clear_screen(void)
5874{
5875 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005876
5877 if (!USE_VTP)
5878 clear_chars(g_coord, Rows * Columns);
5879 else
5880 {
5881 set_console_color_rgb();
5882 gotoxy(1, 1);
5883 vtp_printf("\033[2J");
5884 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005885}
5886
5887
5888/*
5889 * Clear to end of display
5890 */
5891 static void
5892clear_to_end_of_display(void)
5893{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005894 COORD save = g_coord;
5895
5896 if (!USE_VTP)
5897 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005899 else
5900 {
5901 set_console_color_rgb();
5902 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5903 vtp_printf("\033[0J");
5904
5905 gotoxy(save.X + 1, save.Y + 1);
5906 g_coord = save;
5907 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908}
5909
5910
5911/*
5912 * Clear to end of line
5913 */
5914 static void
5915clear_to_end_of_line(void)
5916{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005917 COORD save = g_coord;
5918
5919 if (!USE_VTP)
5920 clear_chars(g_coord, Columns - g_coord.X);
5921 else
5922 {
5923 set_console_color_rgb();
5924 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5925 vtp_printf("\033[0K");
5926
5927 gotoxy(save.X + 1, save.Y + 1);
5928 g_coord = save;
5929 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930}
5931
5932
5933/*
5934 * Scroll the scroll region up by `cLines' lines
5935 */
5936 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005937scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005938{
5939 COORD oldcoord = g_coord;
5940
5941 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5942 delete_lines(cLines);
5943
5944 g_coord = oldcoord;
5945}
5946
5947
5948/*
5949 * Set the scroll region
5950 */
5951 static void
5952set_scroll_region(
5953 unsigned left,
5954 unsigned top,
5955 unsigned right,
5956 unsigned bottom)
5957{
5958 if (left >= right
5959 || top >= bottom
5960 || right > (unsigned) Columns - 1
5961 || bottom > (unsigned) Rows - 1)
5962 return;
5963
5964 g_srScrollRegion.Left = left;
5965 g_srScrollRegion.Top = top;
5966 g_srScrollRegion.Right = right;
5967 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005968
5969 if (USE_VTP)
5970 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971}
5972
5973
5974/*
5975 * Insert `cLines' lines at the current cursor position
5976 */
5977 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005978insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005979{
5980 SMALL_RECT source;
5981 COORD dest;
5982 CHAR_INFO fill;
5983
5984 dest.X = 0;
5985 dest.Y = g_coord.Y + cLines;
5986
5987 source.Left = 0;
5988 source.Top = g_coord.Y;
5989 source.Right = g_srScrollRegion.Right;
5990 source.Bottom = g_srScrollRegion.Bottom - cLines;
5991
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005992 if (!USE_VTP)
5993 {
5994 fill.Char.AsciiChar = ' ';
5995 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005996
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005997 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5998 }
5999 else
6000 {
6001 set_console_color_rgb();
6002
6003 gotoxy(1, source.Top + 1);
6004 vtp_printf("\033[%dT", cLines);
6005 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006
6007 /* Here we have to deal with a win32 console flake: If the scroll
6008 * region looks like abc and we scroll c to a and fill with d we get
6009 * cbd... if we scroll block c one line at a time to a, we get cdd...
6010 * vim expects cdd consistently... So we have to deal with that
6011 * here... (this also occurs scrolling the same way in the other
6012 * direction). */
6013
6014 if (source.Bottom < dest.Y)
6015 {
6016 COORD coord;
6017
6018 coord.X = 0;
6019 coord.Y = source.Bottom;
6020 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6021 }
6022}
6023
6024
6025/*
6026 * Delete `cLines' lines at the current cursor position
6027 */
6028 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006029delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030{
6031 SMALL_RECT source;
6032 COORD dest;
6033 CHAR_INFO fill;
6034 int nb;
6035
6036 dest.X = 0;
6037 dest.Y = g_coord.Y;
6038
6039 source.Left = 0;
6040 source.Top = g_coord.Y + cLines;
6041 source.Right = g_srScrollRegion.Right;
6042 source.Bottom = g_srScrollRegion.Bottom;
6043
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006044 if (!USE_VTP)
6045 {
6046 fill.Char.AsciiChar = ' ';
6047 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006049 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6050 }
6051 else
6052 {
6053 set_console_color_rgb();
6054
6055 gotoxy(1, source.Top + 1);
6056 vtp_printf("\033[%dS", cLines);
6057 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058
6059 /* Here we have to deal with a win32 console flake: If the scroll
6060 * region looks like abc and we scroll c to a and fill with d we get
6061 * cbd... if we scroll block c one line at a time to a, we get cdd...
6062 * vim expects cdd consistently... So we have to deal with that
6063 * here... (this also occurs scrolling the same way in the other
6064 * direction). */
6065
6066 nb = dest.Y + (source.Bottom - source.Top) + 1;
6067
6068 if (nb < source.Top)
6069 {
6070 COORD coord;
6071
6072 coord.X = 0;
6073 coord.Y = nb;
6074 clear_chars(coord, Columns * (source.Top - nb));
6075 }
6076}
6077
6078
6079/*
6080 * Set the cursor position
6081 */
6082 static void
6083gotoxy(
6084 unsigned x,
6085 unsigned y)
6086{
6087 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6088 return;
6089
6090 /* external cursor coords are 1-based; internal are 0-based */
6091 g_coord.X = x - 1;
6092 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006093
6094 if (!USE_VTP)
6095 SetConsoleCursorPosition(g_hConOut, g_coord);
6096 else
6097 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098}
6099
6100
6101/*
6102 * Set the current text attribute = (foreground | background)
6103 * See ../doc/os_win32.txt for the numbers.
6104 */
6105 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006106textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006108 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109
6110 SetConsoleTextAttribute(g_hConOut, wAttr);
6111}
6112
6113
6114 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006115textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006117 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006119 if (!USE_VTP)
6120 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6121 else
6122 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123}
6124
6125
6126 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006127textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006129 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006131 if (!USE_VTP)
6132 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6133 else
6134 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006135}
6136
6137
6138/*
6139 * restore the default text attribute (whatever we started with)
6140 */
6141 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006142normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006144 if (!USE_VTP)
6145 textattr(g_attrDefault);
6146 else
6147 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148}
6149
6150
6151static WORD g_attrPreStandout = 0;
6152
6153/*
6154 * Make the text standout, by brightening it
6155 */
6156 static void
6157standout(void)
6158{
6159 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006160
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6162}
6163
6164
6165/*
6166 * Turn off standout mode
6167 */
6168 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006169standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170{
6171 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006173
6174 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175}
6176
6177
6178/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006179 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180 */
6181 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006182mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183{
6184 char_u *p;
6185 int n;
6186
6187 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6188 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006189 if (
6190#ifdef FEAT_TERMGUICOLORS
6191 !p_tgc &&
6192#endif
6193 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006194 {
6195 p = T_ME + 2;
6196 n = getdigits(&p);
6197 if (*p == 'm' && n > 0)
6198 {
6199 cterm_normal_fg_color = (n & 0xf) + 1;
6200 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6201 }
6202 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006203#ifdef FEAT_TERMGUICOLORS
6204 cterm_normal_fg_gui_color = INVALCOLOR;
6205 cterm_normal_bg_gui_color = INVALCOLOR;
6206#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006207}
6208
6209
6210/*
6211 * visual bell: flash the screen
6212 */
6213 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006214visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215{
6216 COORD coordOrigin = {0, 0};
6217 WORD attrFlash = ~g_attrCurrent & 0xff;
6218
6219 DWORD dwDummy;
6220 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6221
6222 if (oldattrs == NULL)
6223 return;
6224 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6225 coordOrigin, &dwDummy);
6226 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6227 coordOrigin, &dwDummy);
6228
6229 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006230 if (!USE_VTP)
6231 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232 coordOrigin, &dwDummy);
6233 vim_free(oldattrs);
6234}
6235
6236
6237/*
6238 * Make the cursor visible or invisible
6239 */
6240 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006241cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242{
6243 s_cursor_visible = fVisible;
6244#ifdef MCH_CURSOR_SHAPE
6245 mch_update_cursor();
6246#endif
6247}
6248
6249
6250/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006251 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006252 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006254 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006256 char_u *pchBuf,
6257 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006258{
6259 COORD coord = g_coord;
6260 DWORD written;
6261
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006262 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6263 {
6264 static WCHAR *unicodebuf = NULL;
6265 static int unibuflen = 0;
6266 int length;
6267 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006269 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6270 if (unicodebuf == NULL || length > unibuflen)
6271 {
6272 vim_free(unicodebuf);
6273 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6274 unibuflen = length;
6275 }
6276 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6277 unicodebuf, unibuflen);
6278
6279 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006280
6281 if (!USE_VTP)
6282 {
6283 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6284 coord, &written);
6285 /* When writing fails or didn't write a single character, pretend one
6286 * character was written, otherwise we get stuck. */
6287 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6288 coord, &cchwritten) == 0
6289 || cchwritten == 0)
6290 cchwritten = 1;
6291 }
6292 else
6293 {
6294 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6295 NULL) == 0 || cchwritten == 0)
6296 cchwritten = 1;
6297 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006298
6299 if (cchwritten == length)
6300 {
6301 written = cbToWrite;
6302 g_coord.X += (SHORT)cells;
6303 }
6304 else
6305 {
6306 char_u *p = pchBuf;
6307 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006308 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006309 written = p - pchBuf;
6310 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6311 }
6312 }
6313 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006314 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006315 if (!USE_VTP)
6316 {
6317 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6318 coord, &written);
6319 /* When writing fails or didn't write a single character, pretend one
6320 * character was written, otherwise we get stuck. */
6321 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6322 coord, &written) == 0
6323 || written == 0)
6324 written = 1;
6325 }
6326 else
6327 {
6328 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6329 NULL) == 0 || written == 0)
6330 written = 1;
6331 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006332
6333 g_coord.X += (SHORT) written;
6334 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335
6336 while (g_coord.X > g_srScrollRegion.Right)
6337 {
6338 g_coord.X -= (SHORT) Columns;
6339 if (g_coord.Y < g_srScrollRegion.Bottom)
6340 g_coord.Y++;
6341 }
6342
6343 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6344
6345 return written;
6346}
6347
6348
6349/*
6350 * mch_write(): write the output buffer to the screen, translating ESC
6351 * sequences into calls to console output routines.
6352 */
6353 void
6354mch_write(
6355 char_u *s,
6356 int len)
6357{
6358 s[len] = NUL;
6359
6360 if (!term_console)
6361 {
6362 write(1, s, (unsigned)len);
6363 return;
6364 }
6365
6366 /* translate ESC | sequences into faked bios calls */
6367 while (len--)
6368 {
6369 /* optimization: use one single write_chars for runs of text,
6370 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006371 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372
6373 if (p_wd)
6374 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006375 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 if (prefix != 0)
6377 prefix = 1;
6378 }
6379
6380 if (prefix != 0)
6381 {
6382 DWORD nWritten;
6383
6384 nWritten = write_chars(s, prefix);
6385#ifdef MCH_WRITE_DUMP
6386 if (fdDump)
6387 {
6388 fputc('>', fdDump);
6389 fwrite(s, sizeof(char_u), nWritten, fdDump);
6390 fputs("<\n", fdDump);
6391 }
6392#endif
6393 len -= (nWritten - 1);
6394 s += nWritten;
6395 }
6396 else if (s[0] == '\n')
6397 {
6398 /* \n, newline: go to the beginning of the next line or scroll */
6399 if (g_coord.Y == g_srScrollRegion.Bottom)
6400 {
6401 scroll(1);
6402 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6403 }
6404 else
6405 {
6406 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6407 }
6408#ifdef MCH_WRITE_DUMP
6409 if (fdDump)
6410 fputs("\\n\n", fdDump);
6411#endif
6412 s++;
6413 }
6414 else if (s[0] == '\r')
6415 {
6416 /* \r, carriage return: go to beginning of line */
6417 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6418#ifdef MCH_WRITE_DUMP
6419 if (fdDump)
6420 fputs("\\r\n", fdDump);
6421#endif
6422 s++;
6423 }
6424 else if (s[0] == '\b')
6425 {
6426 /* \b, backspace: move cursor one position left */
6427 if (g_coord.X > g_srScrollRegion.Left)
6428 g_coord.X--;
6429 else if (g_coord.Y > g_srScrollRegion.Top)
6430 {
6431 g_coord.X = g_srScrollRegion.Right;
6432 g_coord.Y--;
6433 }
6434 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6435#ifdef MCH_WRITE_DUMP
6436 if (fdDump)
6437 fputs("\\b\n", fdDump);
6438#endif
6439 s++;
6440 }
6441 else if (s[0] == '\a')
6442 {
6443 /* \a, bell */
6444 MessageBeep(0xFFFFFFFF);
6445#ifdef MCH_WRITE_DUMP
6446 if (fdDump)
6447 fputs("\\a\n", fdDump);
6448#endif
6449 s++;
6450 }
6451 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6452 {
6453#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006454 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006456 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006457 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458
6459 switch (s[2])
6460 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006461 case '0': case '1': case '2': case '3': case '4':
6462 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006463 p = s + 1;
6464 do
6465 {
6466 ++p;
6467 args[argc] = getdigits(&p);
6468 argc += (argc < 15) ? 1 : 0;
6469 if (p > s + len)
6470 break;
6471 } while (*p == ';');
6472
Bram Moolenaar071d4272004-06-13 20:20:40 +00006473 if (p > s + len)
6474 break;
6475
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006476 arg1 = args[0];
6477 arg2 = args[1];
6478 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006480 if (argc == 1 && args[0] == 0)
6481 normvideo();
6482 else if (argc == 1)
6483 {
6484 if (USE_VTP)
6485 textcolor((WORD) arg1);
6486 else
6487 textattr((WORD) arg1);
6488 }
6489 else if (USE_VTP)
6490 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006492 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006494 gotoxy(arg2, arg1);
6495 }
6496 else if (argc == 2 && *p == 'r')
6497 {
6498 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6499 }
6500 else if (argc == 1 && *p == 'A')
6501 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502 gotoxy(g_coord.X + 1,
6503 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6504 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006505 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506 {
6507 textbackground((WORD) arg1);
6508 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006509 else if (argc == 1 && *p == 'C')
6510 {
6511 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6512 g_coord.Y + 1);
6513 }
6514 else if (argc == 1 && *p == 'f')
6515 {
6516 textcolor((WORD) arg1);
6517 }
6518 else if (argc == 1 && *p == 'H')
6519 {
6520 gotoxy(1, arg1);
6521 }
6522 else if (argc == 1 && *p == 'L')
6523 {
6524 insert_lines(arg1);
6525 }
6526 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527 {
6528 delete_lines(arg1);
6529 }
6530
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006531 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 s = p + 1;
6533 break;
6534
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536 gotoxy(g_coord.X + 1,
6537 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6538 goto got3;
6539
6540 case 'B':
6541 visual_bell();
6542 goto got3;
6543
6544 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6546 g_coord.Y + 1);
6547 goto got3;
6548
6549 case 'E':
6550 termcap_mode_end();
6551 goto got3;
6552
6553 case 'F':
6554 standout();
6555 goto got3;
6556
6557 case 'f':
6558 standend();
6559 goto got3;
6560
6561 case 'H':
6562 gotoxy(1, 1);
6563 goto got3;
6564
6565 case 'j':
6566 clear_to_end_of_display();
6567 goto got3;
6568
6569 case 'J':
6570 clear_screen();
6571 goto got3;
6572
6573 case 'K':
6574 clear_to_end_of_line();
6575 goto got3;
6576
6577 case 'L':
6578 insert_lines(1);
6579 goto got3;
6580
6581 case 'M':
6582 delete_lines(1);
6583 goto got3;
6584
6585 case 'S':
6586 termcap_mode_start();
6587 goto got3;
6588
6589 case 'V':
6590 cursor_visible(TRUE);
6591 goto got3;
6592
6593 case 'v':
6594 cursor_visible(FALSE);
6595 goto got3;
6596
6597 got3:
6598 s += 3;
6599 len -= 2;
6600 }
6601
6602#ifdef MCH_WRITE_DUMP
6603 if (fdDump)
6604 {
6605 fputs("ESC | ", fdDump);
6606 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6607 fputc('\n', fdDump);
6608 }
6609#endif
6610 }
6611 else
6612 {
6613 /* Write a single character */
6614 DWORD nWritten;
6615
6616 nWritten = write_chars(s, 1);
6617#ifdef MCH_WRITE_DUMP
6618 if (fdDump)
6619 {
6620 fputc('>', fdDump);
6621 fwrite(s, sizeof(char_u), nWritten, fdDump);
6622 fputs("<\n", fdDump);
6623 }
6624#endif
6625
6626 len -= (nWritten - 1);
6627 s += nWritten;
6628 }
6629 }
6630
6631#ifdef MCH_WRITE_DUMP
6632 if (fdDump)
6633 fflush(fdDump);
6634#endif
6635}
6636
6637#endif /* FEAT_GUI_W32 */
6638
6639
6640/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006641 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 */
6643 void
6644mch_delay(
6645 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006646 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647{
6648#ifdef FEAT_GUI_W32
6649 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006650#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006652# ifdef FEAT_MZSCHEME
6653 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6654 {
6655 int towait = p_mzq;
6656
6657 /* if msec is large enough, wait by portions in p_mzq */
6658 while (msec > 0)
6659 {
6660 mzvim_check_threads();
6661 if (msec < towait)
6662 towait = msec;
6663 Sleep(towait);
6664 msec -= towait;
6665 }
6666 }
6667 else
6668# endif
6669 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006671 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672#endif
6673}
6674
6675
6676/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006677 * This version of remove is not scared by a readonly (backup) file.
6678 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 * Return 0 for success, -1 for failure.
6680 */
6681 int
6682mch_remove(char_u *name)
6683{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684 WCHAR *wn = NULL;
6685 int n;
6686
Bram Moolenaar203258c2016-01-17 22:15:16 +01006687 /*
6688 * On Windows, deleting a directory's symbolic link is done by
6689 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6690 */
6691 if (mch_isdir(name) && mch_is_symbolic_link(name))
6692 return mch_rmdir(name);
6693
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006694 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6695
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6697 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006698 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699 if (wn != NULL)
6700 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701 n = DeleteFileW(wn) ? 0 : -1;
6702 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006703 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 }
6705 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006706 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707}
6708
6709
6710/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006711 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 */
6713 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006714mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715{
6716#ifndef FEAT_GUI_W32 /* never used */
6717 if (g_fCtrlCPressed || g_fCBrkPressed)
6718 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006719 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6721 got_int = TRUE;
6722 }
6723#endif
6724}
6725
Bram Moolenaaree273972016-01-02 21:11:51 +01006726/* physical RAM to leave for the OS */
6727#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006728
6729/*
6730 * How much main memory in KiB that can be used by VIM.
6731 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006732 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006733mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006734{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006735 MEMORYSTATUSEX ms;
6736
Bram Moolenaaree273972016-01-02 21:11:51 +01006737 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006738 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6739 * what fits in 32 bits. But it's not always available. */
6740 ms.dwLength = sizeof(MEMORYSTATUSEX);
6741 GlobalMemoryStatusEx(&ms);
6742 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006743 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006744 /* Process address space fits in physical RAM, use all of it. */
6745 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006746 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006747 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006748 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006749 /* Catch old NT box or perverse hardware setup. */
6750 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006751 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006752 /* Use physical RAM less reserve for OS + data. */
6753 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006754}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756/*
6757 * Same code as below, but with wide functions and no comments.
6758 * Return 0 for success, non-zero for failure.
6759 */
6760 int
6761mch_wrename(WCHAR *wold, WCHAR *wnew)
6762{
6763 WCHAR *p;
6764 int i;
6765 WCHAR szTempFile[_MAX_PATH + 1];
6766 WCHAR szNewPath[_MAX_PATH + 1];
6767 HANDLE hf;
6768
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006769 p = wold;
6770 for (i = 0; wold[i] != NUL; ++i)
6771 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6772 && wold[i + 1] != 0)
6773 p = wold + i + 1;
6774 if ((int)(wold + i - p) < 8 || p[6] != '~')
6775 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776
6777 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6778 return -1;
6779 *p = NUL;
6780
6781 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6782 return -2;
6783
6784 if (!DeleteFileW(szTempFile))
6785 return -3;
6786
6787 if (!MoveFileW(wold, szTempFile))
6788 return -4;
6789
6790 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6791 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6792 return -5;
6793 if (!CloseHandle(hf))
6794 return -6;
6795
6796 if (!MoveFileW(szTempFile, wnew))
6797 {
6798 (void)MoveFileW(szTempFile, wold);
6799 return -7;
6800 }
6801
6802 DeleteFileW(szTempFile);
6803
6804 if (!DeleteFileW(wold))
6805 return -8;
6806
6807 return 0;
6808}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809
6810
6811/*
6812 * mch_rename() works around a bug in rename (aka MoveFile) in
6813 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6814 * file whose short file name is "FOO.BAR" (its long file name will
6815 * be correct: "foo.bar~"). Because a file can be accessed by
6816 * either its SFN or its LFN, "foo.bar" has effectively been
6817 * renamed to "foo.bar", which is not at all what was wanted. This
6818 * seems to happen only when renaming files with three-character
6819 * extensions by appending a suffix that does not include ".".
6820 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6821 *
6822 * There is another problem, which isn't really a bug but isn't right either:
6823 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6824 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6825 * service pack 6. Doesn't seem to happen on Windows 98.
6826 *
6827 * Like rename(), returns 0 upon success, non-zero upon failure.
6828 * Should probably set errno appropriately when errors occur.
6829 */
6830 int
6831mch_rename(
6832 const char *pszOldFile,
6833 const char *pszNewFile)
6834{
6835 char szTempFile[_MAX_PATH+1];
6836 char szNewPath[_MAX_PATH+1];
6837 char *pszFilePart;
6838 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006839 WCHAR *wold = NULL;
6840 WCHAR *wnew = NULL;
6841 int retval = -1;
6842
6843 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6844 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006845 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6846 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847 if (wold != NULL && wnew != NULL)
6848 retval = mch_wrename(wold, wnew);
6849 vim_free(wold);
6850 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006851 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853
6854 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006855 * No need to play tricks unless the file name contains a "~" as the
6856 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006857 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006858 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6859 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6860 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006861
6862 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6863 * a directory, no error is returned and pszFilePart will be NULL. */
6864 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6865 || pszFilePart == NULL)
6866 return -1;
6867 *pszFilePart = NUL;
6868
6869 /* Get (and create) a unique temporary file name in directory of new file */
6870 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6871 return -2;
6872
6873 /* blow the temp file away */
6874 if (!DeleteFile(szTempFile))
6875 return -3;
6876
6877 /* rename old file to the temp file */
6878 if (!MoveFile(pszOldFile, szTempFile))
6879 return -4;
6880
6881 /* now create an empty file called pszOldFile; this prevents the operating
6882 * system using pszOldFile as an alias (SFN) if we're renaming within the
6883 * same directory. For example, we're editing a file called
6884 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6885 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6886 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006887 * cause all sorts of problems later in buf_write(). So, we create an
6888 * empty file called filena~1.txt and the system will have to find some
6889 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006890 */
6891 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6892 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6893 return -5;
6894 if (!CloseHandle(hf))
6895 return -6;
6896
6897 /* rename the temp file to the new file */
6898 if (!MoveFile(szTempFile, pszNewFile))
6899 {
6900 /* Renaming failed. Rename the file back to its old name, so that it
6901 * looks like nothing happened. */
6902 (void)MoveFile(szTempFile, pszOldFile);
6903
6904 return -7;
6905 }
6906
6907 /* Seems to be left around on Novell filesystems */
6908 DeleteFile(szTempFile);
6909
6910 /* finally, remove the empty old file */
6911 if (!DeleteFile(pszOldFile))
6912 return -8;
6913
6914 return 0; /* success */
6915}
6916
6917/*
6918 * Get the default shell for the current hardware platform
6919 */
6920 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006921default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 PlatformId();
6924
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006925 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926}
6927
6928/*
6929 * mch_access() extends access() to do more detailed check on network drives.
6930 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6931 */
6932 int
6933mch_access(char *n, int p)
6934{
6935 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936 int retval = -1; /* default: fail */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937 WCHAR *wn = NULL;
6938
6939 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006940 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006942 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943 {
6944 char TempName[_MAX_PATH + 16] = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946
6947 if (p & R_OK)
6948 {
6949 /* Read check is performed by seeing if we can do a find file on
6950 * the directory for any file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951 if (wn != NULL)
6952 {
6953 int i;
6954 WIN32_FIND_DATAW d;
6955
6956 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6957 TempNameW[i] = wn[i];
6958 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6959 TempNameW[i++] = '\\';
6960 TempNameW[i++] = '*';
6961 TempNameW[i++] = 0;
6962
6963 hFile = FindFirstFileW(TempNameW, &d);
6964 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006965 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966 else
6967 (void)FindClose(hFile);
6968 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006969 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970 {
6971 char *pch;
6972 WIN32_FIND_DATA d;
6973
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006974 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975 pch = TempName + STRLEN(TempName) - 1;
6976 if (*pch != '\\' && *pch != '/')
6977 *++pch = '\\';
6978 *++pch = '*';
6979 *++pch = NUL;
6980
6981 hFile = FindFirstFile(TempName, &d);
6982 if (hFile == INVALID_HANDLE_VALUE)
6983 goto getout;
6984 (void)FindClose(hFile);
6985 }
6986 }
6987
6988 if (p & W_OK)
6989 {
6990 /* Trying to create a temporary file in the directory should catch
6991 * directories on read-only network shares. However, in
6992 * directories whose ACL allows writes but denies deletes will end
6993 * up keeping the temporary file :-(. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 if (wn != NULL)
6995 {
6996 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006997 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998 else
6999 DeleteFileW(TempNameW);
7000 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007001 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 {
7003 if (!GetTempFileName(n, "VIM", 0, TempName))
7004 goto getout;
7005 mch_remove((char_u *)TempName);
7006 }
7007 }
7008 }
7009 else
7010 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007011 // Don't consider a file read-only if another process has opened it.
7012 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7013
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014 /* Trying to open the file for the required access does ACL, read-only
7015 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007016 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7017 | ((p & R_OK) ? GENERIC_READ : 0);
7018
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007020 hFile = CreateFileW(wn, access_mode, share_mode,
7021 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007022 else
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007023 hFile = CreateFile(n, access_mode, share_mode,
7024 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025 if (hFile == INVALID_HANDLE_VALUE)
7026 goto getout;
7027 CloseHandle(hFile);
7028 }
7029
7030 retval = 0; /* success */
7031getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033 return retval;
7034}
7035
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007037 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038 */
7039 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007040mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007042 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
Bram Moolenaara12a1612019-01-24 16:39:02 +01007043#ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044 WCHAR *wn;
7045 int f;
7046
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007047 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007048 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007049 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007050 if (wn != NULL)
7051 {
7052 f = _wopen(wn, flags, mode);
7053 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007054 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055 }
7056 }
Bram Moolenaara12a1612019-01-24 16:39:02 +01007057#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007059 /* open() can open a file which name is longer than _MAX_PATH bytes
7060 * and shorter than _MAX_PATH characters successfully, but sometimes it
7061 * causes unexpected error in another part. We make it an error explicitly
7062 * here. */
7063 if (strlen(name) >= _MAX_PATH)
7064 return -1;
7065
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066 return open(name, flags, mode);
7067}
7068
7069/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007070 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 */
7072 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007073mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074{
7075 WCHAR *wn, *wm;
7076 FILE *f = NULL;
7077
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007078 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01007080#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007081 /* Work around an annoying assertion in the Microsoft debug CRT
7082 * when mode's text/binary setting doesn't match _get_fmode(). */
7083 char newMode = mode[strlen(mode) - 1];
7084 int oldMode = 0;
7085
7086 _get_fmode(&oldMode);
7087 if (newMode == 't')
7088 _set_fmode(_O_TEXT);
7089 else if (newMode == 'b')
7090 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007091#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007092 wn = enc_to_utf16((char_u *)name, NULL);
7093 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 if (wn != NULL && wm != NULL)
7095 f = _wfopen(wn, wm);
7096 vim_free(wn);
7097 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007098
Bram Moolenaara12a1612019-01-24 16:39:02 +01007099#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007100 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007101#endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007102 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103 }
7104
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007105 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7106 * and shorter than _MAX_PATH characters successfully, but sometimes it
7107 * causes unexpected error in another part. We make it an error explicitly
7108 * here. */
7109 if (strlen(name) >= _MAX_PATH)
7110 return NULL;
7111
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 return fopen(name, mode);
7113}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114
Bram Moolenaar071d4272004-06-13 20:20:40 +00007115/*
7116 * SUB STREAM (aka info stream) handling:
7117 *
7118 * NTFS can have sub streams for each file. Normal contents of file is
7119 * stored in the main stream, and extra contents (author information and
7120 * title and so on) can be stored in sub stream. After Windows 2000, user
7121 * can access and store those informations in sub streams via explorer's
7122 * property menuitem in right click menu. Those informations in sub streams
7123 * were lost when copying only the main stream. So we have to copy sub
7124 * streams.
7125 *
7126 * Incomplete explanation:
7127 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7128 * More useful info and an example:
7129 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7130 */
7131
7132/*
7133 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7134 * and write to stream "substream" of file "to".
7135 * Errors are ignored.
7136 */
7137 static void
7138copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7139{
7140 HANDLE hTo;
7141 WCHAR *to_name;
7142
7143 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7144 wcscpy(to_name, to);
7145 wcscat(to_name, substream);
7146
7147 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7148 FILE_ATTRIBUTE_NORMAL, NULL);
7149 if (hTo != INVALID_HANDLE_VALUE)
7150 {
7151 long done;
7152 DWORD todo;
7153 DWORD readcnt, written;
7154 char buf[4096];
7155
7156 /* Copy block of bytes at a time. Abort when something goes wrong. */
7157 for (done = 0; done < len; done += written)
7158 {
7159 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007160 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7161 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007162 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7163 FALSE, FALSE, context)
7164 || readcnt != todo
7165 || !WriteFile(hTo, buf, todo, &written, NULL)
7166 || written != todo)
7167 break;
7168 }
7169 CloseHandle(hTo);
7170 }
7171
7172 free(to_name);
7173}
7174
7175/*
7176 * Copy info streams from file "from" to file "to".
7177 */
7178 static void
7179copy_infostreams(char_u *from, char_u *to)
7180{
7181 WCHAR *fromw;
7182 WCHAR *tow;
7183 HANDLE sh;
7184 WIN32_STREAM_ID sid;
7185 int headersize;
7186 WCHAR streamname[_MAX_PATH];
7187 DWORD readcount;
7188 void *context = NULL;
7189 DWORD lo, hi;
7190 int len;
7191
7192 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007193 fromw = enc_to_utf16(from, NULL);
7194 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007195 if (fromw != NULL && tow != NULL)
7196 {
7197 /* Open the file for reading. */
7198 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7199 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7200 if (sh != INVALID_HANDLE_VALUE)
7201 {
7202 /* Use BackupRead() to find the info streams. Repeat until we
7203 * have done them all.*/
7204 for (;;)
7205 {
7206 /* Get the header to find the length of the stream name. If
7207 * the "readcount" is zero we have done all info streams. */
7208 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007209 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007210 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7211 &readcount, FALSE, FALSE, &context)
7212 || readcount == 0)
7213 break;
7214
7215 /* We only deal with streams that have a name. The normal
7216 * file data appears to be without a name, even though docs
7217 * suggest it is called "::$DATA". */
7218 if (sid.dwStreamNameSize > 0)
7219 {
7220 /* Read the stream name. */
7221 if (!BackupRead(sh, (LPBYTE)streamname,
7222 sid.dwStreamNameSize,
7223 &readcount, FALSE, FALSE, &context))
7224 break;
7225
7226 /* Copy an info stream with a name ":anything:$DATA".
7227 * Skip "::$DATA", it has no stream name (examples suggest
7228 * it might be used for the normal file contents).
7229 * Note that BackupRead() counts bytes, but the name is in
7230 * wide characters. */
7231 len = readcount / sizeof(WCHAR);
7232 streamname[len] = 0;
7233 if (len > 7 && wcsicmp(streamname + len - 6,
7234 L":$DATA") == 0)
7235 {
7236 streamname[len - 6] = 0;
7237 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007238 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239 }
7240 }
7241
7242 /* Advance to the next stream. We might try seeking too far,
7243 * but BackupSeek() doesn't skip over stream borders, thus
7244 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007245 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246 &lo, &hi, &context);
7247 }
7248
7249 /* Clear the context. */
7250 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7251
7252 CloseHandle(sh);
7253 }
7254 }
7255 vim_free(fromw);
7256 vim_free(tow);
7257}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007258
7259/*
7260 * Copy file attributes from file "from" to file "to".
7261 * For Windows NT and later we copy info streams.
7262 * Always returns zero, errors are ignored.
7263 */
7264 int
7265mch_copy_file_attribute(char_u *from, char_u *to)
7266{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007267 /* File streams only work on Windows NT and later. */
7268 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007269 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270 return 0;
7271}
7272
7273#if defined(MYRESETSTKOFLW) || defined(PROTO)
7274/*
7275 * Recreate a destroyed stack guard page in win32.
7276 * Written by Benjamin Peterson.
7277 */
7278
7279/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007280# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007281
7282/*
7283 * This function does the same thing as _resetstkoflw(), which is only
7284 * available in DevStudio .net and later.
7285 * Returns 0 for failure, 1 for success.
7286 */
7287 int
7288myresetstkoflw(void)
7289{
7290 BYTE *pStackPtr;
7291 BYTE *pGuardPage;
7292 BYTE *pStackBase;
7293 BYTE *pLowestPossiblePage;
7294 MEMORY_BASIC_INFORMATION mbi;
7295 SYSTEM_INFO si;
7296 DWORD nPageSize;
7297 DWORD dummy;
7298
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300
7301 /* We need to know the system page size. */
7302 GetSystemInfo(&si);
7303 nPageSize = si.dwPageSize;
7304
7305 /* ...and the current stack pointer */
7306 pStackPtr = (BYTE*)_alloca(1);
7307
7308 /* ...and the base of the stack. */
7309 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7310 return 0;
7311 pStackBase = (BYTE*)mbi.AllocationBase;
7312
7313 /* ...and the page thats min_stack_req pages away from stack base; this is
7314 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007315 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316
Bram Moolenaar071d4272004-06-13 20:20:40 +00007317 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007318 /* We want the first committed page in the stack Start at the stack
7319 * base and move forward through memory until we find a committed block.
7320 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007321 BYTE *pBlock = pStackBase;
7322
Bram Moolenaara466c992005-07-09 21:03:22 +00007323 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324 {
7325 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7326 return 0;
7327
7328 pBlock += mbi.RegionSize;
7329
7330 if (mbi.State & MEM_COMMIT)
7331 break;
7332 }
7333
7334 /* mbi now describes the first committed block in the stack. */
7335 if (mbi.Protect & PAGE_GUARD)
7336 return 1;
7337
7338 /* decide where the guard page should start */
7339 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7340 pGuardPage = pLowestPossiblePage;
7341 else
7342 pGuardPage = (BYTE*)mbi.BaseAddress;
7343
7344 /* allocate the guard page */
7345 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7346 return 0;
7347
7348 /* apply the guard attribute to the page */
7349 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7350 &dummy))
7351 return 0;
7352 }
7353
7354 return 1;
7355}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007356#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007357
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007358
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007359/*
7360 * The command line arguments in UCS2
7361 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007362static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007363static LPWSTR *ArglistW = NULL;
7364static int global_argc = 0;
7365static char **global_argv;
7366
7367static int used_file_argc = 0; /* last argument in global_argv[] used
7368 for the argument list. */
7369static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7370 command line arguments added to
7371 the argument list */
7372static int used_file_count = 0; /* nr of entries in used_file_indexes */
7373static int used_file_literal = FALSE; /* take file names literally */
7374static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007375static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007376static int used_alist_count = 0;
7377
7378
7379/*
7380 * Get the command line arguments. Unicode version.
7381 * Returns argc. Zero when something fails.
7382 */
7383 int
7384get_cmd_argsW(char ***argvp)
7385{
7386 char **argv = NULL;
7387 int argc = 0;
7388 int i;
7389
Bram Moolenaar14993322014-09-09 12:25:33 +02007390 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007391 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7392 if (ArglistW != NULL)
7393 {
7394 argv = malloc((nArgsW + 1) * sizeof(char *));
7395 if (argv != NULL)
7396 {
7397 argc = nArgsW;
7398 argv[argc] = NULL;
7399 for (i = 0; i < argc; ++i)
7400 {
7401 int len;
7402
7403 /* Convert each Unicode argument to the current codepage. */
7404 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007405 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007406 (LPSTR *)&argv[i], &len, 0, 0);
7407 if (argv[i] == NULL)
7408 {
7409 /* Out of memory, clear everything. */
7410 while (i > 0)
7411 free(argv[--i]);
7412 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007413 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007414 argc = 0;
7415 }
7416 }
7417 }
7418 }
7419
7420 global_argc = argc;
7421 global_argv = argv;
7422 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007423 {
7424 if (used_file_indexes != NULL)
7425 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007426 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007427 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007428
7429 if (argvp != NULL)
7430 *argvp = argv;
7431 return argc;
7432}
7433
7434 void
7435free_cmd_argsW(void)
7436{
7437 if (ArglistW != NULL)
7438 {
7439 GlobalFree(ArglistW);
7440 ArglistW = NULL;
7441 }
7442}
7443
7444/*
7445 * Remember "name" is an argument that was added to the argument list.
7446 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7447 * is called.
7448 */
7449 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007450used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007451{
7452 int i;
7453
7454 if (used_file_indexes == NULL)
7455 return;
7456 for (i = used_file_argc + 1; i < global_argc; ++i)
7457 if (STRCMP(global_argv[i], name) == 0)
7458 {
7459 used_file_argc = i;
7460 used_file_indexes[used_file_count++] = i;
7461 break;
7462 }
7463 used_file_literal = literal;
7464 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007465 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007466}
7467
7468/*
7469 * Remember the length of the argument list as it was. If it changes then we
7470 * leave it alone when 'encoding' is set.
7471 */
7472 void
7473set_alist_count(void)
7474{
7475 used_alist_count = GARGCOUNT;
7476}
7477
7478/*
7479 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7480 * has been changed while starting up. Use the UCS-2 command line arguments
7481 * and convert them to 'encoding'.
7482 */
7483 void
7484fix_arg_enc(void)
7485{
7486 int i;
7487 int idx;
7488 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007489 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007490
7491 /* Safety checks:
7492 * - if argument count differs between the wide and non-wide argument
7493 * list, something must be wrong.
7494 * - the file name arguments must have been located.
7495 * - the length of the argument list wasn't changed by the user.
7496 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007497 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007498 || ArglistW == NULL
7499 || used_file_indexes == NULL
7500 || used_file_count == 0
7501 || used_alist_count != GARGCOUNT)
7502 return;
7503
Bram Moolenaar86b68352004-12-27 21:59:20 +00007504 /* Remember the buffer numbers for the arguments. */
7505 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7506 if (fnum_list == NULL)
7507 return; /* out of memory */
7508 for (i = 0; i < GARGCOUNT; ++i)
7509 fnum_list[i] = GARGLIST[i].ae_fnum;
7510
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007511 /* Clear the argument list. Make room for the new arguments. */
7512 alist_clear(&global_alist);
7513 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007514 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007515
7516 for (i = 0; i < used_file_count; ++i)
7517 {
7518 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007519 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007520 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007521 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007522 int literal = used_file_literal;
7523
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007524# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007525 /* When using diff mode may need to concatenate file name to
7526 * directory name. Just like it's done in main(). */
7527 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7528 && !mch_isdir(alist_name(&GARGLIST[0])))
7529 {
7530 char_u *r;
7531
7532 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7533 if (r != NULL)
7534 {
7535 vim_free(str);
7536 str = r;
7537 }
7538 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007539# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007540 /* Re-use the old buffer by renaming it. When not using literal
7541 * names it's done by alist_expand() below. */
7542 if (used_file_literal)
7543 buf_set_name(fnum_list[i], str);
7544
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007545 /* Check backtick literal. backtick literal is already expanded in
7546 * main.c, so this part add str as literal. */
7547 if (literal == FALSE)
7548 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007549 size_t len = STRLEN(str);
7550
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007551 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7552 literal = TRUE;
7553 }
7554 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007555 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007556 }
7557
7558 if (!used_file_literal)
7559 {
7560 /* Now expand wildcards in the arguments. */
7561 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7562 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007563 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7564 * Also, unset wildignore to not be influenced by this option.
7565 * The arguments specified in command-line should be kept even if
7566 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007567 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007568 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007569 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007570 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007571 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007572 }
7573
7574 /* If wildcard expansion failed, we are editing the first file of the
7575 * arglist and there is no file name: Edit the first argument now. */
7576 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7577 {
7578 do_cmdline_cmd((char_u *)":rewind");
7579 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007580 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007581 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007582
7583 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007584}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007585
7586 int
7587mch_setenv(char *var, char *value, int x)
7588{
7589 char_u *envbuf;
7590
7591 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7592 if (envbuf == NULL)
7593 return -1;
7594
7595 sprintf((char *)envbuf, "%s=%s", var, value);
7596
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007597 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7598 {
7599 WCHAR *p = enc_to_utf16(envbuf, NULL);
7600
7601 vim_free(envbuf);
7602 if (p == NULL)
7603 return -1;
7604 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007605#ifdef libintl_wputenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007606 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007607#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007608 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7609 vim_free(p);
7610 }
7611 else
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007612 {
7613 _putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007614#ifdef libintl_putenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007615 libintl_putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007616#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007617 /* Unlike Un*x systems, we can free the string for _putenv(). */
7618 vim_free(envbuf);
7619 }
7620
7621 return 0;
7622}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007623
7624#ifndef FEAT_GUI_W32
7625
7626/*
7627 * Support for 256 colors and 24-bit colors was added in Windows 10
7628 * version 1703 (Creators update).
7629 */
7630# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7631
7632 static void
7633vtp_init(void)
7634{
7635 DWORD ver, mode;
7636 HMODULE hKerneldll;
7637 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007638# ifdef FEAT_TERMGUICOLORS
7639 COLORREF fg, bg;
7640# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007641
7642 ver = get_build_number();
7643 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7644 GetConsoleMode(g_hConOut, &mode);
7645 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7646 if (SetConsoleMode(g_hConOut, mode) == 0)
7647 vtp_working = 0;
7648
7649 /* Use functions supported from Vista */
7650 hKerneldll = GetModuleHandle("kernel32.dll");
7651 if (hKerneldll != NULL)
7652 {
7653 pGetConsoleScreenBufferInfoEx =
7654 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7655 hKerneldll, "GetConsoleScreenBufferInfoEx");
7656 pSetConsoleScreenBufferInfoEx =
7657 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7658 hKerneldll, "SetConsoleScreenBufferInfoEx");
7659 if (pGetConsoleScreenBufferInfoEx != NULL
7660 && pSetConsoleScreenBufferInfoEx != NULL)
7661 has_csbiex = TRUE;
7662 }
7663
7664 csbi.cbSize = sizeof(csbi);
7665 if (has_csbiex)
7666 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007667 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7668 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7669
7670# ifdef FEAT_TERMGUICOLORS
7671 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7672 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7673 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7674 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7675 default_console_color_bg = bg;
7676 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007677# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007678
7679 set_console_color_rgb();
7680}
7681
7682 static void
7683vtp_exit(void)
7684{
7685 reset_console_color_rgb();
7686}
7687
7688 static int
7689vtp_printf(
7690 char *format,
7691 ...)
7692{
7693 char_u buf[100];
7694 va_list list;
7695 DWORD result;
7696
7697 va_start(list, format);
7698 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7699 va_end(list);
7700 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7701 return (int)result;
7702}
7703
7704 static void
7705vtp_sgr_bulk(
7706 int arg)
7707{
7708 int args[1];
7709
7710 args[0] = arg;
7711 vtp_sgr_bulks(1, args);
7712}
7713
7714 static void
7715vtp_sgr_bulks(
7716 int argc,
7717 int *args
7718)
7719{
7720 /* 2('\033[') + 4('255.') * 16 + NUL */
7721 char_u buf[2 + (4 * 16) + 1];
7722 char_u *p;
7723 int i;
7724
7725 p = buf;
7726 *p++ = '\033';
7727 *p++ = '[';
7728
7729 for (i = 0; i < argc; ++i)
7730 {
7731 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7732 *p++ = ';';
7733 }
7734 p--;
7735 *p++ = 'm';
7736 *p = NUL;
7737 vtp_printf((char *)buf);
7738}
7739
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007740# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007741 static int
7742ctermtoxterm(
7743 int cterm)
7744{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007745 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007746
7747 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7748 return (((int)r << 16) | ((int)g << 8) | (int)b);
7749}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007750# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007751
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007752 static void
7753set_console_color_rgb(void)
7754{
7755# ifdef FEAT_TERMGUICOLORS
7756 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7757 int id;
7758 guicolor_T fg = INVALCOLOR;
7759 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007760 int ctermfg;
7761 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007762
7763 if (!USE_VTP)
7764 return;
7765
7766 id = syn_name2id((char_u *)"Normal");
7767 if (id > 0)
7768 syn_id2colors(id, &fg, &bg);
7769 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007770 {
7771 ctermfg = -1;
7772 if (id > 0)
7773 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007774 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7775 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007776 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007777 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007778 {
7779 ctermbg = -1;
7780 if (id > 0)
7781 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007782 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7783 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007784 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007785 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7786 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7787
7788 csbi.cbSize = sizeof(csbi);
7789 if (has_csbiex)
7790 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7791
7792 csbi.cbSize = sizeof(csbi);
7793 csbi.srWindow.Right += 1;
7794 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007795 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7796 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007797 if (has_csbiex)
7798 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7799# endif
7800}
7801
7802 static void
7803reset_console_color_rgb(void)
7804{
7805# ifdef FEAT_TERMGUICOLORS
7806 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7807
7808 csbi.cbSize = sizeof(csbi);
7809 if (has_csbiex)
7810 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7811
7812 csbi.cbSize = sizeof(csbi);
7813 csbi.srWindow.Right += 1;
7814 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007815 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7816 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007817 if (has_csbiex)
7818 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7819# endif
7820}
7821
7822 void
7823control_console_color_rgb(void)
7824{
7825 if (USE_VTP)
7826 set_console_color_rgb();
7827 else
7828 reset_console_color_rgb();
7829}
7830
7831 int
7832has_vtp_working(void)
7833{
7834 return vtp_working;
7835}
7836
7837 int
7838use_vtp(void)
7839{
7840 return USE_VTP;
7841}
7842
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007843 int
7844is_term_win32(void)
7845{
7846 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7847}
7848
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007849#endif