blob: e4ebc0c6d961ccfbacd2a3d05cd4dc7fe7c873dd [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
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
103typedef int COLORREF;
104typedef int CONSOLE_CURSOR_INFO;
105typedef int COORD;
106typedef int DWORD;
107typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100108typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000109typedef int HDC;
110typedef int HFONT;
111typedef int HICON;
112typedef int HINSTANCE;
113typedef int HWND;
114typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200115typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116typedef int KEY_EVENT_RECORD;
117typedef int LOGFONT;
118typedef int LPBOOL;
119typedef int LPCTSTR;
120typedef int LPDWORD;
121typedef int LPSTR;
122typedef int LPTSTR;
123typedef int LPVOID;
124typedef int MOUSE_EVENT_RECORD;
125typedef int PACL;
126typedef int PDWORD;
127typedef int PHANDLE;
128typedef int PRINTDLG;
129typedef int PSECURITY_DESCRIPTOR;
130typedef int PSID;
131typedef int SECURITY_INFORMATION;
132typedef int SHORT;
133typedef int SMALL_RECT;
134typedef int TEXTMETRIC;
135typedef int TOKEN_INFORMATION_CLASS;
136typedef int TRUSTEE;
137typedef int WORD;
138typedef int WCHAR;
139typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100140typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200141typedef int SE_OBJECT_TYPE;
142typedef int PSNSECINFO;
143typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100144typedef int STARTUPINFO;
145typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200146typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100147# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200150#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100151// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000152static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
153static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
154
Bram Moolenaar0f873732019-12-05 20:28:46 +0100155// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159// The attribute of the screen when the editor was started
160static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161static WORD g_attrCurrent;
162
Bram Moolenaar0f873732019-12-05 20:28:46 +0100163static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
164static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
165static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167static void scroll(unsigned cLines);
168static void set_scroll_region(unsigned left, unsigned top,
169 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100170static void set_scroll_region_tb(unsigned top, unsigned bottom);
171static void set_scroll_region_lr(unsigned left, unsigned right);
172static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000173static void delete_lines(unsigned cLines);
174static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static int s_cursor_visible = TRUE;
177static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200178#endif
179#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100189static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200190static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200192static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100193static void vtp_flag_init();
194
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200195#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100196static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100197static void vtp_init();
198static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_sgr_bulk(int arg);
200static void vtp_sgr_bulks(int argc, int *argv);
201
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200202static int wt_working = 0;
203static void wt_init();
204
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100205static guicolor_T save_console_bg_rgb;
206static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100207static guicolor_T store_console_bg_rgb;
208static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100209
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200210static int g_color_index_bg = 0;
211static int g_color_index_fg = 7;
212
213# ifdef FEAT_TERMGUICOLORS
214static int default_console_color_bg = 0x000000; // black
215static int default_console_color_fg = 0xc0c0c0; // white
216# endif
217
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100218# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200219# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200220# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100221# else
222# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200223# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100224# endif
225
226static void set_console_color_rgb(void);
227static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100228static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100229#endif
230
Bram Moolenaar0f873732019-12-05 20:28:46 +0100231// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
233# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
234#endif
235
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200236#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100237static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238#endif
239
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200240static char_u *exe_path = NULL;
241
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100242static BOOL win8_or_later = FALSE;
243
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200244# if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
245# define UChar UnicodeChar
246# else
247# define UChar uChar.UnicodeChar
248# endif
249
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200250#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100251// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100252typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
253{
254 ULONG cbSize;
255 COORD dwSize;
256 COORD dwCursorPosition;
257 WORD wAttributes;
258 SMALL_RECT srWindow;
259 COORD dwMaximumWindowSize;
260 WORD wPopupAttributes;
261 BOOL bFullscreenSupported;
262 COLORREF ColorTable[16];
263} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
264typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
265static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
266typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
267static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
268static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100269#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100270
271/*
272 * Get version number including build number
273 */
274typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100275#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100276 (((major) << 24) | ((minor) << 16) | (build))
277
278 static DWORD
279get_build_number(void)
280{
281 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
282 HMODULE hNtdll;
283 PfnRtlGetVersion pRtlGetVersion;
284 DWORD ver = MAKE_VER(0, 0, 0);
285
286 hNtdll = GetModuleHandle("ntdll.dll");
287 if (hNtdll != NULL)
288 {
289 pRtlGetVersion =
290 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
291 pRtlGetVersion(&osver);
292 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
293 min(osver.dwMinorVersion, 255),
294 min(osver.dwBuildNumber, 32767));
295 }
296 return ver;
297}
298
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200299#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200300 static BOOL
301is_ambiwidth_event(
302 INPUT_RECORD *ir)
303{
304 return ir->EventType == KEY_EVENT
305 && ir->Event.KeyEvent.bKeyDown
306 && ir->Event.KeyEvent.wRepeatCount == 1
307 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
308 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
309 && ir->Event.KeyEvent.UChar == 0
310 && ir->Event.KeyEvent.dwControlKeyState == 2;
311}
312
313 static void
314make_ambiwidth_event(
315 INPUT_RECORD *down,
316 INPUT_RECORD *up)
317{
318 down->Event.KeyEvent.wVirtualKeyCode = 0;
319 down->Event.KeyEvent.wVirtualScanCode = 0;
320 down->Event.KeyEvent.UChar = up->Event.KeyEvent.UChar;
321 down->Event.KeyEvent.dwControlKeyState = 0;
322}
323
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324/*
325 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100326 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100327 */
328 static BOOL
329read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100330 HANDLE hInput,
331 INPUT_RECORD *lpBuffer,
332 DWORD nLength,
333 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100334{
335 enum
336 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100338 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100339 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100340 static DWORD s_dwIndex = 0;
341 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100342 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100343 int head;
344 int tail;
345 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200346 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100347
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200348 if (nLength == -2)
349 return (s_dwMax > 0) ? TRUE : FALSE;
350
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100351 if (!win8_or_later)
352 {
353 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200354 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
355 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100356 }
357
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100358 if (s_dwMax == 0)
359 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200360 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200361 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200362 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
363 if (dwEvents == 0 && nLength == -1)
364 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
365 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100366 s_dwIndex = 0;
367 s_dwMax = dwEvents;
368 if (dwEvents == 0)
369 {
370 *lpEvents = 0;
371 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100372 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100373
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200374 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
375 if (is_ambiwidth_event(&s_irCache[i]))
376 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
377
Bram Moolenaardd415a62014-02-05 14:02:27 +0100378 if (s_dwMax > 1)
379 {
380 head = 0;
381 tail = s_dwMax - 1;
382 while (head != tail)
383 {
384 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
385 && s_irCache[head + 1].EventType
386 == WINDOW_BUFFER_SIZE_EVENT)
387 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100388 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100389 for (i = head; i < tail; ++i)
390 s_irCache[i] = s_irCache[i + 1];
391 --tail;
392 continue;
393 }
394 head++;
395 }
396 s_dwMax = tail + 1;
397 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100398 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100399
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200400 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
401 {
402 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
403 {
404 s_irPseudo = s_irCache[s_dwIndex];
405 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
406 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
407 *lpBuffer = s_irPseudo;
408 *lpEvents = 1;
409 return TRUE;
410 }
411 }
412
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100413 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200414 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100415 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100416 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100417 return TRUE;
418}
419
420/*
421 * Version of PeekConsoleInput() that works with IME.
422 */
423 static BOOL
424peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100425 HANDLE hInput,
426 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200427 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100428 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100429{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100430 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100431}
432
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100433# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200434 static DWORD
435msg_wait_for_multiple_objects(
436 DWORD nCount,
437 LPHANDLE pHandles,
438 BOOL fWaitAll,
439 DWORD dwMilliseconds,
440 DWORD dwWakeMask)
441{
442 if (read_console_input(NULL, NULL, -2, NULL))
443 return WAIT_OBJECT_0;
444 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
445 dwMilliseconds, dwWakeMask);
446}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100447# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200448
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100449# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200450 static DWORD
451wait_for_single_object(
452 HANDLE hHandle,
453 DWORD dwMilliseconds)
454{
455 if (read_console_input(NULL, NULL, -2, NULL))
456 return WAIT_OBJECT_0;
457 return WaitForSingleObject(hHandle, dwMilliseconds);
458}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100459# endif
460#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200461
Bram Moolenaar071d4272004-06-13 20:20:40 +0000462 static void
463get_exe_name(void)
464{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100465 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
466 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100467#define MAX_ENV_PATH_LEN 8192
468 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200469 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470
471 if (exe_name == NULL)
472 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100473 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100474 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 if (*temp != NUL)
476 exe_name = FullName_save((char_u *)temp, FALSE);
477 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000480 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200481 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000483 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100484 // Append our starting directory to $PATH, so that when doing
485 // "!xxd" it's found in our starting directory. Needed because
486 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200487 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100488 if (p == NULL
489 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200490 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100491 if (p == NULL || *p == NUL)
492 temp[0] = NUL;
493 else
494 {
495 STRCPY(temp, p);
496 STRCAT(temp, ";");
497 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100499 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200500 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000501 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000502 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503}
504
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200505/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100506 * Unescape characters in "p" that appear in "escaped".
507 */
508 static void
509unescape_shellxquote(char_u *p, char_u *escaped)
510{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100511 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100512 int n;
513
514 while (*p != NUL)
515 {
516 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
517 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100518 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100519 p += n;
520 l -= n;
521 }
522}
523
524/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200525 * Load library "name".
526 */
527 HINSTANCE
528vimLoadLib(char *name)
529{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200530 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200531
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200532 // No need to load any library when registering OLE.
533 if (found_register_arg)
534 return dll;
535
Bram Moolenaar0f873732019-12-05 20:28:46 +0100536 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
537 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200538 if (exe_path == NULL)
539 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200540 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200541 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200542 WCHAR old_dirw[MAXPATHL];
543
544 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
545 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100546 // Change directory to where the executable is, both to make
547 // sure we find a .dll there and to avoid looking for a .dll
548 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100549 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200550 dll = LoadLibrary(name);
551 SetCurrentDirectoryW(old_dirw);
552 return dll;
553 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200554 }
555 return dll;
556}
557
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200558#if defined(VIMDLL) || defined(PROTO)
559/*
560 * Check if the current executable file is for the GUI subsystem.
561 */
562 int
563mch_is_gui_executable(void)
564{
565 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
566 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
567 PIMAGE_NT_HEADERS pPE;
568
569 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
570 return FALSE;
571 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
572 if (pPE->Signature != IMAGE_NT_SIGNATURE)
573 return FALSE;
574 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
575 return TRUE;
576 return FALSE;
577}
578#endif
579
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100580#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
581/*
582 * Get related information about 'funcname' which is imported by 'hInst'.
583 * If 'info' is 0, return the function address.
584 * If 'info' is 1, return the module name which the function is imported from.
585 */
586 static void *
587get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
588{
589 PBYTE pImage = (PBYTE)hInst;
590 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
591 PIMAGE_NT_HEADERS pPE;
592 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100593 PIMAGE_THUNK_DATA pIAT; // Import Address Table
594 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100595 PIMAGE_IMPORT_BY_NAME pImpName;
596
597 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
598 return NULL;
599 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
600 if (pPE->Signature != IMAGE_NT_SIGNATURE)
601 return NULL;
602 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
603 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
604 .VirtualAddress);
605 for (; pImpDesc->FirstThunk; ++pImpDesc)
606 {
607 if (!pImpDesc->OriginalFirstThunk)
608 continue;
609 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
610 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
611 for (; pIAT->u1.Function; ++pIAT, ++pINT)
612 {
613 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
614 continue;
615 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
616 + (UINT_PTR)(pINT->u1.AddressOfData));
617 if (strcmp((char *)pImpName->Name, funcname) == 0)
618 {
619 switch (info)
620 {
621 case 0:
622 return (void *)pIAT->u1.Function;
623 case 1:
624 return (void *)(pImage + pImpDesc->Name);
625 default:
626 return NULL;
627 }
628 }
629 }
630 }
631 return NULL;
632}
633
634/*
635 * Get the module handle which 'funcname' in 'hInst' is imported from.
636 */
637 HINSTANCE
638find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
639{
640 char *modulename;
641
642 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
643 if (modulename != NULL)
644 return GetModuleHandleA(modulename);
645 return NULL;
646}
647
648/*
649 * Get the address of 'funcname' which is imported by 'hInst' DLL.
650 */
651 void *
652get_dll_import_func(HINSTANCE hInst, const char *funcname)
653{
654 return get_imported_func_info(hInst, funcname, 0);
655}
656#endif
657
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
659# ifndef GETTEXT_DLL
660# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200661# define GETTEXT_DLL_ALT1 "libintl-8.dll"
662# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000663# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100664// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000665static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200666static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000667static char *null_libintl_textdomain(const char *);
668static char *null_libintl_bindtextdomain(const char *, const char *);
669static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100670static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200672static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000673char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200674char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
675 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000676char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
677char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000679char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
680 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100681int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682
683 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100684dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685{
686 int i;
687 static struct
688 {
689 char *name;
690 FARPROC *ptr;
691 } libintl_entry[] =
692 {
693 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200694 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
696 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
697 {NULL, NULL}
698 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100699 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700
Bram Moolenaar7554c542018-10-06 15:03:15 +0200701 // No need to initialize twice.
702 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000703 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200704 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100705 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100706# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100707 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200708 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100709# endif
710# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200711 if (!hLibintlDLL)
712 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100713# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100714 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200716 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200718 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000719 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200720 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200722 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 }
724 for (i = 0; libintl_entry[i].name != NULL
725 && libintl_entry[i].ptr != NULL; ++i)
726 {
727 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
728 libintl_entry[i].name)) == NULL)
729 {
730 dyn_libintl_end();
731 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000732 {
733 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000734 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000735 verbose_leave();
736 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000737 return 0;
738 }
739 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000740
Bram Moolenaar0f873732019-12-05 20:28:46 +0100741 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000742 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000743 "bind_textdomain_codeset");
744 if (dyn_libintl_bind_textdomain_codeset == NULL)
745 dyn_libintl_bind_textdomain_codeset =
746 null_libintl_bind_textdomain_codeset;
747
Bram Moolenaar0f873732019-12-05 20:28:46 +0100748 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100749 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
750 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100751 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100752 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
753 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100754
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 return 1;
756}
757
758 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100759dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760{
761 if (hLibintlDLL)
762 FreeLibrary(hLibintlDLL);
763 hLibintlDLL = NULL;
764 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200765 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000766 dyn_libintl_textdomain = null_libintl_textdomain;
767 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000768 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100769 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770}
771
772 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000773null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774{
775 return (char*)msgid;
776}
777
778 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200779null_libintl_ngettext(
780 const char *msgid,
781 const char *msgid_plural,
782 unsigned long n)
783{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200784 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200785}
786
Bram Moolenaaree695f72016-08-03 22:08:45 +0200787 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100788null_libintl_bindtextdomain(
789 const char *domainname UNUSED,
790 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791{
792 return NULL;
793}
794
795 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100796null_libintl_bind_textdomain_codeset(
797 const char *domainname UNUSED,
798 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000799{
800 return NULL;
801}
802
803 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100804null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805{
806 return NULL;
807}
808
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200809 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100810null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100811{
812 return 0;
813}
814
Bram Moolenaar0f873732019-12-05 20:28:46 +0100815#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816
Bram Moolenaar0f873732019-12-05 20:28:46 +0100817// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818
819#ifndef VER_PLATFORM_WIN32_WINDOWS
820# define VER_PLATFORM_WIN32_WINDOWS 1
821#endif
822
Bram Moolenaar071d4272004-06-13 20:20:40 +0000823#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100824# ifndef PROTO
825# include <aclapi.h>
826# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200827# ifndef PROTECTED_DACL_SECURITY_INFORMATION
828# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
829# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830#endif
831
Bram Moolenaar27515922013-06-29 15:36:26 +0200832#ifdef HAVE_ACL
833/*
834 * Enables or disables the specified privilege.
835 */
836 static BOOL
837win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
838{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100839 BOOL bResult;
840 LUID luid;
841 HANDLE hToken;
842 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200843
844 if (!OpenProcessToken(GetCurrentProcess(),
845 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
846 return FALSE;
847
848 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
849 {
850 CloseHandle(hToken);
851 return FALSE;
852 }
853
Bram Moolenaar45500912014-07-09 20:51:07 +0200854 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200855 tokenPrivileges.Privileges[0].Luid = luid;
856 tokenPrivileges.Privileges[0].Attributes = bEnable ?
857 SE_PRIVILEGE_ENABLED : 0;
858
859 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
860 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
861
862 CloseHandle(hToken);
863
864 return bResult && GetLastError() == ERROR_SUCCESS;
865}
866#endif
867
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100868#ifdef _MSC_VER
869// Suppress the deprecation warning for using GetVersionEx().
870// It is needed for implementing "windowsversion()".
871# pragma warning(push)
872# pragma warning(disable: 4996)
873#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200875 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876 */
877 void
878PlatformId(void)
879{
880 static int done = FALSE;
881
882 if (!done)
883 {
884 OSVERSIONINFO ovi;
885
886 ovi.dwOSVersionInfoSize = sizeof(ovi);
887 GetVersionEx(&ovi);
888
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200889#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100890 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
891 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200892#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100893 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
894 || ovi.dwMajorVersion > 6)
895 win8_or_later = TRUE;
896
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100898 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200899 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900#endif
901 done = TRUE;
902 }
903}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100904#ifdef _MSC_VER
905# pragma warning(pop)
906#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200908#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100910# define SHIFT (SHIFT_PRESSED)
911# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
912# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
913# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914
915
Bram Moolenaar0f873732019-12-05 20:28:46 +0100916// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
917// We map function keys to their ANSI terminal equivalents, as produced
918// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
919// ANSI key with a value >= '\300' is nonstandard, but provided anyway
920// so that the user can have access to all SHIFT-, CTRL-, and ALT-
921// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000923static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924{
925 WORD wVirtKey;
926 BOOL fAnsiKey;
927 int chAlone;
928 int chShift;
929 int chCtrl;
930 int chAlt;
931} VirtKeyMap[] =
932{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200933// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
935
936 { VK_F1, TRUE, ';', 'T', '^', 'h', },
937 { VK_F2, TRUE, '<', 'U', '_', 'i', },
938 { VK_F3, TRUE, '=', 'V', '`', 'j', },
939 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
940 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
941 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
942 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
943 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
944 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
945 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200946 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
947 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200949 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
950 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
951 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
952 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
953 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
954 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
955 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
956 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
957 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
958 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100959 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200961 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100963# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200964 // Most people don't have F13-F20, but what the hell...
965 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
966 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
967 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
968 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
969 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
970 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
971 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
972 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100973# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200974 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
975 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
976 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
977 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200979 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
980 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
981 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
982 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
983 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
984 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
985 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
986 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
987 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
988 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100989 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990};
991
992
Bram Moolenaar0f873732019-12-05 20:28:46 +0100993/*
994 * The return code indicates key code size.
995 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000998 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999{
1000 UINT uMods = pker->dwControlKeyState;
1001 static int s_iIsDead = 0;
1002 static WORD awAnsiCode[2];
1003 static BYTE abKeystate[256];
1004
1005
1006 if (s_iIsDead == 2)
1007 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001008 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001009 s_iIsDead = 0;
1010 return 1;
1011 }
1012
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001013 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014 return 1;
1015
Bram Moolenaara80faa82020-04-12 19:37:17 +02001016 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017
Bram Moolenaar0f873732019-12-05 20:28:46 +01001018 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001019 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020
1021 if (uMods & SHIFT_PRESSED)
1022 abKeystate[VK_SHIFT] = 0x80;
1023 if (uMods & CAPSLOCK_ON)
1024 abKeystate[VK_CAPITAL] = 1;
1025
1026 if ((uMods & ALT_GR) == ALT_GR)
1027 {
1028 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1029 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1030 }
1031
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001032 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1033 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034
1035 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001036 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
1038 return s_iIsDead;
1039}
1040
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041static BOOL g_fJustGotFocus = FALSE;
1042
1043/*
1044 * Decode a KEY_EVENT into one or two keystrokes
1045 */
1046 static BOOL
1047decode_key_event(
1048 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001049 WCHAR *pch,
1050 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001052 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053{
1054 int i;
1055 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1056
1057 *pch = *pch2 = NUL;
1058 g_fJustGotFocus = FALSE;
1059
Bram Moolenaar0f873732019-12-05 20:28:46 +01001060 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061 if (!pker->bKeyDown)
1062 return FALSE;
1063
Bram Moolenaar0f873732019-12-05 20:28:46 +01001064 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065 switch (pker->wVirtualKeyCode)
1066 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001067 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 case VK_SHIFT:
1069 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001070 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 return FALSE;
1072
1073 default:
1074 break;
1075 }
1076
Bram Moolenaar0f873732019-12-05 20:28:46 +01001077 // special cases
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001078 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001079 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001080 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 if (pker->wVirtualKeyCode == '6')
1082 {
1083 *pch = Ctrl_HAT;
1084 return TRUE;
1085 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001086 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087 else if (pker->wVirtualKeyCode == '2')
1088 {
1089 *pch = NUL;
1090 return TRUE;
1091 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001092 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093 else if (pker->wVirtualKeyCode == 0xBD)
1094 {
1095 *pch = Ctrl__;
1096 return TRUE;
1097 }
1098 }
1099
Bram Moolenaar0f873732019-12-05 20:28:46 +01001100 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1102 {
1103 *pch = K_NUL;
1104 *pch2 = '\017';
1105 return TRUE;
1106 }
1107
K.Takataeeec2542021-06-02 13:28:16 +02001108 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109 {
1110 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1111 {
1112 if (nModifs == 0)
1113 *pch = VirtKeyMap[i].chAlone;
1114 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1115 *pch = VirtKeyMap[i].chShift;
1116 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1117 *pch = VirtKeyMap[i].chCtrl;
1118 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1119 *pch = VirtKeyMap[i].chAlt;
1120
1121 if (*pch != 0)
1122 {
1123 if (VirtKeyMap[i].fAnsiKey)
1124 {
1125 *pch2 = *pch;
1126 *pch = K_NUL;
1127 }
1128
1129 return TRUE;
1130 }
1131 }
1132 }
1133
1134 i = win32_kbd_patch_key(pker);
1135
1136 if (i < 0)
1137 *pch = NUL;
1138 else
1139 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001140 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141
1142 if (pmodifiers != NULL)
1143 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001144 // Pass on the ALT key as a modifier, but only when not combined
1145 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1147 *pmodifiers |= MOD_MASK_ALT;
1148
Bram Moolenaar0f873732019-12-05 20:28:46 +01001149 // Pass on SHIFT only for special keys, because we don't know when
1150 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1152 *pmodifiers |= MOD_MASK_SHIFT;
1153
Bram Moolenaar0f873732019-12-05 20:28:46 +01001154 // Pass on CTRL only for non-special keys, because we don't know
1155 // when it's already included with the character. And not when
1156 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1158 && *pch >= 0x20 && *pch < 0x80)
1159 *pmodifiers |= MOD_MASK_CTRL;
1160 }
1161 }
1162
1163 return (*pch != NUL);
1164}
1165
Bram Moolenaar0f873732019-12-05 20:28:46 +01001166#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167
1168
Bram Moolenaar071d4272004-06-13 20:20:40 +00001169/*
1170 * For the GUI the mouse handling is in gui_w32.c.
1171 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001172#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001174mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175{
1176}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001177#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001178static int g_fMouseAvail = FALSE; // mouse present
1179static int g_fMouseActive = FALSE; // mouse enabled
1180static int g_nMouseClick = -1; // mouse status
1181static int g_xMouse; // mouse x coordinate
1182static int g_yMouse; // mouse y coordinate
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001183static DWORD g_cmodein = 0; // Original console input mode
1184static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185
1186/*
1187 * Enable or disable mouse input
1188 */
1189 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001190mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191{
1192 DWORD cmodein;
1193
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001194# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001195 if (gui.in_use)
1196 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001197# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 if (!g_fMouseAvail)
1199 return;
1200
1201 g_fMouseActive = on;
1202 GetConsoleMode(g_hConIn, &cmodein);
1203
1204 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001205 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001206 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001207 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1208 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001210 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001212 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1213 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001215 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216}
1217
Bram Moolenaar157d8132018-03-06 17:09:20 +01001218
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001219# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001220/*
1221 * Called when 'balloonevalterm' changed.
1222 */
1223 void
1224mch_bevalterm_changed(void)
1225{
1226 mch_setmouse(g_fMouseActive);
1227}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001228# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001229
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230/*
1231 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1232 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1233 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1234 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1235 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1236 * and we return the mouse position in g_xMouse and g_yMouse.
1237 *
1238 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1239 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1240 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1241 *
1242 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1243 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1244 *
1245 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1246 * moves, even if it stays within the same character cell. We ignore
1247 * all MOUSE_MOVED messages if the position hasn't really changed, and
1248 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1249 * we're only interested in MOUSE_DRAG).
1250 *
1251 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1252 * 2-button mouses by pressing the left & right buttons simultaneously.
1253 * In practice, it's almost impossible to click both at the same time,
1254 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1255 * in such cases, if the user is clicking quickly.
1256 */
1257 static BOOL
1258decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001259 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001260{
1261 static int s_nOldButton = -1;
1262 static int s_nOldMouseClick = -1;
1263 static int s_xOldMouse = -1;
1264 static int s_yOldMouse = -1;
1265 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001266# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001267 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001268# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269 static int s_cClicks = 1;
1270 static BOOL s_fReleased = TRUE;
1271 static DWORD s_dwLastClickTime = 0;
1272 static BOOL s_fNextIsMiddle = FALSE;
1273
Bram Moolenaar0f873732019-12-05 20:28:46 +01001274 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001275
1276 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1277 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1278 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1279 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1280
1281 int nButton;
1282
1283 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1284 cButtons = 2;
1285
1286 if (!g_fMouseAvail || !g_fMouseActive)
1287 {
1288 g_nMouseClick = -1;
1289 return FALSE;
1290 }
1291
Bram Moolenaar0f873732019-12-05 20:28:46 +01001292 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001293 if (g_fJustGotFocus)
1294 {
1295 g_fJustGotFocus = FALSE;
1296 return FALSE;
1297 }
1298
Bram Moolenaar0f873732019-12-05 20:28:46 +01001299 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001300 if (g_nMouseClick != -1)
1301 return TRUE;
1302
1303 nButton = -1;
1304 g_xMouse = pmer->dwMousePosition.X;
1305 g_yMouse = pmer->dwMousePosition.Y;
1306
1307 if (pmer->dwEventFlags == MOUSE_MOVED)
1308 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001309 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1310 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001311 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1312 return FALSE;
1313 }
1314
Bram Moolenaar0f873732019-12-05 20:28:46 +01001315 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1317 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001318 nButton = MOUSE_RELEASE;
1319
Bram Moolenaar0f873732019-12-05 20:28:46 +01001320 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001322 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001323# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001324 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001325 if (p_bevalterm)
1326 nButton = MOUSE_DRAG;
1327 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001328# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001329 return FALSE;
1330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331
Bram Moolenaar071d4272004-06-13 20:20:40 +00001332 s_fReleased = TRUE;
1333 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001334 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001336 // on a 2-button mouse, hold down left and right buttons
1337 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001338
1339 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1340 {
1341 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1342
Bram Moolenaar0f873732019-12-05 20:28:46 +01001343 // if either left or right button only is pressed, see if the
1344 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345 if (dwLR == LEFT || dwLR == RIGHT)
1346 {
1347 for (;;)
1348 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001349 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001350 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1351 != WAIT_OBJECT_0)
1352 break;
1353 else
1354 {
1355 DWORD cRecords = 0;
1356 INPUT_RECORD ir;
1357 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1358
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001359 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001360
1361 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1362 || !(pmer2->dwButtonState & LEFT_RIGHT))
1363 break;
1364 else
1365 {
1366 if (pmer2->dwEventFlags != MOUSE_MOVED)
1367 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001368 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001369
1370 return decode_mouse_event(pmer2);
1371 }
1372 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1373 s_yOldMouse == pmer2->dwMousePosition.Y)
1374 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001375 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001376 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001377
Bram Moolenaar0f873732019-12-05 20:28:46 +01001378 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001379 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001380
1381 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1382 break;
1383 }
1384 else
1385 break;
1386 }
1387 }
1388 }
1389 }
1390 }
1391
1392 if (s_fNextIsMiddle)
1393 {
1394 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1395 ? MOUSE_DRAG : MOUSE_MIDDLE;
1396 s_fNextIsMiddle = FALSE;
1397 }
1398 else if (cButtons == 2 &&
1399 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1400 {
1401 nButton = MOUSE_MIDDLE;
1402
1403 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1404 {
1405 s_fNextIsMiddle = TRUE;
1406 nButton = MOUSE_RELEASE;
1407 }
1408 }
1409 else if ((pmer->dwButtonState & LEFT) == LEFT)
1410 nButton = MOUSE_LEFT;
1411 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1412 nButton = MOUSE_MIDDLE;
1413 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1414 nButton = MOUSE_RIGHT;
1415
1416 if (! s_fReleased && ! s_fNextIsMiddle
1417 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1418 return FALSE;
1419
1420 s_fReleased = s_fNextIsMiddle;
1421 }
1422
1423 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1424 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001425 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426 if (nButton != -1 && nButton != MOUSE_RELEASE)
1427 {
1428 DWORD dwCurrentTime = GetTickCount();
1429
1430 if (s_xOldMouse != g_xMouse
1431 || s_yOldMouse != g_yMouse
1432 || s_nOldButton != nButton
1433 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001434# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1438 {
1439 s_cClicks = 1;
1440 }
1441 else if (++s_cClicks > 4)
1442 {
1443 s_cClicks = 1;
1444 }
1445
1446 s_dwLastClickTime = dwCurrentTime;
1447 }
1448 }
1449 else if (pmer->dwEventFlags == MOUSE_MOVED)
1450 {
1451 if (nButton != -1 && nButton != MOUSE_RELEASE)
1452 nButton = MOUSE_DRAG;
1453
1454 s_cClicks = 1;
1455 }
1456
1457 if (nButton == -1)
1458 return FALSE;
1459
1460 if (nButton != MOUSE_RELEASE)
1461 s_nOldButton = nButton;
1462
1463 g_nMouseClick = nButton;
1464
1465 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1466 g_nMouseClick |= MOUSE_SHIFT;
1467 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1468 g_nMouseClick |= MOUSE_CTRL;
1469 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1470 g_nMouseClick |= MOUSE_ALT;
1471
1472 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1473 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1474
Bram Moolenaar0f873732019-12-05 20:28:46 +01001475 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001476 if (s_xOldMouse == g_xMouse
1477 && s_yOldMouse == g_yMouse
1478 && s_nOldMouseClick == g_nMouseClick)
1479 {
1480 g_nMouseClick = -1;
1481 return FALSE;
1482 }
1483
1484 s_xOldMouse = g_xMouse;
1485 s_yOldMouse = g_yMouse;
1486 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001487# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001489# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490 s_nOldMouseClick = g_nMouseClick;
1491
1492 return TRUE;
1493}
1494
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001495#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496
1497
1498#ifdef MCH_CURSOR_SHAPE
1499/*
1500 * Set the shape of the cursor.
1501 * 'thickness' can be from 1 (thin) to 99 (block)
1502 */
1503 static void
1504mch_set_cursor_shape(int thickness)
1505{
1506 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1507 ConsoleCursorInfo.dwSize = thickness;
1508 ConsoleCursorInfo.bVisible = s_cursor_visible;
1509
1510 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1511 if (s_cursor_visible)
1512 SetConsoleCursorPosition(g_hConOut, g_coord);
1513}
1514
1515 void
1516mch_update_cursor(void)
1517{
1518 int idx;
1519 int thickness;
1520
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001521# ifdef VIMDLL
1522 if (gui.in_use)
1523 return;
1524# endif
1525
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526 /*
1527 * How the cursor is drawn depends on the current mode.
1528 */
1529 idx = get_shape_idx(FALSE);
1530
1531 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001532 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 else
1534 thickness = shape_table[idx].percentage;
1535 mch_set_cursor_shape(thickness);
1536}
1537#endif
1538
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001539#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540/*
1541 * Handle FOCUS_EVENT.
1542 */
1543 static void
1544handle_focus_event(INPUT_RECORD ir)
1545{
1546 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1547 ui_focus_change((int)g_fJustGotFocus);
1548}
1549
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001550static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1551
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552/*
1553 * Wait until console input from keyboard or mouse is available,
1554 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001555 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001556 * Return TRUE if something is available FALSE if not.
1557 */
1558 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001559WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560{
1561 DWORD dwNow = 0, dwEndTime = 0;
1562 INPUT_RECORD ir;
1563 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001564 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001565# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001566 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001567# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568
1569 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001570 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571 dwEndTime = GetTickCount() + msec;
1572 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001573 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574 dwEndTime = INFINITE;
1575
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001576 // We need to loop until the end of the time period, because
1577 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 for (;;)
1579 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001580 // Only process messages when waiting.
1581 if (msec != 0)
1582 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001583# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001584 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001585# endif
1586# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001587 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001588# endif
1589# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001590 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001591# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001592 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001593
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001594 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001595# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001596 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001597# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 )
1599 return TRUE;
1600
1601 if (msec > 0)
1602 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001603 // If the specified wait time has passed, return. Beware that
1604 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001606 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 break;
1608 }
1609 if (msec != 0)
1610 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001611 DWORD dwWaitTime = dwEndTime - dwNow;
1612
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001613 // Don't wait for more than 11 msec to avoid dropping characters,
1614 // check channel while waiting for input and handle a callback from
1615 // 'balloonexpr'.
1616 if (dwWaitTime > 11)
1617 dwWaitTime = 11;
1618
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001619# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001620 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001621 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001622# endif
1623# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001624 // When waiting very briefly don't trigger timers.
1625 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001626 {
1627 long due_time;
1628
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001629 // Trigger timers and then get the time in msec until the next
1630 // one is due. Wait up to that time.
1631 due_time = check_due_timer();
1632 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001633 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001634 // timer may have used feedkeys().
1635 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001636 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001637 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1638 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001639 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001640# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001641 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001642# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001643 // Wait for either an event on the console input or a
1644 // message in the client-server window.
1645 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1646 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001647# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001648 wait_for_single_object(g_hConIn, dwWaitTime)
1649 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001650# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001651 )
1652 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 }
1654
1655 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001656 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001658# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001659 // May have to redraw if the cursor ends up in the wrong place.
1660 // Only when not peeking.
1661 if (State & CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662 {
1663 CONSOLE_SCREEN_BUFFER_INFO csbi;
1664
1665 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1666 {
1667 if (csbi.dwCursorPosition.Y != msg_row)
1668 {
matveyte08795e2021-05-07 15:00:17 +02001669 // The screen is now messed up, must redraw the command
1670 // line and later all the windows.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 redraw_all_later(CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001672 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673 redrawcmd();
1674 }
1675 }
1676 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001677# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678
1679 if (cRecords > 0)
1680 {
1681 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1682 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001683# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001684 // Windows IME sends two '\n's with only one 'ENTER'. First:
1685 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001686 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1688 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001689 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 continue;
1691 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001692# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1694 NULL, FALSE))
1695 return TRUE;
1696 }
1697
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001698 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699
1700 if (ir.EventType == FOCUS_EVENT)
1701 handle_focus_event(ir);
1702 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001703 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001704 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1705
Bram Moolenaar36698e32019-12-11 22:57:40 +01001706 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001707 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001708 if (dwSize.X != Columns || dwSize.Y != Rows)
1709 {
1710 CONSOLE_SCREEN_BUFFER_INFO csbi;
1711 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001712 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001713 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001714 if (dwSize.X != Columns || dwSize.Y != Rows)
1715 {
1716 ResizeConBuf(g_hConOut, dwSize);
1717 shell_resized();
1718 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001719 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001720 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 else if (ir.EventType == MOUSE_EVENT
1722 && decode_mouse_event(&ir.Event.MouseEvent))
1723 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724 }
1725 else if (msec == 0)
1726 break;
1727 }
1728
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001729# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001730 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 if (input_available())
1732 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001733# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001734
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735 return FALSE;
1736}
1737
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738/*
1739 * return non-zero if a character is available
1740 */
1741 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001742mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001744# ifdef VIMDLL
1745 if (gui.in_use)
1746 return TRUE;
1747# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001748 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001750
1751# if defined(FEAT_TERMINAL) || defined(PROTO)
1752/*
1753 * Check for any pending input or messages.
1754 */
1755 int
1756mch_check_messages(void)
1757{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001758# ifdef VIMDLL
1759 if (gui.in_use)
1760 return TRUE;
1761# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001762 return WaitForChar(0L, TRUE);
1763}
1764# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001765
1766/*
1767 * Create the console input. Used when reading stdin doesn't work.
1768 */
1769 static void
1770create_conin(void)
1771{
1772 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1773 FILE_SHARE_READ|FILE_SHARE_WRITE,
1774 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001775 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776 did_create_conin = TRUE;
1777}
1778
1779/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001780 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001782 static WCHAR
1783tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001784{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001785 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786
1787 for (;;)
1788 {
1789 INPUT_RECORD ir;
1790 DWORD cRecords = 0;
1791
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001792# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001793 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794 if (input_available())
1795 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 if (g_nMouseClick != -1)
1797 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001798# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001799 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800 {
1801 if (did_create_conin)
1802 read_error_exit();
1803 create_conin();
1804 continue;
1805 }
1806
1807 if (ir.EventType == KEY_EVENT)
1808 {
1809 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1810 pmodifiers, TRUE))
1811 return ch;
1812 }
1813 else if (ir.EventType == FOCUS_EVENT)
1814 handle_focus_event(ir);
1815 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1816 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 else if (ir.EventType == MOUSE_EVENT)
1818 {
1819 if (decode_mouse_event(&ir.Event.MouseEvent))
1820 return 0;
1821 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822 }
1823}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001824#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825
1826
1827/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001828 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001829 * Get one or more characters from the keyboard or the mouse.
1830 * If time == 0, do not wait for characters.
1831 * If time == n, wait a short time for characters.
1832 * If time == -1, wait forever for characters.
1833 * Returns the number of characters read into buf.
1834 */
1835 int
1836mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001837 char_u *buf UNUSED,
1838 int maxlen UNUSED,
1839 long time UNUSED,
1840 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001842#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001843
1844 int len;
1845 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001846# ifdef VIMDLL
1847// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1848# define TYPEAHEADSPACE 6
1849# else
1850# define TYPEAHEADSPACE 0
1851# endif
1852# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001853 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 static int typeaheadlen = 0;
1855
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001856# ifdef VIMDLL
1857 if (gui.in_use)
1858 return 0;
1859# endif
1860
Bram Moolenaar0f873732019-12-05 20:28:46 +01001861 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862 if (typeaheadlen > 0)
1863 goto theend;
1864
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865 if (time >= 0)
1866 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001867 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001869 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001870 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001872 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873
Bram Moolenaar3918c952005-03-15 22:34:55 +00001874 /*
1875 * If there is no character available within 2 seconds (default)
1876 * write the autoscript file to disk. Or cause the CursorHold event
1877 * to be triggered.
1878 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001879 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001880 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001881 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001883 buf[0] = K_SPECIAL;
1884 buf[1] = KS_EXTRA;
1885 buf[2] = (int)KE_CURSORHOLD;
1886 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001888 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 }
1890 }
1891
1892 /*
1893 * Try to read as many characters as there are, until the buffer is full.
1894 */
1895
Bram Moolenaar0f873732019-12-05 20:28:46 +01001896 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 g_fCBrkPressed = FALSE;
1898
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001899# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900 if (fdDump)
1901 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001902# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001903
Bram Moolenaar0f873732019-12-05 20:28:46 +01001904 // Keep looping until there is something in the typeahead buffer and more
1905 // to get and still room in the buffer (up to two bytes for a char and
1906 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001907 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001908 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909 {
1910 if (typebuf_changed(tb_change_cnt))
1911 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001912 // "buf" may be invalid now if a client put something in the
1913 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914 typeaheadlen = 0;
1915 break;
1916 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917 if (g_nMouseClick != -1)
1918 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001919# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920 if (fdDump)
1921 fprintf(fdDump, "{%02x @ %d, %d}",
1922 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001923# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 typeahead[typeaheadlen++] = ESC + 128;
1925 typeahead[typeaheadlen++] = 'M';
1926 typeahead[typeaheadlen++] = g_nMouseClick;
1927 typeahead[typeaheadlen++] = g_xMouse + '!';
1928 typeahead[typeaheadlen++] = g_yMouse + '!';
1929 g_nMouseClick = -1;
1930 }
1931 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001933 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934 int modifiers = 0;
1935
1936 c = tgetch(&modifiers, &ch2);
1937
1938 if (typebuf_changed(tb_change_cnt))
1939 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001940 // "buf" may be invalid now if a client put something in the
1941 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 typeaheadlen = 0;
1943 break;
1944 }
1945
1946 if (c == Ctrl_C && ctrl_c_interrupts)
1947 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001948# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001950# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001951 got_int = TRUE;
1952 }
1953
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955 {
1956 int n = 1;
1957
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001958 if (ch2 == NUL)
1959 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001960 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001961 char_u *p;
1962 WCHAR ch[2];
1963
1964 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001965 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001966 {
1967 ch[1] = tgetch(&modifiers, &ch2);
1968 n++;
1969 }
1970 p = utf16_to_enc(ch, &n);
1971 if (p != NULL)
1972 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001973 for (i = 0, j = 0; i < n; i++)
1974 {
1975 typeahead[typeaheadlen + j++] = p[i];
1976# ifdef VIMDLL
1977 if (p[i] == CSI)
1978 {
1979 typeahead[typeaheadlen + j++] = KS_EXTRA;
1980 typeahead[typeaheadlen + j++] = KE_CSI;
1981 }
1982# endif
1983 }
1984 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001985 vim_free(p);
1986 }
1987 }
1988 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001989 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001990 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001991# ifdef VIMDLL
1992 if (c == CSI)
1993 {
1994 typeahead[typeaheadlen + 1] = KS_EXTRA;
1995 typeahead[typeaheadlen + 2] = KE_CSI;
1996 n = 3;
1997 }
1998# endif
1999 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000 if (ch2 != NUL)
2001 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002002 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002003 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002004 switch (ch2)
2005 {
2006 case (WCHAR)'\324': // SHIFT+Insert
2007 case (WCHAR)'\325': // CTRL+Insert
2008 case (WCHAR)'\327': // SHIFT+Delete
2009 case (WCHAR)'\330': // CTRL+Delete
2010 typeahead[typeaheadlen + n] = (char_u)ch2;
2011 n++;
2012 break;
2013
2014 default:
2015 typeahead[typeaheadlen + n] = 3;
2016 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2017 n += 2;
2018 break;
2019 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002020 }
2021 else
2022 {
2023 typeahead[typeaheadlen + n] = 3;
2024 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2025 n += 2;
2026 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002027 }
2028
Bram Moolenaar0f873732019-12-05 20:28:46 +01002029 // Use the ALT key to set the 8th bit of the character
2030 // when it's one byte, the 8th bit isn't set yet and not
2031 // using a double-byte encoding (would become a lead
2032 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 if ((modifiers & MOD_MASK_ALT)
2034 && n == 1
2035 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 )
2038 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002039 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2040 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041 modifiers &= ~MOD_MASK_ALT;
2042 }
2043
2044 if (modifiers != 0)
2045 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002046 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047 mch_memmove(typeahead + typeaheadlen + 3,
2048 typeahead + typeaheadlen, n);
2049 typeahead[typeaheadlen++] = K_SPECIAL;
2050 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2051 typeahead[typeaheadlen++] = modifiers;
2052 }
2053
2054 typeaheadlen += n;
2055
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002056# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 if (fdDump)
2058 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002059# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 }
2061 }
2062 }
2063
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002064# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 if (fdDump)
2066 {
2067 fputs("]\n", fdDump);
2068 fflush(fdDump);
2069 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002070# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002073 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074 len = 0;
2075 while (len < maxlen && typeaheadlen > 0)
2076 {
2077 buf[len++] = typeahead[0];
2078 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2079 }
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002080# ifdef FEAT_JOB_CHANNEL
2081 if (len > 0)
2082 {
2083 buf[len] = NUL;
2084 ch_log(NULL, "raw key input: \"%s\"", buf);
2085 }
2086# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 return len;
2088
Bram Moolenaar0f873732019-12-05 20:28:46 +01002089#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002091#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092}
2093
Bram Moolenaar82881492012-11-20 16:53:39 +01002094#ifndef PROTO
2095# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002096# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002097# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002098#endif
2099
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002100/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002101 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002102 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2103 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002104 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002105 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002107executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108{
Bram Moolenaar95da1362020-05-30 18:37:55 +02002109 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002110 {
Bram Moolenaar95da1362020-05-30 18:37:55 +02002111 if (path != NULL)
2112 *path = FullName_save((char_u *)name, FALSE);
2113 return TRUE;
2114 }
2115 return FALSE;
2116}
2117
2118/*
2119 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2120 * If "use_path" is FALSE: Return TRUE if "name" exists.
2121 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2122 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2123 * the allocated memory.
2124 */
2125 static int
2126executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2127{
2128 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2129 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2130 // UTF-8.
2131 char_u buf[_MAX_PATH * 3];
2132 size_t len = STRLEN(name);
2133 size_t tmplen;
2134 char_u *p, *e, *e2;
2135 char_u *pathbuf = NULL;
2136 char_u *pathext = NULL;
2137 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002138 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002139 int noext = FALSE;
2140 int retval = FALSE;
2141
2142 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002143 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002144
2145 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002146 shname = gettail(p_sh);
2147 if (strstr((char *)shname, "sh") != NULL &&
2148 !(strstr((char *)shname, "powershell") != NULL
2149 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002150 noext = TRUE;
2151
2152 if (use_pathext)
2153 {
2154 pathext = mch_getenv("PATHEXT");
2155 if (pathext == NULL)
2156 pathext = (char_u *)".com;.exe;.bat;.cmd";
2157
2158 if (noext == FALSE)
2159 {
2160 /*
2161 * Loop over all extensions in $PATHEXT.
2162 * Check "name" ends with extension.
2163 */
2164 p = pathext;
2165 while (*p)
2166 {
2167 if (p[0] == ';'
2168 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2169 {
2170 // Skip empty or single ".".
2171 ++p;
2172 continue;
2173 }
2174 e = vim_strchr(p, ';');
2175 if (e == NULL)
2176 e = p + STRLEN(p);
2177 tmplen = e - p;
2178
2179 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2180 {
2181 noext = TRUE;
2182 break;
2183 }
2184
2185 p = e;
2186 }
2187 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002188 }
2189
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002190 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002191 if (pathext == NULL)
2192 pathext = (char_u *)".";
2193 else if (noext == TRUE)
2194 {
2195 if (pathextbuf == NULL)
2196 pathextbuf = alloc(STRLEN(pathext) + 3);
2197 if (pathextbuf == NULL)
2198 {
2199 retval = FALSE;
2200 goto theend;
2201 }
2202 STRCPY(pathextbuf, ".;");
2203 STRCAT(pathextbuf, pathext);
2204 pathext = pathextbuf;
2205 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002206
Bram Moolenaar95da1362020-05-30 18:37:55 +02002207 // Use $PATH when "use_path" is TRUE and "name" is basename.
2208 if (use_path && gettail((char_u *)name) == (char_u *)name)
2209 {
2210 p = mch_getenv("PATH");
2211 if (p != NULL)
2212 {
2213 pathbuf = alloc(STRLEN(p) + 3);
2214 if (pathbuf == NULL)
2215 {
2216 retval = FALSE;
2217 goto theend;
2218 }
2219 STRCPY(pathbuf, ".;");
2220 STRCAT(pathbuf, p);
2221 }
2222 }
2223
2224 /*
2225 * Walk through all entries in $PATH to check if "name" exists there and
2226 * is an executable file.
2227 */
2228 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2229 while (*p)
2230 {
2231 if (*p == ';') // Skip empty entry
2232 {
2233 ++p;
2234 continue;
2235 }
2236 e = vim_strchr(p, ';');
2237 if (e == NULL)
2238 e = p + STRLEN(p);
2239
2240 if (e - p + len + 2 > sizeof(buf))
2241 {
2242 retval = FALSE;
2243 goto theend;
2244 }
2245 // A single "." that means current dir.
2246 if (e - p == 1 && *p == '.')
2247 STRCPY(buf, name);
2248 else
2249 {
2250 vim_strncpy(buf, p, e - p);
2251 add_pathsep(buf);
2252 STRCAT(buf, name);
2253 }
2254 tmplen = STRLEN(buf);
2255
2256 /*
2257 * Loop over all extensions in $PATHEXT.
2258 * Check "name" with extension added.
2259 */
2260 p = pathext;
2261 while (*p)
2262 {
2263 if (*p == ';')
2264 {
2265 // Skip empty entry
2266 ++p;
2267 continue;
2268 }
2269 e2 = vim_strchr(p, (int)';');
2270 if (e2 == NULL)
2271 e2 = p + STRLEN(p);
2272
2273 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2274 {
2275 // Not a single "." that means no extension is added.
2276 if (e2 - p + tmplen + 1 > sizeof(buf))
2277 {
2278 retval = FALSE;
2279 goto theend;
2280 }
2281 vim_strncpy(buf + tmplen, p, e2 - p);
2282 }
2283 if (executable_file((char *)buf, path))
2284 {
2285 retval = TRUE;
2286 goto theend;
2287 }
2288
2289 p = e2;
2290 }
2291
2292 p = e;
2293 }
2294
2295theend:
2296 free(pathextbuf);
2297 free(pathbuf);
2298 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299}
2300
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002301#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2302 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002303/*
2304 * Bad parameter handler.
2305 *
2306 * Certain MS CRT functions will intentionally crash when passed invalid
2307 * parameters to highlight possible security holes. Setting this function as
2308 * the bad parameter handler will prevent the crash.
2309 *
2310 * In debug builds the parameters contain CRT information that might help track
2311 * down the source of a problem, but in non-debug builds the arguments are all
2312 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2313 * worth allowing these to make debugging of issues easier.
2314 */
2315 static void
2316bad_param_handler(const wchar_t *expression,
2317 const wchar_t *function,
2318 const wchar_t *file,
2319 unsigned int line,
2320 uintptr_t pReserved)
2321{
2322}
2323
2324# define SET_INVALID_PARAM_HANDLER \
2325 ((void)_set_invalid_parameter_handler(bad_param_handler))
2326#else
2327# define SET_INVALID_PARAM_HANDLER
2328#endif
2329
Bram Moolenaar4f974752019-02-17 17:44:42 +01002330#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331
2332/*
2333 * GUI version of mch_init().
2334 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002335 static void
2336mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002338# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002340# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341
Bram Moolenaar0f873732019-12-05 20:28:46 +01002342 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002343 SET_INVALID_PARAM_HANDLER;
2344
Bram Moolenaar0f873732019-12-05 20:28:46 +01002345 // Let critical errors result in a failure, not in a dialog box. Required
2346 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347 SetErrorMode(SEM_FAILCRITICALERRORS);
2348
Bram Moolenaar0f873732019-12-05 20:28:46 +01002349 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350
Bram Moolenaar0f873732019-12-05 20:28:46 +01002351 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 Rows = 25;
2353 Columns = 80;
2354
Bram Moolenaar0f873732019-12-05 20:28:46 +01002355 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356 {
2357 char_u vimrun_location[_MAX_PATH + 4];
2358
Bram Moolenaar0f873732019-12-05 20:28:46 +01002359 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 STRCPY(vimrun_location, exe_name);
2361 STRCPY(gettail(vimrun_location), "vimrun.exe");
2362 if (mch_getperm(vimrun_location) >= 0)
2363 {
2364 if (*skiptowhite(vimrun_location) != NUL)
2365 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002366 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 mch_memmove(vimrun_location + 1, vimrun_location,
2368 STRLEN(vimrun_location) + 1);
2369 *vimrun_location = '"';
2370 STRCPY(gettail(vimrun_location), "vimrun\" ");
2371 }
2372 else
2373 STRCPY(gettail(vimrun_location), "vimrun ");
2374
2375 vimrun_path = (char *)vim_strsave(vimrun_location);
2376 s_dont_use_vimrun = FALSE;
2377 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002378 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 s_dont_use_vimrun = FALSE;
2380
Bram Moolenaar0f873732019-12-05 20:28:46 +01002381 // Don't give the warning for a missing vimrun.exe right now, but only
2382 // when vimrun was supposed to be used. Don't bother people that do
2383 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384 if (s_dont_use_vimrun)
2385 need_vimrun_warning = TRUE;
2386 }
2387
2388 /*
2389 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2390 * Otherwise the default "findstr /n" is used.
2391 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002392 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2394
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002395# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002396 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002397# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002398
2399 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400}
2401
2402
Bram Moolenaar0f873732019-12-05 20:28:46 +01002403#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002404
2405#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002407# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2408# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409
2410/*
2411 * ClearConsoleBuffer()
2412 * Description:
2413 * Clears the entire contents of the console screen buffer, using the
2414 * specified attribute.
2415 * Returns:
2416 * TRUE on success
2417 */
2418 static BOOL
2419ClearConsoleBuffer(WORD wAttribute)
2420{
2421 CONSOLE_SCREEN_BUFFER_INFO csbi;
2422 COORD coord;
2423 DWORD NumCells, dummy;
2424
2425 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2426 return FALSE;
2427
2428 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2429 coord.X = 0;
2430 coord.Y = 0;
2431 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2432 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2435 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437
2438 return TRUE;
2439}
2440
2441/*
2442 * FitConsoleWindow()
2443 * Description:
2444 * Checks if the console window will fit within given buffer dimensions.
2445 * Also, if requested, will shrink the window to fit.
2446 * Returns:
2447 * TRUE on success
2448 */
2449 static BOOL
2450FitConsoleWindow(
2451 COORD dwBufferSize,
2452 BOOL WantAdjust)
2453{
2454 CONSOLE_SCREEN_BUFFER_INFO csbi;
2455 COORD dwWindowSize;
2456 BOOL NeedAdjust = FALSE;
2457
2458 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2459 {
2460 /*
2461 * A buffer resize will fail if the current console window does
2462 * not lie completely within that buffer. To avoid this, we might
2463 * have to move and possibly shrink the window.
2464 */
2465 if (csbi.srWindow.Right >= dwBufferSize.X)
2466 {
2467 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2468 if (dwWindowSize.X > dwBufferSize.X)
2469 dwWindowSize.X = dwBufferSize.X;
2470 csbi.srWindow.Right = dwBufferSize.X - 1;
2471 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2472 NeedAdjust = TRUE;
2473 }
2474 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2475 {
2476 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2477 if (dwWindowSize.Y > dwBufferSize.Y)
2478 dwWindowSize.Y = dwBufferSize.Y;
2479 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2480 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2481 NeedAdjust = TRUE;
2482 }
2483 if (NeedAdjust && WantAdjust)
2484 {
2485 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2486 return FALSE;
2487 }
2488 return TRUE;
2489 }
2490
2491 return FALSE;
2492}
2493
2494typedef struct ConsoleBufferStruct
2495{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002496 BOOL IsValid;
2497 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002498 PCHAR_INFO Buffer;
2499 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002500 PSMALL_RECT Regions;
2501 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502} ConsoleBuffer;
2503
2504/*
2505 * SaveConsoleBuffer()
2506 * Description:
2507 * Saves important information about the console buffer, including the
2508 * actual buffer contents. The saved information is suitable for later
2509 * restoration by RestoreConsoleBuffer().
2510 * Returns:
2511 * TRUE if all information was saved; FALSE otherwise
2512 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2513 */
2514 static BOOL
2515SaveConsoleBuffer(
2516 ConsoleBuffer *cb)
2517{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002518 DWORD NumCells;
2519 COORD BufferCoord;
2520 SMALL_RECT ReadRegion;
2521 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002522 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002523
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 if (cb == NULL)
2525 return FALSE;
2526
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002527 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 {
2529 cb->IsValid = FALSE;
2530 return FALSE;
2531 }
2532 cb->IsValid = TRUE;
2533
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002534 /*
2535 * Allocate a buffer large enough to hold the entire console screen
2536 * buffer. If this ConsoleBuffer structure has already been initialized
2537 * with a buffer of the correct size, then just use that one.
2538 */
2539 if (!cb->IsValid || cb->Buffer == NULL ||
2540 cb->BufferSize.X != cb->Info.dwSize.X ||
2541 cb->BufferSize.Y != cb->Info.dwSize.Y)
2542 {
2543 cb->BufferSize.X = cb->Info.dwSize.X;
2544 cb->BufferSize.Y = cb->Info.dwSize.Y;
2545 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2546 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002547 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002548 if (cb->Buffer == NULL)
2549 return FALSE;
2550 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551
2552 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002553 * We will now copy the console screen buffer into our buffer.
2554 * ReadConsoleOutput() seems to be limited as far as how much you
2555 * can read at a time. Empirically, this number seems to be about
2556 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2557 * in chunks until it is all copied. The chunks will all have the
2558 * same horizontal characteristics, so initialize them now. The
2559 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002561 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002562 ReadRegion.Left = 0;
2563 ReadRegion.Right = cb->Info.dwSize.X - 1;
2564 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002565
2566 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2567 if (cb->Regions == NULL || numregions != cb->NumRegions)
2568 {
2569 cb->NumRegions = numregions;
2570 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002571 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002572 if (cb->Regions == NULL)
2573 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002574 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002575 return FALSE;
2576 }
2577 }
2578
2579 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002581 /*
2582 * Read into position (0, Y) in our buffer.
2583 */
2584 BufferCoord.Y = Y;
2585 /*
2586 * Read the region whose top left corner is (0, Y) and whose bottom
2587 * right corner is (width - 1, Y + Y_incr - 1). This should define
2588 * a region of size width by Y_incr. Don't worry if this region is
2589 * too large for the remaining buffer; it will be cropped.
2590 */
2591 ReadRegion.Top = Y;
2592 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002593 if (!ReadConsoleOutputW(g_hConOut, // output handle
2594 cb->Buffer, // our buffer
2595 cb->BufferSize, // dimensions of our buffer
2596 BufferCoord, // offset in our buffer
2597 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002598 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002599 VIM_CLEAR(cb->Buffer);
2600 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002601 return FALSE;
2602 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002603 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604 }
2605
2606 return TRUE;
2607}
2608
2609/*
2610 * RestoreConsoleBuffer()
2611 * Description:
2612 * Restores important information about the console buffer, including the
2613 * actual buffer contents, if desired. The information to restore is in
2614 * the same format used by SaveConsoleBuffer().
2615 * Returns:
2616 * TRUE on success
2617 */
2618 static BOOL
2619RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002620 ConsoleBuffer *cb,
2621 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002623 COORD BufferCoord;
2624 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002625 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626
2627 if (cb == NULL || !cb->IsValid)
2628 return FALSE;
2629
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002630 /*
2631 * Before restoring the buffer contents, clear the current buffer, and
2632 * restore the cursor position and window information. Doing this now
2633 * prevents old buffer contents from "flashing" onto the screen.
2634 */
2635 if (RestoreScreen)
2636 ClearConsoleBuffer(cb->Info.wAttributes);
2637
2638 FitConsoleWindow(cb->Info.dwSize, TRUE);
2639 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2640 return FALSE;
2641 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2642 return FALSE;
2643
2644 if (!RestoreScreen)
2645 {
2646 /*
2647 * No need to restore the screen buffer contents, so we're done.
2648 */
2649 return TRUE;
2650 }
2651
2652 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2653 return FALSE;
2654 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2655 return FALSE;
2656
2657 /*
2658 * Restore the screen buffer contents.
2659 */
2660 if (cb->Buffer != NULL)
2661 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002662 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002663 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002664 BufferCoord.X = cb->Regions[i].Left;
2665 BufferCoord.Y = cb->Regions[i].Top;
2666 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002667 if (!WriteConsoleOutputW(g_hConOut, // output handle
2668 cb->Buffer, // our buffer
2669 cb->BufferSize, // dimensions of our buffer
2670 BufferCoord, // offset in our buffer
2671 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002672 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002673 }
2674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675
2676 return TRUE;
2677}
2678
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002679# define FEAT_RESTORE_ORIG_SCREEN
2680# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002681static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002682# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683static ConsoleBuffer g_cbNonTermcap = { 0 };
2684static ConsoleBuffer g_cbTermcap = { 0 };
2685
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002687HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688static HICON g_hOrigIconSmall = NULL;
2689static HICON g_hOrigIcon = NULL;
2690static HICON g_hVimIcon = NULL;
2691static BOOL g_fCanChangeIcon = FALSE;
2692
Bram Moolenaar0f873732019-12-05 20:28:46 +01002693// ICON* are not defined in VC++ 4.0
Bram Moolenaar651fca82021-11-29 20:39:38 +00002694# ifndef ICON_SMALL
2695# define ICON_SMALL 0
2696# endif
2697# ifndef ICON_BIG
2698# define ICON_BIG 1
2699# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700/*
2701 * GetConsoleIcon()
2702 * Description:
2703 * Attempts to retrieve the small icon and/or the big icon currently in
2704 * use by a given window.
2705 * Returns:
2706 * TRUE on success
2707 */
2708 static BOOL
2709GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002710 HWND hWnd,
2711 HICON *phIconSmall,
2712 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713{
2714 if (hWnd == NULL)
2715 return FALSE;
2716
2717 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002718 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2719 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002721 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2722 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723 return TRUE;
2724}
2725
2726/*
2727 * SetConsoleIcon()
2728 * Description:
2729 * Attempts to change the small icon and/or the big icon currently in
2730 * use by a given window.
2731 * Returns:
2732 * TRUE on success
2733 */
2734 static BOOL
2735SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002736 HWND hWnd,
2737 HICON hIconSmall,
2738 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002739{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740 if (hWnd == NULL)
2741 return FALSE;
2742
2743 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002744 SendMessage(hWnd, WM_SETICON,
2745 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002747 SendMessage(hWnd, WM_SETICON,
2748 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749 return TRUE;
2750}
2751
2752/*
2753 * SaveConsoleTitleAndIcon()
2754 * Description:
2755 * Saves the current console window title in g_szOrigTitle, for later
2756 * restoration. Also, attempts to obtain a handle to the console window,
2757 * and use it to save the small and big icons currently in use by the
2758 * console window. This is not always possible on some versions of Windows;
2759 * nor is it possible when running Vim remotely using Telnet (since the
2760 * console window the user sees is owned by a remote process).
2761 */
2762 static void
2763SaveConsoleTitleAndIcon(void)
2764{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002765 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2767 return;
2768
2769 /*
2770 * Obtain a handle to the console window using GetConsoleWindow() from
2771 * KERNEL32.DLL; we need to handle in order to change the window icon.
2772 * This function only exists on NT-based Windows, starting with Windows
2773 * 2000. On older operating systems, we can't change the window icon
2774 * anyway.
2775 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002776 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777 if (g_hWnd == NULL)
2778 return;
2779
Bram Moolenaar0f873732019-12-05 20:28:46 +01002780 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2782 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2783 return;
2784
Bram Moolenaar0f873732019-12-05 20:28:46 +01002785 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002786 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002787 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788 if (g_hVimIcon != NULL)
2789 g_fCanChangeIcon = TRUE;
2790}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791
2792static int g_fWindInitCalled = FALSE;
2793static int g_fTermcapMode = FALSE;
2794static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795
2796/*
2797 * non-GUI version of mch_init().
2798 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002799 static void
2800mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002802# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002803 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002804# endif
2805# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002806 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002807# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002808
Bram Moolenaar0f873732019-12-05 20:28:46 +01002809 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002810 SET_INVALID_PARAM_HANDLER;
2811
Bram Moolenaar0f873732019-12-05 20:28:46 +01002812 // Let critical errors result in a failure, not in a dialog box. Required
2813 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814 SetErrorMode(SEM_FAILCRITICALERRORS);
2815
Bram Moolenaar0f873732019-12-05 20:28:46 +01002816 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817 out_flush();
2818
Bram Moolenaar0f873732019-12-05 20:28:46 +01002819 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820 if (read_cmd_fd == 0)
2821 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2822 else
2823 create_conin();
2824 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2825
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002826# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002827 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002828 SaveConsoleBuffer(&g_cbOrig);
2829 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002830# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002831 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002832 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2833 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002834# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 if (cterm_normal_fg_color == 0)
2836 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2837 if (cterm_normal_bg_color == 0)
2838 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2839
Bram Moolenaarbdace832019-03-02 10:13:42 +01002840 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002841 g_color_index_fg = g_attrDefault & 0xf;
2842 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2843
Bram Moolenaar0f873732019-12-05 20:28:46 +01002844 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845 update_tcap(g_attrCurrent);
2846
2847 GetConsoleCursorInfo(g_hConOut, &g_cci);
2848 GetConsoleMode(g_hConIn, &g_cmodein);
2849 GetConsoleMode(g_hConOut, &g_cmodeout);
2850
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851 SaveConsoleTitleAndIcon();
2852 /*
2853 * Set both the small and big icons of the console window to Vim's icon.
2854 * Note that Vim presently only has one size of icon (32x32), but it
2855 * automatically gets scaled down to 16x16 when setting the small icon.
2856 */
2857 if (g_fCanChangeIcon)
2858 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859
2860 ui_get_shellsize();
2861
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002862# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863 fdDump = fopen("dump", "wt");
2864
2865 if (fdDump)
2866 {
2867 time_t t;
2868
2869 time(&t);
2870 fputs(ctime(&t), fdDump);
2871 fflush(fdDump);
2872 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002873# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874
2875 g_fWindInitCalled = TRUE;
2876
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002879# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002880 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002881# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002882
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002883 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002884 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002885 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886}
2887
2888/*
2889 * non-GUI version of mch_exit().
2890 * Shut down and exit with status `r'
2891 * Careful: mch_exit() may be called before mch_init()!
2892 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002893 static void
2894mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002896 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002898 vtp_exit();
2899
Bram Moolenaar955f1982017-02-05 15:10:51 +01002900 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901 if (g_fWindInitCalled)
2902 settmode(TMODE_COOK);
2903
Bram Moolenaar0f873732019-12-05 20:28:46 +01002904 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905
2906 if (g_fWindInitCalled)
2907 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002908 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909 /*
2910 * Restore both the small and big icons of the console window to
2911 * what they were at startup. Don't do this when the window is
2912 * closed, Vim would hang here.
2913 */
2914 if (g_fCanChangeIcon && !g_fForceExit)
2915 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002917# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918 if (fdDump)
2919 {
2920 time_t t;
2921
2922 time(&t);
2923 fputs(ctime(&t), fdDump);
2924 fclose(fdDump);
2925 }
2926 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002927# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 }
2929
2930 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002931 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 SetConsoleMode(g_hConOut, g_cmodeout);
2933
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002934# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002936# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937
2938 exit(r);
2939}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002940#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002942 void
2943mch_init(void)
2944{
2945#ifdef VIMDLL
2946 if (gui.starting)
2947 mch_init_g();
2948 else
2949 mch_init_c();
2950#elif defined(FEAT_GUI_MSWIN)
2951 mch_init_g();
2952#else
2953 mch_init_c();
2954#endif
2955}
2956
2957 void
2958mch_exit(int r)
2959{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002960#ifdef FEAT_NETBEANS_INTG
2961 netbeans_send_disconnect();
2962#endif
2963
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002964#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002965 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002966 mch_exit_g(r);
2967 else
2968 mch_exit_c(r);
2969#elif defined(FEAT_GUI_MSWIN)
2970 mch_exit_g(r);
2971#else
2972 mch_exit_c(r);
2973#endif
2974}
2975
Bram Moolenaar071d4272004-06-13 20:20:40 +00002976/*
2977 * Do we have an interactive window?
2978 */
2979 int
2980mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002981 int argc UNUSED,
2982 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983{
2984 get_exe_name();
2985
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002986#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002987 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002989# ifdef VIMDLL
2990 if (gui.in_use)
2991 return OK;
2992# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993 if (isatty(1))
2994 return OK;
2995 return FAIL;
2996#endif
2997}
2998
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002999/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003000 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003001 * When "len" is > 0, also expand short to long filenames.
3002 */
3003 void
3004fname_case(
3005 char_u *name,
3006 int len)
3007{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003008 int flen;
3009 WCHAR *p;
3010 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003012 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003013 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014 return;
3015
3016 slash_adjust(name);
3017
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003018 p = enc_to_utf16(name, NULL);
3019 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003020 return;
3021
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003022 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003024 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003026 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003028 if (len > 0 || flen >= (int)STRLEN(q))
3029 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3030 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 }
3032 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003033 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034}
3035
3036
3037/*
3038 * Insert user name in s[len].
3039 */
3040 int
3041mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003042 char_u *s,
3043 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003045 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003046 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003048 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003049 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003050 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003051
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003052 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003053 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003054 vim_strncpy(s, p, len - 1);
3055 vim_free(p);
3056 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003057 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003058 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059 s[0] = NUL;
3060 return FAIL;
3061}
3062
3063
3064/*
3065 * Insert host name in s[len].
3066 */
3067 void
3068mch_get_host_name(
3069 char_u *s,
3070 int len)
3071{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003072 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003073 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003075 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003076 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003077 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003078
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003079 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003080 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003081 vim_strncpy(s, p, len - 1);
3082 vim_free(p);
3083 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003084 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003085 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086}
3087
3088
3089/*
3090 * return process ID
3091 */
3092 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003093mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094{
3095 return (long)GetCurrentProcessId();
3096}
3097
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003098/*
3099 * return TRUE if process "pid" is still running
3100 */
3101 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003102mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003103{
3104 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3105 DWORD status = 0;
3106 int ret = FALSE;
3107
3108 if (hProcess == NULL)
3109 return FALSE; // might not have access
3110 if (GetExitCodeProcess(hProcess, &status) )
3111 ret = status == STILL_ACTIVE;
3112 CloseHandle(hProcess);
3113 return ret;
3114}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115
3116/*
3117 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3118 * Return OK for success, FAIL for failure.
3119 */
3120 int
3121mch_dirname(
3122 char_u *buf,
3123 int len)
3124{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003125 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003126
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127 /*
3128 * Originally this was:
3129 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3130 * But the Win32s known bug list says that getcwd() doesn't work
3131 * so use the Win32 system call instead. <Negri>
3132 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003133 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003135 WCHAR wcbuf[_MAX_PATH + 1];
3136 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003138 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003140 p = utf16_to_enc(wcbuf, NULL);
3141 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003142 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003143 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003144 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003145 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146 }
3147 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003148 if (p == NULL)
3149 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003150
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003151 if (p != NULL)
3152 {
3153 vim_strncpy(buf, p, len - 1);
3154 vim_free(p);
3155 return OK;
3156 }
3157 }
3158 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159}
3160
3161/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003162 * Get file permissions for "name".
3163 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003164 */
3165 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003166mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003168 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003169 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003171 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003172 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173}
3174
3175
3176/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003177 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003178 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003179 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 */
3181 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003182mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003184 long n;
3185 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003186
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003187 p = enc_to_utf16(name, NULL);
3188 if (p == NULL)
3189 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003191 n = _wchmod(p, perm);
3192 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003193 if (n == -1)
3194 return FAIL;
3195
3196 win32_set_archive(name);
3197
3198 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199}
3200
3201/*
3202 * Set hidden flag for "name".
3203 */
3204 void
3205mch_hide(char_u *name)
3206{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003207 int attrs = win32_getattrs(name);
3208 if (attrs == -1)
3209 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003211 attrs |= FILE_ATTRIBUTE_HIDDEN;
3212 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213}
3214
3215/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003216 * Return TRUE if file "name" exists and is hidden.
3217 */
3218 int
3219mch_ishidden(char_u *name)
3220{
3221 int f = win32_getattrs(name);
3222
3223 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003224 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003225
3226 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3227}
3228
3229/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003230 * return TRUE if "name" is a directory
3231 * return FALSE if "name" is not a directory or upon error
3232 */
3233 int
3234mch_isdir(char_u *name)
3235{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003236 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237
3238 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003239 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240
3241 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3242}
3243
3244/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003245 * return TRUE if "name" is a directory, NOT a symlink to a directory
3246 * return FALSE if "name" is not a directory
3247 * return FALSE for error
3248 */
3249 int
3250mch_isrealdir(char_u *name)
3251{
3252 return mch_isdir(name) && !mch_is_symbolic_link(name);
3253}
3254
3255/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003256 * Create directory "name".
3257 * Return 0 on success, -1 on error.
3258 */
3259 int
3260mch_mkdir(char_u *name)
3261{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003262 WCHAR *p;
3263 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003264
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003265 p = enc_to_utf16(name, NULL);
3266 if (p == NULL)
3267 return -1;
3268 retval = _wmkdir(p);
3269 vim_free(p);
3270 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003271}
3272
3273/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003274 * Delete directory "name".
3275 * Return 0 on success, -1 on error.
3276 */
3277 int
3278mch_rmdir(char_u *name)
3279{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003280 WCHAR *p;
3281 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003282
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003283 p = enc_to_utf16(name, NULL);
3284 if (p == NULL)
3285 return -1;
3286 retval = _wrmdir(p);
3287 vim_free(p);
3288 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003289}
3290
3291/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003292 * Return TRUE if file "fname" has more than one link.
3293 */
3294 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003295mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003296{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003297 BY_HANDLE_FILE_INFORMATION info;
3298
3299 return win32_fileinfo(fname, &info) == FILEINFO_OK
3300 && info.nNumberOfLinks > 1;
3301}
3302
3303/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003304 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003305 */
3306 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003307mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003308{
3309 HANDLE hFind;
3310 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003311 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003312 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003313 WIN32_FIND_DATAW findDataW;
3314
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003315 wn = enc_to_utf16(name, NULL);
3316 if (wn == NULL)
3317 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003318
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003319 hFind = FindFirstFileW(wn, &findDataW);
3320 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003321 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003322 {
3323 fileFlags = findDataW.dwFileAttributes;
3324 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003325 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003326 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003327
3328 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003329 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3330 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003331 res = TRUE;
3332
3333 return res;
3334}
3335
3336/*
3337 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3338 * link.
3339 */
3340 int
3341mch_is_linked(char_u *fname)
3342{
3343 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3344 return TRUE;
3345 return FALSE;
3346}
3347
3348/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003349 * Get the by-handle-file-information for "fname".
3350 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003351 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003352 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3353 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3354 */
3355 int
3356win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3357{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003358 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003359 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003360 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003361
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003362 wn = enc_to_utf16(fname, NULL);
3363 if (wn == NULL)
3364 return FILEINFO_ENC_FAIL;
3365
3366 hFile = CreateFileW(wn, // file name
3367 GENERIC_READ, // access mode
3368 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3369 NULL, // security descriptor
3370 OPEN_EXISTING, // creation disposition
3371 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3372 NULL); // handle to template file
3373 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003374
3375 if (hFile != INVALID_HANDLE_VALUE)
3376 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003377 if (GetFileInformationByHandle(hFile, info) != 0)
3378 res = FILEINFO_OK;
3379 else
3380 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003381 CloseHandle(hFile);
3382 }
3383
Bram Moolenaar03f48552006-02-28 23:52:23 +00003384 return res;
3385}
3386
3387/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003388 * get file attributes for `name'
3389 * -1 : error
3390 * else FILE_ATTRIBUTE_* defined in winnt.h
3391 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003392 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003393win32_getattrs(char_u *name)
3394{
3395 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003396 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003397
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003398 p = enc_to_utf16(name, NULL);
3399 if (p == NULL)
3400 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003401
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003402 attr = GetFileAttributesW(p);
3403 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003404
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003405 return attr;
3406}
3407
3408/*
3409 * set file attributes for `name' to `attrs'
3410 *
3411 * return -1 for failure, 0 otherwise
3412 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003413 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003414win32_setattrs(char_u *name, int attrs)
3415{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003416 int res;
3417 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003418
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003419 p = enc_to_utf16(name, NULL);
3420 if (p == NULL)
3421 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003422
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003423 res = SetFileAttributesW(p, attrs);
3424 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003425
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003426 return res ? 0 : -1;
3427}
3428
3429/*
3430 * Set archive flag for "name".
3431 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003432 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003433win32_set_archive(char_u *name)
3434{
3435 int attrs = win32_getattrs(name);
3436 if (attrs == -1)
3437 return -1;
3438
3439 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3440 return win32_setattrs(name, attrs);
3441}
3442
3443/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444 * Return TRUE if file or directory "name" is writable (not readonly).
3445 * Strange semantics of Win32: a readonly directory is writable, but you can't
3446 * delete a file. Let's say this means it is writable.
3447 */
3448 int
3449mch_writable(char_u *name)
3450{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003451 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003452
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003453 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3454 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003455}
3456
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003458 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003459 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003460 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3461 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462 */
3463 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003464mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003466 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003468
3469/*
3470 * Check what "name" is:
3471 * NODE_NORMAL: file or directory (or doesn't exist)
3472 * NODE_WRITABLE: writable device, socket, fifo, etc.
3473 * NODE_OTHER: non-writable things
3474 */
3475 int
3476mch_nodetype(char_u *name)
3477{
3478 HANDLE hFile;
3479 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003480 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481
Bram Moolenaar0f873732019-12-05 20:28:46 +01003482 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3483 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3484 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003485 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3486 return NODE_WRITABLE;
3487
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003488 wn = enc_to_utf16(name, NULL);
3489 if (wn == NULL)
3490 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003491
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003492 hFile = CreateFileW(wn, // file name
3493 GENERIC_WRITE, // access mode
3494 0, // share mode
3495 NULL, // security descriptor
3496 OPEN_EXISTING, // creation disposition
3497 0, // file attributes
3498 NULL); // handle to template file
3499 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 if (hFile == INVALID_HANDLE_VALUE)
3501 return NODE_NORMAL;
3502
3503 type = GetFileType(hFile);
3504 CloseHandle(hFile);
3505 if (type == FILE_TYPE_CHAR)
3506 return NODE_WRITABLE;
3507 if (type == FILE_TYPE_DISK)
3508 return NODE_NORMAL;
3509 return NODE_OTHER;
3510}
3511
3512#ifdef HAVE_ACL
3513struct my_acl
3514{
3515 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3516 PSID pSidOwner;
3517 PSID pSidGroup;
3518 PACL pDacl;
3519 PACL pSacl;
3520};
3521#endif
3522
3523/*
3524 * Return a pointer to the ACL of file "fname" in allocated memory.
3525 * Return NULL if the ACL is not available for whatever reason.
3526 */
3527 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003528mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529{
3530#ifndef HAVE_ACL
3531 return (vim_acl_T)NULL;
3532#else
3533 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003534 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003536 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003537 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003539 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003540
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003541 wn = enc_to_utf16(fname, NULL);
3542 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003543 {
3544 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003545 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003546 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003547
3548 // Try to retrieve the entire security descriptor.
3549 err = GetNamedSecurityInfoW(
3550 wn, // Abstract filename
3551 SE_FILE_OBJECT, // File Object
3552 OWNER_SECURITY_INFORMATION |
3553 GROUP_SECURITY_INFORMATION |
3554 DACL_SECURITY_INFORMATION |
3555 SACL_SECURITY_INFORMATION,
3556 &p->pSidOwner, // Ownership information.
3557 &p->pSidGroup, // Group membership.
3558 &p->pDacl, // Discretionary information.
3559 &p->pSacl, // For auditing purposes.
3560 &p->pSecurityDescriptor);
3561 if (err == ERROR_ACCESS_DENIED ||
3562 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003563 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003564 // Retrieve only DACL.
3565 (void)GetNamedSecurityInfoW(
3566 wn,
3567 SE_FILE_OBJECT,
3568 DACL_SECURITY_INFORMATION,
3569 NULL,
3570 NULL,
3571 &p->pDacl,
3572 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003573 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003574 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003575 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003576 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003577 mch_free_acl((vim_acl_T)p);
3578 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003579 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003580 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003581 }
3582
3583 return (vim_acl_T)p;
3584#endif
3585}
3586
Bram Moolenaar27515922013-06-29 15:36:26 +02003587#ifdef HAVE_ACL
3588/*
3589 * Check if "acl" contains inherited ACE.
3590 */
3591 static BOOL
3592is_acl_inherited(PACL acl)
3593{
3594 DWORD i;
3595 ACL_SIZE_INFORMATION acl_info;
3596 PACCESS_ALLOWED_ACE ace;
3597
3598 acl_info.AceCount = 0;
3599 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3600 for (i = 0; i < acl_info.AceCount; i++)
3601 {
3602 GetAce(acl, i, (LPVOID *)&ace);
3603 if (ace->Header.AceFlags & INHERITED_ACE)
3604 return TRUE;
3605 }
3606 return FALSE;
3607}
3608#endif
3609
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610/*
3611 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3612 * Errors are ignored.
3613 * This must only be called with "acl" equal to what mch_get_acl() returned.
3614 */
3615 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003616mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003617{
3618#ifdef HAVE_ACL
3619 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003620 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003621 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003622
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003623 if (p == NULL)
3624 return;
3625
3626 wn = enc_to_utf16(fname, NULL);
3627 if (wn == NULL)
3628 return;
3629
3630 // Set security flags
3631 if (p->pSidOwner)
3632 sec_info |= OWNER_SECURITY_INFORMATION;
3633 if (p->pSidGroup)
3634 sec_info |= GROUP_SECURITY_INFORMATION;
3635 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003636 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003637 sec_info |= DACL_SECURITY_INFORMATION;
3638 // Do not inherit its parent's DACL.
3639 // If the DACL is inherited, Cygwin permissions would be changed.
3640 if (!is_acl_inherited(p->pDacl))
3641 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003642 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003643 if (p->pSacl)
3644 sec_info |= SACL_SECURITY_INFORMATION;
3645
3646 (void)SetNamedSecurityInfoW(
3647 wn, // Abstract filename
3648 SE_FILE_OBJECT, // File Object
3649 sec_info,
3650 p->pSidOwner, // Ownership information.
3651 p->pSidGroup, // Group membership.
3652 p->pDacl, // Discretionary information.
3653 p->pSacl // For auditing purposes.
3654 );
3655 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656#endif
3657}
3658
3659 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003660mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003661{
3662#ifdef HAVE_ACL
3663 struct my_acl *p = (struct my_acl *)acl;
3664
3665 if (p != NULL)
3666 {
3667 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3668 vim_free(p);
3669 }
3670#endif
3671}
3672
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003673#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674
3675/*
3676 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3677 */
3678 static BOOL WINAPI
3679handler_routine(
3680 DWORD dwCtrlType)
3681{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003682 INPUT_RECORD ir;
3683 DWORD out;
3684
Bram Moolenaar071d4272004-06-13 20:20:40 +00003685 switch (dwCtrlType)
3686 {
3687 case CTRL_C_EVENT:
3688 if (ctrl_c_interrupts)
3689 g_fCtrlCPressed = TRUE;
3690 return TRUE;
3691
3692 case CTRL_BREAK_EVENT:
3693 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003694 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003695 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003696 ir.EventType = KEY_EVENT;
3697 ir.Event.KeyEvent.bKeyDown = TRUE;
3698 ir.Event.KeyEvent.wRepeatCount = 1;
3699 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3700 ir.Event.KeyEvent.wVirtualScanCode = 0;
3701 ir.Event.KeyEvent.dwControlKeyState = 0;
3702 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3703 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 return TRUE;
3705
Bram Moolenaar0f873732019-12-05 20:28:46 +01003706 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707 case CTRL_CLOSE_EVENT:
3708 case CTRL_LOGOFF_EVENT:
3709 case CTRL_SHUTDOWN_EVENT:
3710 windgoto((int)Rows - 1, 0);
3711 g_fForceExit = TRUE;
3712
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003713 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714 (dwCtrlType == CTRL_CLOSE_EVENT
3715 ? _("close")
3716 : dwCtrlType == CTRL_LOGOFF_EVENT
3717 ? _("logoff")
3718 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003719# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003720 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003721# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722
Bram Moolenaar0f873732019-12-05 20:28:46 +01003723 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724
Bram Moolenaar0f873732019-12-05 20:28:46 +01003725 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726
3727 default:
3728 return FALSE;
3729 }
3730}
3731
3732
3733/*
3734 * set the tty in (raw) ? "raw" : "cooked" mode
3735 */
3736 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003737mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738{
3739 DWORD cmodein;
3740 DWORD cmodeout;
3741 BOOL bEnableHandler;
3742
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003743# ifdef VIMDLL
3744 if (gui.in_use)
3745 return;
3746# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747 GetConsoleMode(g_hConIn, &cmodein);
3748 GetConsoleMode(g_hConOut, &cmodeout);
3749 if (tmode == TMODE_RAW)
3750 {
3751 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3752 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003754 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003755 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003756 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3757 }
3758 else
3759 {
3760 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3761 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003762 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003763# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003764 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3765 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003766 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003767# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003768 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003769# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003770 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 bEnableHandler = TRUE;
3772 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003773 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 {
3775 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3776 ENABLE_ECHO_INPUT);
3777 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3778 bEnableHandler = FALSE;
3779 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003780 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 SetConsoleMode(g_hConOut, cmodeout);
3782 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3783
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003784# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 if (fdDump)
3786 {
3787 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3788 tmode == TMODE_RAW ? "raw" :
3789 tmode == TMODE_COOK ? "cooked" : "normal",
3790 cmodein, cmodeout);
3791 fflush(fdDump);
3792 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003793# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794}
3795
3796
3797/*
3798 * Get the size of the current window in `Rows' and `Columns'
3799 * Return OK when size could be determined, FAIL otherwise.
3800 */
3801 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003802mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803{
3804 CONSOLE_SCREEN_BUFFER_INFO csbi;
3805
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003806# ifdef VIMDLL
3807 if (gui.in_use)
3808 return OK;
3809# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3811 {
3812 /*
3813 * For some reason, we are trying to get the screen dimensions
3814 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3815 * variables are really intended to mean the size of Vim screen
3816 * while in termcap mode.
3817 */
3818 Rows = g_cbTermcap.Info.dwSize.Y;
3819 Columns = g_cbTermcap.Info.dwSize.X;
3820 }
3821 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3822 {
3823 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3824 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3825 }
3826 else
3827 {
3828 Rows = 25;
3829 Columns = 80;
3830 }
3831 return OK;
3832}
3833
3834/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003835 * Resize console buffer to 'COORD'
3836 */
3837 static void
3838ResizeConBuf(
3839 HANDLE hConsole,
3840 COORD coordScreen)
3841{
3842 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3843 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003844# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003845 if (fdDump)
3846 {
3847 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3848 GetLastError());
3849 fflush(fdDump);
3850 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003851# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003852 }
3853}
3854
3855/*
3856 * Resize console window size to 'srWindowRect'
3857 */
3858 static void
3859ResizeWindow(
3860 HANDLE hConsole,
3861 SMALL_RECT srWindowRect)
3862{
3863 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3864 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003865# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003866 if (fdDump)
3867 {
3868 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3869 GetLastError());
3870 fflush(fdDump);
3871 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003872# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003873 }
3874}
3875
3876/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877 * Set a console window to `xSize' * `ySize'
3878 */
3879 static void
3880ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003881 HANDLE hConsole,
3882 int xSize,
3883 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003885 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3886 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003888 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003889 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003891# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892 if (fdDump)
3893 {
3894 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3895 fflush(fdDump);
3896 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003897# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003898
Bram Moolenaar0f873732019-12-05 20:28:46 +01003899 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003900 coordScreen = GetLargestConsoleWindowSize(hConsole);
3901
Bram Moolenaar0f873732019-12-05 20:28:46 +01003902 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3904 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3905 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3906
3907 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3908 {
3909 int sx, sy;
3910
3911 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3912 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3913 if (sy < ySize || sx < xSize)
3914 {
3915 /*
3916 * Increasing number of lines/columns, do buffer first.
3917 * Use the maximal size in x and y direction.
3918 */
3919 if (sy < ySize)
3920 coordScreen.Y = ySize;
3921 else
3922 coordScreen.Y = sy;
3923 if (sx < xSize)
3924 coordScreen.X = xSize;
3925 else
3926 coordScreen.X = sx;
3927 SetConsoleScreenBufferSize(hConsole, coordScreen);
3928 }
3929 }
3930
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003931 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932 coordScreen.X = xSize;
3933 coordScreen.Y = ySize;
3934
Bram Moolenaar2551c032018-08-23 22:38:31 +02003935 // In the new console call API, only the first time in reverse order
3936 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003938 ResizeWindow(hConsole, srWindowRect);
3939 ResizeConBuf(hConsole, coordScreen);
3940 }
3941 else
3942 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003943 // Workaround for a Windows 10 bug
3944 cursor.X = srWindowRect.Left;
3945 cursor.Y = srWindowRect.Top;
3946 SetConsoleCursorPosition(hConsole, cursor);
3947
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003948 ResizeConBuf(hConsole, coordScreen);
3949 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003950 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 }
3952}
3953
3954
3955/*
3956 * Set the console window to `Rows' * `Columns'
3957 */
3958 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003959mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960{
3961 COORD coordScreen;
3962
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003963# ifdef VIMDLL
3964 if (gui.in_use)
3965 return;
3966# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01003967 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968 if (suppress_winsize != 0)
3969 {
3970 suppress_winsize = 2;
3971 return;
3972 }
3973
3974 if (term_console)
3975 {
3976 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3977
Bram Moolenaar0f873732019-12-05 20:28:46 +01003978 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00003979 if (Rows > coordScreen.Y)
3980 Rows = coordScreen.Y;
3981 if (Columns > coordScreen.X)
3982 Columns = coordScreen.X;
3983
3984 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3985 }
3986}
3987
3988/*
3989 * Rows and/or Columns has changed.
3990 */
3991 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003992mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003994# ifdef VIMDLL
3995 if (gui.in_use)
3996 return;
3997# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003998 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3999}
4000
4001
4002/*
4003 * Called when started up, to set the winsize that was delayed.
4004 */
4005 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004006mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004007{
4008 if (suppress_winsize == 2)
4009 {
4010 suppress_winsize = 0;
4011 mch_set_shellsize();
4012 shell_resized();
4013 }
4014 suppress_winsize = 0;
4015}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004016#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004018 static BOOL
4019vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004020 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004021 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004022 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004023 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004024 PROCESS_INFORMATION *pi,
4025 LPVOID *env,
4026 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004027{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004028 BOOL ret = FALSE;
4029 WCHAR *wcmd, *wcwd = NULL;
4030
4031 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4032 if (wcmd == NULL)
4033 return FALSE;
4034 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004035 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004036 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4037 if (wcwd == NULL)
4038 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004039 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004040
4041 ret = CreateProcessW(
4042 NULL, // Executable name
4043 wcmd, // Command to execute
4044 NULL, // Process security attributes
4045 NULL, // Thread security attributes
4046 inherit_handles, // Inherit handles
4047 flags, // Creation flags
4048 env, // Environment
4049 wcwd, // Current directory
4050 (LPSTARTUPINFOW)si, // Startup information
4051 pi); // Process information
4052theend:
4053 vim_free(wcmd);
4054 vim_free(wcwd);
4055 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004056}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057
4058
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004059 static HINSTANCE
4060vim_shell_execute(
4061 char *cmd,
4062 INT n_show_cmd)
4063{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004064 HINSTANCE ret;
4065 WCHAR *wcmd;
4066
4067 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4068 if (wcmd == NULL)
4069 return (HINSTANCE) 0;
4070
4071 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4072 vim_free(wcmd);
4073 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004074}
4075
4076
Bram Moolenaar4f974752019-02-17 17:44:42 +01004077#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078
4079/*
4080 * Specialised version of system() for Win32 GUI mode.
4081 * This version proceeds as follows:
4082 * 1. Create a console window for use by the subprocess
4083 * 2. Run the subprocess (it gets the allocated console by default)
4084 * 3. Wait for the subprocess to terminate and get its exit code
4085 * 4. Prompt the user to press a key to close the console window
4086 */
4087 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004088mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004089{
4090 STARTUPINFO si;
4091 PROCESS_INFORMATION pi;
4092 DWORD ret = 0;
4093 HWND hwnd = GetFocus();
4094
4095 si.cb = sizeof(si);
4096 si.lpReserved = NULL;
4097 si.lpDesktop = NULL;
4098 si.lpTitle = NULL;
4099 si.dwFlags = STARTF_USESHOWWINDOW;
4100 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004101 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004102 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004103 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004104 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004105 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 else
4107 si.wShowWindow = SW_SHOWNORMAL;
4108 si.cbReserved2 = 0;
4109 si.lpReserved2 = NULL;
4110
Bram Moolenaar0f873732019-12-05 20:28:46 +01004111 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004112 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004113 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4114 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115
Bram Moolenaar0f873732019-12-05 20:28:46 +01004116 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004118# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119 int delay = 1;
4120
Bram Moolenaar0f873732019-12-05 20:28:46 +01004121 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 for (;;)
4123 {
4124 MSG msg;
4125
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004126 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 {
4128 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004129 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004130 delay = 1;
4131 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 }
4133 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4134 break;
4135
Bram Moolenaar0f873732019-12-05 20:28:46 +01004136 // We start waiting for a very short time and then increase it, so
4137 // that we respond quickly when the process is quick, and don't
4138 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139 if (delay < 50)
4140 delay += 10;
4141 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004142# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004144# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145
Bram Moolenaar0f873732019-12-05 20:28:46 +01004146 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147 GetExitCodeProcess(pi.hProcess, &ret);
4148 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149
Bram Moolenaar0f873732019-12-05 20:28:46 +01004150 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 CloseHandle(pi.hThread);
4152 CloseHandle(pi.hProcess);
4153
Bram Moolenaar0f873732019-12-05 20:28:46 +01004154 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4156
4157 return ret;
4158}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004159
4160/*
4161 * Thread launched by the gui to send the current buffer data to the
4162 * process. This way avoid to hang up vim totally if the children
4163 * process take a long time to process the lines.
4164 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004165 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004166sub_process_writer(LPVOID param)
4167{
4168 HANDLE g_hChildStd_IN_Wr = param;
4169 linenr_T lnum = curbuf->b_op_start.lnum;
4170 DWORD len = 0;
4171 DWORD l;
4172 char_u *lp = ml_get(lnum);
4173 char_u *s;
4174 int written = 0;
4175
4176 for (;;)
4177 {
4178 l = (DWORD)STRLEN(lp + written);
4179 if (l == 0)
4180 len = 0;
4181 else if (lp[written] == NL)
4182 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004183 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004184 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4185 }
4186 else
4187 {
4188 s = vim_strchr(lp + written, NL);
4189 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4190 s == NULL ? l : (DWORD)(s - (lp + written)),
4191 &len, NULL);
4192 }
4193 if (len == (int)l)
4194 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004195 // Finished a line, add a NL, unless this line should not have
4196 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004197 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004198 || (!curbuf->b_p_bin
4199 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004200 || (lnum != curbuf->b_no_eol_lnum
4201 && (lnum != curbuf->b_ml.ml_line_count
4202 || curbuf->b_p_eol)))
4203 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004204 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4205 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004206 }
4207
4208 ++lnum;
4209 if (lnum > curbuf->b_op_end.lnum)
4210 break;
4211
4212 lp = ml_get(lnum);
4213 written = 0;
4214 }
4215 else if (len > 0)
4216 written += len;
4217 }
4218
Bram Moolenaar0f873732019-12-05 20:28:46 +01004219 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004220 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004221 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004222}
4223
4224
Bram Moolenaar0f873732019-12-05 20:28:46 +01004225# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004226
4227/*
4228 * This function read from the children's stdout and write the
4229 * data on screen or in the buffer accordingly.
4230 */
4231 static void
4232dump_pipe(int options,
4233 HANDLE g_hChildStd_OUT_Rd,
4234 garray_T *ga,
4235 char_u buffer[],
4236 DWORD *buffer_off)
4237{
4238 DWORD availableBytes = 0;
4239 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004240 int ret;
4241 DWORD len;
4242 DWORD toRead;
4243 int repeatCount;
4244
Bram Moolenaar0f873732019-12-05 20:28:46 +01004245 // we query the pipe to see if there is any data to read
4246 // to avoid to perform a blocking read
4247 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4248 NULL, // optional buffer
4249 0, // buffer size
4250 NULL, // number of read bytes
4251 &availableBytes, // available bytes total
4252 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004253
4254 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004255 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004256 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004257 {
4258 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004259 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004260 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004261 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004262
Bram Moolenaar0f873732019-12-05 20:28:46 +01004263 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004264 if (len == 0)
4265 break;
4266
4267 availableBytes -= len;
4268
4269 if (options & SHELL_READ)
4270 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004271 // Do NUL -> NL translation, append NL separated
4272 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004273 for (i = 0; i < len; ++i)
4274 {
4275 if (buffer[i] == NL)
4276 append_ga_line(ga);
4277 else if (buffer[i] == NUL)
4278 ga_append(ga, NL);
4279 else
4280 ga_append(ga, buffer[i]);
4281 }
4282 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004283 else if (has_mbyte)
4284 {
4285 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004286 int c;
4287 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004288
4289 len += *buffer_off;
4290 buffer[len] = NUL;
4291
Bram Moolenaar0f873732019-12-05 20:28:46 +01004292 // Check if the last character in buffer[] is
4293 // incomplete, keep these bytes for the next
4294 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004295 for (p = buffer; p < buffer + len; p += l)
4296 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004297 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004299 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004300 else if (MB_BYTE2LEN(*p) != l)
4301 break;
4302 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004303 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004304 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004305 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004306 if (len >= 12)
4307 ++p;
4308 else
4309 {
4310 *buffer_off = len;
4311 return;
4312 }
4313 }
4314 c = *p;
4315 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004316 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004317 if (p < buffer + len)
4318 {
4319 *p = c;
4320 *buffer_off = (DWORD)((buffer + len) - p);
4321 mch_memmove(buffer, p, *buffer_off);
4322 return;
4323 }
4324 *buffer_off = 0;
4325 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004326 else
4327 {
4328 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004329 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004330 }
4331
4332 windgoto(msg_row, msg_col);
4333 cursor_on();
4334 out_flush();
4335 }
4336}
4337
4338/*
4339 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4340 * for communication and doesn't open any new window.
4341 */
4342 static int
4343mch_system_piped(char *cmd, int options)
4344{
4345 STARTUPINFO si;
4346 PROCESS_INFORMATION pi;
4347 DWORD ret = 0;
4348
4349 HANDLE g_hChildStd_IN_Rd = NULL;
4350 HANDLE g_hChildStd_IN_Wr = NULL;
4351 HANDLE g_hChildStd_OUT_Rd = NULL;
4352 HANDLE g_hChildStd_OUT_Wr = NULL;
4353
Bram Moolenaar0f873732019-12-05 20:28:46 +01004354 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004355 DWORD len;
4356
Bram Moolenaar0f873732019-12-05 20:28:46 +01004357 // buffer used to receive keys
4358 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4359 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004360
4361 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004362 int noread_cnt = 0;
4363 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004364 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004365 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004366 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004367
4368 SECURITY_ATTRIBUTES saAttr;
4369
Bram Moolenaar0f873732019-12-05 20:28:46 +01004370 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004371 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4372 saAttr.bInheritHandle = TRUE;
4373 saAttr.lpSecurityDescriptor = NULL;
4374
4375 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004376 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004377 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004378 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004379 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004380 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004381 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004382 {
4383 CloseHandle(g_hChildStd_IN_Rd);
4384 CloseHandle(g_hChildStd_IN_Wr);
4385 CloseHandle(g_hChildStd_OUT_Rd);
4386 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004387 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004388 }
4389
4390 si.cb = sizeof(si);
4391 si.lpReserved = NULL;
4392 si.lpDesktop = NULL;
4393 si.lpTitle = NULL;
4394 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4395
Bram Moolenaar0f873732019-12-05 20:28:46 +01004396 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004397 si.hStdError = g_hChildStd_OUT_Wr;
4398 si.hStdOutput = g_hChildStd_OUT_Wr;
4399 si.hStdInput = g_hChildStd_IN_Rd;
4400 si.wShowWindow = SW_HIDE;
4401 si.cbReserved2 = 0;
4402 si.lpReserved2 = NULL;
4403
4404 if (options & SHELL_READ)
4405 ga_init2(&ga, 1, BUFLEN);
4406
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004407 if (cmd != NULL)
4408 {
4409 p = (char *)vim_strsave((char_u *)cmd);
4410 if (p != NULL)
4411 unescape_shellxquote((char_u *)p, p_sxe);
4412 else
4413 p = cmd;
4414 }
4415
Bram Moolenaar0f873732019-12-05 20:28:46 +01004416 // Now, run the command.
4417 // About "Inherit handles" being TRUE: this command can be litigious,
4418 // handle inheritance was deactivated for pending temp file, but, if we
4419 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004420 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4421 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004423 if (p != cmd)
4424 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004425
Bram Moolenaar0f873732019-12-05 20:28:46 +01004426 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004427 CloseHandle(g_hChildStd_IN_Rd);
4428 CloseHandle(g_hChildStd_OUT_Wr);
4429
4430 if (options & SHELL_WRITE)
4431 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004432 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004433 _beginthreadex(NULL, // security attributes
4434 0, // default stack size
4435 sub_process_writer, // function to be executed
4436 g_hChildStd_IN_Wr, // parameter
4437 0, // creation flag, start immediately
4438 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004439 CloseHandle(thread);
4440 g_hChildStd_IN_Wr = NULL;
4441 }
4442
Bram Moolenaar0f873732019-12-05 20:28:46 +01004443 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004444 for (;;)
4445 {
4446 MSG msg;
4447
Bram Moolenaar175d0702013-12-11 18:36:33 +01004448 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004449 {
4450 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004451 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004452 }
4453
Bram Moolenaar0f873732019-12-05 20:28:46 +01004454 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004455 if ((options & (SHELL_READ|SHELL_WRITE))
4456# ifdef FEAT_GUI
4457 || gui.in_use
4458# endif
4459 )
4460 {
4461 len = 0;
4462 if (!(options & SHELL_EXPAND)
4463 && ((options &
4464 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4465 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4466# ifdef FEAT_GUI
4467 || gui.in_use
4468# endif
4469 )
4470 && (ta_len > 0 || noread_cnt > 4))
4471 {
4472 if (ta_len == 0)
4473 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004474 // Get extra characters when we don't have any. Reset the
4475 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004476 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004477 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4478 }
4479 if (ta_len > 0 || len > 0)
4480 {
4481 /*
4482 * For pipes: Check for CTRL-C: send interrupt signal to
4483 * child. Check for CTRL-D: EOF, close pipe to child.
4484 */
4485 if (len == 1 && cmd != NULL)
4486 {
4487 if (ta_buf[ta_len] == Ctrl_C)
4488 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004489 // Learn what exit code is expected, for
4490 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004491 TerminateProcess(pi.hProcess, 9);
4492 }
4493 if (ta_buf[ta_len] == Ctrl_D)
4494 {
4495 CloseHandle(g_hChildStd_IN_Wr);
4496 g_hChildStd_IN_Wr = NULL;
4497 }
4498 }
4499
Bram Moolenaarf4140482020-02-15 23:06:45 +01004500 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004501
4502 /*
4503 * For pipes: echo the typed characters. For a pty this
4504 * does not seem to work.
4505 */
4506 for (i = ta_len; i < ta_len + len; ++i)
4507 {
4508 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4509 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004510 else if (has_mbyte)
4511 {
4512 int l = (*mb_ptr2len)(ta_buf + i);
4513
4514 msg_outtrans_len(ta_buf + i, l);
4515 i += l - 1;
4516 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004517 else
4518 msg_outtrans_len(ta_buf + i, 1);
4519 }
4520 windgoto(msg_row, msg_col);
4521 out_flush();
4522
4523 ta_len += len;
4524
4525 /*
4526 * Write the characters to the child, unless EOF has been
4527 * typed for pipes. Write one character at a time, to
4528 * avoid losing too much typeahead. When writing buffer
4529 * lines, drop the typed characters (only check for
4530 * CTRL-C).
4531 */
4532 if (options & SHELL_WRITE)
4533 ta_len = 0;
4534 else if (g_hChildStd_IN_Wr != NULL)
4535 {
4536 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4537 1, &len, NULL);
4538 // if we are typing in, we want to keep things reactive
4539 delay = 1;
4540 if (len > 0)
4541 {
4542 ta_len -= len;
4543 mch_memmove(ta_buf, ta_buf + len, ta_len);
4544 }
4545 }
4546 }
4547 }
4548 }
4549
4550 if (ta_len)
4551 ui_inchar_undo(ta_buf, ta_len);
4552
4553 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4554 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004555 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004556 break;
4557 }
4558
4559 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004560 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004561
Bram Moolenaar0f873732019-12-05 20:28:46 +01004562 // We start waiting for a very short time and then increase it, so
4563 // that we respond quickly when the process is quick, and don't
4564 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004565 if (delay < 50)
4566 delay += 10;
4567 }
4568
Bram Moolenaar0f873732019-12-05 20:28:46 +01004569 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004570 CloseHandle(g_hChildStd_OUT_Rd);
4571 if (g_hChildStd_IN_Wr != NULL)
4572 CloseHandle(g_hChildStd_IN_Wr);
4573
4574 WaitForSingleObject(pi.hProcess, INFINITE);
4575
Bram Moolenaar0f873732019-12-05 20:28:46 +01004576 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004577 GetExitCodeProcess(pi.hProcess, &ret);
4578
4579 if (options & SHELL_READ)
4580 {
4581 if (ga.ga_len > 0)
4582 {
4583 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004584 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004585 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4586 }
4587 else
4588 curbuf->b_no_eol_lnum = 0;
4589 ga_clear(&ga);
4590 }
4591
Bram Moolenaar0f873732019-12-05 20:28:46 +01004592 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004593 CloseHandle(pi.hThread);
4594 CloseHandle(pi.hProcess);
4595
4596 return ret;
4597}
4598
4599 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004600mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004601{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004602 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004603 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004604 return mch_system_piped(cmd, options);
4605 else
4606 return mch_system_classic(cmd, options);
4607}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004608#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004609
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004610#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004611 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004612mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004613{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004614 int ret;
4615 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004616 char_u *buf;
4617 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004618
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004619 // If the command starts and ends with double quotes, enclose the command
4620 // in parentheses.
4621 len = STRLEN(cmd);
4622 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4623 {
4624 len += 3;
4625 buf = alloc(len);
4626 if (buf == NULL)
4627 return -1;
4628 vim_snprintf((char *)buf, len, "(%s)", cmd);
4629 wcmd = enc_to_utf16(buf, NULL);
4630 free(buf);
4631 }
4632 else
4633 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4634
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004635 if (wcmd == NULL)
4636 return -1;
4637
4638 ret = _wsystem(wcmd);
4639 vim_free(wcmd);
4640 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004641}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004642
4643#endif
4644
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004645 static int
4646mch_system(char *cmd, int options)
4647{
4648#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004649 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004650 return mch_system_g(cmd, options);
4651 else
4652 return mch_system_c(cmd, options);
4653#elif defined(FEAT_GUI_MSWIN)
4654 return mch_system_g(cmd, options);
4655#else
4656 return mch_system_c(cmd, options);
4657#endif
4658}
4659
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004660#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4661/*
4662 * Use a terminal window to run a shell command in.
4663 */
4664 static int
4665mch_call_shell_terminal(
4666 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004667 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004668{
4669 jobopt_T opt;
4670 char_u *newcmd = NULL;
4671 typval_T argvar[2];
4672 long_u cmdlen;
4673 int retval = -1;
4674 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004675 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004676 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004677 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004678
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004679 if (cmd == NULL)
4680 cmdlen = STRLEN(p_sh) + 1;
4681 else
4682 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004683 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004684 if (newcmd == NULL)
4685 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004686 if (cmd == NULL)
4687 {
4688 STRCPY(newcmd, p_sh);
4689 ch_log(NULL, "starting terminal to run a shell");
4690 }
4691 else
4692 {
4693 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4694 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4695 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004696
4697 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004698
4699 argvar[0].v_type = VAR_STRING;
4700 argvar[0].vval.v_string = newcmd;
4701 argvar[1].v_type = VAR_UNKNOWN;
4702 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004703 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004704 {
4705 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004706 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004707 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004708
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004709 job = term_getjob(buf->b_term);
4710 ++job->jv_refcount;
4711
Bram Moolenaar0f873732019-12-05 20:28:46 +01004712 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004713 aucmd_prepbuf(&aco, buf);
4714
4715 clear_oparg(&oa);
4716 while (term_use_loop())
4717 {
4718 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4719 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004720 // If terminal_loop() returns OK we got a key that is handled
4721 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004722 if (terminal_loop(TRUE) == OK)
4723 normal_cmd(&oa, TRUE);
4724 }
4725 else
4726 normal_cmd(&oa, TRUE);
4727 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004728 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004729 ch_log(NULL, "system command finished");
4730
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004731 job_unref(job);
4732
Bram Moolenaar0f873732019-12-05 20:28:46 +01004733 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004734 aucmd_restbuf(&aco);
4735
4736 wait_return(TRUE);
4737 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4738
4739 vim_free(newcmd);
4740 return retval;
4741}
4742#endif
4743
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744/*
4745 * Either execute a command by calling the shell or start a new shell
4746 */
4747 int
4748mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004749 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004750 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004751{
4752 int x = 0;
4753 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004754 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004755
Bram Moolenaar0f873732019-12-05 20:28:46 +01004756 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004757 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004758 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004759 if (cmd == NULL)
4760 wcscat(szShellTitle, L" :sh");
4761 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004762 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004763 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004764
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004765 if (wn != NULL)
4766 {
4767 wcscat(szShellTitle, L" - !");
4768 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004769 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004770 wcscat(szShellTitle, wn);
4771 SetConsoleTitleW(szShellTitle);
4772 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004773 }
4774 }
4775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776
4777 out_flush();
4778
4779#ifdef MCH_WRITE_DUMP
4780 if (fdDump)
4781 {
4782 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4783 fflush(fdDump);
4784 }
4785#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004786#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004787 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004788 if (
4789# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004790 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004791# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004792 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004793 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4794 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004795 char_u *cmdbase = cmd;
4796
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004797 if (cmdbase != NULL)
4798 // Skip a leading quote and (.
4799 while (*cmdbase == '"' || *cmdbase == '(')
4800 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004801
4802 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004803 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4804 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004805 {
4806 // Use a terminal window to run the command in.
4807 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004808 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004809 return x;
4810 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004811 }
4812#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813
4814 /*
4815 * Catch all deadly signals while running the external command, because a
4816 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4817 */
4818 signal(SIGINT, SIG_IGN);
4819#if defined(__GNUC__) && !defined(__MINGW32__)
4820 signal(SIGKILL, SIG_IGN);
4821#else
4822 signal(SIGBREAK, SIG_IGN);
4823#endif
4824 signal(SIGILL, SIG_IGN);
4825 signal(SIGFPE, SIG_IGN);
4826 signal(SIGSEGV, SIG_IGN);
4827 signal(SIGTERM, SIG_IGN);
4828 signal(SIGABRT, SIG_IGN);
4829
4830 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004831 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004832
4833 if (cmd == NULL)
4834 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004835 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836 }
4837 else
4838 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004839 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004840 char_u *newcmd = NULL;
4841 char_u *cmdbase = cmd;
4842 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004843
Bram Moolenaar0f873732019-12-05 20:28:46 +01004844 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004845 if (*cmdbase == '"' )
4846 ++cmdbase;
4847 if (*cmdbase == '(')
4848 ++cmdbase;
4849
Bram Moolenaar1c465442017-03-12 20:10:05 +01004850 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004851 {
4852 STARTUPINFO si;
4853 PROCESS_INFORMATION pi;
4854 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004855 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004856 char_u *p;
4857
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004858 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004859 si.cb = sizeof(si);
4860 si.lpReserved = NULL;
4861 si.lpDesktop = NULL;
4862 si.lpTitle = NULL;
4863 si.dwFlags = 0;
4864 si.cbReserved2 = 0;
4865 si.lpReserved2 = NULL;
4866
4867 cmdbase = skipwhite(cmdbase + 5);
4868 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004869 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004870 {
4871 cmdbase = skipwhite(cmdbase + 4);
4872 si.dwFlags = STARTF_USESHOWWINDOW;
4873 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004874 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004875 }
4876 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004877 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004878 {
4879 cmdbase = skipwhite(cmdbase + 2);
4880 flags = CREATE_NO_WINDOW;
4881 si.dwFlags = STARTF_USESTDHANDLES;
4882 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004883 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004884 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004885 NULL, // Security att.
4886 OPEN_EXISTING, // Open flags
4887 FILE_ATTRIBUTE_NORMAL, // File att.
4888 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004889 si.hStdOutput = si.hStdInput;
4890 si.hStdError = si.hStdInput;
4891 }
4892
Bram Moolenaar0f873732019-12-05 20:28:46 +01004893 // Remove a trailing ", ) and )" if they have a match
4894 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004895 if (cmdbase > cmd)
4896 {
4897 p = cmdbase + STRLEN(cmdbase);
4898 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4899 *--p = NUL;
4900 if (p > cmdbase && p[-1] == ')'
4901 && (*cmd =='(' || cmd[1] == '('))
4902 *--p = NUL;
4903 }
4904
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004905 newcmd = cmdbase;
4906 unescape_shellxquote(cmdbase, p_sxe);
4907
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004908 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004909 * If creating new console, arguments are passed to the
4910 * 'cmd.exe' as-is. If it's not, arguments are not treated
4911 * correctly for current 'cmd.exe'. So unescape characters in
4912 * shellxescape except '|' for avoiding to be treated as
4913 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004914 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004915 if (flags != CREATE_NEW_CONSOLE)
4916 {
4917 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004918 char_u *cmd_shell = mch_getenv("COMSPEC");
4919
4920 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004921 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004922
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004923 subcmd = vim_strsave_escaped_ext(cmdbase,
4924 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004925 if (subcmd != NULL)
4926 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004927 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004928 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004929 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004930 if (newcmd != NULL)
4931 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004932 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004933 else
4934 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004935 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004936 }
4937 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004938
4939 /*
4940 * Now, start the command as a process, so that it doesn't
4941 * inherit our handles which causes unpleasant dangling swap
4942 * files if we exit before the spawned process
4943 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004944 if (vim_create_process((char *)newcmd, FALSE, flags,
4945 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004946 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004947 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4948 > (HINSTANCE)32)
4949 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004950 else
4951 {
4952 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004953#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004954# ifdef VIMDLL
4955 if (gui.in_use)
4956# endif
4957 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004958#endif
4959 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004960
4961 if (newcmd != cmdbase)
4962 vim_free(newcmd);
4963
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004964 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004965 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004966 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004967 CloseHandle(si.hStdInput);
4968 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004969 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004970 CloseHandle(pi.hThread);
4971 CloseHandle(pi.hProcess);
4972 }
4973 else
4974 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004975 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004976#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004977 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004978 (!s_dont_use_vimrun && p_stmp ?
4979 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4980 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004981#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004982 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004983
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004984 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004985 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004987#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004988 if (
4989# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004990 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004991# endif
4992 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004994 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4995 "External commands will not pause after completion.\n"
4996 "See :help win32-vimrun for more information.");
4997 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004998 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4999 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005000
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005001 if (wmsg != NULL && wtitle != NULL)
5002 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5003 vim_free(wmsg);
5004 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005005 need_vimrun_warning = FALSE;
5006 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005007 if (
5008# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005009 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005010# endif
5011 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005012 // Use vimrun to execute the command. It opens a console
5013 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005014 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005015 vimrun_path,
5016 (msg_silent != 0 || (options & SHELL_DOOUT))
5017 ? "-s " : "",
5018 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005019 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005020# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005021 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005022# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005023 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005024 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005025 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5026 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005027 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005029 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005030 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005031 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005032 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005033 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005034 }
5035 }
5036
5037 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005038 {
5039 // The shell may have messed with the mode, always set it.
5040 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005041 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005042 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043
Bram Moolenaar0f873732019-12-05 20:28:46 +01005044 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005046#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005047 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005048 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005049#endif
5050 )
5051 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005052 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005053 msg_putchar('\n');
5054 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005055 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056
5057 signal(SIGINT, SIG_DFL);
5058#if defined(__GNUC__) && !defined(__MINGW32__)
5059 signal(SIGKILL, SIG_DFL);
5060#else
5061 signal(SIGBREAK, SIG_DFL);
5062#endif
5063 signal(SIGILL, SIG_DFL);
5064 signal(SIGFPE, SIG_DFL);
5065 signal(SIGSEGV, SIG_DFL);
5066 signal(SIGTERM, SIG_DFL);
5067 signal(SIGABRT, SIG_DFL);
5068
5069 return x;
5070}
5071
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005072#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005073 static HANDLE
5074job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005075 char_u *fname,
5076 DWORD dwDesiredAccess,
5077 DWORD dwShareMode,
5078 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5079 DWORD dwCreationDisposition,
5080 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005081{
5082 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005083 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005084
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005085 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005086 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005087 return INVALID_HANDLE_VALUE;
5088
5089 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5090 lpSecurityAttributes, dwCreationDisposition,
5091 dwFlagsAndAttributes, NULL);
5092 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005093 return h;
5094}
5095
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005096/*
5097 * Turn the dictionary "env" into a NUL separated list that can be used as the
5098 * environment argument of vim_create_process().
5099 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005100 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005101win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005102{
5103 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005104 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005105 LPVOID base = GetEnvironmentStringsW();
5106
Bram Moolenaar0f873732019-12-05 20:28:46 +01005107 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005108 if (ga_grow(gap, 1) == FAIL)
5109 return;
5110
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005111 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005112 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005113 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005114 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005115 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005116 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005117 typval_T *item = &dict_lookup(hi)->di_tv;
5118 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005119 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005120 --todo;
5121 if (wkey != NULL && wval != NULL)
5122 {
5123 size_t n;
5124 size_t lkey = wcslen(wkey);
5125 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005126
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005127 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5128 continue;
5129 for (n = 0; n < lkey; n++)
5130 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5131 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5132 for (n = 0; n < lval; n++)
5133 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5134 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5135 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005136 vim_free(wkey);
5137 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005138 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005139 }
5140 }
5141
Bram Moolenaar355757a2020-02-10 22:06:32 +01005142 if (base)
5143 {
5144 WCHAR *p = (WCHAR*) base;
5145
5146 // for last \0
5147 if (ga_grow(gap, 1) == FAIL)
5148 return;
5149
5150 while (*p != 0 || *(p + 1) != 0)
5151 {
5152 if (ga_grow(gap, 1) == OK)
5153 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5154 p++;
5155 }
5156 FreeEnvironmentStrings(base);
5157 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5158 }
5159
Bram Moolenaar493359e2018-06-12 20:25:52 +02005160# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005161 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005162# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005163 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005164 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005165# endif
5166# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005167 char_u *version = get_vim_var_str(VV_VERSION);
5168 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005169# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005170 // size of "VIM_SERVERNAME=" and value,
5171 // plus "VIM_TERMINAL=" and value,
5172 // plus two terminating NULs
5173 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005174# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005175 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005176# endif
5177# ifdef FEAT_TERMINAL
5178 + 13 + version_len + 2
5179# endif
5180 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005181
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005182 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005183 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005184# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005185 for (n = 0; n < 15; n++)
5186 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5187 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005188 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005189 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5190 (WCHAR)servername[n];
5191 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005192# endif
5193# ifdef FEAT_TERMINAL
5194 if (is_terminal)
5195 {
5196 for (n = 0; n < 13; n++)
5197 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5198 (WCHAR)"VIM_TERMINAL="[n];
5199 for (n = 0; n < version_len; n++)
5200 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5201 (WCHAR)version[n];
5202 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5203 }
5204# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005205 }
5206 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005207# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005208}
5209
Bram Moolenaarb091f302019-01-19 14:37:00 +01005210/*
5211 * Create a pair of pipes.
5212 * Return TRUE for success, FALSE for failure.
5213 */
5214 static BOOL
5215create_pipe_pair(HANDLE handles[2])
5216{
5217 static LONG s;
5218 char name[64];
5219 SECURITY_ATTRIBUTES sa;
5220
5221 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5222 GetCurrentProcessId(),
5223 InterlockedIncrement(&s));
5224
5225 // Create named pipe. Max size of named pipe is 65535.
5226 handles[1] = CreateNamedPipe(
5227 name,
5228 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5229 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005230 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005231
5232 if (handles[1] == INVALID_HANDLE_VALUE)
5233 return FALSE;
5234
5235 sa.nLength = sizeof(sa);
5236 sa.bInheritHandle = TRUE;
5237 sa.lpSecurityDescriptor = NULL;
5238
5239 handles[0] = CreateFile(name,
5240 FILE_GENERIC_READ,
5241 FILE_SHARE_READ, &sa,
5242 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5243
5244 if (handles[0] == INVALID_HANDLE_VALUE)
5245 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005246 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005247 return FALSE;
5248 }
5249
5250 return TRUE;
5251}
5252
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005253 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005254mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005255{
5256 STARTUPINFO si;
5257 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005258 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005259 SECURITY_ATTRIBUTES saAttr;
5260 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005261 HANDLE ifd[2];
5262 HANDLE ofd[2];
5263 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005264 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005265
5266 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5267 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5268 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5269 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5270 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5271 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5272 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5273
5274 if (use_out_for_err && use_null_for_out)
5275 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005276
5277 ifd[0] = INVALID_HANDLE_VALUE;
5278 ifd[1] = INVALID_HANDLE_VALUE;
5279 ofd[0] = INVALID_HANDLE_VALUE;
5280 ofd[1] = INVALID_HANDLE_VALUE;
5281 efd[0] = INVALID_HANDLE_VALUE;
5282 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005283 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005284
Bram Moolenaar14207f42016-10-27 21:13:10 +02005285 jo = CreateJobObject(NULL, NULL);
5286 if (jo == NULL)
5287 {
5288 job->jv_status = JOB_FAILED;
5289 goto failed;
5290 }
5291
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005292 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005293 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005294
Bram Moolenaar76467df2016-02-12 19:30:26 +01005295 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005296 ZeroMemory(&si, sizeof(si));
5297 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005298 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005299 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005300
Bram Moolenaard8070362016-02-15 21:56:54 +01005301 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5302 saAttr.bInheritHandle = TRUE;
5303 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005304
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005305 if (use_file_for_in)
5306 {
5307 char_u *fname = options->jo_io_name[PART_IN];
5308
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005309 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5310 FILE_SHARE_READ | FILE_SHARE_WRITE,
5311 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5312 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005313 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005314 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005315 goto failed;
5316 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005317 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005318 else if (!use_null_for_in
5319 && (!create_pipe_pair(ifd)
5320 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005321 goto failed;
5322
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005323 if (use_file_for_out)
5324 {
5325 char_u *fname = options->jo_io_name[PART_OUT];
5326
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005327 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5328 FILE_SHARE_READ | FILE_SHARE_WRITE,
5329 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5330 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005331 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005332 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005333 goto failed;
5334 }
5335 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005336 else if (!use_null_for_out &&
5337 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005338 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005339 goto failed;
5340
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005341 if (use_file_for_err)
5342 {
5343 char_u *fname = options->jo_io_name[PART_ERR];
5344
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005345 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5346 FILE_SHARE_READ | FILE_SHARE_WRITE,
5347 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5348 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005349 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005350 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005351 goto failed;
5352 }
5353 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005354 else if (!use_out_for_err && !use_null_for_err &&
5355 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005356 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005357 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005358
Bram Moolenaard8070362016-02-15 21:56:54 +01005359 si.dwFlags |= STARTF_USESTDHANDLES;
5360 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005361 si.hStdOutput = ofd[1];
5362 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5363
5364 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5365 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005366 if (options->jo_set & JO_CHANNEL)
5367 {
5368 channel = options->jo_channel;
5369 if (channel != NULL)
5370 ++channel->ch_refcount;
5371 }
5372 else
5373 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005374 if (channel == NULL)
5375 goto failed;
5376 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005377
5378 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005379 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005380 CREATE_DEFAULT_ERROR_MODE |
5381 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005382 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005383 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005384 &si, &pi,
5385 ga.ga_data,
5386 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005387 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005388 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005389 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005390 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005391 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005392
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005393 ga_clear(&ga);
5394
Bram Moolenaar14207f42016-10-27 21:13:10 +02005395 if (!AssignProcessToJobObject(jo, pi.hProcess))
5396 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005397 // if failing, switch the way to terminate
5398 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005399 CloseHandle(jo);
5400 jo = NULL;
5401 }
5402 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005403 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005404 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005405 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005406 job->jv_status = JOB_STARTED;
5407
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005408 CloseHandle(ifd[0]);
5409 CloseHandle(ofd[1]);
5410 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005411 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005412
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005413 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005414 if (channel != NULL)
5415 {
5416 channel_set_pipes(channel,
5417 use_file_for_in || use_null_for_in
5418 ? INVALID_FD : (sock_T)ifd[1],
5419 use_file_for_out || use_null_for_out
5420 ? INVALID_FD : (sock_T)ofd[0],
5421 use_out_for_err || use_file_for_err || use_null_for_err
5422 ? INVALID_FD : (sock_T)efd[0]);
5423 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005424 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005425 return;
5426
5427failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005428 CloseHandle(ifd[0]);
5429 CloseHandle(ofd[0]);
5430 CloseHandle(efd[0]);
5431 CloseHandle(ifd[1]);
5432 CloseHandle(ofd[1]);
5433 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005434 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005435 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005436}
5437
5438 char *
5439mch_job_status(job_T *job)
5440{
5441 DWORD dwExitCode = 0;
5442
Bram Moolenaar76467df2016-02-12 19:30:26 +01005443 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5444 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005445 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005446 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005447 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005448 {
5449 ch_log(job->jv_channel, "Job ended");
5450 job->jv_status = JOB_ENDED;
5451 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005452 return "dead";
5453 }
5454 return "run";
5455}
5456
Bram Moolenaar97792de2016-10-15 18:36:49 +02005457 job_T *
5458mch_detect_ended_job(job_T *job_list)
5459{
5460 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5461 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5462 job_T *job = job_list;
5463
5464 while (job != NULL)
5465 {
5466 DWORD n;
5467 DWORD result;
5468
5469 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5470 && job != NULL; job = job->jv_next)
5471 {
5472 if (job->jv_status == JOB_STARTED)
5473 {
5474 jobHandles[n] = job->jv_proc_info.hProcess;
5475 jobArray[n] = job;
5476 ++n;
5477 }
5478 }
5479 if (n == 0)
5480 continue;
5481 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5482 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5483 {
5484 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5485
5486 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5487 return wait_job;
5488 }
5489 }
5490 return NULL;
5491}
5492
Bram Moolenaarfb630902016-10-29 14:55:00 +02005493 static BOOL
5494terminate_all(HANDLE process, int code)
5495{
5496 PROCESSENTRY32 pe;
5497 HANDLE h = INVALID_HANDLE_VALUE;
5498 DWORD pid = GetProcessId(process);
5499
5500 if (pid != 0)
5501 {
5502 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5503 if (h != INVALID_HANDLE_VALUE)
5504 {
5505 pe.dwSize = sizeof(PROCESSENTRY32);
5506 if (!Process32First(h, &pe))
5507 goto theend;
5508
5509 do
5510 {
5511 if (pe.th32ParentProcessID == pid)
5512 {
5513 HANDLE ph = OpenProcess(
5514 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5515 if (ph != NULL)
5516 {
5517 terminate_all(ph, code);
5518 CloseHandle(ph);
5519 }
5520 }
5521 } while (Process32Next(h, &pe));
5522
5523 CloseHandle(h);
5524 }
5525 }
5526
5527theend:
5528 return TerminateProcess(process, code);
5529}
5530
5531/*
5532 * Send a (deadly) signal to "job".
5533 * Return FAIL if it didn't work.
5534 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005535 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005536mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005537{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005538 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005539
Bram Moolenaar923d9262016-02-25 20:56:01 +01005540 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005541 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005542 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005543 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005544 {
5545 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5546 job->jv_channel->ch_killing = TRUE;
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005547 return TerminateJobObject(job->jv_job_object, -1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005548 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005549 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005550 }
5551
5552 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5553 return FAIL;
5554 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005555 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5556 job->jv_proc_info.dwProcessId)
5557 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005558 FreeConsole();
5559 return ret;
5560}
5561
5562/*
5563 * Clear the data related to "job".
5564 */
5565 void
5566mch_clear_job(job_T *job)
5567{
5568 if (job->jv_status != JOB_FAILED)
5569 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005570 if (job->jv_job_object != NULL)
5571 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005572 CloseHandle(job->jv_proc_info.hProcess);
5573 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005574}
5575#endif
5576
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005578#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005579
5580/*
5581 * Start termcap mode
5582 */
5583 static void
5584termcap_mode_start(void)
5585{
5586 DWORD cmodein;
5587
5588 if (g_fTermcapMode)
5589 return;
5590
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005591 if (!p_rs && USE_VTP)
5592 vtp_printf("\033[?1049h");
5593
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594 SaveConsoleBuffer(&g_cbNonTermcap);
5595
5596 if (g_cbTermcap.IsValid)
5597 {
5598 /*
5599 * We've been in termcap mode before. Restore certain screen
5600 * characteristics, including the buffer size and the window
5601 * size. Since we will be redrawing the screen, we don't need
5602 * to restore the actual contents of the buffer.
5603 */
5604 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005605 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005606 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5607 Rows = g_cbTermcap.Info.dwSize.Y;
5608 Columns = g_cbTermcap.Info.dwSize.X;
5609 }
5610 else
5611 {
5612 /*
5613 * This is our first time entering termcap mode. Clear the console
5614 * screen buffer, and resize the buffer to match the current window
5615 * size. We will use this as the size of our editing environment.
5616 */
5617 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005618 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5620 }
5621
Bram Moolenaar071d4272004-06-13 20:20:40 +00005622 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623
5624 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005625 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005626 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005628 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005630 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005631 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005633 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5634 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005636 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005637
5638 redraw_later_clear();
5639 g_fTermcapMode = TRUE;
5640}
5641
5642
5643/*
5644 * End termcap mode
5645 */
5646 static void
5647termcap_mode_end(void)
5648{
5649 DWORD cmodein;
5650 ConsoleBuffer *cb;
5651 COORD coord;
5652 DWORD dwDummy;
5653
5654 if (!g_fTermcapMode)
5655 return;
5656
5657 SaveConsoleBuffer(&g_cbTermcap);
5658
5659 GetConsoleMode(g_hConIn, &cmodein);
5660 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005661 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5662 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005664# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005665 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005666# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005668# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005669 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005670 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 SetConsoleCursorInfo(g_hConOut, &g_cci);
5672
5673 if (p_rs || exiting)
5674 {
5675 /*
5676 * Clear anything that happens to be on the current line.
5677 */
5678 coord.X = 0;
5679 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5680 FillConsoleOutputCharacter(g_hConOut, ' ',
5681 cb->Info.dwSize.X, coord, &dwDummy);
5682 /*
5683 * The following is just for aesthetics. If we are exiting without
5684 * restoring the screen, then we want to have a prompt string
5685 * appear at the bottom line. However, the command interpreter
5686 * seems to always advance the cursor one line before displaying
5687 * the prompt string, which causes the screen to scroll. To
5688 * counter this, move the cursor up one line before exiting.
5689 */
5690 if (exiting && !p_rs)
5691 coord.Y--;
5692 /*
5693 * Position the cursor at the leftmost column of the desired row.
5694 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005695 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 }
5697
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005698 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005699 vtp_printf("\033[?1049l");
5700
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701 g_fTermcapMode = FALSE;
5702}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005703#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704
5705
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005706#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 void
5708mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005709 char_u *s UNUSED,
5710 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005712 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005713}
5714
5715#else
5716
5717/*
5718 * clear `n' chars, starting from `coord'
5719 */
5720 static void
5721clear_chars(
5722 COORD coord,
5723 DWORD n)
5724{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005725 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005726 {
5727 DWORD dwDummy;
5728
5729 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5730 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5731 &dwDummy);
5732 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005733 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005734 {
5735 set_console_color_rgb();
5736 gotoxy(coord.X + 1, coord.Y + 1);
5737 vtp_printf("\033[%dX", n);
5738 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005739}
5740
5741
5742/*
5743 * Clear the screen
5744 */
5745 static void
5746clear_screen(void)
5747{
5748 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005749
5750 if (!USE_VTP)
5751 clear_chars(g_coord, Rows * Columns);
5752 else
5753 {
5754 set_console_color_rgb();
5755 gotoxy(1, 1);
5756 vtp_printf("\033[2J");
5757 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758}
5759
5760
5761/*
5762 * Clear to end of display
5763 */
5764 static void
5765clear_to_end_of_display(void)
5766{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005767 COORD save = g_coord;
5768
5769 if (!USE_VTP)
5770 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005772 else
5773 {
5774 set_console_color_rgb();
5775 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5776 vtp_printf("\033[0J");
5777
5778 gotoxy(save.X + 1, save.Y + 1);
5779 g_coord = save;
5780 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005781}
5782
5783
5784/*
5785 * Clear to end of line
5786 */
5787 static void
5788clear_to_end_of_line(void)
5789{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005790 COORD save = g_coord;
5791
5792 if (!USE_VTP)
5793 clear_chars(g_coord, Columns - g_coord.X);
5794 else
5795 {
5796 set_console_color_rgb();
5797 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5798 vtp_printf("\033[0K");
5799
5800 gotoxy(save.X + 1, save.Y + 1);
5801 g_coord = save;
5802 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803}
5804
5805
5806/*
5807 * Scroll the scroll region up by `cLines' lines
5808 */
5809 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005810scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811{
5812 COORD oldcoord = g_coord;
5813
5814 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5815 delete_lines(cLines);
5816
5817 g_coord = oldcoord;
5818}
5819
5820
5821/*
5822 * Set the scroll region
5823 */
5824 static void
5825set_scroll_region(
5826 unsigned left,
5827 unsigned top,
5828 unsigned right,
5829 unsigned bottom)
5830{
5831 if (left >= right
5832 || top >= bottom
5833 || right > (unsigned) Columns - 1
5834 || bottom > (unsigned) Rows - 1)
5835 return;
5836
5837 g_srScrollRegion.Left = left;
5838 g_srScrollRegion.Top = top;
5839 g_srScrollRegion.Right = right;
5840 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005841}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005842
Bram Moolenaar6982f422019-02-16 16:48:01 +01005843 static void
5844set_scroll_region_tb(
5845 unsigned top,
5846 unsigned bottom)
5847{
5848 if (top >= bottom || bottom > (unsigned)Rows - 1)
5849 return;
5850
5851 g_srScrollRegion.Top = top;
5852 g_srScrollRegion.Bottom = bottom;
5853}
5854
5855 static void
5856set_scroll_region_lr(
5857 unsigned left,
5858 unsigned right)
5859{
5860 if (left >= right || right > (unsigned)Columns - 1)
5861 return;
5862
5863 g_srScrollRegion.Left = left;
5864 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005865}
5866
5867
5868/*
5869 * Insert `cLines' lines at the current cursor position
5870 */
5871 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005872insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005874 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875 COORD dest;
5876 CHAR_INFO fill;
5877
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005878 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5879
Bram Moolenaar6982f422019-02-16 16:48:01 +01005880 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881 dest.Y = g_coord.Y + cLines;
5882
Bram Moolenaar6982f422019-02-16 16:48:01 +01005883 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884 source.Top = g_coord.Y;
5885 source.Right = g_srScrollRegion.Right;
5886 source.Bottom = g_srScrollRegion.Bottom - cLines;
5887
Bram Moolenaar6982f422019-02-16 16:48:01 +01005888 clip.Left = g_srScrollRegion.Left;
5889 clip.Top = g_coord.Y;
5890 clip.Right = g_srScrollRegion.Right;
5891 clip.Bottom = g_srScrollRegion.Bottom;
5892
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005893 fill.Char.AsciiChar = ' ';
5894 if (!USE_VTP)
5895 fill.Attributes = g_attrCurrent;
5896 else
5897 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005899 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005900
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005901 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5902
Bram Moolenaar6982f422019-02-16 16:48:01 +01005903 // Here we have to deal with a win32 console flake: If the scroll
5904 // region looks like abc and we scroll c to a and fill with d we get
5905 // cbd... if we scroll block c one line at a time to a, we get cdd...
5906 // vim expects cdd consistently... So we have to deal with that
5907 // here... (this also occurs scrolling the same way in the other
5908 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909
5910 if (source.Bottom < dest.Y)
5911 {
5912 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005913 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914
Bram Moolenaar6982f422019-02-16 16:48:01 +01005915 coord.X = source.Left;
5916 for (i = clip.Top; i < dest.Y; ++i)
5917 {
5918 coord.Y = i;
5919 clear_chars(coord, source.Right - source.Left + 1);
5920 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005922
5923 if (USE_WT)
5924 {
5925 COORD coord;
5926 int i;
5927
5928 coord.X = source.Left;
5929 for (i = source.Top; i < dest.Y; ++i)
5930 {
5931 coord.Y = i;
5932 clear_chars(coord, source.Right - source.Left + 1);
5933 }
5934 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935}
5936
5937
5938/*
5939 * Delete `cLines' lines at the current cursor position
5940 */
5941 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005942delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005944 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945 COORD dest;
5946 CHAR_INFO fill;
5947 int nb;
5948
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005949 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5950
Bram Moolenaar6982f422019-02-16 16:48:01 +01005951 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952 dest.Y = g_coord.Y;
5953
Bram Moolenaar6982f422019-02-16 16:48:01 +01005954 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955 source.Top = g_coord.Y + cLines;
5956 source.Right = g_srScrollRegion.Right;
5957 source.Bottom = g_srScrollRegion.Bottom;
5958
Bram Moolenaar6982f422019-02-16 16:48:01 +01005959 clip.Left = g_srScrollRegion.Left;
5960 clip.Top = g_coord.Y;
5961 clip.Right = g_srScrollRegion.Right;
5962 clip.Bottom = g_srScrollRegion.Bottom;
5963
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005964 fill.Char.AsciiChar = ' ';
5965 if (!USE_VTP)
5966 fill.Attributes = g_attrCurrent;
5967 else
5968 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005970 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005971
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005972 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5973
Bram Moolenaar6982f422019-02-16 16:48:01 +01005974 // Here we have to deal with a win32 console flake; See insert_lines()
5975 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005976
5977 nb = dest.Y + (source.Bottom - source.Top) + 1;
5978
5979 if (nb < source.Top)
5980 {
5981 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005982 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005983
Bram Moolenaar6982f422019-02-16 16:48:01 +01005984 coord.X = source.Left;
5985 for (i = nb; i < clip.Bottom; ++i)
5986 {
5987 coord.Y = i;
5988 clear_chars(coord, source.Right - source.Left + 1);
5989 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005990 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005991
5992 if (USE_WT)
5993 {
5994 COORD coord;
5995 int i;
5996
5997 coord.X = source.Left;
5998 for (i = nb; i <= source.Bottom; ++i)
5999 {
6000 coord.Y = i;
6001 clear_chars(coord, source.Right - source.Left + 1);
6002 }
6003 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004}
6005
6006
6007/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006008 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009 */
6010 static void
6011gotoxy(
6012 unsigned x,
6013 unsigned y)
6014{
6015 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6016 return;
6017
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006018 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006019 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006020 // There are reports of double-width characters not displayed
6021 // correctly. This workaround should fix it, similar to how it's done
6022 // for VTP.
6023 g_coord.X = 0;
6024 SetConsoleCursorPosition(g_hConOut, g_coord);
6025
Bram Moolenaar2313b612019-09-27 14:14:32 +02006026 // external cursor coords are 1-based; internal are 0-based
6027 g_coord.X = x - 1;
6028 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006029 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006030 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006031 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006032 {
6033 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006034 // destruction. Insider build bug. Always enabled because it's cheap
6035 // and avoids mistakes with recognizing the build.
6036 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006037
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006038 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006039
6040 g_coord.X = x - 1;
6041 g_coord.Y = y - 1;
6042 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043}
6044
6045
6046/*
6047 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006048 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049 */
6050 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006051textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006053 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054
6055 SetConsoleTextAttribute(g_hConOut, wAttr);
6056}
6057
6058
6059 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006060textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006061{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006062 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006063
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006064 if (!USE_VTP)
6065 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6066 else
6067 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068}
6069
6070
6071 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006072textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006073{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006074 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006076 if (!USE_VTP)
6077 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6078 else
6079 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080}
6081
6082
6083/*
6084 * restore the default text attribute (whatever we started with)
6085 */
6086 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006087normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006088{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006089 if (!USE_VTP)
6090 textattr(g_attrDefault);
6091 else
6092 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006093}
6094
6095
6096static WORD g_attrPreStandout = 0;
6097
6098/*
6099 * Make the text standout, by brightening it
6100 */
6101 static void
6102standout(void)
6103{
6104 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006105
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6107}
6108
6109
6110/*
6111 * Turn off standout mode
6112 */
6113 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006114standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115{
6116 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006118
6119 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006120}
6121
6122
6123/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006124 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125 */
6126 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006127mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128{
6129 char_u *p;
6130 int n;
6131
6132 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6133 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006134 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006135# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006136 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006137# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006138 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139 {
6140 p = T_ME + 2;
6141 n = getdigits(&p);
6142 if (*p == 'm' && n > 0)
6143 {
6144 cterm_normal_fg_color = (n & 0xf) + 1;
6145 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6146 }
6147 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006148# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006149 cterm_normal_fg_gui_color = INVALCOLOR;
6150 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006151# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152}
6153
6154
6155/*
6156 * visual bell: flash the screen
6157 */
6158 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006159visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006160{
6161 COORD coordOrigin = {0, 0};
6162 WORD attrFlash = ~g_attrCurrent & 0xff;
6163
6164 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006165 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166
6167 if (oldattrs == NULL)
6168 return;
6169 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6170 coordOrigin, &dwDummy);
6171 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6172 coordOrigin, &dwDummy);
6173
Bram Moolenaar0f873732019-12-05 20:28:46 +01006174 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006175 if (!USE_VTP)
6176 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177 coordOrigin, &dwDummy);
6178 vim_free(oldattrs);
6179}
6180
6181
6182/*
6183 * Make the cursor visible or invisible
6184 */
6185 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006186cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187{
6188 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006189
6190 if (USE_VTP)
6191 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6192
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006193# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006194 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006195# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196}
6197
6198
6199/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006200 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006201 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006202 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006203 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006205 char_u *pchBuf,
6206 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006207{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006208 COORD coord = g_coord;
6209 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006210 DWORD n, cchwritten;
6211 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006212 static WCHAR *unicodebuf = NULL;
6213 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006214 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006215 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006216 static WCHAR *utf8spbuf = NULL;
6217 static int utf8splength;
6218 static DWORD utf8spcells;
6219 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006221 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006222 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006223 utf8usingbuf = &unicodebuf;
6224 do
6225 {
6226 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6227 unicodebuf, unibuflen);
6228 if (length && length <= unibuflen)
6229 break;
6230 vim_free(unicodebuf);
6231 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6232 unibuflen = unibuflen ? 0 : length;
6233 } while(1);
6234 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006235 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006236 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6237 {
6238 if (utf8usingbuf != &utf8spbuf)
6239 {
6240 if (utf8spbuf == NULL)
6241 {
6242 cells = mb_string2cells((char_u *)" ", 1);
6243 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6244 utf8spbuf = LALLOC_MULT(WCHAR, length);
6245 if (utf8spbuf != NULL)
6246 {
6247 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6248 utf8usingbuf = &utf8spbuf;
6249 utf8splength = length;
6250 utf8spcells = cells;
6251 }
6252 }
6253 else
6254 {
6255 utf8usingbuf = &utf8spbuf;
6256 length = utf8splength;
6257 cells = utf8spcells;
6258 }
6259 }
6260 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006261
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006262 if (!USE_VTP)
6263 {
6264 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6265 coord, &written);
6266 // When writing fails or didn't write a single character, pretend one
6267 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006268 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006269 coord, &cchwritten) == 0
6270 || cchwritten == 0 || cchwritten == (DWORD)-1)
6271 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006272 }
6273 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006274 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006275 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006276 NULL) == 0 || cchwritten == 0)
6277 cchwritten = 1;
6278 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006279
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006280 if (cchwritten == length)
6281 {
6282 written = cbToWrite;
6283 g_coord.X += (SHORT)cells;
6284 }
6285 else
6286 {
6287 char_u *p = pchBuf;
6288 for (n = 0; n < cchwritten; n++)
6289 MB_CPTR_ADV(p);
6290 written = p - pchBuf;
6291 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006292 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293
6294 while (g_coord.X > g_srScrollRegion.Right)
6295 {
6296 g_coord.X -= (SHORT) Columns;
6297 if (g_coord.Y < g_srScrollRegion.Bottom)
6298 g_coord.Y++;
6299 }
6300
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006301 // Cursor under VTP is always in the correct position, no need to reset.
6302 if (!USE_VTP)
6303 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304
6305 return written;
6306}
6307
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006308 static char_u *
6309get_seq(
6310 int *args,
6311 int *count,
6312 char_u *head)
6313{
6314 int argc;
6315 char_u *p;
6316
6317 if (head == NULL || *head != '\033')
6318 return NULL;
6319
6320 argc = 0;
6321 p = head;
6322 ++p;
6323 do
6324 {
6325 ++p;
6326 args[argc] = getdigits(&p);
6327 argc += (argc < 15) ? 1 : 0;
6328 } while (*p == ';');
6329 *count = argc;
6330
6331 return p;
6332}
6333
6334 static char_u *
6335get_sgr(
6336 int *args,
6337 int *count,
6338 char_u *head)
6339{
6340 char_u *p = get_seq(args, count, head);
6341
6342 return (p && *p == 'm') ? ++p : NULL;
6343}
6344
6345/*
6346 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6347 */
6348 static char_u *
6349sgrn2(
6350 char_u *head,
6351 int n)
6352{
6353 int argc;
6354 int args[16];
6355 char_u *p = get_sgr(args, &argc, head);
6356
6357 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6358}
6359
6360/*
6361 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6362 */
6363 static char_u *
6364sgrnc(
6365 char_u *head,
6366 int n)
6367{
6368 int argc;
6369 int args[16];
6370 char_u *p = get_sgr(args, &argc, head);
6371
6372 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6373 ? p : NULL;
6374}
6375
6376 static char_u *
6377skipblank(char_u *q)
6378{
6379 char_u *p = q;
6380
6381 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6382 ++p;
6383 return p;
6384}
6385
6386/*
6387 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6388 * NULL.
6389 */
6390 static char_u *
6391sgrn2c(
6392 char_u *head,
6393 int n)
6394{
6395 char_u *p = sgrn2(head, n);
6396
6397 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6398}
6399
6400/*
6401 * If there is only a newline between the sequence immediately following it,
6402 * a pointer to the character following the newline is returned.
6403 * Otherwise NULL.
6404 */
6405 static char_u *
6406sgrn2cn(
6407 char_u *head,
6408 int n)
6409{
6410 char_u *p = sgrn2(head, n);
6411
6412 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6413}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006414
6415/*
6416 * mch_write(): write the output buffer to the screen, translating ESC
6417 * sequences into calls to console output routines.
6418 */
6419 void
6420mch_write(
6421 char_u *s,
6422 int len)
6423{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006424 char_u *end = s + len;
6425
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006426# ifdef VIMDLL
6427 if (gui.in_use)
6428 return;
6429# endif
6430
Bram Moolenaar071d4272004-06-13 20:20:40 +00006431 if (!term_console)
6432 {
6433 write(1, s, (unsigned)len);
6434 return;
6435 }
6436
Bram Moolenaar0f873732019-12-05 20:28:46 +01006437 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006438 while (len--)
6439 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006440 int prefix = -1;
6441 char_u ch;
6442
6443 // While processing a sequence, on rare occasions it seems that another
6444 // sequence may be inserted asynchronously.
6445 if (len < 0)
6446 {
6447 redraw_all_later(CLEAR);
6448 return;
6449 }
6450
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006451 while (s + ++prefix < end)
6452 {
6453 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006454 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6455 && ch != '\a' && ch != '\033'))
6456 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006457 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458
6459 if (p_wd)
6460 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006461 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462 if (prefix != 0)
6463 prefix = 1;
6464 }
6465
6466 if (prefix != 0)
6467 {
6468 DWORD nWritten;
6469
6470 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006471# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472 if (fdDump)
6473 {
6474 fputc('>', fdDump);
6475 fwrite(s, sizeof(char_u), nWritten, fdDump);
6476 fputs("<\n", fdDump);
6477 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006478# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479 len -= (nWritten - 1);
6480 s += nWritten;
6481 }
6482 else if (s[0] == '\n')
6483 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006484 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 if (g_coord.Y == g_srScrollRegion.Bottom)
6486 {
6487 scroll(1);
6488 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6489 }
6490 else
6491 {
6492 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6493 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006494# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006495 if (fdDump)
6496 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006497# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 s++;
6499 }
6500 else if (s[0] == '\r')
6501 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006502 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006504# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006505 if (fdDump)
6506 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006507# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508 s++;
6509 }
6510 else if (s[0] == '\b')
6511 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006512 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 if (g_coord.X > g_srScrollRegion.Left)
6514 g_coord.X--;
6515 else if (g_coord.Y > g_srScrollRegion.Top)
6516 {
6517 g_coord.X = g_srScrollRegion.Right;
6518 g_coord.Y--;
6519 }
6520 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006521# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 if (fdDump)
6523 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006524# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525 s++;
6526 }
6527 else if (s[0] == '\a')
6528 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006529 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006531# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 if (fdDump)
6533 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006534# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 s++;
6536 }
6537 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6538 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006539# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006540 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006541# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006542 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006543 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006544 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545
6546 switch (s[2])
6547 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 case '0': case '1': case '2': case '3': case '4':
6549 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006550 if (*(p = get_seq(args, &argc, s)) != 'm')
6551 goto notsgr;
6552
6553 p = s;
6554
6555 // Handling frequent optional sequences. Output to the screen
6556 // takes too long, so do not output as much as possible.
6557
6558 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6559 // resetFG,FG,BG are omitted.
6560 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006561 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006562 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6563 len = len + 1 - (int)(p - s);
6564 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006566 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006568 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6569 // omitted.
6570 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6571 p = sp;
6572
6573 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6574 // omitted.
6575 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6576 p = sp;
6577
6578 // If BG,BG of SGR are connected, the first BG can be omitted.
6579 if (sgrn2((sp = sgrn2(p, 48)), 48))
6580 p = sp;
6581
6582 // If restoreFG and FG are connected, the restoreFG can be
6583 // omitted.
6584 if (sgrn2((sp = sgrnc(p, 39)), 38))
6585 p = sp;
6586
6587 p = get_seq(args, &argc, p);
6588
6589notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006590 arg1 = args[0];
6591 arg2 = args[1];
6592 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006594 if (argc == 1 && args[0] == 0)
6595 normvideo();
6596 else if (argc == 1)
6597 {
6598 if (USE_VTP)
6599 textcolor((WORD) arg1);
6600 else
6601 textattr((WORD) arg1);
6602 }
6603 else if (USE_VTP)
6604 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006606 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006608 gotoxy(arg2, arg1);
6609 }
6610 else if (argc == 2 && *p == 'r')
6611 {
6612 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6613 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006614 else if (argc == 2 && *p == 'R')
6615 {
6616 set_scroll_region_tb(arg1, arg2);
6617 }
6618 else if (argc == 2 && *p == 'V')
6619 {
6620 set_scroll_region_lr(arg1, arg2);
6621 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006622 else if (argc == 1 && *p == 'A')
6623 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624 gotoxy(g_coord.X + 1,
6625 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6626 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006627 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006628 {
6629 textbackground((WORD) arg1);
6630 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006631 else if (argc == 1 && *p == 'C')
6632 {
6633 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6634 g_coord.Y + 1);
6635 }
6636 else if (argc == 1 && *p == 'f')
6637 {
6638 textcolor((WORD) arg1);
6639 }
6640 else if (argc == 1 && *p == 'H')
6641 {
6642 gotoxy(1, arg1);
6643 }
6644 else if (argc == 1 && *p == 'L')
6645 {
6646 insert_lines(arg1);
6647 }
6648 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 {
6650 delete_lines(arg1);
6651 }
6652
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006653 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654 s = p + 1;
6655 break;
6656
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658 gotoxy(g_coord.X + 1,
6659 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6660 goto got3;
6661
6662 case 'B':
6663 visual_bell();
6664 goto got3;
6665
6666 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6668 g_coord.Y + 1);
6669 goto got3;
6670
6671 case 'E':
6672 termcap_mode_end();
6673 goto got3;
6674
6675 case 'F':
6676 standout();
6677 goto got3;
6678
6679 case 'f':
6680 standend();
6681 goto got3;
6682
6683 case 'H':
6684 gotoxy(1, 1);
6685 goto got3;
6686
6687 case 'j':
6688 clear_to_end_of_display();
6689 goto got3;
6690
6691 case 'J':
6692 clear_screen();
6693 goto got3;
6694
6695 case 'K':
6696 clear_to_end_of_line();
6697 goto got3;
6698
6699 case 'L':
6700 insert_lines(1);
6701 goto got3;
6702
6703 case 'M':
6704 delete_lines(1);
6705 goto got3;
6706
6707 case 'S':
6708 termcap_mode_start();
6709 goto got3;
6710
6711 case 'V':
6712 cursor_visible(TRUE);
6713 goto got3;
6714
6715 case 'v':
6716 cursor_visible(FALSE);
6717 goto got3;
6718
6719 got3:
6720 s += 3;
6721 len -= 2;
6722 }
6723
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006724# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 if (fdDump)
6726 {
6727 fputs("ESC | ", fdDump);
6728 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6729 fputc('\n', fdDump);
6730 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006731# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732 }
6733 else
6734 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006735 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736 DWORD nWritten;
6737
6738 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006739# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740 if (fdDump)
6741 {
6742 fputc('>', fdDump);
6743 fwrite(s, sizeof(char_u), nWritten, fdDump);
6744 fputs("<\n", fdDump);
6745 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006746# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747
6748 len -= (nWritten - 1);
6749 s += nWritten;
6750 }
6751 }
6752
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006753# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754 if (fdDump)
6755 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006756# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757}
6758
Bram Moolenaar0f873732019-12-05 20:28:46 +01006759#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760
6761
6762/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006763 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764 */
6765 void
6766mch_delay(
6767 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006768 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006770#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006771 Sleep((int)msec); // never wait for input
6772#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006773# ifdef VIMDLL
6774 if (gui.in_use)
6775 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006776 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006777 return;
6778 }
6779# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006780 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006781# ifdef FEAT_MZSCHEME
6782 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6783 {
6784 int towait = p_mzq;
6785
Bram Moolenaar0f873732019-12-05 20:28:46 +01006786 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006787 while (msec > 0)
6788 {
6789 mzvim_check_threads();
6790 if (msec < towait)
6791 towait = msec;
6792 Sleep(towait);
6793 msec -= towait;
6794 }
6795 }
6796 else
6797# endif
6798 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006800 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801#endif
6802}
6803
6804
6805/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006806 * This version of remove is not scared by a readonly (backup) file.
6807 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808 * Return 0 for success, -1 for failure.
6809 */
6810 int
6811mch_remove(char_u *name)
6812{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006813 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006814 int n;
6815
Bram Moolenaar203258c2016-01-17 22:15:16 +01006816 /*
6817 * On Windows, deleting a directory's symbolic link is done by
6818 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6819 */
6820 if (mch_isdir(name) && mch_is_symbolic_link(name))
6821 return mch_rmdir(name);
6822
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006823 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6824
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006825 wn = enc_to_utf16(name, NULL);
6826 if (wn == NULL)
6827 return -1;
6828
6829 n = DeleteFileW(wn) ? 0 : -1;
6830 vim_free(wn);
6831 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006832}
6833
6834
6835/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006836 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837 */
6838 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006839mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006841#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6842# ifdef VIMDLL
6843 if (!gui.in_use)
6844# endif
6845 if (g_fCtrlCPressed || g_fCBrkPressed)
6846 {
6847 ctrl_break_was_pressed = g_fCBrkPressed;
6848 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6849 got_int = TRUE;
6850 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851#endif
6852}
6853
Bram Moolenaar0f873732019-12-05 20:28:46 +01006854// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006855#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006856
6857/*
6858 * How much main memory in KiB that can be used by VIM.
6859 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006860 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006861mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006862{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006863 MEMORYSTATUSEX ms;
6864
Bram Moolenaar0f873732019-12-05 20:28:46 +01006865 // Need to use GlobalMemoryStatusEx() when there is more memory than
6866 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006867 ms.dwLength = sizeof(MEMORYSTATUSEX);
6868 GlobalMemoryStatusEx(&ms);
6869 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006870 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006871 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006872 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006873 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006874 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006875 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006876 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006877 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006878 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006879 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006880 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006881}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882
Bram Moolenaar071d4272004-06-13 20:20:40 +00006883/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006884 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6886 * file whose short file name is "FOO.BAR" (its long file name will
6887 * be correct: "foo.bar~"). Because a file can be accessed by
6888 * either its SFN or its LFN, "foo.bar" has effectively been
6889 * renamed to "foo.bar", which is not at all what was wanted. This
6890 * seems to happen only when renaming files with three-character
6891 * extensions by appending a suffix that does not include ".".
6892 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6893 *
6894 * There is another problem, which isn't really a bug but isn't right either:
6895 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6896 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6897 * service pack 6. Doesn't seem to happen on Windows 98.
6898 *
6899 * Like rename(), returns 0 upon success, non-zero upon failure.
6900 * Should probably set errno appropriately when errors occur.
6901 */
6902 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006903mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006905 WCHAR *p;
6906 int i;
6907 WCHAR szTempFile[_MAX_PATH + 1];
6908 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006911 // No need to play tricks unless the file name contains a "~" as the
6912 // seventh character.
6913 p = wold;
6914 for (i = 0; wold[i] != NUL; ++i)
6915 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6916 && wold[i + 1] != 0)
6917 p = wold + i + 1;
6918 if ((int)(wold + i - p) < 8 || p[6] != '~')
6919 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006921 // Get base path of new file name. Undocumented feature: If pszNewFile is
6922 // a directory, no error is returned and pszFilePart will be NULL.
6923 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006925 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006927 // Get (and create) a unique temporary file name in directory of new file
6928 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929 return -2;
6930
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006931 // blow the temp file away
6932 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933 return -3;
6934
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006935 // rename old file to the temp file
6936 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937 return -4;
6938
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006939 // now create an empty file called pszOldFile; this prevents the operating
6940 // system using pszOldFile as an alias (SFN) if we're renaming within the
6941 // same directory. For example, we're editing a file called
6942 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6943 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6944 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6945 // cause all sorts of problems later in buf_write(). So, we create an
6946 // empty file called filena~1.txt and the system will have to find some
6947 // other SFN for filena~1.txt~, such as filena~2.txt
6948 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6950 return -5;
6951 if (!CloseHandle(hf))
6952 return -6;
6953
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006954 // rename the temp file to the new file
6955 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006957 // Renaming failed. Rename the file back to its old name, so that it
6958 // looks like nothing happened.
6959 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006960 return -7;
6961 }
6962
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006963 // Seems to be left around on Novell filesystems
6964 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006965
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006966 // finally, remove the empty old file
6967 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968 return -8;
6969
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006970 return 0;
6971}
6972
6973
6974/*
6975 * Converts the filenames to UTF-16, then call mch_wrename().
6976 * Like rename(), returns 0 upon success, non-zero upon failure.
6977 */
6978 int
6979mch_rename(
6980 const char *pszOldFile,
6981 const char *pszNewFile)
6982{
6983 WCHAR *wold = NULL;
6984 WCHAR *wnew = NULL;
6985 int retval = -1;
6986
6987 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6988 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6989 if (wold != NULL && wnew != NULL)
6990 retval = mch_wrename(wold, wnew);
6991 vim_free(wold);
6992 vim_free(wnew);
6993 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994}
6995
6996/*
6997 * Get the default shell for the current hardware platform
6998 */
6999 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007000default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007002 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007003}
7004
7005/*
7006 * mch_access() extends access() to do more detailed check on network drives.
7007 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7008 */
7009 int
7010mch_access(char *n, int p)
7011{
7012 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007013 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007014 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007016 wn = enc_to_utf16((char_u *)n, NULL);
7017 if (wn == NULL)
7018 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007020 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007021 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007022 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007023
7024 if (p & R_OK)
7025 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007026 // Read check is performed by seeing if we can do a find file on
7027 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007028 int i;
7029 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007030
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007031 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7032 TempNameW[i] = wn[i];
7033 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7034 TempNameW[i++] = '\\';
7035 TempNameW[i++] = '*';
7036 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007038 hFile = FindFirstFileW(TempNameW, &d);
7039 if (hFile == INVALID_HANDLE_VALUE)
7040 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007041 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007042 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007043 }
7044
7045 if (p & W_OK)
7046 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007047 // Trying to create a temporary file in the directory should catch
7048 // directories on read-only network shares. However, in
7049 // directories whose ACL allows writes but denies deletes will end
7050 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007051 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7052 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007053 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007054 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055 }
7056 }
7057 else
7058 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007059 // Don't consider a file read-only if another process has opened it.
7060 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7061
Bram Moolenaar0f873732019-12-05 20:28:46 +01007062 // Trying to open the file for the required access does ACL, read-only
7063 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007064 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7065 | ((p & R_OK) ? GENERIC_READ : 0);
7066
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007067 hFile = CreateFileW(wn, access_mode, share_mode,
7068 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069 if (hFile == INVALID_HANDLE_VALUE)
7070 goto getout;
7071 CloseHandle(hFile);
7072 }
7073
Bram Moolenaar0f873732019-12-05 20:28:46 +01007074 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007075getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077 return retval;
7078}
7079
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007081 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082 */
7083 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007084mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085{
7086 WCHAR *wn;
7087 int f;
7088
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007089 wn = enc_to_utf16((char_u *)name, NULL);
7090 if (wn == NULL)
7091 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007093 f = _wopen(wn, flags, mode);
7094 vim_free(wn);
7095 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096}
7097
7098/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007099 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 */
7101 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007102mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103{
7104 WCHAR *wn, *wm;
7105 FILE *f = NULL;
7106
Bram Moolenaara12a1612019-01-24 16:39:02 +01007107#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007108 // Work around an annoying assertion in the Microsoft debug CRT
7109 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007110 char newMode = mode[strlen(mode) - 1];
7111 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007112
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007113 _get_fmode(&oldMode);
7114 if (newMode == 't')
7115 _set_fmode(_O_TEXT);
7116 else if (newMode == 'b')
7117 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007118#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007119 wn = enc_to_utf16((char_u *)name, NULL);
7120 wm = enc_to_utf16((char_u *)mode, NULL);
7121 if (wn != NULL && wm != NULL)
7122 f = _wfopen(wn, wm);
7123 vim_free(wn);
7124 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007125
Bram Moolenaara12a1612019-01-24 16:39:02 +01007126#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007127 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007128#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007129 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007130}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132/*
7133 * SUB STREAM (aka info stream) handling:
7134 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007135 * NTFS can have sub streams for each file. The normal contents of a file is
7136 * stored in the main stream, and extra contents (author information, title and
7137 * so on) can be stored in a sub stream. After Windows 2000, the user can
7138 * access and store this information in sub streams via an explorer's property
7139 * menu item in the right click menu. This information in sub streams was lost
7140 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007141 *
7142 * Incomplete explanation:
7143 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7144 * More useful info and an example:
7145 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7146 */
7147
7148/*
7149 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7150 * and write to stream "substream" of file "to".
7151 * Errors are ignored.
7152 */
7153 static void
7154copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7155{
7156 HANDLE hTo;
7157 WCHAR *to_name;
7158
7159 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7160 wcscpy(to_name, to);
7161 wcscat(to_name, substream);
7162
7163 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7164 FILE_ATTRIBUTE_NORMAL, NULL);
7165 if (hTo != INVALID_HANDLE_VALUE)
7166 {
7167 long done;
7168 DWORD todo;
7169 DWORD readcnt, written;
7170 char buf[4096];
7171
Bram Moolenaar0f873732019-12-05 20:28:46 +01007172 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007173 for (done = 0; done < len; done += written)
7174 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007175 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007176 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7177 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007178 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7179 FALSE, FALSE, context)
7180 || readcnt != todo
7181 || !WriteFile(hTo, buf, todo, &written, NULL)
7182 || written != todo)
7183 break;
7184 }
7185 CloseHandle(hTo);
7186 }
7187
7188 free(to_name);
7189}
7190
7191/*
7192 * Copy info streams from file "from" to file "to".
7193 */
7194 static void
7195copy_infostreams(char_u *from, char_u *to)
7196{
7197 WCHAR *fromw;
7198 WCHAR *tow;
7199 HANDLE sh;
7200 WIN32_STREAM_ID sid;
7201 int headersize;
7202 WCHAR streamname[_MAX_PATH];
7203 DWORD readcount;
7204 void *context = NULL;
7205 DWORD lo, hi;
7206 int len;
7207
Bram Moolenaar0f873732019-12-05 20:28:46 +01007208 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007209 fromw = enc_to_utf16(from, NULL);
7210 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 if (fromw != NULL && tow != NULL)
7212 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007213 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007214 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7215 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7216 if (sh != INVALID_HANDLE_VALUE)
7217 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007218 // Use BackupRead() to find the info streams. Repeat until we
7219 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007220 for (;;)
7221 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007222 // Get the header to find the length of the stream name. If
7223 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007224 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007225 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007226 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7227 &readcount, FALSE, FALSE, &context)
7228 || readcount == 0)
7229 break;
7230
Bram Moolenaar0f873732019-12-05 20:28:46 +01007231 // We only deal with streams that have a name. The normal
7232 // file data appears to be without a name, even though docs
7233 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007234 if (sid.dwStreamNameSize > 0)
7235 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007236 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007237 if (!BackupRead(sh, (LPBYTE)streamname,
7238 sid.dwStreamNameSize,
7239 &readcount, FALSE, FALSE, &context))
7240 break;
7241
Bram Moolenaar0f873732019-12-05 20:28:46 +01007242 // Copy an info stream with a name ":anything:$DATA".
7243 // Skip "::$DATA", it has no stream name (examples suggest
7244 // it might be used for the normal file contents).
7245 // Note that BackupRead() counts bytes, but the name is in
7246 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007247 len = readcount / sizeof(WCHAR);
7248 streamname[len] = 0;
7249 if (len > 7 && wcsicmp(streamname + len - 6,
7250 L":$DATA") == 0)
7251 {
7252 streamname[len - 6] = 0;
7253 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007254 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255 }
7256 }
7257
Bram Moolenaar0f873732019-12-05 20:28:46 +01007258 // Advance to the next stream. We might try seeking too far,
7259 // but BackupSeek() doesn't skip over stream borders, thus
7260 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007261 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007262 &lo, &hi, &context);
7263 }
7264
Bram Moolenaar0f873732019-12-05 20:28:46 +01007265 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7267
7268 CloseHandle(sh);
7269 }
7270 }
7271 vim_free(fromw);
7272 vim_free(tow);
7273}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007274
7275/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007276 * ntdll.dll definitions
7277 */
7278#define FileEaInformation 7
7279#ifndef STATUS_SUCCESS
7280# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7281#endif
7282
7283typedef struct _FILE_FULL_EA_INFORMATION_ {
7284 ULONG NextEntryOffset;
7285 UCHAR Flags;
7286 UCHAR EaNameLength;
7287 USHORT EaValueLength;
7288 CHAR EaName[1];
7289} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7290
7291typedef struct _FILE_EA_INFORMATION_ {
7292 ULONG EaSize;
7293} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7294
7295typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7296 PHANDLE FileHandle,
7297 ACCESS_MASK DesiredAccess,
7298 POBJECT_ATTRIBUTES ObjectAttributes,
7299 PIO_STATUS_BLOCK IoStatusBlock,
7300 ULONG ShareAccess,
7301 ULONG OpenOptions);
7302typedef NTSTATUS (NTAPI *PfnNtClose)(
7303 HANDLE Handle);
7304typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7305 HANDLE FileHandle,
7306 PIO_STATUS_BLOCK IoStatusBlock,
7307 PVOID Buffer,
7308 ULONG Length);
7309typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7310 HANDLE FileHandle,
7311 PIO_STATUS_BLOCK IoStatusBlock,
7312 PVOID Buffer,
7313 ULONG Length,
7314 BOOLEAN ReturnSingleEntry,
7315 PVOID EaList,
7316 ULONG EaListLength,
7317 PULONG EaIndex,
7318 BOOLEAN RestartScan);
7319typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7320 HANDLE FileHandle,
7321 PIO_STATUS_BLOCK IoStatusBlock,
7322 PVOID FileInformation,
7323 ULONG Length,
7324 FILE_INFORMATION_CLASS FileInformationClass);
7325typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7326 PUNICODE_STRING DestinationString,
7327 PCWSTR SourceString);
7328
7329PfnNtOpenFile pNtOpenFile = NULL;
7330PfnNtClose pNtClose = NULL;
7331PfnNtSetEaFile pNtSetEaFile = NULL;
7332PfnNtQueryEaFile pNtQueryEaFile = NULL;
7333PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7334PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7335
7336/*
7337 * Load ntdll.dll functions.
7338 */
7339 static BOOL
7340load_ntdll(void)
7341{
7342 static int loaded = -1;
7343
7344 if (loaded == -1)
7345 {
7346 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7347 if (hNtdll != NULL)
7348 {
7349 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7350 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7351 pNtSetEaFile = (PfnNtSetEaFile)
7352 GetProcAddress(hNtdll, "NtSetEaFile");
7353 pNtQueryEaFile = (PfnNtQueryEaFile)
7354 GetProcAddress(hNtdll, "NtQueryEaFile");
7355 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7356 GetProcAddress(hNtdll, "NtQueryInformationFile");
7357 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7358 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7359 }
7360 if (pNtOpenFile == NULL
7361 || pNtClose == NULL
7362 || pNtSetEaFile == NULL
7363 || pNtQueryEaFile == NULL
7364 || pNtQueryInformationFile == NULL
7365 || pRtlInitUnicodeString == NULL)
7366 loaded = FALSE;
7367 else
7368 loaded = TRUE;
7369 }
7370 return (BOOL) loaded;
7371}
7372
7373/*
7374 * Copy extended attributes (EA) from file "from" to file "to".
7375 */
7376 static void
7377copy_extattr(char_u *from, char_u *to)
7378{
7379 char_u *fromf = NULL;
7380 char_u *tof = NULL;
7381 WCHAR *fromw = NULL;
7382 WCHAR *tow = NULL;
7383 UNICODE_STRING u;
7384 HANDLE h;
7385 OBJECT_ATTRIBUTES oa;
7386 IO_STATUS_BLOCK iosb;
7387 FILE_EA_INFORMATION_ eainfo = {0};
7388 void *ea = NULL;
7389
7390 if (!load_ntdll())
7391 return;
7392
7393 // Convert the file names to the fully qualified object names.
7394 fromf = alloc(STRLEN(from) + 5);
7395 tof = alloc(STRLEN(to) + 5);
7396 if (fromf == NULL || tof == NULL)
7397 goto theend;
7398 STRCPY(fromf, "\\??\\");
7399 STRCAT(fromf, from);
7400 STRCPY(tof, "\\??\\");
7401 STRCAT(tof, to);
7402
7403 // Convert the names to wide characters.
7404 fromw = enc_to_utf16(fromf, NULL);
7405 tow = enc_to_utf16(tof, NULL);
7406 if (fromw == NULL || tow == NULL)
7407 goto theend;
7408
7409 // Get the EA.
7410 pRtlInitUnicodeString(&u, fromw);
7411 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7412 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7413 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7414 goto theend;
7415 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7416 FileEaInformation);
7417 if (eainfo.EaSize != 0)
7418 {
7419 ea = alloc(eainfo.EaSize);
7420 if (ea != NULL)
7421 {
7422 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7423 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7424 {
7425 vim_free(ea);
7426 ea = NULL;
7427 }
7428 }
7429 }
7430 pNtClose(h);
7431
7432 // Set the EA.
7433 if (ea != NULL)
7434 {
7435 pRtlInitUnicodeString(&u, tow);
7436 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7437 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7438 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7439 goto theend;
7440
7441 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7442 pNtClose(h);
7443 }
7444
7445theend:
7446 vim_free(fromf);
7447 vim_free(tof);
7448 vim_free(fromw);
7449 vim_free(tow);
7450 vim_free(ea);
7451}
7452
7453/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007454 * Copy file attributes from file "from" to file "to".
7455 * For Windows NT and later we copy info streams.
7456 * Always returns zero, errors are ignored.
7457 */
7458 int
7459mch_copy_file_attribute(char_u *from, char_u *to)
7460{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007461 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007462 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007463 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464 return 0;
7465}
7466
7467#if defined(MYRESETSTKOFLW) || defined(PROTO)
7468/*
7469 * Recreate a destroyed stack guard page in win32.
7470 * Written by Benjamin Peterson.
7471 */
7472
Bram Moolenaar0f873732019-12-05 20:28:46 +01007473// These magic numbers are from the MS header files
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007474# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475
7476/*
7477 * This function does the same thing as _resetstkoflw(), which is only
7478 * available in DevStudio .net and later.
7479 * Returns 0 for failure, 1 for success.
7480 */
7481 int
7482myresetstkoflw(void)
7483{
7484 BYTE *pStackPtr;
7485 BYTE *pGuardPage;
7486 BYTE *pStackBase;
7487 BYTE *pLowestPossiblePage;
7488 MEMORY_BASIC_INFORMATION mbi;
7489 SYSTEM_INFO si;
7490 DWORD nPageSize;
7491 DWORD dummy;
7492
Bram Moolenaar0f873732019-12-05 20:28:46 +01007493 // We need to know the system page size.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007494 GetSystemInfo(&si);
7495 nPageSize = si.dwPageSize;
7496
Bram Moolenaar0f873732019-12-05 20:28:46 +01007497 // ...and the current stack pointer
Bram Moolenaar071d4272004-06-13 20:20:40 +00007498 pStackPtr = (BYTE*)_alloca(1);
7499
Bram Moolenaar0f873732019-12-05 20:28:46 +01007500 // ...and the base of the stack.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007501 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7502 return 0;
7503 pStackBase = (BYTE*)mbi.AllocationBase;
7504
Bram Moolenaar4b96df52020-01-26 22:00:26 +01007505 // ...and the page that's min_stack_req pages away from stack base; this is
Bram Moolenaar0f873732019-12-05 20:28:46 +01007506 // the lowest page we could use.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007507 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508
Bram Moolenaar071d4272004-06-13 20:20:40 +00007509 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007510 // We want the first committed page in the stack Start at the stack
7511 // base and move forward through memory until we find a committed block.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007512 BYTE *pBlock = pStackBase;
7513
Bram Moolenaara466c992005-07-09 21:03:22 +00007514 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515 {
7516 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7517 return 0;
7518
7519 pBlock += mbi.RegionSize;
7520
7521 if (mbi.State & MEM_COMMIT)
7522 break;
7523 }
7524
Bram Moolenaar0f873732019-12-05 20:28:46 +01007525 // mbi now describes the first committed block in the stack.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007526 if (mbi.Protect & PAGE_GUARD)
7527 return 1;
7528
Bram Moolenaar0f873732019-12-05 20:28:46 +01007529 // decide where the guard page should start
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7531 pGuardPage = pLowestPossiblePage;
7532 else
7533 pGuardPage = (BYTE*)mbi.BaseAddress;
7534
Bram Moolenaar0f873732019-12-05 20:28:46 +01007535 // allocate the guard page
Bram Moolenaar071d4272004-06-13 20:20:40 +00007536 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7537 return 0;
7538
Bram Moolenaar0f873732019-12-05 20:28:46 +01007539 // apply the guard attribute to the page
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7541 &dummy))
7542 return 0;
7543 }
7544
7545 return 1;
7546}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007547#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007548
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007549
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007550/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007551 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007552 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007553static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007554static LPWSTR *ArglistW = NULL;
7555static int global_argc = 0;
7556static char **global_argv;
7557
Bram Moolenaar0f873732019-12-05 20:28:46 +01007558static int used_file_argc = 0; // last argument in global_argv[] used
7559 // for the argument list.
7560static int *used_file_indexes = NULL; // indexes in global_argv[] for
7561 // command line arguments added to
7562 // the argument list
7563static int used_file_count = 0; // nr of entries in used_file_indexes
7564static int used_file_literal = FALSE; // take file names literally
7565static int used_file_full_path = FALSE; // file name was full path
7566static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007567static int used_alist_count = 0;
7568
7569
7570/*
7571 * Get the command line arguments. Unicode version.
7572 * Returns argc. Zero when something fails.
7573 */
7574 int
7575get_cmd_argsW(char ***argvp)
7576{
7577 char **argv = NULL;
7578 int argc = 0;
7579 int i;
7580
Bram Moolenaar14993322014-09-09 12:25:33 +02007581 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007582 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7583 if (ArglistW != NULL)
7584 {
7585 argv = malloc((nArgsW + 1) * sizeof(char *));
7586 if (argv != NULL)
7587 {
7588 argc = nArgsW;
7589 argv[argc] = NULL;
7590 for (i = 0; i < argc; ++i)
7591 {
7592 int len;
7593
K.Takatadc73b4b2021-06-08 18:32:36 +02007594 // Convert each Unicode argument to UTF-8.
7595 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007596 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007597 (LPSTR *)&argv[i], &len, 0, 0);
7598 if (argv[i] == NULL)
7599 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007600 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007601 while (i > 0)
7602 free(argv[--i]);
7603 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007604 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007605 argc = 0;
7606 }
7607 }
7608 }
7609 }
7610
7611 global_argc = argc;
7612 global_argv = argv;
7613 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007614 {
7615 if (used_file_indexes != NULL)
7616 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007617 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007618 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007619
7620 if (argvp != NULL)
7621 *argvp = argv;
7622 return argc;
7623}
7624
7625 void
7626free_cmd_argsW(void)
7627{
7628 if (ArglistW != NULL)
7629 {
7630 GlobalFree(ArglistW);
7631 ArglistW = NULL;
7632 }
7633}
7634
7635/*
7636 * Remember "name" is an argument that was added to the argument list.
7637 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7638 * is called.
7639 */
7640 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007641used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007642{
7643 int i;
7644
7645 if (used_file_indexes == NULL)
7646 return;
7647 for (i = used_file_argc + 1; i < global_argc; ++i)
7648 if (STRCMP(global_argv[i], name) == 0)
7649 {
7650 used_file_argc = i;
7651 used_file_indexes[used_file_count++] = i;
7652 break;
7653 }
7654 used_file_literal = literal;
7655 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007656 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007657}
7658
7659/*
7660 * Remember the length of the argument list as it was. If it changes then we
7661 * leave it alone when 'encoding' is set.
7662 */
7663 void
7664set_alist_count(void)
7665{
7666 used_alist_count = GARGCOUNT;
7667}
7668
7669/*
7670 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007671 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007672 * and convert them to 'encoding'.
7673 */
7674 void
7675fix_arg_enc(void)
7676{
7677 int i;
7678 int idx;
7679 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007680 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007681
Bram Moolenaar0f873732019-12-05 20:28:46 +01007682 // Safety checks:
7683 // - if argument count differs between the wide and non-wide argument
7684 // list, something must be wrong.
7685 // - the file name arguments must have been located.
7686 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007687 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007688 || ArglistW == NULL
7689 || used_file_indexes == NULL
7690 || used_file_count == 0
7691 || used_alist_count != GARGCOUNT)
7692 return;
7693
Bram Moolenaar0f873732019-12-05 20:28:46 +01007694 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007695 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007696 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007697 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007698 for (i = 0; i < GARGCOUNT; ++i)
7699 fnum_list[i] = GARGLIST[i].ae_fnum;
7700
Bram Moolenaar0f873732019-12-05 20:28:46 +01007701 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007702 alist_clear(&global_alist);
7703 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007704 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007705
7706 for (i = 0; i < used_file_count; ++i)
7707 {
7708 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007709 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007710 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007711 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007712 int literal = used_file_literal;
7713
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007714#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007715 // When using diff mode may need to concatenate file name to
7716 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007717 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7718 && !mch_isdir(alist_name(&GARGLIST[0])))
7719 {
7720 char_u *r;
7721
7722 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7723 if (r != NULL)
7724 {
7725 vim_free(str);
7726 str = r;
7727 }
7728 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007729#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007730 // Re-use the old buffer by renaming it. When not using literal
7731 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007732 if (used_file_literal)
7733 buf_set_name(fnum_list[i], str);
7734
Bram Moolenaar0f873732019-12-05 20:28:46 +01007735 // Check backtick literal. backtick literal is already expanded in
7736 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007737 if (literal == FALSE)
7738 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007739 size_t len = STRLEN(str);
7740
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007741 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7742 literal = TRUE;
7743 }
7744 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007745 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007746 }
7747
7748 if (!used_file_literal)
7749 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007750 // Now expand wildcards in the arguments.
7751 // Temporarily add '(' and ')' to 'isfname'. These are valid
7752 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007753 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007754 // Also, unset wildignore to not be influenced by this option.
7755 // The arguments specified in command-line should be kept even if
7756 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007757 // Use :legacy so that it also works when in Vim9 script.
7758 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7759 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007760 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007761 do_cmdline_cmd(
7762 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7763 do_cmdline_cmd(
7764 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007765 }
7766
Bram Moolenaar0f873732019-12-05 20:28:46 +01007767 // If wildcard expansion failed, we are editing the first file of the
7768 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007769 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7770 {
7771 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007772 if (GARGCOUNT == 1 && used_file_full_path
7773 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7774 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007775 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007776
7777 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007778}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007779
7780 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007781mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007782{
7783 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007784 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007785
Bram Moolenaar964b3742019-05-24 18:54:09 +02007786 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007787 if (envbuf == NULL)
7788 return -1;
7789
7790 sprintf((char *)envbuf, "%s=%s", var, value);
7791
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007792 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007793
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007794 vim_free(envbuf);
7795 if (p == NULL)
7796 return -1;
7797 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007798#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007799 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007800#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007801 // Unlike Un*x systems, we can free the string for _wputenv().
7802 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007803
7804 return 0;
7805}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007806
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007807/*
7808 * Support for 256 colors and 24-bit colors was added in Windows 10
7809 * version 1703 (Creators update).
7810 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007811#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7812
7813/*
7814 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007815 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007816 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007817#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007818
7819/*
7820 * ConPTY differences between versions, need different logic.
7821 * version 1903 (May 2019 update).
7822 */
7823#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7824
7825/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007826 * version 1909 (November 2019 update).
7827 */
7828#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7829
7830/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007831 * Stay ahead of the next update, and when it's done, fix this.
7832 * version ? (2020 update, temporarily use the build number of insider preview)
7833 */
7834#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7835
7836/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007837 * Confirm until this version. Also the logic changes.
7838 * insider preview.
7839 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007840#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007841
7842/*
7843 * Not stable now.
7844 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007845#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007846
7847 static void
7848vtp_flag_init(void)
7849{
7850 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007851#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007852 DWORD mode;
7853 HANDLE out;
7854
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007855# ifdef VIMDLL
7856 if (!gui.in_use)
7857# endif
7858 {
7859 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007860
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007861 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7862 GetConsoleMode(out, &mode);
7863 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7864 if (SetConsoleMode(out, mode) == 0)
7865 vtp_working = 0;
7866 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007867#endif
7868
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007869 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007870 conpty_working = 1;
7871 if (ver >= CONPTY_STABLE_BUILD)
7872 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007873
Bram Moolenaar57da6982019-09-13 22:30:11 +02007874 if (ver <= CONPTY_INSIDER_BUILD)
7875 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007876 if (ver <= CONPTY_1909_BUILD)
7877 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007878 if (ver <= CONPTY_1903_BUILD)
7879 conpty_type = 2;
7880 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7881 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007882
7883 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7884 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007885}
7886
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007887#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007888
7889 static void
7890vtp_init(void)
7891{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007892 HMODULE hKerneldll;
7893 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007894# ifdef FEAT_TERMGUICOLORS
7895 COLORREF fg, bg;
7896# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007897
Bram Moolenaar0f873732019-12-05 20:28:46 +01007898 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007899 hKerneldll = GetModuleHandle("kernel32.dll");
7900 if (hKerneldll != NULL)
7901 {
7902 pGetConsoleScreenBufferInfoEx =
7903 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7904 hKerneldll, "GetConsoleScreenBufferInfoEx");
7905 pSetConsoleScreenBufferInfoEx =
7906 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7907 hKerneldll, "SetConsoleScreenBufferInfoEx");
7908 if (pGetConsoleScreenBufferInfoEx != NULL
7909 && pSetConsoleScreenBufferInfoEx != NULL)
7910 has_csbiex = TRUE;
7911 }
7912
7913 csbi.cbSize = sizeof(csbi);
7914 if (has_csbiex)
7915 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007916 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7917 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007918 store_console_bg_rgb = save_console_bg_rgb;
7919 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007920
7921# ifdef FEAT_TERMGUICOLORS
7922 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7923 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7924 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7925 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7926 default_console_color_bg = bg;
7927 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007928# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007929
7930 set_console_color_rgb();
7931}
7932
7933 static void
7934vtp_exit(void)
7935{
Bram Moolenaardf543822020-01-30 11:53:59 +01007936 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007937}
7938
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007939 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007940vtp_printf(
7941 char *format,
7942 ...)
7943{
7944 char_u buf[100];
7945 va_list list;
7946 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007947 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007948
7949 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007950 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007951 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007952 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007953 return (int)result;
7954}
7955
7956 static void
7957vtp_sgr_bulk(
7958 int arg)
7959{
7960 int args[1];
7961
7962 args[0] = arg;
7963 vtp_sgr_bulks(1, args);
7964}
7965
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007966#define FAST256(x) \
7967 if ((*p-- = "0123456789"[(n = x % 10)]) \
7968 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7969 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7970
7971#define FAST256CASE(x) \
7972 case x: \
7973 FAST256(newargs[x - 1]);
7974
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007975 static void
7976vtp_sgr_bulks(
7977 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007978 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007979{
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007980#define MAXSGR 16
7981#define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
7982 char_u buf[SGRBUFSIZE];
7983 char_u *p;
7984 int in, out;
7985 int newargs[16];
7986 static int sgrfgr = -1, sgrfgg, sgrfgb;
7987 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007988
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007989 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007990 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007991 sgrfgr = sgrbgr = -1;
7992 vtp_printf("033[m");
7993 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007994 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007995
7996 in = out = 0;
7997 while (in < argc)
7998 {
7999 int s = args[in];
8000 int copylen = 1;
8001
8002 if (s == 38)
8003 {
8004 if (argc - in >= 5 && args[in + 1] == 2)
8005 {
8006 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8007 && sgrfgb == args[in + 4])
8008 {
8009 in += 5;
8010 copylen = 0;
8011 }
8012 else
8013 {
8014 sgrfgr = args[in + 2];
8015 sgrfgg = args[in + 3];
8016 sgrfgb = args[in + 4];
8017 copylen = 5;
8018 }
8019 }
8020 else if (argc - in >= 3 && args[in + 1] == 5)
8021 {
8022 sgrfgr = -1;
8023 copylen = 3;
8024 }
8025 }
8026 else if (s == 48)
8027 {
8028 if (argc - in >= 5 && args[in + 1] == 2)
8029 {
8030 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8031 && sgrbgb == args[in + 4])
8032 {
8033 in += 5;
8034 copylen = 0;
8035 }
8036 else
8037 {
8038 sgrbgr = args[in + 2];
8039 sgrbgg = args[in + 3];
8040 sgrbgb = args[in + 4];
8041 copylen = 5;
8042 }
8043 }
8044 else if (argc - in >= 3 && args[in + 1] == 5)
8045 {
8046 sgrbgr = -1;
8047 copylen = 3;
8048 }
8049 }
8050 else if (30 <= s && s <= 39)
8051 sgrfgr = -1;
8052 else if (90 <= s && s <= 97)
8053 sgrfgr = -1;
8054 else if (40 <= s && s <= 49)
8055 sgrbgr = -1;
8056 else if (100 <= s && s <= 107)
8057 sgrbgr = -1;
8058 else if (s == 0)
8059 sgrfgr = sgrbgr = -1;
8060
8061 while (copylen--)
8062 newargs[out++] = args[in++];
8063 }
8064
8065 p = &buf[sizeof(buf) - 1];
8066 *p-- = 'm';
8067
8068 switch (out)
8069 {
8070 int n, m;
8071 DWORD r;
8072
8073 FAST256CASE(16);
8074 *p-- = ';';
8075 FAST256CASE(15);
8076 *p-- = ';';
8077 FAST256CASE(14);
8078 *p-- = ';';
8079 FAST256CASE(13);
8080 *p-- = ';';
8081 FAST256CASE(12);
8082 *p-- = ';';
8083 FAST256CASE(11);
8084 *p-- = ';';
8085 FAST256CASE(10);
8086 *p-- = ';';
8087 FAST256CASE(9);
8088 *p-- = ';';
8089 FAST256CASE(8);
8090 *p-- = ';';
8091 FAST256CASE(7);
8092 *p-- = ';';
8093 FAST256CASE(6);
8094 *p-- = ';';
8095 FAST256CASE(5);
8096 *p-- = ';';
8097 FAST256CASE(4);
8098 *p-- = ';';
8099 FAST256CASE(3);
8100 *p-- = ';';
8101 FAST256CASE(2);
8102 *p-- = ';';
8103 FAST256CASE(1);
8104 *p-- = '[';
8105 *p = '\033';
8106 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8107 default:
8108 break;
8109 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008110}
8111
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008112 static void
8113wt_init(void)
8114{
8115 wt_working = (mch_getenv("WT_SESSION") != NULL);
8116}
8117
8118 int
8119use_wt(void)
8120{
8121 return USE_WT;
8122}
8123
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008124# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008125 static int
8126ctermtoxterm(
8127 int cterm)
8128{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008129 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008130
8131 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8132 return (((int)r << 16) | ((int)g << 8) | (int)b);
8133}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008134# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008135
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008136 static void
8137set_console_color_rgb(void)
8138{
8139# ifdef FEAT_TERMGUICOLORS
8140 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008141 guicolor_T fg, bg;
8142 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008143
8144 if (!USE_VTP)
8145 return;
8146
Bram Moolenaara050b942019-12-02 21:35:31 +01008147 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8148
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008149 if (USE_WT)
8150 {
8151 term_fg_rgb_color(fg);
8152 term_bg_rgb_color(bg);
8153 return;
8154 }
8155
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008156 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8157 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8158
8159 csbi.cbSize = sizeof(csbi);
8160 if (has_csbiex)
8161 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8162
8163 csbi.cbSize = sizeof(csbi);
8164 csbi.srWindow.Right += 1;
8165 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008166 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8167 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008168 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8169 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008170 if (has_csbiex)
8171 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8172# endif
8173}
8174
Bram Moolenaara050b942019-12-02 21:35:31 +01008175# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8176 void
8177get_default_console_color(
8178 int *cterm_fg,
8179 int *cterm_bg,
8180 guicolor_T *gui_fg,
8181 guicolor_T *gui_bg)
8182{
8183 int id;
8184 guicolor_T guifg = INVALCOLOR;
8185 guicolor_T guibg = INVALCOLOR;
8186 int ctermfg = 0;
8187 int ctermbg = 0;
8188
8189 id = syn_name2id((char_u *)"Normal");
8190 if (id > 0 && p_tgc)
8191 syn_id2colors(id, &guifg, &guibg);
8192 if (guifg == INVALCOLOR)
8193 {
8194 ctermfg = -1;
8195 if (id > 0)
8196 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8197 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8198 : default_console_color_fg;
8199 cterm_normal_fg_gui_color = guifg;
8200 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8201 }
8202 if (guibg == INVALCOLOR)
8203 {
8204 ctermbg = -1;
8205 if (id > 0)
8206 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8207 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8208 : default_console_color_bg;
8209 cterm_normal_bg_gui_color = guibg;
8210 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8211 }
8212
8213 *cterm_fg = ctermfg;
8214 *cterm_bg = ctermbg;
8215 *gui_fg = guifg;
8216 *gui_bg = guibg;
8217}
8218# endif
8219
Bram Moolenaardf543822020-01-30 11:53:59 +01008220/*
8221 * Set the console colors to the original colors or the last set colors.
8222 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008223 static void
8224reset_console_color_rgb(void)
8225{
8226# ifdef FEAT_TERMGUICOLORS
8227 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8228
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008229 if (USE_WT)
8230 return;
8231
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008232 csbi.cbSize = sizeof(csbi);
8233 if (has_csbiex)
8234 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8235
8236 csbi.cbSize = sizeof(csbi);
8237 csbi.srWindow.Right += 1;
8238 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008239 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8240 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8241 if (has_csbiex)
8242 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8243# endif
8244}
8245
8246/*
8247 * Set the console colors to the original colors.
8248 */
8249 static void
8250restore_console_color_rgb(void)
8251{
8252# ifdef FEAT_TERMGUICOLORS
8253 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8254
8255 csbi.cbSize = sizeof(csbi);
8256 if (has_csbiex)
8257 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8258
8259 csbi.cbSize = sizeof(csbi);
8260 csbi.srWindow.Right += 1;
8261 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008262 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8263 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008264 if (has_csbiex)
8265 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8266# endif
8267}
8268
8269 void
8270control_console_color_rgb(void)
8271{
8272 if (USE_VTP)
8273 set_console_color_rgb();
8274 else
8275 reset_console_color_rgb();
8276}
8277
8278 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008279use_vtp(void)
8280{
8281 return USE_VTP;
8282}
8283
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008284 int
8285is_term_win32(void)
8286{
8287 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8288}
8289
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008290 int
8291has_vtp_working(void)
8292{
8293 return vtp_working;
8294}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008295
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008296#endif
8297
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008298 int
8299has_conpty_working(void)
8300{
8301 return conpty_working;
8302}
8303
8304 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008305get_conpty_type(void)
8306{
8307 return conpty_type;
8308}
8309
8310 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008311is_conpty_stable(void)
8312{
8313 return conpty_stable;
8314}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008315
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008316 int
8317get_conpty_fix_type(void)
8318{
8319 return conpty_fix_type;
8320}
8321
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008322#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008323 void
8324resize_console_buf(void)
8325{
8326 CONSOLE_SCREEN_BUFFER_INFO csbi;
8327 COORD coord;
8328 SMALL_RECT newsize;
8329
8330 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8331 {
8332 coord.X = SRWIDTH(csbi.srWindow);
8333 coord.Y = SRHEIGHT(csbi.srWindow);
8334 SetConsoleScreenBufferSize(g_hConOut, coord);
8335
8336 newsize.Left = 0;
8337 newsize.Top = 0;
8338 newsize.Right = coord.X - 1;
8339 newsize.Bottom = coord.Y - 1;
8340 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8341
8342 SetConsoleScreenBufferSize(g_hConOut, coord);
8343 }
8344}
8345#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008346
8347 char *
8348GetWin32Error(void)
8349{
8350 char *msg = NULL;
8351 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8352 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
8353 if (msg != NULL)
8354 {
8355 // remove trailing \r\n
8356 char *pcrlf = strstr(msg, "\r\n");
8357 if (pcrlf != NULL)
8358 *pcrlf = '\0';
8359 }
8360 return msg;
8361}