blob: 1b961b22cf9634ca6cae8cdd723b5d86f4c7dc9d [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
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
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
Bram Moolenaar4f974752019-02-17 17:44:42 +010048# if defined(FEAT_TITLE) && !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010049# 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 Moolenaarafde13b2019-04-28 19:46:49 +0200149#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150/* Win32 Console handles for input and output */
151static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
152static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
153
154/* Win32 Screen buffer,coordinate,console I/O information */
155static SMALL_RECT g_srScrollRegion;
156static COORD g_coord; /* 0-based, but external coords are 1-based */
157
158/* The attribute of the screen when the editor was started */
159static WORD g_attrDefault = 7; /* lightgray text on black background */
160static WORD g_attrCurrent;
161
162static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
163static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
164static int g_fForceExit = FALSE; /* set when forcefully exiting */
165
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166static void scroll(unsigned cLines);
167static void set_scroll_region(unsigned left, unsigned top,
168 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100169static void set_scroll_region_tb(unsigned top, unsigned bottom);
170static void set_scroll_region_lr(unsigned left, unsigned right);
171static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000172static void delete_lines(unsigned cLines);
173static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static int s_cursor_visible = TRUE;
176static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200177#endif
178#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179static int s_dont_use_vimrun = TRUE;
180static int need_vimrun_warning = FALSE;
181static char *vimrun_path = "vimrun ";
182#endif
183
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200184static int win32_getattrs(char_u *name);
185static int win32_setattrs(char_u *name, int attrs);
186static int win32_set_archive(char_u *name);
187
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100188static int conpty_working = 0;
189static int conpty_stable = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100190static void vtp_flag_init();
191
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200192#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100193static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100194static void vtp_init();
195static void vtp_exit();
196static int vtp_printf(char *format, ...);
197static void vtp_sgr_bulk(int arg);
198static void vtp_sgr_bulks(int argc, int *argv);
199
200static guicolor_T save_console_bg_rgb;
201static guicolor_T save_console_fg_rgb;
202
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200203static int g_color_index_bg = 0;
204static int g_color_index_fg = 7;
205
206# ifdef FEAT_TERMGUICOLORS
207static int default_console_color_bg = 0x000000; // black
208static int default_console_color_fg = 0xc0c0c0; // white
209# endif
210
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100211# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200212# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100213# else
214# define USE_VTP 0
215# endif
216
217static void set_console_color_rgb(void);
218static void reset_console_color_rgb(void);
219#endif
220
221/* This flag is newly created from Windows 10 */
222#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
223# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
224#endif
225
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200226#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000227static int suppress_winsize = 1; /* don't fiddle with console */
228#endif
229
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200230static char_u *exe_path = NULL;
231
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100232static BOOL win8_or_later = FALSE;
233
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200234#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100235/* Dynamic loading for portability */
236typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
237{
238 ULONG cbSize;
239 COORD dwSize;
240 COORD dwCursorPosition;
241 WORD wAttributes;
242 SMALL_RECT srWindow;
243 COORD dwMaximumWindowSize;
244 WORD wPopupAttributes;
245 BOOL bFullscreenSupported;
246 COLORREF ColorTable[16];
247} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
248typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
249static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
250typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
251static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
252static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100253#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100254
255/*
256 * Get version number including build number
257 */
258typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
259# define MAKE_VER(major, minor, build) \
260 (((major) << 24) | ((minor) << 16) | (build))
261
262 static DWORD
263get_build_number(void)
264{
265 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
266 HMODULE hNtdll;
267 PfnRtlGetVersion pRtlGetVersion;
268 DWORD ver = MAKE_VER(0, 0, 0);
269
270 hNtdll = GetModuleHandle("ntdll.dll");
271 if (hNtdll != NULL)
272 {
273 pRtlGetVersion =
274 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
275 pRtlGetVersion(&osver);
276 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
277 min(osver.dwMinorVersion, 255),
278 min(osver.dwBuildNumber, 32767));
279 }
280 return ver;
281}
282
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200283#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100284/*
285 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100286 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100287 */
288 static BOOL
289read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 HANDLE hInput,
291 INPUT_RECORD *lpBuffer,
292 DWORD nLength,
293 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100294{
295 enum
296 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100297 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100299 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100300 static DWORD s_dwIndex = 0;
301 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100302 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100303 int head;
304 int tail;
305 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100306
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200307 if (nLength == -2)
308 return (s_dwMax > 0) ? TRUE : FALSE;
309
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100310 if (!win8_or_later)
311 {
312 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200313 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
314 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100315 }
316
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100317 if (s_dwMax == 0)
318 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200320 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
321 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100323 s_dwIndex = 0;
324 s_dwMax = dwEvents;
325 if (dwEvents == 0)
326 {
327 *lpEvents = 0;
328 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100329 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100330
331 if (s_dwMax > 1)
332 {
333 head = 0;
334 tail = s_dwMax - 1;
335 while (head != tail)
336 {
337 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
338 && s_irCache[head + 1].EventType
339 == WINDOW_BUFFER_SIZE_EVENT)
340 {
341 /* Remove duplicate event to avoid flicker. */
342 for (i = head; i < tail; ++i)
343 s_irCache[i] = s_irCache[i + 1];
344 --tail;
345 continue;
346 }
347 head++;
348 }
349 s_dwMax = tail + 1;
350 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100351 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100352
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100353 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200354 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100355 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100356 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100357 return TRUE;
358}
359
360/*
361 * Version of PeekConsoleInput() that works with IME.
362 */
363 static BOOL
364peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100365 HANDLE hInput,
366 INPUT_RECORD *lpBuffer,
367 DWORD nLength,
368 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100369{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100370 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100371}
372
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100373# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200374 static DWORD
375msg_wait_for_multiple_objects(
376 DWORD nCount,
377 LPHANDLE pHandles,
378 BOOL fWaitAll,
379 DWORD dwMilliseconds,
380 DWORD dwWakeMask)
381{
382 if (read_console_input(NULL, NULL, -2, NULL))
383 return WAIT_OBJECT_0;
384 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
385 dwMilliseconds, dwWakeMask);
386}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100387# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200388
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100389# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200390 static DWORD
391wait_for_single_object(
392 HANDLE hHandle,
393 DWORD dwMilliseconds)
394{
395 if (read_console_input(NULL, NULL, -2, NULL))
396 return WAIT_OBJECT_0;
397 return WaitForSingleObject(hHandle, dwMilliseconds);
398}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100399# endif
400#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200401
Bram Moolenaar071d4272004-06-13 20:20:40 +0000402 static void
403get_exe_name(void)
404{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100405 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
406 * as the maximum length that works (plus a NUL byte). */
407#define MAX_ENV_PATH_LEN 8192
408 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200409 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410
411 if (exe_name == NULL)
412 {
413 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100414 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000415 if (*temp != NUL)
416 exe_name = FullName_save((char_u *)temp, FALSE);
417 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000418
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200419 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000420 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200421 exe_path = vim_strnsave(exe_name,
422 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200423 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000424 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200425 /* Append our starting directory to $PATH, so that when doing
426 * "!xxd" it's found in our starting directory. Needed because
427 * SearchPath() also looks there. */
428 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100429 if (p == NULL
430 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200431 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100432 if (p == NULL || *p == NUL)
433 temp[0] = NUL;
434 else
435 {
436 STRCPY(temp, p);
437 STRCAT(temp, ";");
438 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200439 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100440 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200441 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000442 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000443 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444}
445
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200446/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100447 * Unescape characters in "p" that appear in "escaped".
448 */
449 static void
450unescape_shellxquote(char_u *p, char_u *escaped)
451{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100452 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100453 int n;
454
455 while (*p != NUL)
456 {
457 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
458 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100459 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100460 p += n;
461 l -= n;
462 }
463}
464
465/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200466 * Load library "name".
467 */
468 HINSTANCE
469vimLoadLib(char *name)
470{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200471 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200473 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
474 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 if (exe_path == NULL)
476 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200477 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200479 WCHAR old_dirw[MAXPATHL];
480
481 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
482 {
483 /* Change directory to where the executable is, both to make
484 * sure we find a .dll there and to avoid looking for a .dll
485 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100486 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 dll = LoadLibrary(name);
488 SetCurrentDirectoryW(old_dirw);
489 return dll;
490 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200491 }
492 return dll;
493}
494
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200495#if defined(VIMDLL) || defined(PROTO)
496/*
497 * Check if the current executable file is for the GUI subsystem.
498 */
499 int
500mch_is_gui_executable(void)
501{
502 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
503 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
504 PIMAGE_NT_HEADERS pPE;
505
506 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
507 return FALSE;
508 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
509 if (pPE->Signature != IMAGE_NT_SIGNATURE)
510 return FALSE;
511 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
512 return TRUE;
513 return FALSE;
514}
515#endif
516
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100517#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
518/*
519 * Get related information about 'funcname' which is imported by 'hInst'.
520 * If 'info' is 0, return the function address.
521 * If 'info' is 1, return the module name which the function is imported from.
522 */
523 static void *
524get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
525{
526 PBYTE pImage = (PBYTE)hInst;
527 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
528 PIMAGE_NT_HEADERS pPE;
529 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
530 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
531 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
532 PIMAGE_IMPORT_BY_NAME pImpName;
533
534 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
535 return NULL;
536 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
537 if (pPE->Signature != IMAGE_NT_SIGNATURE)
538 return NULL;
539 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
540 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
541 .VirtualAddress);
542 for (; pImpDesc->FirstThunk; ++pImpDesc)
543 {
544 if (!pImpDesc->OriginalFirstThunk)
545 continue;
546 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
547 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
548 for (; pIAT->u1.Function; ++pIAT, ++pINT)
549 {
550 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
551 continue;
552 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
553 + (UINT_PTR)(pINT->u1.AddressOfData));
554 if (strcmp((char *)pImpName->Name, funcname) == 0)
555 {
556 switch (info)
557 {
558 case 0:
559 return (void *)pIAT->u1.Function;
560 case 1:
561 return (void *)(pImage + pImpDesc->Name);
562 default:
563 return NULL;
564 }
565 }
566 }
567 }
568 return NULL;
569}
570
571/*
572 * Get the module handle which 'funcname' in 'hInst' is imported from.
573 */
574 HINSTANCE
575find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
576{
577 char *modulename;
578
579 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
580 if (modulename != NULL)
581 return GetModuleHandleA(modulename);
582 return NULL;
583}
584
585/*
586 * Get the address of 'funcname' which is imported by 'hInst' DLL.
587 */
588 void *
589get_dll_import_func(HINSTANCE hInst, const char *funcname)
590{
591 return get_imported_func_info(hInst, funcname, 0);
592}
593#endif
594
Bram Moolenaar071d4272004-06-13 20:20:40 +0000595#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
596# ifndef GETTEXT_DLL
597# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200598# define GETTEXT_DLL_ALT1 "libintl-8.dll"
599# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000600# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200601/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000602static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200603static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000604static char *null_libintl_textdomain(const char *);
605static char *null_libintl_bindtextdomain(const char *, const char *);
606static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100607static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200609static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000610char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200611char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
612 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000613char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
614char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000616char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
617 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100618int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619
620 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100621dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622{
623 int i;
624 static struct
625 {
626 char *name;
627 FARPROC *ptr;
628 } libintl_entry[] =
629 {
630 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200631 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
633 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
634 {NULL, NULL}
635 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100636 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000637
Bram Moolenaar7554c542018-10-06 15:03:15 +0200638 // No need to initialize twice.
639 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200641 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100642 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200643#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100644 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200645 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
646#endif
647#ifdef GETTEXT_DLL_ALT2
648 if (!hLibintlDLL)
649 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100650#endif
651 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200653 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200655 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100656 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200657 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200659 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000660 }
661 for (i = 0; libintl_entry[i].name != NULL
662 && libintl_entry[i].ptr != NULL; ++i)
663 {
664 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
665 libintl_entry[i].name)) == NULL)
666 {
667 dyn_libintl_end();
668 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000669 {
670 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100671 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000672 verbose_leave();
673 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000674 return 0;
675 }
676 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000677
678 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000679 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000680 "bind_textdomain_codeset");
681 if (dyn_libintl_bind_textdomain_codeset == NULL)
682 dyn_libintl_bind_textdomain_codeset =
683 null_libintl_bind_textdomain_codeset;
684
Bram Moolenaar0eb035c2019-04-02 22:15:55 +0200685 /* _wputenv() function for the libintl.dll is optional. */
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100686 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
687 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100688 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100689 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
690 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100691
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692 return 1;
693}
694
695 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100696dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697{
698 if (hLibintlDLL)
699 FreeLibrary(hLibintlDLL);
700 hLibintlDLL = NULL;
701 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200702 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000703 dyn_libintl_textdomain = null_libintl_textdomain;
704 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000705 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100706 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000707}
708
709 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000710null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000711{
712 return (char*)msgid;
713}
714
715 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200716null_libintl_ngettext(
717 const char *msgid,
718 const char *msgid_plural,
719 unsigned long n)
720{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200721 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200722}
723
Bram Moolenaaree695f72016-08-03 22:08:45 +0200724 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100725null_libintl_bindtextdomain(
726 const char *domainname UNUSED,
727 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728{
729 return NULL;
730}
731
732 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100733null_libintl_bind_textdomain_codeset(
734 const char *domainname UNUSED,
735 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000736{
737 return NULL;
738}
739
740 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100741null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742{
743 return NULL;
744}
745
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200746 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100747null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100748{
749 return 0;
750}
751
Bram Moolenaar071d4272004-06-13 20:20:40 +0000752#endif /* DYNAMIC_GETTEXT */
753
754/* This symbol is not defined in older versions of the SDK or Visual C++ */
755
756#ifndef VER_PLATFORM_WIN32_WINDOWS
757# define VER_PLATFORM_WIN32_WINDOWS 1
758#endif
759
760DWORD g_PlatformId;
761
762#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100763# ifndef PROTO
764# include <aclapi.h>
765# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200766# ifndef PROTECTED_DACL_SECURITY_INFORMATION
767# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
768# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769#endif
770
Bram Moolenaar27515922013-06-29 15:36:26 +0200771#ifdef HAVE_ACL
772/*
773 * Enables or disables the specified privilege.
774 */
775 static BOOL
776win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
777{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100778 BOOL bResult;
779 LUID luid;
780 HANDLE hToken;
781 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200782
783 if (!OpenProcessToken(GetCurrentProcess(),
784 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
785 return FALSE;
786
787 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
788 {
789 CloseHandle(hToken);
790 return FALSE;
791 }
792
Bram Moolenaar45500912014-07-09 20:51:07 +0200793 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200794 tokenPrivileges.Privileges[0].Luid = luid;
795 tokenPrivileges.Privileges[0].Attributes = bEnable ?
796 SE_PRIVILEGE_ENABLED : 0;
797
798 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
799 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
800
801 CloseHandle(hToken);
802
803 return bResult && GetLastError() == ERROR_SUCCESS;
804}
805#endif
806
Bram Moolenaar071d4272004-06-13 20:20:40 +0000807/*
808 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
809 * VER_PLATFORM_WIN32_WINDOWS (Win95).
810 */
811 void
812PlatformId(void)
813{
814 static int done = FALSE;
815
816 if (!done)
817 {
818 OSVERSIONINFO ovi;
819
820 ovi.dwOSVersionInfoSize = sizeof(ovi);
821 GetVersionEx(&ovi);
822
823 g_PlatformId = ovi.dwPlatformId;
824
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100825 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
826 || ovi.dwMajorVersion > 6)
827 win8_or_later = TRUE;
828
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200830 /* Enable privilege for getting or setting SACLs. */
831 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832#endif
833 done = TRUE;
834 }
835}
836
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200837#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838
839#define SHIFT (SHIFT_PRESSED)
840#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
841#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
842#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
843
844
845/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
846 * We map function keys to their ANSI terminal equivalents, as produced
847 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
848 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
849 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
850 * combinations of function/arrow/etc keys.
851 */
852
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000853static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854{
855 WORD wVirtKey;
856 BOOL fAnsiKey;
857 int chAlone;
858 int chShift;
859 int chCtrl;
860 int chAlt;
861} VirtKeyMap[] =
862{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200863// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
865
866 { VK_F1, TRUE, ';', 'T', '^', 'h', },
867 { VK_F2, TRUE, '<', 'U', '_', 'i', },
868 { VK_F3, TRUE, '=', 'V', '`', 'j', },
869 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
870 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
871 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
872 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
873 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
874 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
875 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200876 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
877 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200879 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
880 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
881 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
882 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
883 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
884 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
885 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
886 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
887 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
888 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100889 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200891 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892
893#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200894 // Most people don't have F13-F20, but what the hell...
895 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
896 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
897 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
898 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
899 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
900 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
901 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
902 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200904 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
905 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
906 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
907 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200909 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
910 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
911 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
912 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
913 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
914 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
915 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
916 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
917 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
918 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100919 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920};
921
922
923#ifdef _MSC_VER
924// The ToAscii bug destroys several registers. Need to turn off optimization
925// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000926# pragma warning(push)
927# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928# pragma optimize("", off)
929#endif
930
931#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200932# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200934# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935#endif
936
937/* The return code indicates key code size. */
938 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000940 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941{
942 UINT uMods = pker->dwControlKeyState;
943 static int s_iIsDead = 0;
944 static WORD awAnsiCode[2];
945 static BYTE abKeystate[256];
946
947
948 if (s_iIsDead == 2)
949 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200950 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951 s_iIsDead = 0;
952 return 1;
953 }
954
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200955 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000956 return 1;
957
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200958 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200961 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962
963 if (uMods & SHIFT_PRESSED)
964 abKeystate[VK_SHIFT] = 0x80;
965 if (uMods & CAPSLOCK_ON)
966 abKeystate[VK_CAPITAL] = 1;
967
968 if ((uMods & ALT_GR) == ALT_GR)
969 {
970 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
971 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
972 }
973
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200974 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
975 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976
977 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200978 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979
980 return s_iIsDead;
981}
982
983#ifdef _MSC_VER
984/* MUST switch optimization on again here, otherwise a call to
985 * decode_key_event() may crash (e.g. when hitting caps-lock) */
986# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000987# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000988
989# if (_MSC_VER < 1100)
990/* MUST turn off global optimisation for this next function, or
991 * pressing ctrl-minus in insert mode crashes Vim when built with
992 * VC4.1. -- negri. */
993# pragma optimize("g", off)
994# endif
995#endif
996
997static BOOL g_fJustGotFocus = FALSE;
998
999/*
1000 * Decode a KEY_EVENT into one or two keystrokes
1001 */
1002 static BOOL
1003decode_key_event(
1004 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001005 WCHAR *pch,
1006 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001007 int *pmodifiers,
1008 BOOL fDoPost)
1009{
1010 int i;
1011 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1012
1013 *pch = *pch2 = NUL;
1014 g_fJustGotFocus = FALSE;
1015
1016 /* ignore key up events */
1017 if (!pker->bKeyDown)
1018 return FALSE;
1019
1020 /* ignore some keystrokes */
1021 switch (pker->wVirtualKeyCode)
1022 {
1023 /* modifiers */
1024 case VK_SHIFT:
1025 case VK_CONTROL:
1026 case VK_MENU: /* Alt key */
1027 return FALSE;
1028
1029 default:
1030 break;
1031 }
1032
1033 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001034 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035 {
1036 /* Ctrl-6 is Ctrl-^ */
1037 if (pker->wVirtualKeyCode == '6')
1038 {
1039 *pch = Ctrl_HAT;
1040 return TRUE;
1041 }
1042 /* Ctrl-2 is Ctrl-@ */
1043 else if (pker->wVirtualKeyCode == '2')
1044 {
1045 *pch = NUL;
1046 return TRUE;
1047 }
1048 /* Ctrl-- is Ctrl-_ */
1049 else if (pker->wVirtualKeyCode == 0xBD)
1050 {
1051 *pch = Ctrl__;
1052 return TRUE;
1053 }
1054 }
1055
1056 /* Shift-TAB */
1057 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1058 {
1059 *pch = K_NUL;
1060 *pch2 = '\017';
1061 return TRUE;
1062 }
1063
1064 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1065 {
1066 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1067 {
1068 if (nModifs == 0)
1069 *pch = VirtKeyMap[i].chAlone;
1070 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1071 *pch = VirtKeyMap[i].chShift;
1072 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1073 *pch = VirtKeyMap[i].chCtrl;
1074 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1075 *pch = VirtKeyMap[i].chAlt;
1076
1077 if (*pch != 0)
1078 {
1079 if (VirtKeyMap[i].fAnsiKey)
1080 {
1081 *pch2 = *pch;
1082 *pch = K_NUL;
1083 }
1084
1085 return TRUE;
1086 }
1087 }
1088 }
1089
1090 i = win32_kbd_patch_key(pker);
1091
1092 if (i < 0)
1093 *pch = NUL;
1094 else
1095 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001096 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097
1098 if (pmodifiers != NULL)
1099 {
1100 /* Pass on the ALT key as a modifier, but only when not combined
1101 * with CTRL (which is ALTGR). */
1102 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1103 *pmodifiers |= MOD_MASK_ALT;
1104
1105 /* Pass on SHIFT only for special keys, because we don't know when
1106 * it's already included with the character. */
1107 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1108 *pmodifiers |= MOD_MASK_SHIFT;
1109
1110 /* Pass on CTRL only for non-special keys, because we don't know
1111 * when it's already included with the character. And not when
1112 * combined with ALT (which is ALTGR). */
1113 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1114 && *pch >= 0x20 && *pch < 0x80)
1115 *pmodifiers |= MOD_MASK_CTRL;
1116 }
1117 }
1118
1119 return (*pch != NUL);
1120}
1121
1122#ifdef _MSC_VER
1123# pragma optimize("", on)
1124#endif
1125
Bram Moolenaar4f974752019-02-17 17:44:42 +01001126#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127
1128
1129#ifdef FEAT_MOUSE
1130
1131/*
1132 * For the GUI the mouse handling is in gui_w32.c.
1133 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001134# if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001135 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001136mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137{
1138}
1139# else
1140static int g_fMouseAvail = FALSE; /* mouse present */
1141static int g_fMouseActive = FALSE; /* mouse enabled */
1142static int g_nMouseClick = -1; /* mouse status */
1143static int g_xMouse; /* mouse x coordinate */
1144static int g_yMouse; /* mouse y coordinate */
1145
1146/*
1147 * Enable or disable mouse input
1148 */
1149 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001150mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151{
1152 DWORD cmodein;
1153
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001154# ifdef VIMDLL
1155 if (gui.in_use)
1156 return;
1157# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158 if (!g_fMouseAvail)
1159 return;
1160
1161 g_fMouseActive = on;
1162 GetConsoleMode(g_hConIn, &cmodein);
1163
1164 if (g_fMouseActive)
1165 cmodein |= ENABLE_MOUSE_INPUT;
1166 else
1167 cmodein &= ~ENABLE_MOUSE_INPUT;
1168
1169 SetConsoleMode(g_hConIn, cmodein);
1170}
1171
Bram Moolenaar157d8132018-03-06 17:09:20 +01001172
1173#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1174/*
1175 * Called when 'balloonevalterm' changed.
1176 */
1177 void
1178mch_bevalterm_changed(void)
1179{
1180 mch_setmouse(g_fMouseActive);
1181}
1182#endif
1183
Bram Moolenaar071d4272004-06-13 20:20:40 +00001184/*
1185 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1186 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1187 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1188 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1189 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1190 * and we return the mouse position in g_xMouse and g_yMouse.
1191 *
1192 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1193 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1194 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1195 *
1196 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1197 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1198 *
1199 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1200 * moves, even if it stays within the same character cell. We ignore
1201 * all MOUSE_MOVED messages if the position hasn't really changed, and
1202 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1203 * we're only interested in MOUSE_DRAG).
1204 *
1205 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1206 * 2-button mouses by pressing the left & right buttons simultaneously.
1207 * In practice, it's almost impossible to click both at the same time,
1208 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1209 * in such cases, if the user is clicking quickly.
1210 */
1211 static BOOL
1212decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001213 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214{
1215 static int s_nOldButton = -1;
1216 static int s_nOldMouseClick = -1;
1217 static int s_xOldMouse = -1;
1218 static int s_yOldMouse = -1;
1219 static linenr_T s_old_topline = 0;
1220#ifdef FEAT_DIFF
1221 static int s_old_topfill = 0;
1222#endif
1223 static int s_cClicks = 1;
1224 static BOOL s_fReleased = TRUE;
1225 static DWORD s_dwLastClickTime = 0;
1226 static BOOL s_fNextIsMiddle = FALSE;
1227
1228 static DWORD cButtons = 0; /* number of buttons supported */
1229
1230 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1231 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1232 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1233 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1234
1235 int nButton;
1236
1237 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1238 cButtons = 2;
1239
1240 if (!g_fMouseAvail || !g_fMouseActive)
1241 {
1242 g_nMouseClick = -1;
1243 return FALSE;
1244 }
1245
1246 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1247 if (g_fJustGotFocus)
1248 {
1249 g_fJustGotFocus = FALSE;
1250 return FALSE;
1251 }
1252
1253 /* unprocessed mouse click? */
1254 if (g_nMouseClick != -1)
1255 return TRUE;
1256
1257 nButton = -1;
1258 g_xMouse = pmer->dwMousePosition.X;
1259 g_yMouse = pmer->dwMousePosition.Y;
1260
1261 if (pmer->dwEventFlags == MOUSE_MOVED)
1262 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001263 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264 * events even when the mouse moves only within a char cell.) */
1265 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1266 return FALSE;
1267 }
1268
1269 /* If no buttons are pressed... */
1270 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1271 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001272 nButton = MOUSE_RELEASE;
1273
Bram Moolenaar071d4272004-06-13 20:20:40 +00001274 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1275 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001276 {
1277#ifdef FEAT_BEVAL_TERM
1278 /* do return mouse move events when we want them */
1279 if (p_bevalterm)
1280 nButton = MOUSE_DRAG;
1281 else
1282#endif
1283 return FALSE;
1284 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286 s_fReleased = TRUE;
1287 }
1288 else /* one or more buttons pressed */
1289 {
1290 /* on a 2-button mouse, hold down left and right buttons
1291 * simultaneously to get MIDDLE. */
1292
1293 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1294 {
1295 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1296
1297 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001298 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299 if (dwLR == LEFT || dwLR == RIGHT)
1300 {
1301 for (;;)
1302 {
1303 /* wait a short time for next input event */
1304 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1305 != WAIT_OBJECT_0)
1306 break;
1307 else
1308 {
1309 DWORD cRecords = 0;
1310 INPUT_RECORD ir;
1311 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1312
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001313 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001314
1315 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1316 || !(pmer2->dwButtonState & LEFT_RIGHT))
1317 break;
1318 else
1319 {
1320 if (pmer2->dwEventFlags != MOUSE_MOVED)
1321 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001322 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323
1324 return decode_mouse_event(pmer2);
1325 }
1326 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1327 s_yOldMouse == pmer2->dwMousePosition.Y)
1328 {
1329 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001330 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331
1332 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001333 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001334
1335 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1336 break;
1337 }
1338 else
1339 break;
1340 }
1341 }
1342 }
1343 }
1344 }
1345
1346 if (s_fNextIsMiddle)
1347 {
1348 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1349 ? MOUSE_DRAG : MOUSE_MIDDLE;
1350 s_fNextIsMiddle = FALSE;
1351 }
1352 else if (cButtons == 2 &&
1353 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1354 {
1355 nButton = MOUSE_MIDDLE;
1356
1357 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1358 {
1359 s_fNextIsMiddle = TRUE;
1360 nButton = MOUSE_RELEASE;
1361 }
1362 }
1363 else if ((pmer->dwButtonState & LEFT) == LEFT)
1364 nButton = MOUSE_LEFT;
1365 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1366 nButton = MOUSE_MIDDLE;
1367 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1368 nButton = MOUSE_RIGHT;
1369
1370 if (! s_fReleased && ! s_fNextIsMiddle
1371 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1372 return FALSE;
1373
1374 s_fReleased = s_fNextIsMiddle;
1375 }
1376
1377 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1378 {
1379 /* button pressed or released, without mouse moving */
1380 if (nButton != -1 && nButton != MOUSE_RELEASE)
1381 {
1382 DWORD dwCurrentTime = GetTickCount();
1383
1384 if (s_xOldMouse != g_xMouse
1385 || s_yOldMouse != g_yMouse
1386 || s_nOldButton != nButton
1387 || s_old_topline != curwin->w_topline
1388#ifdef FEAT_DIFF
1389 || s_old_topfill != curwin->w_topfill
1390#endif
1391 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1392 {
1393 s_cClicks = 1;
1394 }
1395 else if (++s_cClicks > 4)
1396 {
1397 s_cClicks = 1;
1398 }
1399
1400 s_dwLastClickTime = dwCurrentTime;
1401 }
1402 }
1403 else if (pmer->dwEventFlags == MOUSE_MOVED)
1404 {
1405 if (nButton != -1 && nButton != MOUSE_RELEASE)
1406 nButton = MOUSE_DRAG;
1407
1408 s_cClicks = 1;
1409 }
1410
1411 if (nButton == -1)
1412 return FALSE;
1413
1414 if (nButton != MOUSE_RELEASE)
1415 s_nOldButton = nButton;
1416
1417 g_nMouseClick = nButton;
1418
1419 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1420 g_nMouseClick |= MOUSE_SHIFT;
1421 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1422 g_nMouseClick |= MOUSE_CTRL;
1423 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1424 g_nMouseClick |= MOUSE_ALT;
1425
1426 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1427 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1428
1429 /* only pass on interesting (i.e., different) mouse events */
1430 if (s_xOldMouse == g_xMouse
1431 && s_yOldMouse == g_yMouse
1432 && s_nOldMouseClick == g_nMouseClick)
1433 {
1434 g_nMouseClick = -1;
1435 return FALSE;
1436 }
1437
1438 s_xOldMouse = g_xMouse;
1439 s_yOldMouse = g_yMouse;
1440 s_old_topline = curwin->w_topline;
1441#ifdef FEAT_DIFF
1442 s_old_topfill = curwin->w_topfill;
1443#endif
1444 s_nOldMouseClick = g_nMouseClick;
1445
1446 return TRUE;
1447}
1448
Bram Moolenaar4f974752019-02-17 17:44:42 +01001449# endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450#endif /* FEAT_MOUSE */
1451
1452
1453#ifdef MCH_CURSOR_SHAPE
1454/*
1455 * Set the shape of the cursor.
1456 * 'thickness' can be from 1 (thin) to 99 (block)
1457 */
1458 static void
1459mch_set_cursor_shape(int thickness)
1460{
1461 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1462 ConsoleCursorInfo.dwSize = thickness;
1463 ConsoleCursorInfo.bVisible = s_cursor_visible;
1464
1465 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1466 if (s_cursor_visible)
1467 SetConsoleCursorPosition(g_hConOut, g_coord);
1468}
1469
1470 void
1471mch_update_cursor(void)
1472{
1473 int idx;
1474 int thickness;
1475
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001476# ifdef VIMDLL
1477 if (gui.in_use)
1478 return;
1479# endif
1480
Bram Moolenaar071d4272004-06-13 20:20:40 +00001481 /*
1482 * How the cursor is drawn depends on the current mode.
1483 */
1484 idx = get_shape_idx(FALSE);
1485
1486 if (shape_table[idx].shape == SHAPE_BLOCK)
1487 thickness = 99; /* 100 doesn't work on W95 */
1488 else
1489 thickness = shape_table[idx].percentage;
1490 mch_set_cursor_shape(thickness);
1491}
1492#endif
1493
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001494#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495/*
1496 * Handle FOCUS_EVENT.
1497 */
1498 static void
1499handle_focus_event(INPUT_RECORD ir)
1500{
1501 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1502 ui_focus_change((int)g_fJustGotFocus);
1503}
1504
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001505static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1506
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507/*
1508 * Wait until console input from keyboard or mouse is available,
1509 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001510 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511 * Return TRUE if something is available FALSE if not.
1512 */
1513 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001514WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515{
1516 DWORD dwNow = 0, dwEndTime = 0;
1517 INPUT_RECORD ir;
1518 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001519 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001520#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001521 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001522#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523
1524 if (msec > 0)
1525 /* Wait until the specified time has elapsed. */
1526 dwEndTime = GetTickCount() + msec;
1527 else if (msec < 0)
1528 /* Wait forever. */
1529 dwEndTime = INFINITE;
1530
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001531 // We need to loop until the end of the time period, because
1532 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 for (;;)
1534 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001535 // Only process messages when waiting.
1536 if (msec != 0)
1537 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001538#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001539 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001540#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001541#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001542 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001543#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001545 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001547 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001548
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549 if (0
1550#ifdef FEAT_MOUSE
1551 || g_nMouseClick != -1
1552#endif
1553#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001554 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555#endif
1556 )
1557 return TRUE;
1558
1559 if (msec > 0)
1560 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001561 /* If the specified wait time has passed, return. Beware that
1562 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001564 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565 break;
1566 }
1567 if (msec != 0)
1568 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001569 DWORD dwWaitTime = dwEndTime - dwNow;
1570
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001571#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001572 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001573 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001574 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001575 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001576 /* If there is readahead then parse_queued_messages() timed out
1577 * and we should call it again soon. */
1578 if (channel_any_readahead())
1579 dwWaitTime = 10;
1580 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001581#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001582#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001583 if (p_beval && dwWaitTime > 100)
1584 /* The 'balloonexpr' may indirectly invoke a callback while
1585 * waiting for a character, need to check often. */
1586 dwWaitTime = 100;
1587#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001588#ifdef FEAT_MZSCHEME
1589 if (mzthreads_allowed() && p_mzq > 0
1590 && (msec < 0 || (long)dwWaitTime > p_mzq))
1591 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1592#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001593#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001594 // When waiting very briefly don't trigger timers.
1595 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001596 {
1597 long due_time;
1598
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001599 // Trigger timers and then get the time in msec until the next
1600 // one is due. Wait up to that time.
1601 due_time = check_due_timer();
1602 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001603 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001604 // timer may have used feedkeys().
1605 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001606 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001607 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1608 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001609 }
1610#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001611 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001613 // Wait for either an event on the console input or a
1614 // message in the client-server window.
1615 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1616 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001618 wait_for_single_object(g_hConIn, dwWaitTime)
1619 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001621 )
1622 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623 }
1624
1625 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001626 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627
1628#ifdef FEAT_MBYTE_IME
1629 if (State & CMDLINE && msg_row == Rows - 1)
1630 {
1631 CONSOLE_SCREEN_BUFFER_INFO csbi;
1632
1633 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1634 {
1635 if (csbi.dwCursorPosition.Y != msg_row)
1636 {
1637 /* The screen is now messed up, must redraw the
1638 * command line and later all the windows. */
1639 redraw_all_later(CLEAR);
1640 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1641 redrawcmd();
1642 }
1643 }
1644 }
1645#endif
1646
1647 if (cRecords > 0)
1648 {
1649 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1650 {
1651#ifdef FEAT_MBYTE_IME
1652 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1653 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001654 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001655 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1656 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001657 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658 continue;
1659 }
1660#endif
1661 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1662 NULL, FALSE))
1663 return TRUE;
1664 }
1665
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001666 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667
1668 if (ir.EventType == FOCUS_EVENT)
1669 handle_focus_event(ir);
1670 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001671 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001672 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1673
1674 // Only call shell_resized() when the size actually change to
1675 // avoid the screen is cleard.
1676 if (dwSize.X != Columns || dwSize.Y != Rows)
1677 {
1678 CONSOLE_SCREEN_BUFFER_INFO csbi;
1679 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
1680 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1681 ResizeConBuf(g_hConOut, dwSize);
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001682 shell_resized();
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001683 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001684 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685#ifdef FEAT_MOUSE
1686 else if (ir.EventType == MOUSE_EVENT
1687 && decode_mouse_event(&ir.Event.MouseEvent))
1688 return TRUE;
1689#endif
1690 }
1691 else if (msec == 0)
1692 break;
1693 }
1694
1695#ifdef FEAT_CLIENTSERVER
1696 /* Something might have been received while we were waiting. */
1697 if (input_available())
1698 return TRUE;
1699#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001700
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701 return FALSE;
1702}
1703
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704/*
1705 * return non-zero if a character is available
1706 */
1707 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001708mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001710# ifdef VIMDLL
1711 if (gui.in_use)
1712 return TRUE;
1713# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001714 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001716
1717# if defined(FEAT_TERMINAL) || defined(PROTO)
1718/*
1719 * Check for any pending input or messages.
1720 */
1721 int
1722mch_check_messages(void)
1723{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001724# ifdef VIMDLL
1725 if (gui.in_use)
1726 return TRUE;
1727# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001728 return WaitForChar(0L, TRUE);
1729}
1730# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731
1732/*
1733 * Create the console input. Used when reading stdin doesn't work.
1734 */
1735 static void
1736create_conin(void)
1737{
1738 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1739 FILE_SHARE_READ|FILE_SHARE_WRITE,
1740 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001741 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742 did_create_conin = TRUE;
1743}
1744
1745/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001746 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001747 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001748 static WCHAR
1749tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001750{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001751 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752
1753 for (;;)
1754 {
1755 INPUT_RECORD ir;
1756 DWORD cRecords = 0;
1757
1758#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001759 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 if (input_available())
1761 return 0;
1762# ifdef FEAT_MOUSE
1763 if (g_nMouseClick != -1)
1764 return 0;
1765# endif
1766#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001767 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768 {
1769 if (did_create_conin)
1770 read_error_exit();
1771 create_conin();
1772 continue;
1773 }
1774
1775 if (ir.EventType == KEY_EVENT)
1776 {
1777 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1778 pmodifiers, TRUE))
1779 return ch;
1780 }
1781 else if (ir.EventType == FOCUS_EVENT)
1782 handle_focus_event(ir);
1783 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1784 shell_resized();
1785#ifdef FEAT_MOUSE
1786 else if (ir.EventType == MOUSE_EVENT)
1787 {
1788 if (decode_mouse_event(&ir.Event.MouseEvent))
1789 return 0;
1790 }
1791#endif
1792 }
1793}
Bram Moolenaar4f974752019-02-17 17:44:42 +01001794#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795
1796
1797/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001798 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 * Get one or more characters from the keyboard or the mouse.
1800 * If time == 0, do not wait for characters.
1801 * If time == n, wait a short time for characters.
1802 * If time == -1, wait forever for characters.
1803 * Returns the number of characters read into buf.
1804 */
1805 int
1806mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001807 char_u *buf UNUSED,
1808 int maxlen UNUSED,
1809 long time UNUSED,
1810 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001812#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813
1814 int len;
1815 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816#define TYPEAHEADLEN 20
1817 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1818 static int typeaheadlen = 0;
1819
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001820# ifdef VIMDLL
1821 if (gui.in_use)
1822 return 0;
1823# endif
1824
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 /* First use any typeahead that was kept because "buf" was too small. */
1826 if (typeaheadlen > 0)
1827 goto theend;
1828
Bram Moolenaar071d4272004-06-13 20:20:40 +00001829 if (time >= 0)
1830 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001831 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 }
1834 else /* time == -1, wait forever */
1835 {
1836 mch_set_winsize_now(); /* Allow winsize changes from now on */
1837
Bram Moolenaar3918c952005-03-15 22:34:55 +00001838 /*
1839 * If there is no character available within 2 seconds (default)
1840 * write the autoscript file to disk. Or cause the CursorHold event
1841 * to be triggered.
1842 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001843 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001845 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001847 buf[0] = K_SPECIAL;
1848 buf[1] = KS_EXTRA;
1849 buf[2] = (int)KE_CURSORHOLD;
1850 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001852 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001853 }
1854 }
1855
1856 /*
1857 * Try to read as many characters as there are, until the buffer is full.
1858 */
1859
1860 /* we will get at least one key. Get more if they are available. */
1861 g_fCBrkPressed = FALSE;
1862
1863#ifdef MCH_WRITE_DUMP
1864 if (fdDump)
1865 fputc('[', fdDump);
1866#endif
1867
1868 /* Keep looping until there is something in the typeahead buffer and more
1869 * to get and still room in the buffer (up to two bytes for a char and
1870 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001871 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872 && typeaheadlen + 5 <= TYPEAHEADLEN)
1873 {
1874 if (typebuf_changed(tb_change_cnt))
1875 {
1876 /* "buf" may be invalid now if a client put something in the
1877 * typeahead buffer and "buf" is in the typeahead buffer. */
1878 typeaheadlen = 0;
1879 break;
1880 }
1881#ifdef FEAT_MOUSE
1882 if (g_nMouseClick != -1)
1883 {
1884# ifdef MCH_WRITE_DUMP
1885 if (fdDump)
1886 fprintf(fdDump, "{%02x @ %d, %d}",
1887 g_nMouseClick, g_xMouse, g_yMouse);
1888# endif
1889 typeahead[typeaheadlen++] = ESC + 128;
1890 typeahead[typeaheadlen++] = 'M';
1891 typeahead[typeaheadlen++] = g_nMouseClick;
1892 typeahead[typeaheadlen++] = g_xMouse + '!';
1893 typeahead[typeaheadlen++] = g_yMouse + '!';
1894 g_nMouseClick = -1;
1895 }
1896 else
1897#endif
1898 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001899 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900 int modifiers = 0;
1901
1902 c = tgetch(&modifiers, &ch2);
1903
1904 if (typebuf_changed(tb_change_cnt))
1905 {
1906 /* "buf" may be invalid now if a client put something in the
1907 * typeahead buffer and "buf" is in the typeahead buffer. */
1908 typeaheadlen = 0;
1909 break;
1910 }
1911
1912 if (c == Ctrl_C && ctrl_c_interrupts)
1913 {
1914#if defined(FEAT_CLIENTSERVER)
1915 trash_input_buf();
1916#endif
1917 got_int = TRUE;
1918 }
1919
1920#ifdef FEAT_MOUSE
1921 if (g_nMouseClick == -1)
1922#endif
1923 {
1924 int n = 1;
1925
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001926 if (ch2 == NUL)
1927 {
1928 int i;
1929 char_u *p;
1930 WCHAR ch[2];
1931
1932 ch[0] = c;
1933 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1934 {
1935 ch[1] = tgetch(&modifiers, &ch2);
1936 n++;
1937 }
1938 p = utf16_to_enc(ch, &n);
1939 if (p != NULL)
1940 {
1941 for (i = 0; i < n; i++)
1942 typeahead[typeaheadlen + i] = p[i];
1943 vim_free(p);
1944 }
1945 }
1946 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001947 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 if (ch2 != NUL)
1949 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001950 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001951 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001952 switch (ch2)
1953 {
1954 case (WCHAR)'\324': // SHIFT+Insert
1955 case (WCHAR)'\325': // CTRL+Insert
1956 case (WCHAR)'\327': // SHIFT+Delete
1957 case (WCHAR)'\330': // CTRL+Delete
1958 typeahead[typeaheadlen + n] = (char_u)ch2;
1959 n++;
1960 break;
1961
1962 default:
1963 typeahead[typeaheadlen + n] = 3;
1964 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1965 n += 2;
1966 break;
1967 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001968 }
1969 else
1970 {
1971 typeahead[typeaheadlen + n] = 3;
1972 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1973 n += 2;
1974 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001975 }
1976
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 /* Use the ALT key to set the 8th bit of the character
1978 * when it's one byte, the 8th bit isn't set yet and not
1979 * using a double-byte encoding (would become a lead
1980 * byte). */
1981 if ((modifiers & MOD_MASK_ALT)
1982 && n == 1
1983 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 )
1986 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001987 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1988 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989 modifiers &= ~MOD_MASK_ALT;
1990 }
1991
1992 if (modifiers != 0)
1993 {
1994 /* Prepend modifiers to the character. */
1995 mch_memmove(typeahead + typeaheadlen + 3,
1996 typeahead + typeaheadlen, n);
1997 typeahead[typeaheadlen++] = K_SPECIAL;
1998 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1999 typeahead[typeaheadlen++] = modifiers;
2000 }
2001
2002 typeaheadlen += n;
2003
2004#ifdef MCH_WRITE_DUMP
2005 if (fdDump)
2006 fputc(c, fdDump);
2007#endif
2008 }
2009 }
2010 }
2011
2012#ifdef MCH_WRITE_DUMP
2013 if (fdDump)
2014 {
2015 fputs("]\n", fdDump);
2016 fflush(fdDump);
2017 }
2018#endif
2019
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020theend:
2021 /* Move typeahead to "buf", as much as fits. */
2022 len = 0;
2023 while (len < maxlen && typeaheadlen > 0)
2024 {
2025 buf[len++] = typeahead[0];
2026 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2027 }
2028 return len;
2029
Bram Moolenaar4f974752019-02-17 17:44:42 +01002030#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 return 0;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002032#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033}
2034
Bram Moolenaar82881492012-11-20 16:53:39 +01002035#ifndef PROTO
2036# ifndef __MINGW32__
2037# include <shellapi.h> /* required for FindExecutable() */
2038# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039#endif
2040
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002041/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002042 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2043 * If "use_path" is FALSE: Return TRUE if "name" exists.
2044 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2045 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002046 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002047 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002049executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002051 WCHAR *p;
2052 WCHAR fnamew[_MAX_PATH];
2053 WCHAR *dumw;
2054 WCHAR *wcurpath, *wnewpath;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002055 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056
Bram Moolenaar43663192017-03-05 14:29:12 +01002057 if (!use_path)
2058 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002059 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002060 {
2061 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002062 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002063 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002064 *path = vim_strsave((char_u *)name);
2065 else
2066 *path = FullName_save((char_u *)name, FALSE);
2067 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002068 return TRUE;
2069 }
2070 return FALSE;
2071 }
2072
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002073 p = enc_to_utf16((char_u *)name, NULL);
2074 if (p == NULL)
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002075 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002076
2077 wcurpath = _wgetenv(L"PATH");
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002078 wnewpath = ALLOC_MULT(WCHAR, wcslen(wcurpath) + 3);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002079 if (wnewpath == NULL)
2080 return FALSE;
2081 wcscpy(wnewpath, L".;");
2082 wcscat(wnewpath, wcurpath);
2083 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2084 vim_free(wnewpath);
2085 vim_free(p);
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002086 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002087 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002088 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002089 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002090 if (path != NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002091 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002092 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093}
2094
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002095#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2096 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002097/*
2098 * Bad parameter handler.
2099 *
2100 * Certain MS CRT functions will intentionally crash when passed invalid
2101 * parameters to highlight possible security holes. Setting this function as
2102 * the bad parameter handler will prevent the crash.
2103 *
2104 * In debug builds the parameters contain CRT information that might help track
2105 * down the source of a problem, but in non-debug builds the arguments are all
2106 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2107 * worth allowing these to make debugging of issues easier.
2108 */
2109 static void
2110bad_param_handler(const wchar_t *expression,
2111 const wchar_t *function,
2112 const wchar_t *file,
2113 unsigned int line,
2114 uintptr_t pReserved)
2115{
2116}
2117
2118# define SET_INVALID_PARAM_HANDLER \
2119 ((void)_set_invalid_parameter_handler(bad_param_handler))
2120#else
2121# define SET_INVALID_PARAM_HANDLER
2122#endif
2123
Bram Moolenaar4f974752019-02-17 17:44:42 +01002124#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002125
2126/*
2127 * GUI version of mch_init().
2128 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002129 static void
2130mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131{
2132#ifndef __MINGW32__
2133 extern int _fmode;
2134#endif
2135
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002136 /* Silently handle invalid parameters to CRT functions */
2137 SET_INVALID_PARAM_HANDLER;
2138
Bram Moolenaar071d4272004-06-13 20:20:40 +00002139 /* Let critical errors result in a failure, not in a dialog box. Required
2140 * for the timestamp test to work on removed floppies. */
2141 SetErrorMode(SEM_FAILCRITICALERRORS);
2142
2143 _fmode = O_BINARY; /* we do our own CR-LF translation */
2144
2145 /* Specify window size. Is there a place to get the default from? */
2146 Rows = 25;
2147 Columns = 80;
2148
2149 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002150 {
2151 char_u vimrun_location[_MAX_PATH + 4];
2152
2153 /* First try in same directory as gvim.exe */
2154 STRCPY(vimrun_location, exe_name);
2155 STRCPY(gettail(vimrun_location), "vimrun.exe");
2156 if (mch_getperm(vimrun_location) >= 0)
2157 {
2158 if (*skiptowhite(vimrun_location) != NUL)
2159 {
2160 /* Enclose path with white space in double quotes. */
2161 mch_memmove(vimrun_location + 1, vimrun_location,
2162 STRLEN(vimrun_location) + 1);
2163 *vimrun_location = '"';
2164 STRCPY(gettail(vimrun_location), "vimrun\" ");
2165 }
2166 else
2167 STRCPY(gettail(vimrun_location), "vimrun ");
2168
2169 vimrun_path = (char *)vim_strsave(vimrun_location);
2170 s_dont_use_vimrun = FALSE;
2171 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002172 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173 s_dont_use_vimrun = FALSE;
2174
2175 /* Don't give the warning for a missing vimrun.exe right now, but only
2176 * when vimrun was supposed to be used. Don't bother people that do
2177 * not need vimrun.exe. */
2178 if (s_dont_use_vimrun)
2179 need_vimrun_warning = TRUE;
2180 }
2181
2182 /*
2183 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2184 * Otherwise the default "findstr /n" is used.
2185 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002186 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002187 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2188
2189#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002190 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002191#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002192
2193 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194}
2195
2196
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002197#endif /* FEAT_GUI_MSWIN */
2198
2199#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200
2201#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2202#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2203
2204/*
2205 * ClearConsoleBuffer()
2206 * Description:
2207 * Clears the entire contents of the console screen buffer, using the
2208 * specified attribute.
2209 * Returns:
2210 * TRUE on success
2211 */
2212 static BOOL
2213ClearConsoleBuffer(WORD wAttribute)
2214{
2215 CONSOLE_SCREEN_BUFFER_INFO csbi;
2216 COORD coord;
2217 DWORD NumCells, dummy;
2218
2219 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2220 return FALSE;
2221
2222 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2223 coord.X = 0;
2224 coord.Y = 0;
2225 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2226 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002227 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2229 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231
2232 return TRUE;
2233}
2234
2235/*
2236 * FitConsoleWindow()
2237 * Description:
2238 * Checks if the console window will fit within given buffer dimensions.
2239 * Also, if requested, will shrink the window to fit.
2240 * Returns:
2241 * TRUE on success
2242 */
2243 static BOOL
2244FitConsoleWindow(
2245 COORD dwBufferSize,
2246 BOOL WantAdjust)
2247{
2248 CONSOLE_SCREEN_BUFFER_INFO csbi;
2249 COORD dwWindowSize;
2250 BOOL NeedAdjust = FALSE;
2251
2252 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2253 {
2254 /*
2255 * A buffer resize will fail if the current console window does
2256 * not lie completely within that buffer. To avoid this, we might
2257 * have to move and possibly shrink the window.
2258 */
2259 if (csbi.srWindow.Right >= dwBufferSize.X)
2260 {
2261 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2262 if (dwWindowSize.X > dwBufferSize.X)
2263 dwWindowSize.X = dwBufferSize.X;
2264 csbi.srWindow.Right = dwBufferSize.X - 1;
2265 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2266 NeedAdjust = TRUE;
2267 }
2268 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2269 {
2270 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2271 if (dwWindowSize.Y > dwBufferSize.Y)
2272 dwWindowSize.Y = dwBufferSize.Y;
2273 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2274 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2275 NeedAdjust = TRUE;
2276 }
2277 if (NeedAdjust && WantAdjust)
2278 {
2279 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2280 return FALSE;
2281 }
2282 return TRUE;
2283 }
2284
2285 return FALSE;
2286}
2287
2288typedef struct ConsoleBufferStruct
2289{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002290 BOOL IsValid;
2291 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002292 PCHAR_INFO Buffer;
2293 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002294 PSMALL_RECT Regions;
2295 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296} ConsoleBuffer;
2297
2298/*
2299 * SaveConsoleBuffer()
2300 * Description:
2301 * Saves important information about the console buffer, including the
2302 * actual buffer contents. The saved information is suitable for later
2303 * restoration by RestoreConsoleBuffer().
2304 * Returns:
2305 * TRUE if all information was saved; FALSE otherwise
2306 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2307 */
2308 static BOOL
2309SaveConsoleBuffer(
2310 ConsoleBuffer *cb)
2311{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002312 DWORD NumCells;
2313 COORD BufferCoord;
2314 SMALL_RECT ReadRegion;
2315 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002316 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002317
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 if (cb == NULL)
2319 return FALSE;
2320
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002321 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322 {
2323 cb->IsValid = FALSE;
2324 return FALSE;
2325 }
2326 cb->IsValid = TRUE;
2327
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002328 /*
2329 * Allocate a buffer large enough to hold the entire console screen
2330 * buffer. If this ConsoleBuffer structure has already been initialized
2331 * with a buffer of the correct size, then just use that one.
2332 */
2333 if (!cb->IsValid || cb->Buffer == NULL ||
2334 cb->BufferSize.X != cb->Info.dwSize.X ||
2335 cb->BufferSize.Y != cb->Info.dwSize.Y)
2336 {
2337 cb->BufferSize.X = cb->Info.dwSize.X;
2338 cb->BufferSize.Y = cb->Info.dwSize.Y;
2339 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2340 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002341 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002342 if (cb->Buffer == NULL)
2343 return FALSE;
2344 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345
2346 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002347 * We will now copy the console screen buffer into our buffer.
2348 * ReadConsoleOutput() seems to be limited as far as how much you
2349 * can read at a time. Empirically, this number seems to be about
2350 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2351 * in chunks until it is all copied. The chunks will all have the
2352 * same horizontal characteristics, so initialize them now. The
2353 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002355 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002356 ReadRegion.Left = 0;
2357 ReadRegion.Right = cb->Info.dwSize.X - 1;
2358 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002359
2360 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2361 if (cb->Regions == NULL || numregions != cb->NumRegions)
2362 {
2363 cb->NumRegions = numregions;
2364 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002365 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002366 if (cb->Regions == NULL)
2367 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002368 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002369 return FALSE;
2370 }
2371 }
2372
2373 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002375 /*
2376 * Read into position (0, Y) in our buffer.
2377 */
2378 BufferCoord.Y = Y;
2379 /*
2380 * Read the region whose top left corner is (0, Y) and whose bottom
2381 * right corner is (width - 1, Y + Y_incr - 1). This should define
2382 * a region of size width by Y_incr. Don't worry if this region is
2383 * too large for the remaining buffer; it will be cropped.
2384 */
2385 ReadRegion.Top = Y;
2386 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002387 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002388 cb->Buffer, /* our buffer */
2389 cb->BufferSize, /* dimensions of our buffer */
2390 BufferCoord, /* offset in our buffer */
2391 &ReadRegion)) /* region to save */
2392 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002393 VIM_CLEAR(cb->Buffer);
2394 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002395 return FALSE;
2396 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002397 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 }
2399
2400 return TRUE;
2401}
2402
2403/*
2404 * RestoreConsoleBuffer()
2405 * Description:
2406 * Restores important information about the console buffer, including the
2407 * actual buffer contents, if desired. The information to restore is in
2408 * the same format used by SaveConsoleBuffer().
2409 * Returns:
2410 * TRUE on success
2411 */
2412 static BOOL
2413RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002414 ConsoleBuffer *cb,
2415 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002417 COORD BufferCoord;
2418 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002419 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420
2421 if (cb == NULL || !cb->IsValid)
2422 return FALSE;
2423
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002424 /*
2425 * Before restoring the buffer contents, clear the current buffer, and
2426 * restore the cursor position and window information. Doing this now
2427 * prevents old buffer contents from "flashing" onto the screen.
2428 */
2429 if (RestoreScreen)
2430 ClearConsoleBuffer(cb->Info.wAttributes);
2431
2432 FitConsoleWindow(cb->Info.dwSize, TRUE);
2433 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2434 return FALSE;
2435 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2436 return FALSE;
2437
2438 if (!RestoreScreen)
2439 {
2440 /*
2441 * No need to restore the screen buffer contents, so we're done.
2442 */
2443 return TRUE;
2444 }
2445
2446 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2447 return FALSE;
2448 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2449 return FALSE;
2450
2451 /*
2452 * Restore the screen buffer contents.
2453 */
2454 if (cb->Buffer != NULL)
2455 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002456 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002457 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002458 BufferCoord.X = cb->Regions[i].Left;
2459 BufferCoord.Y = cb->Regions[i].Top;
2460 WriteRegion = cb->Regions[i];
2461 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2462 cb->Buffer, /* our buffer */
2463 cb->BufferSize, /* dimensions of our buffer */
2464 BufferCoord, /* offset in our buffer */
2465 &WriteRegion)) /* region to restore */
Bram Moolenaar444fda22017-08-11 20:37:00 +02002466 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002467 }
2468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469
2470 return TRUE;
2471}
2472
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002473#define FEAT_RESTORE_ORIG_SCREEN
2474#ifdef FEAT_RESTORE_ORIG_SCREEN
2475static ConsoleBuffer g_cbOrig = { 0 };
2476#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477static ConsoleBuffer g_cbNonTermcap = { 0 };
2478static ConsoleBuffer g_cbTermcap = { 0 };
2479
2480#ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481char g_szOrigTitle[256] = { 0 };
2482HWND g_hWnd = NULL; /* also used in os_mswin.c */
2483static HICON g_hOrigIconSmall = NULL;
2484static HICON g_hOrigIcon = NULL;
2485static HICON g_hVimIcon = NULL;
2486static BOOL g_fCanChangeIcon = FALSE;
2487
2488/* ICON* are not defined in VC++ 4.0 */
2489#ifndef ICON_SMALL
2490#define ICON_SMALL 0
2491#endif
2492#ifndef ICON_BIG
2493#define ICON_BIG 1
2494#endif
2495/*
2496 * GetConsoleIcon()
2497 * Description:
2498 * Attempts to retrieve the small icon and/or the big icon currently in
2499 * use by a given window.
2500 * Returns:
2501 * TRUE on success
2502 */
2503 static BOOL
2504GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002505 HWND hWnd,
2506 HICON *phIconSmall,
2507 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508{
2509 if (hWnd == NULL)
2510 return FALSE;
2511
2512 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002513 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2514 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002516 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2517 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 return TRUE;
2519}
2520
2521/*
2522 * SetConsoleIcon()
2523 * Description:
2524 * Attempts to change the small icon and/or the big icon currently in
2525 * use by a given window.
2526 * Returns:
2527 * TRUE on success
2528 */
2529 static BOOL
2530SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002531 HWND hWnd,
2532 HICON hIconSmall,
2533 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 if (hWnd == NULL)
2536 return FALSE;
2537
2538 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002539 SendMessage(hWnd, WM_SETICON,
2540 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002542 SendMessage(hWnd, WM_SETICON,
2543 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 return TRUE;
2545}
2546
2547/*
2548 * SaveConsoleTitleAndIcon()
2549 * Description:
2550 * Saves the current console window title in g_szOrigTitle, for later
2551 * restoration. Also, attempts to obtain a handle to the console window,
2552 * and use it to save the small and big icons currently in use by the
2553 * console window. This is not always possible on some versions of Windows;
2554 * nor is it possible when running Vim remotely using Telnet (since the
2555 * console window the user sees is owned by a remote process).
2556 */
2557 static void
2558SaveConsoleTitleAndIcon(void)
2559{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560 /* Save the original title. */
2561 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2562 return;
2563
2564 /*
2565 * Obtain a handle to the console window using GetConsoleWindow() from
2566 * KERNEL32.DLL; we need to handle in order to change the window icon.
2567 * This function only exists on NT-based Windows, starting with Windows
2568 * 2000. On older operating systems, we can't change the window icon
2569 * anyway.
2570 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002571 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 if (g_hWnd == NULL)
2573 return;
2574
2575 /* Save the original console window icon. */
2576 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2577 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2578 return;
2579
2580 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002581 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002582 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002583 if (g_hVimIcon != NULL)
2584 g_fCanChangeIcon = TRUE;
2585}
2586#endif
2587
2588static int g_fWindInitCalled = FALSE;
2589static int g_fTermcapMode = FALSE;
2590static CONSOLE_CURSOR_INFO g_cci;
2591static DWORD g_cmodein = 0;
2592static DWORD g_cmodeout = 0;
2593
2594/*
2595 * non-GUI version of mch_init().
2596 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002597 static void
2598mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002600#ifndef FEAT_RESTORE_ORIG_SCREEN
2601 CONSOLE_SCREEN_BUFFER_INFO csbi;
2602#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603#ifndef __MINGW32__
2604 extern int _fmode;
2605#endif
2606
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002607 /* Silently handle invalid parameters to CRT functions */
2608 SET_INVALID_PARAM_HANDLER;
2609
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610 /* Let critical errors result in a failure, not in a dialog box. Required
2611 * for the timestamp test to work on removed floppies. */
2612 SetErrorMode(SEM_FAILCRITICALERRORS);
2613
2614 _fmode = O_BINARY; /* we do our own CR-LF translation */
2615 out_flush();
2616
2617 /* Obtain handles for the standard Console I/O devices */
2618 if (read_cmd_fd == 0)
2619 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2620 else
2621 create_conin();
2622 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2623
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002624#ifdef FEAT_RESTORE_ORIG_SCREEN
2625 /* Save the initial console buffer for later restoration */
2626 SaveConsoleBuffer(&g_cbOrig);
2627 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2628#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002629 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002630 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2631 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2632#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633 if (cterm_normal_fg_color == 0)
2634 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2635 if (cterm_normal_bg_color == 0)
2636 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2637
Bram Moolenaarbdace832019-03-02 10:13:42 +01002638 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002639 g_color_index_fg = g_attrDefault & 0xf;
2640 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2641
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 /* set termcap codes to current text attributes */
2643 update_tcap(g_attrCurrent);
2644
2645 GetConsoleCursorInfo(g_hConOut, &g_cci);
2646 GetConsoleMode(g_hConIn, &g_cmodein);
2647 GetConsoleMode(g_hConOut, &g_cmodeout);
2648
2649#ifdef FEAT_TITLE
2650 SaveConsoleTitleAndIcon();
2651 /*
2652 * Set both the small and big icons of the console window to Vim's icon.
2653 * Note that Vim presently only has one size of icon (32x32), but it
2654 * automatically gets scaled down to 16x16 when setting the small icon.
2655 */
2656 if (g_fCanChangeIcon)
2657 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2658#endif
2659
2660 ui_get_shellsize();
2661
2662#ifdef MCH_WRITE_DUMP
2663 fdDump = fopen("dump", "wt");
2664
2665 if (fdDump)
2666 {
2667 time_t t;
2668
2669 time(&t);
2670 fputs(ctime(&t), fdDump);
2671 fflush(fdDump);
2672 }
2673#endif
2674
2675 g_fWindInitCalled = TRUE;
2676
2677#ifdef FEAT_MOUSE
2678 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2679#endif
2680
2681#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002682 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002684
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002685 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002686 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687}
2688
2689/*
2690 * non-GUI version of mch_exit().
2691 * Shut down and exit with status `r'
2692 * Careful: mch_exit() may be called before mch_init()!
2693 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002694 static void
2695mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002696{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002697 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002698
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002699 vtp_exit();
2700
Bram Moolenaar955f1982017-02-05 15:10:51 +01002701 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702 if (g_fWindInitCalled)
2703 settmode(TMODE_COOK);
2704
2705 ml_close_all(TRUE); /* remove all memfiles */
2706
2707 if (g_fWindInitCalled)
2708 {
2709#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002710 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 /*
2712 * Restore both the small and big icons of the console window to
2713 * what they were at startup. Don't do this when the window is
2714 * closed, Vim would hang here.
2715 */
2716 if (g_fCanChangeIcon && !g_fForceExit)
2717 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2718#endif
2719
2720#ifdef MCH_WRITE_DUMP
2721 if (fdDump)
2722 {
2723 time_t t;
2724
2725 time(&t);
2726 fputs(ctime(&t), fdDump);
2727 fclose(fdDump);
2728 }
2729 fdDump = NULL;
2730#endif
2731 }
2732
2733 SetConsoleCursorInfo(g_hConOut, &g_cci);
2734 SetConsoleMode(g_hConIn, g_cmodein);
2735 SetConsoleMode(g_hConOut, g_cmodeout);
2736
2737#ifdef DYNAMIC_GETTEXT
2738 dyn_libintl_end();
2739#endif
2740
2741 exit(r);
2742}
Bram Moolenaar4f974752019-02-17 17:44:42 +01002743#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002745 void
2746mch_init(void)
2747{
2748#ifdef VIMDLL
2749 if (gui.starting)
2750 mch_init_g();
2751 else
2752 mch_init_c();
2753#elif defined(FEAT_GUI_MSWIN)
2754 mch_init_g();
2755#else
2756 mch_init_c();
2757#endif
2758}
2759
2760 void
2761mch_exit(int r)
2762{
2763#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002764 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002765 mch_exit_g(r);
2766 else
2767 mch_exit_c(r);
2768#elif defined(FEAT_GUI_MSWIN)
2769 mch_exit_g(r);
2770#else
2771 mch_exit_c(r);
2772#endif
2773}
2774
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775/*
2776 * Do we have an interactive window?
2777 */
2778 int
2779mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002780 int argc UNUSED,
2781 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782{
2783 get_exe_name();
2784
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002785#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786 return OK; /* GUI always has a tty */
2787#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002788# ifdef VIMDLL
2789 if (gui.in_use)
2790 return OK;
2791# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792 if (isatty(1))
2793 return OK;
2794 return FAIL;
2795#endif
2796}
2797
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002798/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002799 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 * When "len" is > 0, also expand short to long filenames.
2801 */
2802 void
2803fname_case(
2804 char_u *name,
2805 int len)
2806{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002807 int flen;
2808 WCHAR *p;
2809 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002811 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002812 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002813 return;
2814
2815 slash_adjust(name);
2816
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002817 p = enc_to_utf16(name, NULL);
2818 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002819 return;
2820
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002821 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002823 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002825 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002826 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002827 if (len > 0 || flen >= (int)STRLEN(q))
2828 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2829 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002830 }
2831 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002832 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833}
2834
2835
2836/*
2837 * Insert user name in s[len].
2838 */
2839 int
2840mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002841 char_u *s,
2842 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002844 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2845 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002847 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002848 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002849 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002850
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002851 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002852 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002853 vim_strncpy(s, p, len - 1);
2854 vim_free(p);
2855 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002856 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002857 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858 s[0] = NUL;
2859 return FAIL;
2860}
2861
2862
2863/*
2864 * Insert host name in s[len].
2865 */
2866 void
2867mch_get_host_name(
2868 char_u *s,
2869 int len)
2870{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002871 WCHAR wszHostName[256 + 1];
2872 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002874 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002875 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002876 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002877
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002878 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002879 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002880 vim_strncpy(s, p, len - 1);
2881 vim_free(p);
2882 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002883 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002884 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885}
2886
2887
2888/*
2889 * return process ID
2890 */
2891 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002892mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893{
2894 return (long)GetCurrentProcessId();
2895}
2896
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002897/*
2898 * return TRUE if process "pid" is still running
2899 */
2900 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02002901mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002902{
2903 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
2904 DWORD status = 0;
2905 int ret = FALSE;
2906
2907 if (hProcess == NULL)
2908 return FALSE; // might not have access
2909 if (GetExitCodeProcess(hProcess, &status) )
2910 ret = status == STILL_ACTIVE;
2911 CloseHandle(hProcess);
2912 return ret;
2913}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914
2915/*
2916 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2917 * Return OK for success, FAIL for failure.
2918 */
2919 int
2920mch_dirname(
2921 char_u *buf,
2922 int len)
2923{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002924 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002925
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 /*
2927 * Originally this was:
2928 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2929 * But the Win32s known bug list says that getcwd() doesn't work
2930 * so use the Win32 system call instead. <Negri>
2931 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002932 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002934 WCHAR wcbuf[_MAX_PATH + 1];
2935 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002937 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002938 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002939 p = utf16_to_enc(wcbuf, NULL);
2940 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002941 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002942 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002944 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945 }
2946 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002947 if (p == NULL)
2948 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002949
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002950 if (p != NULL)
2951 {
2952 vim_strncpy(buf, p, len - 1);
2953 vim_free(p);
2954 return OK;
2955 }
2956 }
2957 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958}
2959
2960/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002961 * Get file permissions for "name".
2962 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963 */
2964 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002965mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002967 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002968 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002970 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002971 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972}
2973
2974
2975/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002976 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002977 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002978 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 */
2980 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002981mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002983 long n;
2984 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002985
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002986 p = enc_to_utf16(name, NULL);
2987 if (p == NULL)
2988 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002990 n = _wchmod(p, perm);
2991 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002992 if (n == -1)
2993 return FAIL;
2994
2995 win32_set_archive(name);
2996
2997 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998}
2999
3000/*
3001 * Set hidden flag for "name".
3002 */
3003 void
3004mch_hide(char_u *name)
3005{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003006 int attrs = win32_getattrs(name);
3007 if (attrs == -1)
3008 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003010 attrs |= FILE_ATTRIBUTE_HIDDEN;
3011 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012}
3013
3014/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003015 * Return TRUE if file "name" exists and is hidden.
3016 */
3017 int
3018mch_ishidden(char_u *name)
3019{
3020 int f = win32_getattrs(name);
3021
3022 if (f == -1)
3023 return FALSE; /* file does not exist at all */
3024
3025 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3026}
3027
3028/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029 * return TRUE if "name" is a directory
3030 * return FALSE if "name" is not a directory or upon error
3031 */
3032 int
3033mch_isdir(char_u *name)
3034{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003035 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036
3037 if (f == -1)
3038 return FALSE; /* file does not exist at all */
3039
3040 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3041}
3042
3043/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003044 * return TRUE if "name" is a directory, NOT a symlink to a directory
3045 * return FALSE if "name" is not a directory
3046 * return FALSE for error
3047 */
3048 int
3049mch_isrealdir(char_u *name)
3050{
3051 return mch_isdir(name) && !mch_is_symbolic_link(name);
3052}
3053
3054/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003055 * Create directory "name".
3056 * Return 0 on success, -1 on error.
3057 */
3058 int
3059mch_mkdir(char_u *name)
3060{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003061 WCHAR *p;
3062 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003063
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003064 p = enc_to_utf16(name, NULL);
3065 if (p == NULL)
3066 return -1;
3067 retval = _wmkdir(p);
3068 vim_free(p);
3069 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003070}
3071
3072/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003073 * Delete directory "name".
3074 * Return 0 on success, -1 on error.
3075 */
3076 int
3077mch_rmdir(char_u *name)
3078{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003079 WCHAR *p;
3080 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003081
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003082 p = enc_to_utf16(name, NULL);
3083 if (p == NULL)
3084 return -1;
3085 retval = _wrmdir(p);
3086 vim_free(p);
3087 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003088}
3089
3090/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003091 * Return TRUE if file "fname" has more than one link.
3092 */
3093 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003094mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003095{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003096 BY_HANDLE_FILE_INFORMATION info;
3097
3098 return win32_fileinfo(fname, &info) == FILEINFO_OK
3099 && info.nNumberOfLinks > 1;
3100}
3101
3102/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003103 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003104 */
3105 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003106mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003107{
3108 HANDLE hFind;
3109 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003110 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003111 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003112 WIN32_FIND_DATAW findDataW;
3113
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003114 wn = enc_to_utf16(name, NULL);
3115 if (wn == NULL)
3116 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003117
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003118 hFind = FindFirstFileW(wn, &findDataW);
3119 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003120 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003121 {
3122 fileFlags = findDataW.dwFileAttributes;
3123 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003124 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003125 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003126
3127 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003128 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3129 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003130 res = TRUE;
3131
3132 return res;
3133}
3134
3135/*
3136 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3137 * link.
3138 */
3139 int
3140mch_is_linked(char_u *fname)
3141{
3142 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3143 return TRUE;
3144 return FALSE;
3145}
3146
3147/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003148 * Get the by-handle-file-information for "fname".
3149 * Returns FILEINFO_OK when OK.
3150 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3151 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3152 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3153 */
3154 int
3155win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3156{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003157 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003158 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003159 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003160
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003161 wn = enc_to_utf16(fname, NULL);
3162 if (wn == NULL)
3163 return FILEINFO_ENC_FAIL;
3164
3165 hFile = CreateFileW(wn, // file name
3166 GENERIC_READ, // access mode
3167 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3168 NULL, // security descriptor
3169 OPEN_EXISTING, // creation disposition
3170 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3171 NULL); // handle to template file
3172 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003173
3174 if (hFile != INVALID_HANDLE_VALUE)
3175 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003176 if (GetFileInformationByHandle(hFile, info) != 0)
3177 res = FILEINFO_OK;
3178 else
3179 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003180 CloseHandle(hFile);
3181 }
3182
Bram Moolenaar03f48552006-02-28 23:52:23 +00003183 return res;
3184}
3185
3186/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003187 * get file attributes for `name'
3188 * -1 : error
3189 * else FILE_ATTRIBUTE_* defined in winnt.h
3190 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003191 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003192win32_getattrs(char_u *name)
3193{
3194 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003195 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003196
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003197 p = enc_to_utf16(name, NULL);
3198 if (p == NULL)
3199 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003200
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003201 attr = GetFileAttributesW(p);
3202 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003203
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003204 return attr;
3205}
3206
3207/*
3208 * set file attributes for `name' to `attrs'
3209 *
3210 * return -1 for failure, 0 otherwise
3211 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003212 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003213win32_setattrs(char_u *name, int attrs)
3214{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003215 int res;
3216 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003217
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003218 p = enc_to_utf16(name, NULL);
3219 if (p == NULL)
3220 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003221
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003222 res = SetFileAttributesW(p, attrs);
3223 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003224
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003225 return res ? 0 : -1;
3226}
3227
3228/*
3229 * Set archive flag for "name".
3230 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003231 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003232win32_set_archive(char_u *name)
3233{
3234 int attrs = win32_getattrs(name);
3235 if (attrs == -1)
3236 return -1;
3237
3238 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3239 return win32_setattrs(name, attrs);
3240}
3241
3242/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 * Return TRUE if file or directory "name" is writable (not readonly).
3244 * Strange semantics of Win32: a readonly directory is writable, but you can't
3245 * delete a file. Let's say this means it is writable.
3246 */
3247 int
3248mch_writable(char_u *name)
3249{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003250 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003252 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3253 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254}
3255
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003257 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003258 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003259 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3260 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 */
3262 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003263mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264{
Bram Moolenaar86621892019-03-30 21:51:28 +01003265 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
3266 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
3267 // UTF-8.
3268 char_u buf[_MAX_PATH * 3];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003269 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003270 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003271
Bram Moolenaar86621892019-03-30 21:51:28 +01003272 if (len >= sizeof(buf)) // safety check
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003273 return FALSE;
3274
Bram Moolenaar86621892019-03-30 21:51:28 +01003275 // Try using the name directly when a Unix-shell like 'shell'.
Bram Moolenaar82956662018-10-06 15:18:45 +02003276 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003277 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003278 return TRUE;
3279
3280 /*
3281 * Loop over all extensions in $PATHEXT.
3282 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003283 p = mch_getenv("PATHEXT");
3284 if (p == NULL)
3285 p = (char_u *)".com;.exe;.bat;.cmd";
3286 saved = vim_strsave(p);
3287 if (saved == NULL)
3288 return FALSE;
3289 p = saved;
3290 while (*p)
3291 {
3292 char_u *tmp = vim_strchr(p, ';');
3293
3294 if (tmp != NULL)
3295 *tmp = NUL;
3296 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3297 && executable_exists((char *)name, path, use_path))
3298 {
3299 vim_free(saved);
3300 return TRUE;
3301 }
3302 if (tmp == NULL)
3303 break;
3304 p = tmp + 1;
3305 }
3306 vim_free(saved);
3307
Bram Moolenaar86621892019-03-30 21:51:28 +01003308 vim_strncpy(buf, name, sizeof(buf) - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003309 p = mch_getenv("PATHEXT");
3310 if (p == NULL)
3311 p = (char_u *)".com;.exe;.bat;.cmd";
3312 while (*p)
3313 {
3314 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3315 {
3316 /* A single "." means no extension is added. */
3317 buf[len] = NUL;
3318 ++p;
3319 if (*p)
3320 ++p;
3321 }
3322 else
Bram Moolenaar86621892019-03-30 21:51:28 +01003323 copy_option_part(&p, buf + len, sizeof(buf) - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003324 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003325 return TRUE;
3326 }
3327 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003329
3330/*
3331 * Check what "name" is:
3332 * NODE_NORMAL: file or directory (or doesn't exist)
3333 * NODE_WRITABLE: writable device, socket, fifo, etc.
3334 * NODE_OTHER: non-writable things
3335 */
3336 int
3337mch_nodetype(char_u *name)
3338{
3339 HANDLE hFile;
3340 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003341 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342
Bram Moolenaar043545e2006-10-10 16:44:07 +00003343 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3344 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3345 * here. */
3346 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3347 return NODE_WRITABLE;
3348
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003349 wn = enc_to_utf16(name, NULL);
3350 if (wn == NULL)
3351 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003352
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003353 hFile = CreateFileW(wn, // file name
3354 GENERIC_WRITE, // access mode
3355 0, // share mode
3356 NULL, // security descriptor
3357 OPEN_EXISTING, // creation disposition
3358 0, // file attributes
3359 NULL); // handle to template file
3360 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003361 if (hFile == INVALID_HANDLE_VALUE)
3362 return NODE_NORMAL;
3363
3364 type = GetFileType(hFile);
3365 CloseHandle(hFile);
3366 if (type == FILE_TYPE_CHAR)
3367 return NODE_WRITABLE;
3368 if (type == FILE_TYPE_DISK)
3369 return NODE_NORMAL;
3370 return NODE_OTHER;
3371}
3372
3373#ifdef HAVE_ACL
3374struct my_acl
3375{
3376 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3377 PSID pSidOwner;
3378 PSID pSidGroup;
3379 PACL pDacl;
3380 PACL pSacl;
3381};
3382#endif
3383
3384/*
3385 * Return a pointer to the ACL of file "fname" in allocated memory.
3386 * Return NULL if the ACL is not available for whatever reason.
3387 */
3388 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003389mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003390{
3391#ifndef HAVE_ACL
3392 return (vim_acl_T)NULL;
3393#else
3394 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003395 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003396
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003397 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003398 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003400 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003401
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003402 wn = enc_to_utf16(fname, NULL);
3403 if (wn == NULL)
3404 return NULL;
3405
3406 // Try to retrieve the entire security descriptor.
3407 err = GetNamedSecurityInfoW(
3408 wn, // Abstract filename
3409 SE_FILE_OBJECT, // File Object
3410 OWNER_SECURITY_INFORMATION |
3411 GROUP_SECURITY_INFORMATION |
3412 DACL_SECURITY_INFORMATION |
3413 SACL_SECURITY_INFORMATION,
3414 &p->pSidOwner, // Ownership information.
3415 &p->pSidGroup, // Group membership.
3416 &p->pDacl, // Discretionary information.
3417 &p->pSacl, // For auditing purposes.
3418 &p->pSecurityDescriptor);
3419 if (err == ERROR_ACCESS_DENIED ||
3420 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003421 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003422 // Retrieve only DACL.
3423 (void)GetNamedSecurityInfoW(
3424 wn,
3425 SE_FILE_OBJECT,
3426 DACL_SECURITY_INFORMATION,
3427 NULL,
3428 NULL,
3429 &p->pDacl,
3430 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003431 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003432 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003433 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003434 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003435 mch_free_acl((vim_acl_T)p);
3436 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003438 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 }
3440
3441 return (vim_acl_T)p;
3442#endif
3443}
3444
Bram Moolenaar27515922013-06-29 15:36:26 +02003445#ifdef HAVE_ACL
3446/*
3447 * Check if "acl" contains inherited ACE.
3448 */
3449 static BOOL
3450is_acl_inherited(PACL acl)
3451{
3452 DWORD i;
3453 ACL_SIZE_INFORMATION acl_info;
3454 PACCESS_ALLOWED_ACE ace;
3455
3456 acl_info.AceCount = 0;
3457 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3458 for (i = 0; i < acl_info.AceCount; i++)
3459 {
3460 GetAce(acl, i, (LPVOID *)&ace);
3461 if (ace->Header.AceFlags & INHERITED_ACE)
3462 return TRUE;
3463 }
3464 return FALSE;
3465}
3466#endif
3467
Bram Moolenaar071d4272004-06-13 20:20:40 +00003468/*
3469 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3470 * Errors are ignored.
3471 * This must only be called with "acl" equal to what mch_get_acl() returned.
3472 */
3473 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003474mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475{
3476#ifdef HAVE_ACL
3477 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003478 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003479 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003480
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003481 if (p == NULL)
3482 return;
3483
3484 wn = enc_to_utf16(fname, NULL);
3485 if (wn == NULL)
3486 return;
3487
3488 // Set security flags
3489 if (p->pSidOwner)
3490 sec_info |= OWNER_SECURITY_INFORMATION;
3491 if (p->pSidGroup)
3492 sec_info |= GROUP_SECURITY_INFORMATION;
3493 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003494 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003495 sec_info |= DACL_SECURITY_INFORMATION;
3496 // Do not inherit its parent's DACL.
3497 // If the DACL is inherited, Cygwin permissions would be changed.
3498 if (!is_acl_inherited(p->pDacl))
3499 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003500 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003501 if (p->pSacl)
3502 sec_info |= SACL_SECURITY_INFORMATION;
3503
3504 (void)SetNamedSecurityInfoW(
3505 wn, // Abstract filename
3506 SE_FILE_OBJECT, // File Object
3507 sec_info,
3508 p->pSidOwner, // Ownership information.
3509 p->pSidGroup, // Group membership.
3510 p->pDacl, // Discretionary information.
3511 p->pSacl // For auditing purposes.
3512 );
3513 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514#endif
3515}
3516
3517 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003518mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519{
3520#ifdef HAVE_ACL
3521 struct my_acl *p = (struct my_acl *)acl;
3522
3523 if (p != NULL)
3524 {
3525 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3526 vim_free(p);
3527 }
3528#endif
3529}
3530
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003531#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532
3533/*
3534 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3535 */
3536 static BOOL WINAPI
3537handler_routine(
3538 DWORD dwCtrlType)
3539{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003540 INPUT_RECORD ir;
3541 DWORD out;
3542
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543 switch (dwCtrlType)
3544 {
3545 case CTRL_C_EVENT:
3546 if (ctrl_c_interrupts)
3547 g_fCtrlCPressed = TRUE;
3548 return TRUE;
3549
3550 case CTRL_BREAK_EVENT:
3551 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003552 ctrl_break_was_pressed = TRUE;
3553 /* ReadConsoleInput is blocking, send a key event to continue. */
3554 ir.EventType = KEY_EVENT;
3555 ir.Event.KeyEvent.bKeyDown = TRUE;
3556 ir.Event.KeyEvent.wRepeatCount = 1;
3557 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3558 ir.Event.KeyEvent.wVirtualScanCode = 0;
3559 ir.Event.KeyEvent.dwControlKeyState = 0;
3560 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3561 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003562 return TRUE;
3563
3564 /* fatal events: shut down gracefully */
3565 case CTRL_CLOSE_EVENT:
3566 case CTRL_LOGOFF_EVENT:
3567 case CTRL_SHUTDOWN_EVENT:
3568 windgoto((int)Rows - 1, 0);
3569 g_fForceExit = TRUE;
3570
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003571 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 (dwCtrlType == CTRL_CLOSE_EVENT
3573 ? _("close")
3574 : dwCtrlType == CTRL_LOGOFF_EVENT
3575 ? _("logoff")
3576 : _("shutdown")));
3577#ifdef DEBUG
3578 OutputDebugString(IObuff);
3579#endif
3580
3581 preserve_exit(); /* output IObuff, preserve files and exit */
3582
3583 return TRUE; /* not reached */
3584
3585 default:
3586 return FALSE;
3587 }
3588}
3589
3590
3591/*
3592 * set the tty in (raw) ? "raw" : "cooked" mode
3593 */
3594 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003595mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596{
3597 DWORD cmodein;
3598 DWORD cmodeout;
3599 BOOL bEnableHandler;
3600
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003601# ifdef VIMDLL
3602 if (gui.in_use)
3603 return;
3604# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 GetConsoleMode(g_hConIn, &cmodein);
3606 GetConsoleMode(g_hConOut, &cmodeout);
3607 if (tmode == TMODE_RAW)
3608 {
3609 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3610 ENABLE_ECHO_INPUT);
3611#ifdef FEAT_MOUSE
3612 if (g_fMouseActive)
3613 cmodein |= ENABLE_MOUSE_INPUT;
3614#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003615 cmodeout &= ~(
3616#ifdef FEAT_TERMGUICOLORS
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003617 /* Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003618 * VTP. */
3619 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3620#else
3621 ENABLE_PROCESSED_OUTPUT |
3622#endif
3623 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003624 bEnableHandler = TRUE;
3625 }
3626 else /* cooked */
3627 {
3628 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3629 ENABLE_ECHO_INPUT);
3630 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3631 bEnableHandler = FALSE;
3632 }
3633 SetConsoleMode(g_hConIn, cmodein);
3634 SetConsoleMode(g_hConOut, cmodeout);
3635 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3636
3637#ifdef MCH_WRITE_DUMP
3638 if (fdDump)
3639 {
3640 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3641 tmode == TMODE_RAW ? "raw" :
3642 tmode == TMODE_COOK ? "cooked" : "normal",
3643 cmodein, cmodeout);
3644 fflush(fdDump);
3645 }
3646#endif
3647}
3648
3649
3650/*
3651 * Get the size of the current window in `Rows' and `Columns'
3652 * Return OK when size could be determined, FAIL otherwise.
3653 */
3654 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003655mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656{
3657 CONSOLE_SCREEN_BUFFER_INFO csbi;
3658
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003659# ifdef VIMDLL
3660 if (gui.in_use)
3661 return OK;
3662# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3664 {
3665 /*
3666 * For some reason, we are trying to get the screen dimensions
3667 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3668 * variables are really intended to mean the size of Vim screen
3669 * while in termcap mode.
3670 */
3671 Rows = g_cbTermcap.Info.dwSize.Y;
3672 Columns = g_cbTermcap.Info.dwSize.X;
3673 }
3674 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3675 {
3676 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3677 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3678 }
3679 else
3680 {
3681 Rows = 25;
3682 Columns = 80;
3683 }
3684 return OK;
3685}
3686
3687/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003688 * Resize console buffer to 'COORD'
3689 */
3690 static void
3691ResizeConBuf(
3692 HANDLE hConsole,
3693 COORD coordScreen)
3694{
3695 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3696 {
3697#ifdef MCH_WRITE_DUMP
3698 if (fdDump)
3699 {
3700 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3701 GetLastError());
3702 fflush(fdDump);
3703 }
3704#endif
3705 }
3706}
3707
3708/*
3709 * Resize console window size to 'srWindowRect'
3710 */
3711 static void
3712ResizeWindow(
3713 HANDLE hConsole,
3714 SMALL_RECT srWindowRect)
3715{
3716 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3717 {
3718#ifdef MCH_WRITE_DUMP
3719 if (fdDump)
3720 {
3721 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3722 GetLastError());
3723 fflush(fdDump);
3724 }
3725#endif
3726 }
3727}
3728
3729/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730 * Set a console window to `xSize' * `ySize'
3731 */
3732 static void
3733ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003734 HANDLE hConsole,
3735 int xSize,
3736 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737{
3738 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3739 SMALL_RECT srWindowRect; /* hold the new console size */
3740 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003741 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742
3743#ifdef MCH_WRITE_DUMP
3744 if (fdDump)
3745 {
3746 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3747 fflush(fdDump);
3748 }
3749#endif
3750
3751 /* get the largest size we can size the console window to */
3752 coordScreen = GetLargestConsoleWindowSize(hConsole);
3753
3754 /* define the new console window size and scroll position */
3755 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3756 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3757 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3758
3759 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3760 {
3761 int sx, sy;
3762
3763 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3764 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3765 if (sy < ySize || sx < xSize)
3766 {
3767 /*
3768 * Increasing number of lines/columns, do buffer first.
3769 * Use the maximal size in x and y direction.
3770 */
3771 if (sy < ySize)
3772 coordScreen.Y = ySize;
3773 else
3774 coordScreen.Y = sy;
3775 if (sx < xSize)
3776 coordScreen.X = xSize;
3777 else
3778 coordScreen.X = sx;
3779 SetConsoleScreenBufferSize(hConsole, coordScreen);
3780 }
3781 }
3782
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003783 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784 coordScreen.X = xSize;
3785 coordScreen.Y = ySize;
3786
Bram Moolenaar2551c032018-08-23 22:38:31 +02003787 // In the new console call API, only the first time in reverse order
3788 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003790 ResizeWindow(hConsole, srWindowRect);
3791 ResizeConBuf(hConsole, coordScreen);
3792 }
3793 else
3794 {
3795 ResizeConBuf(hConsole, coordScreen);
3796 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003797 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798 }
3799}
3800
3801
3802/*
3803 * Set the console window to `Rows' * `Columns'
3804 */
3805 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003806mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807{
3808 COORD coordScreen;
3809
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003810# ifdef VIMDLL
3811 if (gui.in_use)
3812 return;
3813# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 /* Don't change window size while still starting up */
3815 if (suppress_winsize != 0)
3816 {
3817 suppress_winsize = 2;
3818 return;
3819 }
3820
3821 if (term_console)
3822 {
3823 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3824
3825 /* Clamp Rows and Columns to reasonable values */
3826 if (Rows > coordScreen.Y)
3827 Rows = coordScreen.Y;
3828 if (Columns > coordScreen.X)
3829 Columns = coordScreen.X;
3830
3831 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3832 }
3833}
3834
3835/*
3836 * Rows and/or Columns has changed.
3837 */
3838 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003839mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003841# ifdef VIMDLL
3842 if (gui.in_use)
3843 return;
3844# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003845 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3846}
3847
3848
3849/*
3850 * Called when started up, to set the winsize that was delayed.
3851 */
3852 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003853mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854{
3855 if (suppress_winsize == 2)
3856 {
3857 suppress_winsize = 0;
3858 mch_set_shellsize();
3859 shell_resized();
3860 }
3861 suppress_winsize = 0;
3862}
Bram Moolenaar4f974752019-02-17 17:44:42 +01003863#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003865 static BOOL
3866vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003867 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003868 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003869 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003870 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003871 PROCESS_INFORMATION *pi,
3872 LPVOID *env,
3873 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003874{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003875 BOOL ret = FALSE;
3876 WCHAR *wcmd, *wcwd = NULL;
3877
3878 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3879 if (wcmd == NULL)
3880 return FALSE;
3881 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003882 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003883 wcwd = enc_to_utf16((char_u *)cwd, NULL);
3884 if (wcwd == NULL)
3885 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003886 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003887
3888 ret = CreateProcessW(
3889 NULL, // Executable name
3890 wcmd, // Command to execute
3891 NULL, // Process security attributes
3892 NULL, // Thread security attributes
3893 inherit_handles, // Inherit handles
3894 flags, // Creation flags
3895 env, // Environment
3896 wcwd, // Current directory
3897 (LPSTARTUPINFOW)si, // Startup information
3898 pi); // Process information
3899theend:
3900 vim_free(wcmd);
3901 vim_free(wcwd);
3902 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003903}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003904
3905
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003906 static HINSTANCE
3907vim_shell_execute(
3908 char *cmd,
3909 INT n_show_cmd)
3910{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003911 HINSTANCE ret;
3912 WCHAR *wcmd;
3913
3914 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3915 if (wcmd == NULL)
3916 return (HINSTANCE) 0;
3917
3918 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
3919 vim_free(wcmd);
3920 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003921}
3922
3923
Bram Moolenaar4f974752019-02-17 17:44:42 +01003924#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925
3926/*
3927 * Specialised version of system() for Win32 GUI mode.
3928 * This version proceeds as follows:
3929 * 1. Create a console window for use by the subprocess
3930 * 2. Run the subprocess (it gets the allocated console by default)
3931 * 3. Wait for the subprocess to terminate and get its exit code
3932 * 4. Prompt the user to press a key to close the console window
3933 */
3934 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003935mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936{
3937 STARTUPINFO si;
3938 PROCESS_INFORMATION pi;
3939 DWORD ret = 0;
3940 HWND hwnd = GetFocus();
3941
3942 si.cb = sizeof(si);
3943 si.lpReserved = NULL;
3944 si.lpDesktop = NULL;
3945 si.lpTitle = NULL;
3946 si.dwFlags = STARTF_USESHOWWINDOW;
3947 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003948 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003949 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003951 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003952 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003953 else
3954 si.wShowWindow = SW_SHOWNORMAL;
3955 si.cbReserved2 = 0;
3956 si.lpReserved2 = NULL;
3957
Bram Moolenaar071d4272004-06-13 20:20:40 +00003958 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003959 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003960 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
3961 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962
3963 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003964 {
3965#ifdef FEAT_GUI
3966 int delay = 1;
3967
3968 /* Keep updating the window while waiting for the shell to finish. */
3969 for (;;)
3970 {
3971 MSG msg;
3972
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003973 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974 {
3975 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003976 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003977 delay = 1;
3978 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003979 }
3980 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3981 break;
3982
3983 /* We start waiting for a very short time and then increase it, so
3984 * that we respond quickly when the process is quick, and don't
3985 * consume too much overhead when it's slow. */
3986 if (delay < 50)
3987 delay += 10;
3988 }
3989#else
3990 WaitForSingleObject(pi.hProcess, INFINITE);
3991#endif
3992
3993 /* Get the command exit code */
3994 GetExitCodeProcess(pi.hProcess, &ret);
3995 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996
3997 /* Close the handles to the subprocess, so that it goes away */
3998 CloseHandle(pi.hThread);
3999 CloseHandle(pi.hProcess);
4000
4001 /* Try to get input focus back. Doesn't always work though. */
4002 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4003
4004 return ret;
4005}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004006
4007/*
4008 * Thread launched by the gui to send the current buffer data to the
4009 * process. This way avoid to hang up vim totally if the children
4010 * process take a long time to process the lines.
4011 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004012 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004013sub_process_writer(LPVOID param)
4014{
4015 HANDLE g_hChildStd_IN_Wr = param;
4016 linenr_T lnum = curbuf->b_op_start.lnum;
4017 DWORD len = 0;
4018 DWORD l;
4019 char_u *lp = ml_get(lnum);
4020 char_u *s;
4021 int written = 0;
4022
4023 for (;;)
4024 {
4025 l = (DWORD)STRLEN(lp + written);
4026 if (l == 0)
4027 len = 0;
4028 else if (lp[written] == NL)
4029 {
4030 /* NL -> NUL translation */
4031 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4032 }
4033 else
4034 {
4035 s = vim_strchr(lp + written, NL);
4036 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4037 s == NULL ? l : (DWORD)(s - (lp + written)),
4038 &len, NULL);
4039 }
4040 if (len == (int)l)
4041 {
4042 /* Finished a line, add a NL, unless this line should not have
4043 * one. */
4044 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004045 || (!curbuf->b_p_bin
4046 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004047 || (lnum != curbuf->b_no_eol_lnum
4048 && (lnum != curbuf->b_ml.ml_line_count
4049 || curbuf->b_p_eol)))
4050 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004051 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4052 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004053 }
4054
4055 ++lnum;
4056 if (lnum > curbuf->b_op_end.lnum)
4057 break;
4058
4059 lp = ml_get(lnum);
4060 written = 0;
4061 }
4062 else if (len > 0)
4063 written += len;
4064 }
4065
4066 /* finished all the lines, close pipe */
4067 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004068 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004069}
4070
4071
4072# define BUFLEN 100 /* length for buffer, stolen from unix version */
4073
4074/*
4075 * This function read from the children's stdout and write the
4076 * data on screen or in the buffer accordingly.
4077 */
4078 static void
4079dump_pipe(int options,
4080 HANDLE g_hChildStd_OUT_Rd,
4081 garray_T *ga,
4082 char_u buffer[],
4083 DWORD *buffer_off)
4084{
4085 DWORD availableBytes = 0;
4086 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004087 int ret;
4088 DWORD len;
4089 DWORD toRead;
4090 int repeatCount;
4091
4092 /* we query the pipe to see if there is any data to read
4093 * to avoid to perform a blocking read */
4094 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4095 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004096 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004097 NULL, /* number of read bytes */
4098 &availableBytes, /* available bytes total */
4099 NULL); /* byteLeft */
4100
4101 repeatCount = 0;
4102 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004103 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004104 {
4105 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004106 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004107 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004108 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004109
4110 /* If we haven't read anything, there is a problem */
4111 if (len == 0)
4112 break;
4113
4114 availableBytes -= len;
4115
4116 if (options & SHELL_READ)
4117 {
4118 /* Do NUL -> NL translation, append NL separated
4119 * lines to the current buffer. */
4120 for (i = 0; i < len; ++i)
4121 {
4122 if (buffer[i] == NL)
4123 append_ga_line(ga);
4124 else if (buffer[i] == NUL)
4125 ga_append(ga, NL);
4126 else
4127 ga_append(ga, buffer[i]);
4128 }
4129 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004130 else if (has_mbyte)
4131 {
4132 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004133 int c;
4134 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004135
4136 len += *buffer_off;
4137 buffer[len] = NUL;
4138
4139 /* Check if the last character in buffer[] is
4140 * incomplete, keep these bytes for the next
4141 * round. */
4142 for (p = buffer; p < buffer + len; p += l)
4143 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004144 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004145 if (l == 0)
4146 l = 1; /* NUL byte? */
4147 else if (MB_BYTE2LEN(*p) != l)
4148 break;
4149 }
4150 if (p == buffer) /* no complete character */
4151 {
4152 /* avoid getting stuck at an illegal byte */
4153 if (len >= 12)
4154 ++p;
4155 else
4156 {
4157 *buffer_off = len;
4158 return;
4159 }
4160 }
4161 c = *p;
4162 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004163 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004164 if (p < buffer + len)
4165 {
4166 *p = c;
4167 *buffer_off = (DWORD)((buffer + len) - p);
4168 mch_memmove(buffer, p, *buffer_off);
4169 return;
4170 }
4171 *buffer_off = 0;
4172 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004173 else
4174 {
4175 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004176 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004177 }
4178
4179 windgoto(msg_row, msg_col);
4180 cursor_on();
4181 out_flush();
4182 }
4183}
4184
4185/*
4186 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4187 * for communication and doesn't open any new window.
4188 */
4189 static int
4190mch_system_piped(char *cmd, int options)
4191{
4192 STARTUPINFO si;
4193 PROCESS_INFORMATION pi;
4194 DWORD ret = 0;
4195
4196 HANDLE g_hChildStd_IN_Rd = NULL;
4197 HANDLE g_hChildStd_IN_Wr = NULL;
4198 HANDLE g_hChildStd_OUT_Rd = NULL;
4199 HANDLE g_hChildStd_OUT_Wr = NULL;
4200
4201 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4202 DWORD len;
4203
4204 /* buffer used to receive keys */
4205 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4206 int ta_len = 0; /* valid bytes in ta_buf[] */
4207
4208 DWORD i;
4209 int c;
4210 int noread_cnt = 0;
4211 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004212 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004213 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004214 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004215
4216 SECURITY_ATTRIBUTES saAttr;
4217
4218 /* Set the bInheritHandle flag so pipe handles are inherited. */
4219 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4220 saAttr.bInheritHandle = TRUE;
4221 saAttr.lpSecurityDescriptor = NULL;
4222
4223 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4224 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004225 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004226 /* Create a pipe for the child process's STDIN. */
4227 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4228 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004229 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004230 {
4231 CloseHandle(g_hChildStd_IN_Rd);
4232 CloseHandle(g_hChildStd_IN_Wr);
4233 CloseHandle(g_hChildStd_OUT_Rd);
4234 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004235 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004236 }
4237
4238 si.cb = sizeof(si);
4239 si.lpReserved = NULL;
4240 si.lpDesktop = NULL;
4241 si.lpTitle = NULL;
4242 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4243
4244 /* set-up our file redirection */
4245 si.hStdError = g_hChildStd_OUT_Wr;
4246 si.hStdOutput = g_hChildStd_OUT_Wr;
4247 si.hStdInput = g_hChildStd_IN_Rd;
4248 si.wShowWindow = SW_HIDE;
4249 si.cbReserved2 = 0;
4250 si.lpReserved2 = NULL;
4251
4252 if (options & SHELL_READ)
4253 ga_init2(&ga, 1, BUFLEN);
4254
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004255 if (cmd != NULL)
4256 {
4257 p = (char *)vim_strsave((char_u *)cmd);
4258 if (p != NULL)
4259 unescape_shellxquote((char_u *)p, p_sxe);
4260 else
4261 p = cmd;
4262 }
4263
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004264 /* Now, run the command.
4265 * About "Inherit handles" being TRUE: this command can be litigious,
4266 * handle inheritance was deactivated for pending temp file, but, if we
4267 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004268 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4269 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004270
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004271 if (p != cmd)
4272 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004273
4274 /* Close our unused side of the pipes */
4275 CloseHandle(g_hChildStd_IN_Rd);
4276 CloseHandle(g_hChildStd_OUT_Wr);
4277
4278 if (options & SHELL_WRITE)
4279 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004280 HANDLE thread = (HANDLE)
4281 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004282 0, /* default stack size */
4283 sub_process_writer, /* function to be executed */
4284 g_hChildStd_IN_Wr, /* parameter */
4285 0, /* creation flag, start immediately */
4286 NULL); /* we don't care about thread id */
4287 CloseHandle(thread);
4288 g_hChildStd_IN_Wr = NULL;
4289 }
4290
4291 /* Keep updating the window while waiting for the shell to finish. */
4292 for (;;)
4293 {
4294 MSG msg;
4295
Bram Moolenaar175d0702013-12-11 18:36:33 +01004296 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004297 {
4298 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004299 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004300 }
4301
4302 /* write pipe information in the window */
4303 if ((options & (SHELL_READ|SHELL_WRITE))
4304# ifdef FEAT_GUI
4305 || gui.in_use
4306# endif
4307 )
4308 {
4309 len = 0;
4310 if (!(options & SHELL_EXPAND)
4311 && ((options &
4312 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4313 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4314# ifdef FEAT_GUI
4315 || gui.in_use
4316# endif
4317 )
4318 && (ta_len > 0 || noread_cnt > 4))
4319 {
4320 if (ta_len == 0)
4321 {
4322 /* Get extra characters when we don't have any. Reset the
4323 * counter and timer. */
4324 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004325 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4326 }
4327 if (ta_len > 0 || len > 0)
4328 {
4329 /*
4330 * For pipes: Check for CTRL-C: send interrupt signal to
4331 * child. Check for CTRL-D: EOF, close pipe to child.
4332 */
4333 if (len == 1 && cmd != NULL)
4334 {
4335 if (ta_buf[ta_len] == Ctrl_C)
4336 {
4337 /* Learn what exit code is expected, for
4338 * now put 9 as SIGKILL */
4339 TerminateProcess(pi.hProcess, 9);
4340 }
4341 if (ta_buf[ta_len] == Ctrl_D)
4342 {
4343 CloseHandle(g_hChildStd_IN_Wr);
4344 g_hChildStd_IN_Wr = NULL;
4345 }
4346 }
4347
4348 /* replace K_BS by <BS> and K_DEL by <DEL> */
4349 for (i = ta_len; i < ta_len + len; ++i)
4350 {
4351 if (ta_buf[i] == CSI && len - i > 2)
4352 {
4353 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4354 if (c == K_DEL || c == K_KDEL || c == K_BS)
4355 {
4356 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4357 (size_t)(len - i - 2));
4358 if (c == K_DEL || c == K_KDEL)
4359 ta_buf[i] = DEL;
4360 else
4361 ta_buf[i] = Ctrl_H;
4362 len -= 2;
4363 }
4364 }
4365 else if (ta_buf[i] == '\r')
4366 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004367 if (has_mbyte)
4368 i += (*mb_ptr2len_len)(ta_buf + i,
4369 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004370 }
4371
4372 /*
4373 * For pipes: echo the typed characters. For a pty this
4374 * does not seem to work.
4375 */
4376 for (i = ta_len; i < ta_len + len; ++i)
4377 {
4378 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4379 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004380 else if (has_mbyte)
4381 {
4382 int l = (*mb_ptr2len)(ta_buf + i);
4383
4384 msg_outtrans_len(ta_buf + i, l);
4385 i += l - 1;
4386 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004387 else
4388 msg_outtrans_len(ta_buf + i, 1);
4389 }
4390 windgoto(msg_row, msg_col);
4391 out_flush();
4392
4393 ta_len += len;
4394
4395 /*
4396 * Write the characters to the child, unless EOF has been
4397 * typed for pipes. Write one character at a time, to
4398 * avoid losing too much typeahead. When writing buffer
4399 * lines, drop the typed characters (only check for
4400 * CTRL-C).
4401 */
4402 if (options & SHELL_WRITE)
4403 ta_len = 0;
4404 else if (g_hChildStd_IN_Wr != NULL)
4405 {
4406 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4407 1, &len, NULL);
4408 // if we are typing in, we want to keep things reactive
4409 delay = 1;
4410 if (len > 0)
4411 {
4412 ta_len -= len;
4413 mch_memmove(ta_buf, ta_buf + len, ta_len);
4414 }
4415 }
4416 }
4417 }
4418 }
4419
4420 if (ta_len)
4421 ui_inchar_undo(ta_buf, ta_len);
4422
4423 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4424 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004425 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004426 break;
4427 }
4428
4429 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004430 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004431
4432 /* We start waiting for a very short time and then increase it, so
4433 * that we respond quickly when the process is quick, and don't
4434 * consume too much overhead when it's slow. */
4435 if (delay < 50)
4436 delay += 10;
4437 }
4438
4439 /* Close the pipe */
4440 CloseHandle(g_hChildStd_OUT_Rd);
4441 if (g_hChildStd_IN_Wr != NULL)
4442 CloseHandle(g_hChildStd_IN_Wr);
4443
4444 WaitForSingleObject(pi.hProcess, INFINITE);
4445
4446 /* Get the command exit code */
4447 GetExitCodeProcess(pi.hProcess, &ret);
4448
4449 if (options & SHELL_READ)
4450 {
4451 if (ga.ga_len > 0)
4452 {
4453 append_ga_line(&ga);
4454 /* remember that the NL was missing */
4455 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4456 }
4457 else
4458 curbuf->b_no_eol_lnum = 0;
4459 ga_clear(&ga);
4460 }
4461
4462 /* Close the handles to the subprocess, so that it goes away */
4463 CloseHandle(pi.hThread);
4464 CloseHandle(pi.hProcess);
4465
4466 return ret;
4467}
4468
4469 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004470mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004471{
4472 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004473 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004474 return mch_system_piped(cmd, options);
4475 else
4476 return mch_system_classic(cmd, options);
4477}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004478#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004480#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004481 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004482mch_system_c(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004483{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004484 int ret;
4485 WCHAR *wcmd;
4486
4487 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4488 if (wcmd == NULL)
4489 return -1;
4490
4491 ret = _wsystem(wcmd);
4492 vim_free(wcmd);
4493 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004494}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495
4496#endif
4497
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004498 static int
4499mch_system(char *cmd, int options)
4500{
4501#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004502 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004503 return mch_system_g(cmd, options);
4504 else
4505 return mch_system_c(cmd, options);
4506#elif defined(FEAT_GUI_MSWIN)
4507 return mch_system_g(cmd, options);
4508#else
4509 return mch_system_c(cmd, options);
4510#endif
4511}
4512
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004513#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4514/*
4515 * Use a terminal window to run a shell command in.
4516 */
4517 static int
4518mch_call_shell_terminal(
4519 char_u *cmd,
4520 int options UNUSED) /* SHELL_*, see vim.h */
4521{
4522 jobopt_T opt;
4523 char_u *newcmd = NULL;
4524 typval_T argvar[2];
4525 long_u cmdlen;
4526 int retval = -1;
4527 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004528 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004529 aco_save_T aco;
4530 oparg_T oa; /* operator arguments */
4531
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004532 if (cmd == NULL)
4533 cmdlen = STRLEN(p_sh) + 1;
4534 else
4535 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004536 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004537 if (newcmd == NULL)
4538 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004539 if (cmd == NULL)
4540 {
4541 STRCPY(newcmd, p_sh);
4542 ch_log(NULL, "starting terminal to run a shell");
4543 }
4544 else
4545 {
4546 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4547 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4548 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004549
4550 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004551
4552 argvar[0].v_type = VAR_STRING;
4553 argvar[0].vval.v_string = newcmd;
4554 argvar[1].v_type = VAR_UNKNOWN;
4555 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004556 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004557 {
4558 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004559 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004560 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004561
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004562 job = term_getjob(buf->b_term);
4563 ++job->jv_refcount;
4564
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004565 /* Find a window to make "buf" curbuf. */
4566 aucmd_prepbuf(&aco, buf);
4567
4568 clear_oparg(&oa);
4569 while (term_use_loop())
4570 {
4571 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4572 {
4573 /* If terminal_loop() returns OK we got a key that is handled
4574 * in Normal model. We don't do redrawing anyway. */
4575 if (terminal_loop(TRUE) == OK)
4576 normal_cmd(&oa, TRUE);
4577 }
4578 else
4579 normal_cmd(&oa, TRUE);
4580 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004581 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004582 ch_log(NULL, "system command finished");
4583
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004584 job_unref(job);
4585
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004586 /* restore curwin/curbuf and a few other things */
4587 aucmd_restbuf(&aco);
4588
4589 wait_return(TRUE);
4590 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4591
4592 vim_free(newcmd);
4593 return retval;
4594}
4595#endif
4596
Bram Moolenaar071d4272004-06-13 20:20:40 +00004597/*
4598 * Either execute a command by calling the shell or start a new shell
4599 */
4600 int
4601mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004602 char_u *cmd,
4603 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004604{
4605 int x = 0;
4606 int tmode = cur_tmode;
4607#ifdef FEAT_TITLE
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004608 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004609
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004610 /* Change the title to reflect that we are in a subshell. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004611 if (GetConsoleTitleW(szShellTitle,
4612 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004613 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004614 if (cmd == NULL)
4615 wcscat(szShellTitle, L" :sh");
4616 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004617 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004618 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004619
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004620 if (wn != NULL)
4621 {
4622 wcscat(szShellTitle, L" - !");
4623 if ((wcslen(szShellTitle) + wcslen(wn) <
4624 sizeof(szShellTitle)/sizeof(WCHAR)))
4625 wcscat(szShellTitle, wn);
4626 SetConsoleTitleW(szShellTitle);
4627 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004628 }
4629 }
4630 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631#endif
4632
4633 out_flush();
4634
4635#ifdef MCH_WRITE_DUMP
4636 if (fdDump)
4637 {
4638 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4639 fflush(fdDump);
4640 }
4641#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004642#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004643 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004644 if (
4645# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004646 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004647# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004648 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004649 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4650 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004651 char_u *cmdbase = cmd;
4652
4653 // Skip a leading quote and (.
4654 while (*cmdbase == '"' || *cmdbase == '(')
4655 ++cmdbase;
4656
4657 // Check the command does not begin with "start "
4658 if (STRNICMP(cmdbase, "start", 5) != 0 || !VIM_ISWHITE(cmdbase[5]))
4659 {
4660 // Use a terminal window to run the command in.
4661 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004662# ifdef FEAT_TITLE
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004663 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004664# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004665 return x;
4666 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004667 }
4668#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004669
4670 /*
4671 * Catch all deadly signals while running the external command, because a
4672 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4673 */
4674 signal(SIGINT, SIG_IGN);
4675#if defined(__GNUC__) && !defined(__MINGW32__)
4676 signal(SIGKILL, SIG_IGN);
4677#else
4678 signal(SIGBREAK, SIG_IGN);
4679#endif
4680 signal(SIGILL, SIG_IGN);
4681 signal(SIGFPE, SIG_IGN);
4682 signal(SIGSEGV, SIG_IGN);
4683 signal(SIGTERM, SIG_IGN);
4684 signal(SIGABRT, SIG_IGN);
4685
4686 if (options & SHELL_COOKED)
4687 settmode(TMODE_COOK); /* set to normal mode */
4688
4689 if (cmd == NULL)
4690 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004691 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692 }
4693 else
4694 {
4695 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004696 char_u *newcmd = NULL;
4697 char_u *cmdbase = cmd;
4698 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004699
4700 /* Skip a leading ", ( and "(. */
4701 if (*cmdbase == '"' )
4702 ++cmdbase;
4703 if (*cmdbase == '(')
4704 ++cmdbase;
4705
Bram Moolenaar1c465442017-03-12 20:10:05 +01004706 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004707 {
4708 STARTUPINFO si;
4709 PROCESS_INFORMATION pi;
4710 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004711 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004712 char_u *p;
4713
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004714 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004715 si.cb = sizeof(si);
4716 si.lpReserved = NULL;
4717 si.lpDesktop = NULL;
4718 si.lpTitle = NULL;
4719 si.dwFlags = 0;
4720 si.cbReserved2 = 0;
4721 si.lpReserved2 = NULL;
4722
4723 cmdbase = skipwhite(cmdbase + 5);
4724 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004725 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004726 {
4727 cmdbase = skipwhite(cmdbase + 4);
4728 si.dwFlags = STARTF_USESHOWWINDOW;
4729 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004730 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004731 }
4732 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004733 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004734 {
4735 cmdbase = skipwhite(cmdbase + 2);
4736 flags = CREATE_NO_WINDOW;
4737 si.dwFlags = STARTF_USESTDHANDLES;
4738 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004739 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004740 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004741 NULL, // Security att.
4742 OPEN_EXISTING, // Open flags
4743 FILE_ATTRIBUTE_NORMAL, // File att.
4744 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004745 si.hStdOutput = si.hStdInput;
4746 si.hStdError = si.hStdInput;
4747 }
4748
4749 /* Remove a trailing ", ) and )" if they have a match
4750 * at the start of the command. */
4751 if (cmdbase > cmd)
4752 {
4753 p = cmdbase + STRLEN(cmdbase);
4754 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4755 *--p = NUL;
4756 if (p > cmdbase && p[-1] == ')'
4757 && (*cmd =='(' || cmd[1] == '('))
4758 *--p = NUL;
4759 }
4760
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004761 newcmd = cmdbase;
4762 unescape_shellxquote(cmdbase, p_sxe);
4763
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004764 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004765 * If creating new console, arguments are passed to the
4766 * 'cmd.exe' as-is. If it's not, arguments are not treated
4767 * correctly for current 'cmd.exe'. So unescape characters in
4768 * shellxescape except '|' for avoiding to be treated as
4769 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004770 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004771 if (flags != CREATE_NEW_CONSOLE)
4772 {
4773 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004774 char_u *cmd_shell = mch_getenv("COMSPEC");
4775
4776 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004777 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004778
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004779 subcmd = vim_strsave_escaped_ext(cmdbase,
4780 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004781 if (subcmd != NULL)
4782 {
4783 /* make "cmd.exe /c arguments" */
4784 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004785 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004786 if (newcmd != NULL)
4787 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004788 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004789 else
4790 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004791 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004792 }
4793 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004794
4795 /*
4796 * Now, start the command as a process, so that it doesn't
4797 * inherit our handles which causes unpleasant dangling swap
4798 * files if we exit before the spawned process
4799 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004800 if (vim_create_process((char *)newcmd, FALSE, flags,
4801 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004802 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004803 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4804 > (HINSTANCE)32)
4805 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004806 else
4807 {
4808 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004809#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004810# ifdef VIMDLL
4811 if (gui.in_use)
4812# endif
4813 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004814#endif
4815 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004816
4817 if (newcmd != cmdbase)
4818 vim_free(newcmd);
4819
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004820 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004821 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004822 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004823 CloseHandle(si.hStdInput);
4824 }
4825 /* Close the handles to the subprocess, so that it goes away */
4826 CloseHandle(pi.hThread);
4827 CloseHandle(pi.hProcess);
4828 }
4829 else
4830 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004831 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004832#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004833 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004834 (!s_dont_use_vimrun && p_stmp ?
4835 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4836 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004837#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004838 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004839
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004840 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004841 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004843#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004844 if (
4845# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004846 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004847# endif
4848 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004850 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4851 "External commands will not pause after completion.\n"
4852 "See :help win32-vimrun for more information.");
4853 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004854 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4855 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01004856
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004857 if (wmsg != NULL && wtitle != NULL)
4858 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4859 vim_free(wmsg);
4860 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861 need_vimrun_warning = FALSE;
4862 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004863 if (
4864# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004865 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004866# endif
4867 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004868 // Use vimrun to execute the command. It opens a console
4869 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004870 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871 vimrun_path,
4872 (msg_silent != 0 || (options & SHELL_DOOUT))
4873 ? "-s " : "",
4874 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004875 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004876# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004877 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004878# endif
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004879 STRCMP(p_shcf, "/c") == 0)
4880 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004881 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
4882 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004883 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004884#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004885 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004886 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004887 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004888 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890 }
4891 }
4892
4893 if (tmode == TMODE_RAW)
4894 settmode(TMODE_RAW); /* set to raw mode */
4895
4896 /* Print the return value, unless "vimrun" was used. */
4897 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01004898#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004899 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004900 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901#endif
4902 )
4903 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004904 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004905 msg_putchar('\n');
4906 }
4907#ifdef FEAT_TITLE
4908 resettitle();
4909#endif
4910
4911 signal(SIGINT, SIG_DFL);
4912#if defined(__GNUC__) && !defined(__MINGW32__)
4913 signal(SIGKILL, SIG_DFL);
4914#else
4915 signal(SIGBREAK, SIG_DFL);
4916#endif
4917 signal(SIGILL, SIG_DFL);
4918 signal(SIGFPE, SIG_DFL);
4919 signal(SIGSEGV, SIG_DFL);
4920 signal(SIGTERM, SIG_DFL);
4921 signal(SIGABRT, SIG_DFL);
4922
4923 return x;
4924}
4925
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004926#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004927 static HANDLE
4928job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004929 char_u *fname,
4930 DWORD dwDesiredAccess,
4931 DWORD dwShareMode,
4932 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4933 DWORD dwCreationDisposition,
4934 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004935{
4936 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004937 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004938
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004939 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004940 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004941 return INVALID_HANDLE_VALUE;
4942
4943 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4944 lpSecurityAttributes, dwCreationDisposition,
4945 dwFlagsAndAttributes, NULL);
4946 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004947 return h;
4948}
4949
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004950/*
4951 * Turn the dictionary "env" into a NUL separated list that can be used as the
4952 * environment argument of vim_create_process().
4953 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004954 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004955win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004956{
4957 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004958 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004959 LPVOID base = GetEnvironmentStringsW();
4960
4961 /* for last \0 */
4962 if (ga_grow(gap, 1) == FAIL)
4963 return;
4964
4965 if (base)
4966 {
4967 WCHAR *p = (WCHAR*) base;
4968
4969 /* for last \0 */
4970 if (ga_grow(gap, 1) == FAIL)
4971 return;
4972
4973 while (*p != 0 || *(p + 1) != 0)
4974 {
4975 if (ga_grow(gap, 1) == OK)
4976 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
4977 p++;
4978 }
4979 FreeEnvironmentStrings(base);
4980 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4981 }
4982
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004983 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004984 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004985 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004986 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004987 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004988 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004989 typval_T *item = &dict_lookup(hi)->di_tv;
4990 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004991 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004992 --todo;
4993 if (wkey != NULL && wval != NULL)
4994 {
4995 size_t n;
4996 size_t lkey = wcslen(wkey);
4997 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02004998
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004999 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5000 continue;
5001 for (n = 0; n < lkey; n++)
5002 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5003 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5004 for (n = 0; n < lval; n++)
5005 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5006 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5007 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005008 vim_free(wkey);
5009 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005010 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005011 }
5012 }
5013
Bram Moolenaar493359e2018-06-12 20:25:52 +02005014# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005015 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005016# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005017 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005018 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005019# endif
5020# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005021 char_u *version = get_vim_var_str(VV_VERSION);
5022 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005023# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005024 // size of "VIM_SERVERNAME=" and value,
5025 // plus "VIM_TERMINAL=" and value,
5026 // plus two terminating NULs
5027 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005028# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005029 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005030# endif
5031# ifdef FEAT_TERMINAL
5032 + 13 + version_len + 2
5033# endif
5034 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005035
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005036 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005037 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005038# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005039 for (n = 0; n < 15; n++)
5040 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5041 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005042 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005043 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5044 (WCHAR)servername[n];
5045 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005046# endif
5047# ifdef FEAT_TERMINAL
5048 if (is_terminal)
5049 {
5050 for (n = 0; n < 13; n++)
5051 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5052 (WCHAR)"VIM_TERMINAL="[n];
5053 for (n = 0; n < version_len; n++)
5054 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5055 (WCHAR)version[n];
5056 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5057 }
5058# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005059 }
5060 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005061# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005062}
5063
Bram Moolenaarb091f302019-01-19 14:37:00 +01005064/*
5065 * Create a pair of pipes.
5066 * Return TRUE for success, FALSE for failure.
5067 */
5068 static BOOL
5069create_pipe_pair(HANDLE handles[2])
5070{
5071 static LONG s;
5072 char name[64];
5073 SECURITY_ATTRIBUTES sa;
5074
5075 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5076 GetCurrentProcessId(),
5077 InterlockedIncrement(&s));
5078
5079 // Create named pipe. Max size of named pipe is 65535.
5080 handles[1] = CreateNamedPipe(
5081 name,
5082 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5083 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005084 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005085
5086 if (handles[1] == INVALID_HANDLE_VALUE)
5087 return FALSE;
5088
5089 sa.nLength = sizeof(sa);
5090 sa.bInheritHandle = TRUE;
5091 sa.lpSecurityDescriptor = NULL;
5092
5093 handles[0] = CreateFile(name,
5094 FILE_GENERIC_READ,
5095 FILE_SHARE_READ, &sa,
5096 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5097
5098 if (handles[0] == INVALID_HANDLE_VALUE)
5099 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005100 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005101 return FALSE;
5102 }
5103
5104 return TRUE;
5105}
5106
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005107 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005108mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005109{
5110 STARTUPINFO si;
5111 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005112 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005113 SECURITY_ATTRIBUTES saAttr;
5114 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005115 HANDLE ifd[2];
5116 HANDLE ofd[2];
5117 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005118 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005119
5120 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5121 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5122 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5123 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5124 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5125 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5126 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5127
5128 if (use_out_for_err && use_null_for_out)
5129 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005130
5131 ifd[0] = INVALID_HANDLE_VALUE;
5132 ifd[1] = INVALID_HANDLE_VALUE;
5133 ofd[0] = INVALID_HANDLE_VALUE;
5134 ofd[1] = INVALID_HANDLE_VALUE;
5135 efd[0] = INVALID_HANDLE_VALUE;
5136 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005137 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005138
Bram Moolenaar14207f42016-10-27 21:13:10 +02005139 jo = CreateJobObject(NULL, NULL);
5140 if (jo == NULL)
5141 {
5142 job->jv_status = JOB_FAILED;
5143 goto failed;
5144 }
5145
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005146 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005147 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005148
Bram Moolenaar76467df2016-02-12 19:30:26 +01005149 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005150 ZeroMemory(&si, sizeof(si));
5151 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005152 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005153 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005154
Bram Moolenaard8070362016-02-15 21:56:54 +01005155 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5156 saAttr.bInheritHandle = TRUE;
5157 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005158
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005159 if (use_file_for_in)
5160 {
5161 char_u *fname = options->jo_io_name[PART_IN];
5162
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005163 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5164 FILE_SHARE_READ | FILE_SHARE_WRITE,
5165 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5166 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005167 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005168 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005169 goto failed;
5170 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005171 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005172 else if (!use_null_for_in
5173 && (!create_pipe_pair(ifd)
5174 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005175 goto failed;
5176
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005177 if (use_file_for_out)
5178 {
5179 char_u *fname = options->jo_io_name[PART_OUT];
5180
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005181 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5182 FILE_SHARE_READ | FILE_SHARE_WRITE,
5183 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5184 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005185 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005186 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005187 goto failed;
5188 }
5189 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005190 else if (!use_null_for_out &&
5191 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005192 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005193 goto failed;
5194
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005195 if (use_file_for_err)
5196 {
5197 char_u *fname = options->jo_io_name[PART_ERR];
5198
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005199 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5200 FILE_SHARE_READ | FILE_SHARE_WRITE,
5201 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5202 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005203 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005204 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005205 goto failed;
5206 }
5207 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005208 else if (!use_out_for_err && !use_null_for_err &&
5209 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005210 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005211 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005212
Bram Moolenaard8070362016-02-15 21:56:54 +01005213 si.dwFlags |= STARTF_USESTDHANDLES;
5214 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005215 si.hStdOutput = ofd[1];
5216 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5217
5218 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5219 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005220 if (options->jo_set & JO_CHANNEL)
5221 {
5222 channel = options->jo_channel;
5223 if (channel != NULL)
5224 ++channel->ch_refcount;
5225 }
5226 else
5227 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005228 if (channel == NULL)
5229 goto failed;
5230 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005231
5232 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005233 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005234 CREATE_DEFAULT_ERROR_MODE |
5235 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005236 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005237 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005238 &si, &pi,
5239 ga.ga_data,
5240 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005241 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005242 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005243 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005244 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005245 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005246
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005247 ga_clear(&ga);
5248
Bram Moolenaar14207f42016-10-27 21:13:10 +02005249 if (!AssignProcessToJobObject(jo, pi.hProcess))
5250 {
5251 /* if failing, switch the way to terminate
5252 * process with TerminateProcess. */
5253 CloseHandle(jo);
5254 jo = NULL;
5255 }
5256 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005257 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005258 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005259 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005260 job->jv_status = JOB_STARTED;
5261
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005262 CloseHandle(ifd[0]);
5263 CloseHandle(ofd[1]);
5264 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005265 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005266
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005267 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005268 if (channel != NULL)
5269 {
5270 channel_set_pipes(channel,
5271 use_file_for_in || use_null_for_in
5272 ? INVALID_FD : (sock_T)ifd[1],
5273 use_file_for_out || use_null_for_out
5274 ? INVALID_FD : (sock_T)ofd[0],
5275 use_out_for_err || use_file_for_err || use_null_for_err
5276 ? INVALID_FD : (sock_T)efd[0]);
5277 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005278 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005279 return;
5280
5281failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005282 CloseHandle(ifd[0]);
5283 CloseHandle(ofd[0]);
5284 CloseHandle(efd[0]);
5285 CloseHandle(ifd[1]);
5286 CloseHandle(ofd[1]);
5287 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005288 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005289 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005290}
5291
5292 char *
5293mch_job_status(job_T *job)
5294{
5295 DWORD dwExitCode = 0;
5296
Bram Moolenaar76467df2016-02-12 19:30:26 +01005297 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5298 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005299 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005300 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005301 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005302 {
5303 ch_log(job->jv_channel, "Job ended");
5304 job->jv_status = JOB_ENDED;
5305 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005306 return "dead";
5307 }
5308 return "run";
5309}
5310
Bram Moolenaar97792de2016-10-15 18:36:49 +02005311 job_T *
5312mch_detect_ended_job(job_T *job_list)
5313{
5314 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5315 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5316 job_T *job = job_list;
5317
5318 while (job != NULL)
5319 {
5320 DWORD n;
5321 DWORD result;
5322
5323 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5324 && job != NULL; job = job->jv_next)
5325 {
5326 if (job->jv_status == JOB_STARTED)
5327 {
5328 jobHandles[n] = job->jv_proc_info.hProcess;
5329 jobArray[n] = job;
5330 ++n;
5331 }
5332 }
5333 if (n == 0)
5334 continue;
5335 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5336 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5337 {
5338 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5339
5340 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5341 return wait_job;
5342 }
5343 }
5344 return NULL;
5345}
5346
Bram Moolenaarfb630902016-10-29 14:55:00 +02005347 static BOOL
5348terminate_all(HANDLE process, int code)
5349{
5350 PROCESSENTRY32 pe;
5351 HANDLE h = INVALID_HANDLE_VALUE;
5352 DWORD pid = GetProcessId(process);
5353
5354 if (pid != 0)
5355 {
5356 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5357 if (h != INVALID_HANDLE_VALUE)
5358 {
5359 pe.dwSize = sizeof(PROCESSENTRY32);
5360 if (!Process32First(h, &pe))
5361 goto theend;
5362
5363 do
5364 {
5365 if (pe.th32ParentProcessID == pid)
5366 {
5367 HANDLE ph = OpenProcess(
5368 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5369 if (ph != NULL)
5370 {
5371 terminate_all(ph, code);
5372 CloseHandle(ph);
5373 }
5374 }
5375 } while (Process32Next(h, &pe));
5376
5377 CloseHandle(h);
5378 }
5379 }
5380
5381theend:
5382 return TerminateProcess(process, code);
5383}
5384
5385/*
5386 * Send a (deadly) signal to "job".
5387 * Return FAIL if it didn't work.
5388 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005389 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005390mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005391{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005392 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005393
Bram Moolenaar923d9262016-02-25 20:56:01 +01005394 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005395 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005396 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005397 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005398 {
5399 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5400 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005401 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005402 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005403 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005404 }
5405
5406 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5407 return FAIL;
5408 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005409 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5410 job->jv_proc_info.dwProcessId)
5411 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005412 FreeConsole();
5413 return ret;
5414}
5415
5416/*
5417 * Clear the data related to "job".
5418 */
5419 void
5420mch_clear_job(job_T *job)
5421{
5422 if (job->jv_status != JOB_FAILED)
5423 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005424 if (job->jv_job_object != NULL)
5425 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005426 CloseHandle(job->jv_proc_info.hProcess);
5427 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005428}
5429#endif
5430
Bram Moolenaar071d4272004-06-13 20:20:40 +00005431
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005432#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005433
5434/*
5435 * Start termcap mode
5436 */
5437 static void
5438termcap_mode_start(void)
5439{
5440 DWORD cmodein;
5441
5442 if (g_fTermcapMode)
5443 return;
5444
5445 SaveConsoleBuffer(&g_cbNonTermcap);
5446
5447 if (g_cbTermcap.IsValid)
5448 {
5449 /*
5450 * We've been in termcap mode before. Restore certain screen
5451 * characteristics, including the buffer size and the window
5452 * size. Since we will be redrawing the screen, we don't need
5453 * to restore the actual contents of the buffer.
5454 */
5455 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005456 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005457 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5458 Rows = g_cbTermcap.Info.dwSize.Y;
5459 Columns = g_cbTermcap.Info.dwSize.X;
5460 }
5461 else
5462 {
5463 /*
5464 * This is our first time entering termcap mode. Clear the console
5465 * screen buffer, and resize the buffer to match the current window
5466 * size. We will use this as the size of our editing environment.
5467 */
5468 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005469 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005470 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5471 }
5472
5473#ifdef FEAT_TITLE
5474 resettitle();
5475#endif
5476
5477 GetConsoleMode(g_hConIn, &cmodein);
5478#ifdef FEAT_MOUSE
5479 if (g_fMouseActive)
5480 cmodein |= ENABLE_MOUSE_INPUT;
5481 else
5482 cmodein &= ~ENABLE_MOUSE_INPUT;
5483#endif
5484 cmodein |= ENABLE_WINDOW_INPUT;
5485 SetConsoleMode(g_hConIn, cmodein);
5486
5487 redraw_later_clear();
5488 g_fTermcapMode = TRUE;
5489}
5490
5491
5492/*
5493 * End termcap mode
5494 */
5495 static void
5496termcap_mode_end(void)
5497{
5498 DWORD cmodein;
5499 ConsoleBuffer *cb;
5500 COORD coord;
5501 DWORD dwDummy;
5502
5503 if (!g_fTermcapMode)
5504 return;
5505
5506 SaveConsoleBuffer(&g_cbTermcap);
5507
5508 GetConsoleMode(g_hConIn, &cmodein);
5509 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5510 SetConsoleMode(g_hConIn, cmodein);
5511
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005512#ifdef FEAT_RESTORE_ORIG_SCREEN
5513 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5514#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005516#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005517 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005518 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005519 SetConsoleCursorInfo(g_hConOut, &g_cci);
5520
5521 if (p_rs || exiting)
5522 {
5523 /*
5524 * Clear anything that happens to be on the current line.
5525 */
5526 coord.X = 0;
5527 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5528 FillConsoleOutputCharacter(g_hConOut, ' ',
5529 cb->Info.dwSize.X, coord, &dwDummy);
5530 /*
5531 * The following is just for aesthetics. If we are exiting without
5532 * restoring the screen, then we want to have a prompt string
5533 * appear at the bottom line. However, the command interpreter
5534 * seems to always advance the cursor one line before displaying
5535 * the prompt string, which causes the screen to scroll. To
5536 * counter this, move the cursor up one line before exiting.
5537 */
5538 if (exiting && !p_rs)
5539 coord.Y--;
5540 /*
5541 * Position the cursor at the leftmost column of the desired row.
5542 */
5543 SetConsoleCursorPosition(g_hConOut, coord);
5544 }
5545
5546 g_fTermcapMode = FALSE;
5547}
Bram Moolenaar4f974752019-02-17 17:44:42 +01005548#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549
5550
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005551#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005552 void
5553mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005554 char_u *s UNUSED,
5555 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556{
5557 /* never used */
5558}
5559
5560#else
5561
5562/*
5563 * clear `n' chars, starting from `coord'
5564 */
5565 static void
5566clear_chars(
5567 COORD coord,
5568 DWORD n)
5569{
5570 DWORD dwDummy;
5571
5572 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005573
5574 if (!USE_VTP)
5575 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5576 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005577 {
5578 set_console_color_rgb();
5579 gotoxy(coord.X + 1, coord.Y + 1);
5580 vtp_printf("\033[%dX", n);
5581 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005582}
5583
5584
5585/*
5586 * Clear the screen
5587 */
5588 static void
5589clear_screen(void)
5590{
5591 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005592
5593 if (!USE_VTP)
5594 clear_chars(g_coord, Rows * Columns);
5595 else
5596 {
5597 set_console_color_rgb();
5598 gotoxy(1, 1);
5599 vtp_printf("\033[2J");
5600 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601}
5602
5603
5604/*
5605 * Clear to end of display
5606 */
5607 static void
5608clear_to_end_of_display(void)
5609{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005610 COORD save = g_coord;
5611
5612 if (!USE_VTP)
5613 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005615 else
5616 {
5617 set_console_color_rgb();
5618 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5619 vtp_printf("\033[0J");
5620
5621 gotoxy(save.X + 1, save.Y + 1);
5622 g_coord = save;
5623 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624}
5625
5626
5627/*
5628 * Clear to end of line
5629 */
5630 static void
5631clear_to_end_of_line(void)
5632{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005633 COORD save = g_coord;
5634
5635 if (!USE_VTP)
5636 clear_chars(g_coord, Columns - g_coord.X);
5637 else
5638 {
5639 set_console_color_rgb();
5640 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5641 vtp_printf("\033[0K");
5642
5643 gotoxy(save.X + 1, save.Y + 1);
5644 g_coord = save;
5645 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646}
5647
5648
5649/*
5650 * Scroll the scroll region up by `cLines' lines
5651 */
5652 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005653scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654{
5655 COORD oldcoord = g_coord;
5656
5657 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5658 delete_lines(cLines);
5659
5660 g_coord = oldcoord;
5661}
5662
5663
5664/*
5665 * Set the scroll region
5666 */
5667 static void
5668set_scroll_region(
5669 unsigned left,
5670 unsigned top,
5671 unsigned right,
5672 unsigned bottom)
5673{
5674 if (left >= right
5675 || top >= bottom
5676 || right > (unsigned) Columns - 1
5677 || bottom > (unsigned) Rows - 1)
5678 return;
5679
5680 g_srScrollRegion.Left = left;
5681 g_srScrollRegion.Top = top;
5682 g_srScrollRegion.Right = right;
5683 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005684}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005685
Bram Moolenaar6982f422019-02-16 16:48:01 +01005686 static void
5687set_scroll_region_tb(
5688 unsigned top,
5689 unsigned bottom)
5690{
5691 if (top >= bottom || bottom > (unsigned)Rows - 1)
5692 return;
5693
5694 g_srScrollRegion.Top = top;
5695 g_srScrollRegion.Bottom = bottom;
5696}
5697
5698 static void
5699set_scroll_region_lr(
5700 unsigned left,
5701 unsigned right)
5702{
5703 if (left >= right || right > (unsigned)Columns - 1)
5704 return;
5705
5706 g_srScrollRegion.Left = left;
5707 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708}
5709
5710
5711/*
5712 * Insert `cLines' lines at the current cursor position
5713 */
5714 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005715insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005716{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005717 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718 COORD dest;
5719 CHAR_INFO fill;
5720
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005721 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5722
Bram Moolenaar6982f422019-02-16 16:48:01 +01005723 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724 dest.Y = g_coord.Y + cLines;
5725
Bram Moolenaar6982f422019-02-16 16:48:01 +01005726 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005727 source.Top = g_coord.Y;
5728 source.Right = g_srScrollRegion.Right;
5729 source.Bottom = g_srScrollRegion.Bottom - cLines;
5730
Bram Moolenaar6982f422019-02-16 16:48:01 +01005731 clip.Left = g_srScrollRegion.Left;
5732 clip.Top = g_coord.Y;
5733 clip.Right = g_srScrollRegion.Right;
5734 clip.Bottom = g_srScrollRegion.Bottom;
5735
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005736 fill.Char.AsciiChar = ' ';
5737 if (!USE_VTP)
5738 fill.Attributes = g_attrCurrent;
5739 else
5740 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005742 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005743
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005744 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5745
Bram Moolenaar6982f422019-02-16 16:48:01 +01005746 // Here we have to deal with a win32 console flake: If the scroll
5747 // region looks like abc and we scroll c to a and fill with d we get
5748 // cbd... if we scroll block c one line at a time to a, we get cdd...
5749 // vim expects cdd consistently... So we have to deal with that
5750 // here... (this also occurs scrolling the same way in the other
5751 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752
5753 if (source.Bottom < dest.Y)
5754 {
5755 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005756 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005757
Bram Moolenaar6982f422019-02-16 16:48:01 +01005758 coord.X = source.Left;
5759 for (i = clip.Top; i < dest.Y; ++i)
5760 {
5761 coord.Y = i;
5762 clear_chars(coord, source.Right - source.Left + 1);
5763 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005764 }
5765}
5766
5767
5768/*
5769 * Delete `cLines' lines at the current cursor position
5770 */
5771 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005772delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005774 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775 COORD dest;
5776 CHAR_INFO fill;
5777 int nb;
5778
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005779 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5780
Bram Moolenaar6982f422019-02-16 16:48:01 +01005781 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005782 dest.Y = g_coord.Y;
5783
Bram Moolenaar6982f422019-02-16 16:48:01 +01005784 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005785 source.Top = g_coord.Y + cLines;
5786 source.Right = g_srScrollRegion.Right;
5787 source.Bottom = g_srScrollRegion.Bottom;
5788
Bram Moolenaar6982f422019-02-16 16:48:01 +01005789 clip.Left = g_srScrollRegion.Left;
5790 clip.Top = g_coord.Y;
5791 clip.Right = g_srScrollRegion.Right;
5792 clip.Bottom = g_srScrollRegion.Bottom;
5793
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005794 fill.Char.AsciiChar = ' ';
5795 if (!USE_VTP)
5796 fill.Attributes = g_attrCurrent;
5797 else
5798 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005800 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005801
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005802 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5803
Bram Moolenaar6982f422019-02-16 16:48:01 +01005804 // Here we have to deal with a win32 console flake; See insert_lines()
5805 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806
5807 nb = dest.Y + (source.Bottom - source.Top) + 1;
5808
5809 if (nb < source.Top)
5810 {
5811 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005812 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005813
Bram Moolenaar6982f422019-02-16 16:48:01 +01005814 coord.X = source.Left;
5815 for (i = nb; i < clip.Bottom; ++i)
5816 {
5817 coord.Y = i;
5818 clear_chars(coord, source.Right - source.Left + 1);
5819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820 }
5821}
5822
5823
5824/*
5825 * Set the cursor position
5826 */
5827 static void
5828gotoxy(
5829 unsigned x,
5830 unsigned y)
5831{
5832 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5833 return;
5834
5835 /* external cursor coords are 1-based; internal are 0-based */
5836 g_coord.X = x - 1;
5837 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005838
5839 if (!USE_VTP)
5840 SetConsoleCursorPosition(g_hConOut, g_coord);
5841 else
5842 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843}
5844
5845
5846/*
5847 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005848 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005849 */
5850 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005851textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005852{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005853 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854
5855 SetConsoleTextAttribute(g_hConOut, wAttr);
5856}
5857
5858
5859 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005860textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005862 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005863
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005864 if (!USE_VTP)
5865 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5866 else
5867 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868}
5869
5870
5871 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005872textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005874 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005876 if (!USE_VTP)
5877 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5878 else
5879 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880}
5881
5882
5883/*
5884 * restore the default text attribute (whatever we started with)
5885 */
5886 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005887normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005889 if (!USE_VTP)
5890 textattr(g_attrDefault);
5891 else
5892 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893}
5894
5895
5896static WORD g_attrPreStandout = 0;
5897
5898/*
5899 * Make the text standout, by brightening it
5900 */
5901 static void
5902standout(void)
5903{
5904 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005905
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5907}
5908
5909
5910/*
5911 * Turn off standout mode
5912 */
5913 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005914standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915{
5916 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005918
5919 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920}
5921
5922
5923/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005924 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005925 */
5926 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005927mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928{
5929 char_u *p;
5930 int n;
5931
5932 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5933 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005934 if (
5935#ifdef FEAT_TERMGUICOLORS
5936 !p_tgc &&
5937#endif
5938 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939 {
5940 p = T_ME + 2;
5941 n = getdigits(&p);
5942 if (*p == 'm' && n > 0)
5943 {
5944 cterm_normal_fg_color = (n & 0xf) + 1;
5945 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5946 }
5947 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005948#ifdef FEAT_TERMGUICOLORS
5949 cterm_normal_fg_gui_color = INVALCOLOR;
5950 cterm_normal_bg_gui_color = INVALCOLOR;
5951#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952}
5953
5954
5955/*
5956 * visual bell: flash the screen
5957 */
5958 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005959visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960{
5961 COORD coordOrigin = {0, 0};
5962 WORD attrFlash = ~g_attrCurrent & 0xff;
5963
5964 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005965 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005966
5967 if (oldattrs == NULL)
5968 return;
5969 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5970 coordOrigin, &dwDummy);
5971 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5972 coordOrigin, &dwDummy);
5973
5974 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005975 if (!USE_VTP)
5976 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005977 coordOrigin, &dwDummy);
5978 vim_free(oldattrs);
5979}
5980
5981
5982/*
5983 * Make the cursor visible or invisible
5984 */
5985 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005986cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005987{
5988 s_cursor_visible = fVisible;
5989#ifdef MCH_CURSOR_SHAPE
5990 mch_update_cursor();
5991#endif
5992}
5993
5994
5995/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005996 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005997 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005999 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006000write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006001 char_u *pchBuf,
6002 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006003{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006004 COORD coord = g_coord;
6005 DWORD written;
6006 DWORD n, cchwritten, cells;
6007 static WCHAR *unicodebuf = NULL;
6008 static int unibuflen = 0;
6009 int length;
6010 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006011
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006012 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6013 if (unicodebuf == NULL || length > unibuflen)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006014 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006015 vim_free(unicodebuf);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006016 unicodebuf = LALLOC_MULT(WCHAR, length);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006017 unibuflen = length;
6018 }
6019 MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6020 unicodebuf, unibuflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006021
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006022 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006023
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006024 if (!USE_VTP)
6025 {
6026 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6027 coord, &written);
6028 // When writing fails or didn't write a single character, pretend one
6029 // character was written, otherwise we get stuck.
6030 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6031 coord, &cchwritten) == 0
6032 || cchwritten == 0 || cchwritten == (DWORD)-1)
6033 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006034 }
6035 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006036 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006037 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6038 NULL) == 0 || cchwritten == 0)
6039 cchwritten = 1;
6040 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006041
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006042 if (cchwritten == length)
6043 {
6044 written = cbToWrite;
6045 g_coord.X += (SHORT)cells;
6046 }
6047 else
6048 {
6049 char_u *p = pchBuf;
6050 for (n = 0; n < cchwritten; n++)
6051 MB_CPTR_ADV(p);
6052 written = p - pchBuf;
6053 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006054 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006055
6056 while (g_coord.X > g_srScrollRegion.Right)
6057 {
6058 g_coord.X -= (SHORT) Columns;
6059 if (g_coord.Y < g_srScrollRegion.Bottom)
6060 g_coord.Y++;
6061 }
6062
6063 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6064
6065 return written;
6066}
6067
6068
6069/*
6070 * mch_write(): write the output buffer to the screen, translating ESC
6071 * sequences into calls to console output routines.
6072 */
6073 void
6074mch_write(
6075 char_u *s,
6076 int len)
6077{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006078# ifdef VIMDLL
6079 if (gui.in_use)
6080 return;
6081# endif
6082
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083 s[len] = NUL;
6084
6085 if (!term_console)
6086 {
6087 write(1, s, (unsigned)len);
6088 return;
6089 }
6090
6091 /* translate ESC | sequences into faked bios calls */
6092 while (len--)
6093 {
6094 /* optimization: use one single write_chars for runs of text,
6095 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006096 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097
6098 if (p_wd)
6099 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006100 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006101 if (prefix != 0)
6102 prefix = 1;
6103 }
6104
6105 if (prefix != 0)
6106 {
6107 DWORD nWritten;
6108
6109 nWritten = write_chars(s, prefix);
6110#ifdef MCH_WRITE_DUMP
6111 if (fdDump)
6112 {
6113 fputc('>', fdDump);
6114 fwrite(s, sizeof(char_u), nWritten, fdDump);
6115 fputs("<\n", fdDump);
6116 }
6117#endif
6118 len -= (nWritten - 1);
6119 s += nWritten;
6120 }
6121 else if (s[0] == '\n')
6122 {
6123 /* \n, newline: go to the beginning of the next line or scroll */
6124 if (g_coord.Y == g_srScrollRegion.Bottom)
6125 {
6126 scroll(1);
6127 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6128 }
6129 else
6130 {
6131 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6132 }
6133#ifdef MCH_WRITE_DUMP
6134 if (fdDump)
6135 fputs("\\n\n", fdDump);
6136#endif
6137 s++;
6138 }
6139 else if (s[0] == '\r')
6140 {
6141 /* \r, carriage return: go to beginning of line */
6142 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6143#ifdef MCH_WRITE_DUMP
6144 if (fdDump)
6145 fputs("\\r\n", fdDump);
6146#endif
6147 s++;
6148 }
6149 else if (s[0] == '\b')
6150 {
6151 /* \b, backspace: move cursor one position left */
6152 if (g_coord.X > g_srScrollRegion.Left)
6153 g_coord.X--;
6154 else if (g_coord.Y > g_srScrollRegion.Top)
6155 {
6156 g_coord.X = g_srScrollRegion.Right;
6157 g_coord.Y--;
6158 }
6159 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6160#ifdef MCH_WRITE_DUMP
6161 if (fdDump)
6162 fputs("\\b\n", fdDump);
6163#endif
6164 s++;
6165 }
6166 else if (s[0] == '\a')
6167 {
6168 /* \a, bell */
6169 MessageBeep(0xFFFFFFFF);
6170#ifdef MCH_WRITE_DUMP
6171 if (fdDump)
6172 fputs("\\a\n", fdDump);
6173#endif
6174 s++;
6175 }
6176 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6177 {
6178#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006179 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006181 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006182 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183
6184 switch (s[2])
6185 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186 case '0': case '1': case '2': case '3': case '4':
6187 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006188 p = s + 1;
6189 do
6190 {
6191 ++p;
6192 args[argc] = getdigits(&p);
6193 argc += (argc < 15) ? 1 : 0;
6194 if (p > s + len)
6195 break;
6196 } while (*p == ';');
6197
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198 if (p > s + len)
6199 break;
6200
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006201 arg1 = args[0];
6202 arg2 = args[1];
6203 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006205 if (argc == 1 && args[0] == 0)
6206 normvideo();
6207 else if (argc == 1)
6208 {
6209 if (USE_VTP)
6210 textcolor((WORD) arg1);
6211 else
6212 textattr((WORD) arg1);
6213 }
6214 else if (USE_VTP)
6215 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006217 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006219 gotoxy(arg2, arg1);
6220 }
6221 else if (argc == 2 && *p == 'r')
6222 {
6223 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6224 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006225 else if (argc == 2 && *p == 'R')
6226 {
6227 set_scroll_region_tb(arg1, arg2);
6228 }
6229 else if (argc == 2 && *p == 'V')
6230 {
6231 set_scroll_region_lr(arg1, arg2);
6232 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006233 else if (argc == 1 && *p == 'A')
6234 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235 gotoxy(g_coord.X + 1,
6236 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6237 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006238 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 {
6240 textbackground((WORD) arg1);
6241 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006242 else if (argc == 1 && *p == 'C')
6243 {
6244 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6245 g_coord.Y + 1);
6246 }
6247 else if (argc == 1 && *p == 'f')
6248 {
6249 textcolor((WORD) arg1);
6250 }
6251 else if (argc == 1 && *p == 'H')
6252 {
6253 gotoxy(1, arg1);
6254 }
6255 else if (argc == 1 && *p == 'L')
6256 {
6257 insert_lines(arg1);
6258 }
6259 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 {
6261 delete_lines(arg1);
6262 }
6263
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006264 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 s = p + 1;
6266 break;
6267
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269 gotoxy(g_coord.X + 1,
6270 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6271 goto got3;
6272
6273 case 'B':
6274 visual_bell();
6275 goto got3;
6276
6277 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6279 g_coord.Y + 1);
6280 goto got3;
6281
6282 case 'E':
6283 termcap_mode_end();
6284 goto got3;
6285
6286 case 'F':
6287 standout();
6288 goto got3;
6289
6290 case 'f':
6291 standend();
6292 goto got3;
6293
6294 case 'H':
6295 gotoxy(1, 1);
6296 goto got3;
6297
6298 case 'j':
6299 clear_to_end_of_display();
6300 goto got3;
6301
6302 case 'J':
6303 clear_screen();
6304 goto got3;
6305
6306 case 'K':
6307 clear_to_end_of_line();
6308 goto got3;
6309
6310 case 'L':
6311 insert_lines(1);
6312 goto got3;
6313
6314 case 'M':
6315 delete_lines(1);
6316 goto got3;
6317
6318 case 'S':
6319 termcap_mode_start();
6320 goto got3;
6321
6322 case 'V':
6323 cursor_visible(TRUE);
6324 goto got3;
6325
6326 case 'v':
6327 cursor_visible(FALSE);
6328 goto got3;
6329
6330 got3:
6331 s += 3;
6332 len -= 2;
6333 }
6334
6335#ifdef MCH_WRITE_DUMP
6336 if (fdDump)
6337 {
6338 fputs("ESC | ", fdDump);
6339 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6340 fputc('\n', fdDump);
6341 }
6342#endif
6343 }
6344 else
6345 {
6346 /* Write a single character */
6347 DWORD nWritten;
6348
6349 nWritten = write_chars(s, 1);
6350#ifdef MCH_WRITE_DUMP
6351 if (fdDump)
6352 {
6353 fputc('>', fdDump);
6354 fwrite(s, sizeof(char_u), nWritten, fdDump);
6355 fputs("<\n", fdDump);
6356 }
6357#endif
6358
6359 len -= (nWritten - 1);
6360 s += nWritten;
6361 }
6362 }
6363
6364#ifdef MCH_WRITE_DUMP
6365 if (fdDump)
6366 fflush(fdDump);
6367#endif
6368}
6369
Bram Moolenaar4f974752019-02-17 17:44:42 +01006370#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371
6372
6373/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006374 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 */
6376 void
6377mch_delay(
6378 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006379 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006381#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006383#else /* Console */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006384# ifdef VIMDLL
6385 if (gui.in_use)
6386 {
6387 Sleep((int)msec); /* never wait for input */
6388 return;
6389 }
6390# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006392# ifdef FEAT_MZSCHEME
6393 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6394 {
6395 int towait = p_mzq;
6396
6397 /* if msec is large enough, wait by portions in p_mzq */
6398 while (msec > 0)
6399 {
6400 mzvim_check_threads();
6401 if (msec < towait)
6402 towait = msec;
6403 Sleep(towait);
6404 msec -= towait;
6405 }
6406 }
6407 else
6408# endif
6409 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006411 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006412#endif
6413}
6414
6415
6416/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006417 * This version of remove is not scared by a readonly (backup) file.
6418 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006419 * Return 0 for success, -1 for failure.
6420 */
6421 int
6422mch_remove(char_u *name)
6423{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006424 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 int n;
6426
Bram Moolenaar203258c2016-01-17 22:15:16 +01006427 /*
6428 * On Windows, deleting a directory's symbolic link is done by
6429 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6430 */
6431 if (mch_isdir(name) && mch_is_symbolic_link(name))
6432 return mch_rmdir(name);
6433
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006434 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6435
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006436 wn = enc_to_utf16(name, NULL);
6437 if (wn == NULL)
6438 return -1;
6439
6440 n = DeleteFileW(wn) ? 0 : -1;
6441 vim_free(wn);
6442 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006443}
6444
6445
6446/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006447 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006448 */
6449 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006450mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006452#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6453# ifdef VIMDLL
6454 if (!gui.in_use)
6455# endif
6456 if (g_fCtrlCPressed || g_fCBrkPressed)
6457 {
6458 ctrl_break_was_pressed = g_fCBrkPressed;
6459 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6460 got_int = TRUE;
6461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462#endif
6463}
6464
Bram Moolenaaree273972016-01-02 21:11:51 +01006465/* physical RAM to leave for the OS */
6466#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006467
6468/*
6469 * How much main memory in KiB that can be used by VIM.
6470 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006471 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006472mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006473{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006474 MEMORYSTATUSEX ms;
6475
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006476 /* Need to use GlobalMemoryStatusEx() when there is more memory than
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006477 * what fits in 32 bits. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006478 ms.dwLength = sizeof(MEMORYSTATUSEX);
6479 GlobalMemoryStatusEx(&ms);
6480 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006481 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006482 /* Process address space fits in physical RAM, use all of it. */
6483 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006484 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006485 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006486 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006487 /* Catch old NT box or perverse hardware setup. */
6488 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006489 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006490 /* Use physical RAM less reserve for OS + data. */
6491 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006492}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006495 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6497 * file whose short file name is "FOO.BAR" (its long file name will
6498 * be correct: "foo.bar~"). Because a file can be accessed by
6499 * either its SFN or its LFN, "foo.bar" has effectively been
6500 * renamed to "foo.bar", which is not at all what was wanted. This
6501 * seems to happen only when renaming files with three-character
6502 * extensions by appending a suffix that does not include ".".
6503 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6504 *
6505 * There is another problem, which isn't really a bug but isn't right either:
6506 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6507 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6508 * service pack 6. Doesn't seem to happen on Windows 98.
6509 *
6510 * Like rename(), returns 0 upon success, non-zero upon failure.
6511 * Should probably set errno appropriately when errors occur.
6512 */
6513 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006514mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006516 WCHAR *p;
6517 int i;
6518 WCHAR szTempFile[_MAX_PATH + 1];
6519 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006520 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006522 // No need to play tricks unless the file name contains a "~" as the
6523 // seventh character.
6524 p = wold;
6525 for (i = 0; wold[i] != NUL; ++i)
6526 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6527 && wold[i + 1] != 0)
6528 p = wold + i + 1;
6529 if ((int)(wold + i - p) < 8 || p[6] != '~')
6530 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006532 // Get base path of new file name. Undocumented feature: If pszNewFile is
6533 // a directory, no error is returned and pszFilePart will be NULL.
6534 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006536 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006538 // Get (and create) a unique temporary file name in directory of new file
6539 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 return -2;
6541
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006542 // blow the temp file away
6543 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 return -3;
6545
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006546 // rename old file to the temp file
6547 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 return -4;
6549
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006550 // now create an empty file called pszOldFile; this prevents the operating
6551 // system using pszOldFile as an alias (SFN) if we're renaming within the
6552 // same directory. For example, we're editing a file called
6553 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6554 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6555 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6556 // cause all sorts of problems later in buf_write(). So, we create an
6557 // empty file called filena~1.txt and the system will have to find some
6558 // other SFN for filena~1.txt~, such as filena~2.txt
6559 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6561 return -5;
6562 if (!CloseHandle(hf))
6563 return -6;
6564
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006565 // rename the temp file to the new file
6566 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006568 // Renaming failed. Rename the file back to its old name, so that it
6569 // looks like nothing happened.
6570 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571 return -7;
6572 }
6573
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006574 // Seems to be left around on Novell filesystems
6575 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006577 // finally, remove the empty old file
6578 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579 return -8;
6580
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006581 return 0;
6582}
6583
6584
6585/*
6586 * Converts the filenames to UTF-16, then call mch_wrename().
6587 * Like rename(), returns 0 upon success, non-zero upon failure.
6588 */
6589 int
6590mch_rename(
6591 const char *pszOldFile,
6592 const char *pszNewFile)
6593{
6594 WCHAR *wold = NULL;
6595 WCHAR *wnew = NULL;
6596 int retval = -1;
6597
6598 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6599 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6600 if (wold != NULL && wnew != NULL)
6601 retval = mch_wrename(wold, wnew);
6602 vim_free(wold);
6603 vim_free(wnew);
6604 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605}
6606
6607/*
6608 * Get the default shell for the current hardware platform
6609 */
6610 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006611default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006613 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614}
6615
6616/*
6617 * mch_access() extends access() to do more detailed check on network drives.
6618 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6619 */
6620 int
6621mch_access(char *n, int p)
6622{
6623 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624 int retval = -1; /* default: fail */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006625 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006627 wn = enc_to_utf16((char_u *)n, NULL);
6628 if (wn == NULL)
6629 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006631 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634
6635 if (p & R_OK)
6636 {
6637 /* Read check is performed by seeing if we can do a find file on
6638 * the directory for any file. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006639 int i;
6640 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006642 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6643 TempNameW[i] = wn[i];
6644 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6645 TempNameW[i++] = '\\';
6646 TempNameW[i++] = '*';
6647 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006649 hFile = FindFirstFileW(TempNameW, &d);
6650 if (hFile == INVALID_HANDLE_VALUE)
6651 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006652 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654 }
6655
6656 if (p & W_OK)
6657 {
6658 /* Trying to create a temporary file in the directory should catch
6659 * directories on read-only network shares. However, in
6660 * directories whose ACL allows writes but denies deletes will end
6661 * up keeping the temporary file :-(. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006662 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6663 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006664 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006665 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666 }
6667 }
6668 else
6669 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006670 // Don't consider a file read-only if another process has opened it.
6671 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
6672
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673 /* Trying to open the file for the required access does ACL, read-only
6674 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006675 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
6676 | ((p & R_OK) ? GENERIC_READ : 0);
6677
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006678 hFile = CreateFileW(wn, access_mode, share_mode,
6679 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 if (hFile == INVALID_HANDLE_VALUE)
6681 goto getout;
6682 CloseHandle(hFile);
6683 }
6684
6685 retval = 0; /* success */
6686getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 return retval;
6689}
6690
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006692 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 */
6694 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006695mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696{
6697 WCHAR *wn;
6698 int f;
6699
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006700 wn = enc_to_utf16((char_u *)name, NULL);
6701 if (wn == NULL)
6702 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006704 f = _wopen(wn, flags, mode);
6705 vim_free(wn);
6706 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707}
6708
6709/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006710 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711 */
6712 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006713mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006714{
6715 WCHAR *wn, *wm;
6716 FILE *f = NULL;
6717
Bram Moolenaara12a1612019-01-24 16:39:02 +01006718#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006719 /* Work around an annoying assertion in the Microsoft debug CRT
6720 * when mode's text/binary setting doesn't match _get_fmode(). */
6721 char newMode = mode[strlen(mode) - 1];
6722 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006723
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006724 _get_fmode(&oldMode);
6725 if (newMode == 't')
6726 _set_fmode(_O_TEXT);
6727 else if (newMode == 'b')
6728 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006729#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006730 wn = enc_to_utf16((char_u *)name, NULL);
6731 wm = enc_to_utf16((char_u *)mode, NULL);
6732 if (wn != NULL && wm != NULL)
6733 f = _wfopen(wn, wm);
6734 vim_free(wn);
6735 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006736
Bram Moolenaara12a1612019-01-24 16:39:02 +01006737#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006738 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006739#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006740 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006742
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743/*
6744 * SUB STREAM (aka info stream) handling:
6745 *
6746 * NTFS can have sub streams for each file. Normal contents of file is
6747 * stored in the main stream, and extra contents (author information and
6748 * title and so on) can be stored in sub stream. After Windows 2000, user
6749 * can access and store those informations in sub streams via explorer's
6750 * property menuitem in right click menu. Those informations in sub streams
6751 * were lost when copying only the main stream. So we have to copy sub
6752 * streams.
6753 *
6754 * Incomplete explanation:
6755 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6756 * More useful info and an example:
6757 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6758 */
6759
6760/*
6761 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6762 * and write to stream "substream" of file "to".
6763 * Errors are ignored.
6764 */
6765 static void
6766copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6767{
6768 HANDLE hTo;
6769 WCHAR *to_name;
6770
6771 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6772 wcscpy(to_name, to);
6773 wcscat(to_name, substream);
6774
6775 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6776 FILE_ATTRIBUTE_NORMAL, NULL);
6777 if (hTo != INVALID_HANDLE_VALUE)
6778 {
6779 long done;
6780 DWORD todo;
6781 DWORD readcnt, written;
6782 char buf[4096];
6783
6784 /* Copy block of bytes at a time. Abort when something goes wrong. */
6785 for (done = 0; done < len; done += written)
6786 {
6787 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006788 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6789 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6791 FALSE, FALSE, context)
6792 || readcnt != todo
6793 || !WriteFile(hTo, buf, todo, &written, NULL)
6794 || written != todo)
6795 break;
6796 }
6797 CloseHandle(hTo);
6798 }
6799
6800 free(to_name);
6801}
6802
6803/*
6804 * Copy info streams from file "from" to file "to".
6805 */
6806 static void
6807copy_infostreams(char_u *from, char_u *to)
6808{
6809 WCHAR *fromw;
6810 WCHAR *tow;
6811 HANDLE sh;
6812 WIN32_STREAM_ID sid;
6813 int headersize;
6814 WCHAR streamname[_MAX_PATH];
6815 DWORD readcount;
6816 void *context = NULL;
6817 DWORD lo, hi;
6818 int len;
6819
6820 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006821 fromw = enc_to_utf16(from, NULL);
6822 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823 if (fromw != NULL && tow != NULL)
6824 {
6825 /* Open the file for reading. */
6826 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6827 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6828 if (sh != INVALID_HANDLE_VALUE)
6829 {
6830 /* Use BackupRead() to find the info streams. Repeat until we
6831 * have done them all.*/
6832 for (;;)
6833 {
6834 /* Get the header to find the length of the stream name. If
6835 * the "readcount" is zero we have done all info streams. */
6836 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006837 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6839 &readcount, FALSE, FALSE, &context)
6840 || readcount == 0)
6841 break;
6842
6843 /* We only deal with streams that have a name. The normal
6844 * file data appears to be without a name, even though docs
6845 * suggest it is called "::$DATA". */
6846 if (sid.dwStreamNameSize > 0)
6847 {
6848 /* Read the stream name. */
6849 if (!BackupRead(sh, (LPBYTE)streamname,
6850 sid.dwStreamNameSize,
6851 &readcount, FALSE, FALSE, &context))
6852 break;
6853
6854 /* Copy an info stream with a name ":anything:$DATA".
6855 * Skip "::$DATA", it has no stream name (examples suggest
6856 * it might be used for the normal file contents).
6857 * Note that BackupRead() counts bytes, but the name is in
6858 * wide characters. */
6859 len = readcount / sizeof(WCHAR);
6860 streamname[len] = 0;
6861 if (len > 7 && wcsicmp(streamname + len - 6,
6862 L":$DATA") == 0)
6863 {
6864 streamname[len - 6] = 0;
6865 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006866 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867 }
6868 }
6869
6870 /* Advance to the next stream. We might try seeking too far,
6871 * but BackupSeek() doesn't skip over stream borders, thus
6872 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006873 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874 &lo, &hi, &context);
6875 }
6876
6877 /* Clear the context. */
6878 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6879
6880 CloseHandle(sh);
6881 }
6882 }
6883 vim_free(fromw);
6884 vim_free(tow);
6885}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886
6887/*
6888 * Copy file attributes from file "from" to file "to".
6889 * For Windows NT and later we copy info streams.
6890 * Always returns zero, errors are ignored.
6891 */
6892 int
6893mch_copy_file_attribute(char_u *from, char_u *to)
6894{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895 /* File streams only work on Windows NT and later. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006896 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 return 0;
6898}
6899
6900#if defined(MYRESETSTKOFLW) || defined(PROTO)
6901/*
6902 * Recreate a destroyed stack guard page in win32.
6903 * Written by Benjamin Peterson.
6904 */
6905
6906/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01006907# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908
6909/*
6910 * This function does the same thing as _resetstkoflw(), which is only
6911 * available in DevStudio .net and later.
6912 * Returns 0 for failure, 1 for success.
6913 */
6914 int
6915myresetstkoflw(void)
6916{
6917 BYTE *pStackPtr;
6918 BYTE *pGuardPage;
6919 BYTE *pStackBase;
6920 BYTE *pLowestPossiblePage;
6921 MEMORY_BASIC_INFORMATION mbi;
6922 SYSTEM_INFO si;
6923 DWORD nPageSize;
6924 DWORD dummy;
6925
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926 /* We need to know the system page size. */
6927 GetSystemInfo(&si);
6928 nPageSize = si.dwPageSize;
6929
6930 /* ...and the current stack pointer */
6931 pStackPtr = (BYTE*)_alloca(1);
6932
6933 /* ...and the base of the stack. */
6934 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6935 return 0;
6936 pStackBase = (BYTE*)mbi.AllocationBase;
6937
6938 /* ...and the page thats min_stack_req pages away from stack base; this is
6939 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006940 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006943 /* We want the first committed page in the stack Start at the stack
6944 * base and move forward through memory until we find a committed block.
6945 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946 BYTE *pBlock = pStackBase;
6947
Bram Moolenaara466c992005-07-09 21:03:22 +00006948 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 {
6950 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6951 return 0;
6952
6953 pBlock += mbi.RegionSize;
6954
6955 if (mbi.State & MEM_COMMIT)
6956 break;
6957 }
6958
6959 /* mbi now describes the first committed block in the stack. */
6960 if (mbi.Protect & PAGE_GUARD)
6961 return 1;
6962
6963 /* decide where the guard page should start */
6964 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6965 pGuardPage = pLowestPossiblePage;
6966 else
6967 pGuardPage = (BYTE*)mbi.BaseAddress;
6968
6969 /* allocate the guard page */
6970 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6971 return 0;
6972
6973 /* apply the guard attribute to the page */
6974 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6975 &dummy))
6976 return 0;
6977 }
6978
6979 return 1;
6980}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006981#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006983
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006984/*
6985 * The command line arguments in UCS2
6986 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006987static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006988static LPWSTR *ArglistW = NULL;
6989static int global_argc = 0;
6990static char **global_argv;
6991
6992static int used_file_argc = 0; /* last argument in global_argv[] used
6993 for the argument list. */
6994static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6995 command line arguments added to
6996 the argument list */
6997static int used_file_count = 0; /* nr of entries in used_file_indexes */
6998static int used_file_literal = FALSE; /* take file names literally */
6999static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007000static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007001static int used_alist_count = 0;
7002
7003
7004/*
7005 * Get the command line arguments. Unicode version.
7006 * Returns argc. Zero when something fails.
7007 */
7008 int
7009get_cmd_argsW(char ***argvp)
7010{
7011 char **argv = NULL;
7012 int argc = 0;
7013 int i;
7014
Bram Moolenaar14993322014-09-09 12:25:33 +02007015 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007016 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7017 if (ArglistW != NULL)
7018 {
7019 argv = malloc((nArgsW + 1) * sizeof(char *));
7020 if (argv != NULL)
7021 {
7022 argc = nArgsW;
7023 argv[argc] = NULL;
7024 for (i = 0; i < argc; ++i)
7025 {
7026 int len;
7027
7028 /* Convert each Unicode argument to the current codepage. */
7029 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007030 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007031 (LPSTR *)&argv[i], &len, 0, 0);
7032 if (argv[i] == NULL)
7033 {
7034 /* Out of memory, clear everything. */
7035 while (i > 0)
7036 free(argv[--i]);
7037 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007038 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007039 argc = 0;
7040 }
7041 }
7042 }
7043 }
7044
7045 global_argc = argc;
7046 global_argv = argv;
7047 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007048 {
7049 if (used_file_indexes != NULL)
7050 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007051 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007052 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007053
7054 if (argvp != NULL)
7055 *argvp = argv;
7056 return argc;
7057}
7058
7059 void
7060free_cmd_argsW(void)
7061{
7062 if (ArglistW != NULL)
7063 {
7064 GlobalFree(ArglistW);
7065 ArglistW = NULL;
7066 }
7067}
7068
7069/*
7070 * Remember "name" is an argument that was added to the argument list.
7071 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7072 * is called.
7073 */
7074 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007075used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007076{
7077 int i;
7078
7079 if (used_file_indexes == NULL)
7080 return;
7081 for (i = used_file_argc + 1; i < global_argc; ++i)
7082 if (STRCMP(global_argv[i], name) == 0)
7083 {
7084 used_file_argc = i;
7085 used_file_indexes[used_file_count++] = i;
7086 break;
7087 }
7088 used_file_literal = literal;
7089 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007090 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007091}
7092
7093/*
7094 * Remember the length of the argument list as it was. If it changes then we
7095 * leave it alone when 'encoding' is set.
7096 */
7097 void
7098set_alist_count(void)
7099{
7100 used_alist_count = GARGCOUNT;
7101}
7102
7103/*
7104 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7105 * has been changed while starting up. Use the UCS-2 command line arguments
7106 * and convert them to 'encoding'.
7107 */
7108 void
7109fix_arg_enc(void)
7110{
7111 int i;
7112 int idx;
7113 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007114 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007115
7116 /* Safety checks:
7117 * - if argument count differs between the wide and non-wide argument
7118 * list, something must be wrong.
7119 * - the file name arguments must have been located.
7120 * - the length of the argument list wasn't changed by the user.
7121 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007122 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007123 || ArglistW == NULL
7124 || used_file_indexes == NULL
7125 || used_file_count == 0
7126 || used_alist_count != GARGCOUNT)
7127 return;
7128
Bram Moolenaar86b68352004-12-27 21:59:20 +00007129 /* Remember the buffer numbers for the arguments. */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007130 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007131 if (fnum_list == NULL)
7132 return; /* out of memory */
7133 for (i = 0; i < GARGCOUNT; ++i)
7134 fnum_list[i] = GARGLIST[i].ae_fnum;
7135
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007136 /* Clear the argument list. Make room for the new arguments. */
7137 alist_clear(&global_alist);
7138 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007139 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007140
7141 for (i = 0; i < used_file_count; ++i)
7142 {
7143 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007144 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007145 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007146 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007147 int literal = used_file_literal;
7148
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007149# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007150 /* When using diff mode may need to concatenate file name to
7151 * directory name. Just like it's done in main(). */
7152 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7153 && !mch_isdir(alist_name(&GARGLIST[0])))
7154 {
7155 char_u *r;
7156
7157 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7158 if (r != NULL)
7159 {
7160 vim_free(str);
7161 str = r;
7162 }
7163 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007164# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007165 /* Re-use the old buffer by renaming it. When not using literal
7166 * names it's done by alist_expand() below. */
7167 if (used_file_literal)
7168 buf_set_name(fnum_list[i], str);
7169
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007170 /* Check backtick literal. backtick literal is already expanded in
7171 * main.c, so this part add str as literal. */
7172 if (literal == FALSE)
7173 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007174 size_t len = STRLEN(str);
7175
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007176 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7177 literal = TRUE;
7178 }
7179 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007180 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007181 }
7182
7183 if (!used_file_literal)
7184 {
7185 /* Now expand wildcards in the arguments. */
7186 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7187 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007188 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7189 * Also, unset wildignore to not be influenced by this option.
7190 * The arguments specified in command-line should be kept even if
7191 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007192 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007193 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007194 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007195 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007196 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007197 }
7198
7199 /* If wildcard expansion failed, we are editing the first file of the
7200 * arglist and there is no file name: Edit the first argument now. */
7201 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7202 {
7203 do_cmdline_cmd((char_u *)":rewind");
7204 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007205 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007206 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007207
7208 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007209}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007210
7211 int
7212mch_setenv(char *var, char *value, int x)
7213{
7214 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007215 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007216
Bram Moolenaar964b3742019-05-24 18:54:09 +02007217 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007218 if (envbuf == NULL)
7219 return -1;
7220
7221 sprintf((char *)envbuf, "%s=%s", var, value);
7222
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007223 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007224
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007225 vim_free(envbuf);
7226 if (p == NULL)
7227 return -1;
7228 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007229#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007230 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007231#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007232 // Unlike Un*x systems, we can free the string for _wputenv().
7233 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007234
7235 return 0;
7236}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007237
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007238/*
7239 * Support for 256 colors and 24-bit colors was added in Windows 10
7240 * version 1703 (Creators update).
7241 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007242#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7243
7244/*
7245 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007246 * version 1809 (October 2018 update). However, that version is unstable.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007247 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007248#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
7249#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007250
7251 static void
7252vtp_flag_init(void)
7253{
7254 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007255#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007256 DWORD mode;
7257 HANDLE out;
7258
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007259# ifdef VIMDLL
7260 if (!gui.in_use)
7261# endif
7262 {
7263 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007264
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007265 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7266 GetConsoleMode(out, &mode);
7267 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7268 if (SetConsoleMode(out, mode) == 0)
7269 vtp_working = 0;
7270 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007271#endif
7272
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007273 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007274 conpty_working = 1;
7275 if (ver >= CONPTY_STABLE_BUILD)
7276 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007277
7278}
7279
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007280#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007281
7282 static void
7283vtp_init(void)
7284{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007285 HMODULE hKerneldll;
7286 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007287# ifdef FEAT_TERMGUICOLORS
7288 COLORREF fg, bg;
7289# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007290
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007291 /* Use functions supported from Vista */
7292 hKerneldll = GetModuleHandle("kernel32.dll");
7293 if (hKerneldll != NULL)
7294 {
7295 pGetConsoleScreenBufferInfoEx =
7296 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7297 hKerneldll, "GetConsoleScreenBufferInfoEx");
7298 pSetConsoleScreenBufferInfoEx =
7299 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7300 hKerneldll, "SetConsoleScreenBufferInfoEx");
7301 if (pGetConsoleScreenBufferInfoEx != NULL
7302 && pSetConsoleScreenBufferInfoEx != NULL)
7303 has_csbiex = TRUE;
7304 }
7305
7306 csbi.cbSize = sizeof(csbi);
7307 if (has_csbiex)
7308 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007309 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7310 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7311
7312# ifdef FEAT_TERMGUICOLORS
7313 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7314 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7315 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7316 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7317 default_console_color_bg = bg;
7318 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007319# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007320
7321 set_console_color_rgb();
7322}
7323
7324 static void
7325vtp_exit(void)
7326{
7327 reset_console_color_rgb();
7328}
7329
7330 static int
7331vtp_printf(
7332 char *format,
7333 ...)
7334{
7335 char_u buf[100];
7336 va_list list;
7337 DWORD result;
7338
7339 va_start(list, format);
7340 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7341 va_end(list);
7342 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7343 return (int)result;
7344}
7345
7346 static void
7347vtp_sgr_bulk(
7348 int arg)
7349{
7350 int args[1];
7351
7352 args[0] = arg;
7353 vtp_sgr_bulks(1, args);
7354}
7355
7356 static void
7357vtp_sgr_bulks(
7358 int argc,
7359 int *args
7360)
7361{
7362 /* 2('\033[') + 4('255.') * 16 + NUL */
7363 char_u buf[2 + (4 * 16) + 1];
7364 char_u *p;
7365 int i;
7366
7367 p = buf;
7368 *p++ = '\033';
7369 *p++ = '[';
7370
7371 for (i = 0; i < argc; ++i)
7372 {
7373 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7374 *p++ = ';';
7375 }
7376 p--;
7377 *p++ = 'm';
7378 *p = NUL;
7379 vtp_printf((char *)buf);
7380}
7381
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007382# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007383 static int
7384ctermtoxterm(
7385 int cterm)
7386{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007387 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007388
7389 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7390 return (((int)r << 16) | ((int)g << 8) | (int)b);
7391}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007392# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007393
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007394 static void
7395set_console_color_rgb(void)
7396{
7397# ifdef FEAT_TERMGUICOLORS
7398 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7399 int id;
7400 guicolor_T fg = INVALCOLOR;
7401 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007402 int ctermfg;
7403 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007404
7405 if (!USE_VTP)
7406 return;
7407
7408 id = syn_name2id((char_u *)"Normal");
Bram Moolenaard5a58862019-03-07 06:40:27 +01007409 if (id > 0 && p_tgc)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007410 syn_id2colors(id, &fg, &bg);
7411 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007412 {
7413 ctermfg = -1;
7414 if (id > 0)
7415 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007416 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7417 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007418 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007419 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007420 {
7421 ctermbg = -1;
7422 if (id > 0)
7423 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007424 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7425 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007426 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007427 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7428 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7429
7430 csbi.cbSize = sizeof(csbi);
7431 if (has_csbiex)
7432 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7433
7434 csbi.cbSize = sizeof(csbi);
7435 csbi.srWindow.Right += 1;
7436 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007437 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7438 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007439 if (has_csbiex)
7440 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7441# endif
7442}
7443
7444 static void
7445reset_console_color_rgb(void)
7446{
7447# ifdef FEAT_TERMGUICOLORS
7448 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7449
7450 csbi.cbSize = sizeof(csbi);
7451 if (has_csbiex)
7452 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7453
7454 csbi.cbSize = sizeof(csbi);
7455 csbi.srWindow.Right += 1;
7456 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007457 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7458 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007459 if (has_csbiex)
7460 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7461# endif
7462}
7463
7464 void
7465control_console_color_rgb(void)
7466{
7467 if (USE_VTP)
7468 set_console_color_rgb();
7469 else
7470 reset_console_color_rgb();
7471}
7472
7473 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007474use_vtp(void)
7475{
7476 return USE_VTP;
7477}
7478
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007479 int
7480is_term_win32(void)
7481{
7482 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7483}
7484
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007485 int
7486has_vtp_working(void)
7487{
7488 return vtp_working;
7489}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007490
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007491#endif
7492
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007493 int
7494has_conpty_working(void)
7495{
7496 return conpty_working;
7497}
7498
7499 int
7500is_conpty_stable(void)
7501{
7502 return conpty_stable;
7503}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007504
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007505#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007506 void
7507resize_console_buf(void)
7508{
7509 CONSOLE_SCREEN_BUFFER_INFO csbi;
7510 COORD coord;
7511 SMALL_RECT newsize;
7512
7513 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
7514 {
7515 coord.X = SRWIDTH(csbi.srWindow);
7516 coord.Y = SRHEIGHT(csbi.srWindow);
7517 SetConsoleScreenBufferSize(g_hConOut, coord);
7518
7519 newsize.Left = 0;
7520 newsize.Top = 0;
7521 newsize.Right = coord.X - 1;
7522 newsize.Bottom = coord.Y - 1;
7523 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
7524
7525 SetConsoleScreenBufferSize(g_hConOut, coord);
7526 }
7527}
7528#endif