blob: e6ffcbac9212df980c291604c7e5b29b3a351a39 [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;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#endif
181#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182static int s_dont_use_vimrun = TRUE;
183static int need_vimrun_warning = FALSE;
184static char *vimrun_path = "vimrun ";
185#endif
186
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200187static int win32_getattrs(char_u *name);
188static int win32_setattrs(char_u *name, int attrs);
189static int win32_set_archive(char_u *name);
190
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200192static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200194static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200204static int wt_working = 0;
205static void wt_init();
206
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100207static guicolor_T save_console_bg_rgb;
208static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100209static guicolor_T store_console_bg_rgb;
210static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100211
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200212static int g_color_index_bg = 0;
213static int g_color_index_fg = 7;
214
215# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100216static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200217static int default_console_color_fg = 0xc0c0c0; // white
218# endif
219
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100220# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200221# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100223# else
224# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200225# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100226# endif
227
228static void set_console_color_rgb(void);
229static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100230static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100231#endif
232
Bram Moolenaar0f873732019-12-05 20:28:46 +0100233// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100234#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
235# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
236#endif
237
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200238#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100239static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240#endif
241
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200242static char_u *exe_path = NULL;
243
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100244static BOOL win8_or_later = FALSE;
245
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200246#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100247// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
249{
250 ULONG cbSize;
251 COORD dwSize;
252 COORD dwCursorPosition;
253 WORD wAttributes;
254 SMALL_RECT srWindow;
255 COORD dwMaximumWindowSize;
256 WORD wPopupAttributes;
257 BOOL bFullscreenSupported;
258 COLORREF ColorTable[16];
259} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
260typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
261static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
262typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
263static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
264static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100265#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100266
267/*
268 * Get version number including build number
269 */
270typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100271#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100272 (((major) << 24) | ((minor) << 16) | (build))
273
274 static DWORD
275get_build_number(void)
276{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100277 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100278 HMODULE hNtdll;
279 PfnRtlGetVersion pRtlGetVersion;
280 DWORD ver = MAKE_VER(0, 0, 0);
281
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100282 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100283 hNtdll = GetModuleHandle("ntdll.dll");
284 if (hNtdll != NULL)
285 {
286 pRtlGetVersion =
287 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
288 pRtlGetVersion(&osver);
289 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
290 min(osver.dwMinorVersion, 255),
291 min(osver.dwBuildNumber, 32767));
292 }
293 return ver;
294}
295
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200296#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200297 static BOOL
298is_ambiwidth_event(
299 INPUT_RECORD *ir)
300{
301 return ir->EventType == KEY_EVENT
302 && ir->Event.KeyEvent.bKeyDown
303 && ir->Event.KeyEvent.wRepeatCount == 1
304 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
305 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000306 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200307 && ir->Event.KeyEvent.dwControlKeyState == 2;
308}
309
310 static void
311make_ambiwidth_event(
312 INPUT_RECORD *down,
313 INPUT_RECORD *up)
314{
315 down->Event.KeyEvent.wVirtualKeyCode = 0;
316 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000317 down->Event.KeyEvent.uChar.UnicodeChar
318 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200319 down->Event.KeyEvent.dwControlKeyState = 0;
320}
321
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322/*
323 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100324 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325 */
326 static BOOL
327read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100328 HANDLE hInput,
329 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100330 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100331 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100332{
333 enum
334 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100335 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100336 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100338 static DWORD s_dwIndex = 0;
339 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100340 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100341 int head;
342 int tail;
343 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200344 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100345
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200346 if (nLength == -2)
347 return (s_dwMax > 0) ? TRUE : FALSE;
348
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100349 if (!win8_or_later)
350 {
351 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200352 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
353 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100354 }
355
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100356 if (s_dwMax == 0)
357 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200358 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200359 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200360 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
361 if (dwEvents == 0 && nLength == -1)
362 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
363 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100364 s_dwIndex = 0;
365 s_dwMax = dwEvents;
366 if (dwEvents == 0)
367 {
368 *lpEvents = 0;
369 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100370 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100371
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200372 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
373 if (is_ambiwidth_event(&s_irCache[i]))
374 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
375
Bram Moolenaardd415a62014-02-05 14:02:27 +0100376 if (s_dwMax > 1)
377 {
378 head = 0;
379 tail = s_dwMax - 1;
380 while (head != tail)
381 {
382 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
383 && s_irCache[head + 1].EventType
384 == WINDOW_BUFFER_SIZE_EVENT)
385 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100386 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100387 for (i = head; i < tail; ++i)
388 s_irCache[i] = s_irCache[i + 1];
389 --tail;
390 continue;
391 }
392 head++;
393 }
394 s_dwMax = tail + 1;
395 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100396 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100397
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200398 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
399 {
400 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
401 {
402 s_irPseudo = s_irCache[s_dwIndex];
403 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
404 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
405 *lpBuffer = s_irPseudo;
406 *lpEvents = 1;
407 return TRUE;
408 }
409 }
410
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100411 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200412 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100413 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100414 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100415 return TRUE;
416}
417
418/*
419 * Version of PeekConsoleInput() that works with IME.
420 */
421 static BOOL
422peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100423 HANDLE hInput,
424 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200425 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100426 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100427{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100428 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100429}
430
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100431# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200432 static DWORD
433msg_wait_for_multiple_objects(
434 DWORD nCount,
435 LPHANDLE pHandles,
436 BOOL fWaitAll,
437 DWORD dwMilliseconds,
438 DWORD dwWakeMask)
439{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100440 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200441 return WAIT_OBJECT_0;
442 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
443 dwMilliseconds, dwWakeMask);
444}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100445# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200446
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100447# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200448 static DWORD
449wait_for_single_object(
450 HANDLE hHandle,
451 DWORD dwMilliseconds)
452{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100453 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200454 return WAIT_OBJECT_0;
455 return WaitForSingleObject(hHandle, dwMilliseconds);
456}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100457# endif
458#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200459
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460 static void
461get_exe_name(void)
462{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100463 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
464 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100465#define MAX_ENV_PATH_LEN 8192
466 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200467 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468
469 if (exe_name == NULL)
470 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100471 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100472 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473 if (*temp != NUL)
474 exe_name = FullName_save((char_u *)temp, FALSE);
475 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000476
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200479 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000481 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100482 // Append our starting directory to $PATH, so that when doing
483 // "!xxd" it's found in our starting directory. Needed because
484 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200485 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100486 if (p == NULL
487 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200488 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100489 if (p == NULL || *p == NUL)
490 temp[0] = NUL;
491 else
492 {
493 STRCPY(temp, p);
494 STRCAT(temp, ";");
495 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200496 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100497 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000499 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000500 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501}
502
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200503/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100504 * Unescape characters in "p" that appear in "escaped".
505 */
506 static void
507unescape_shellxquote(char_u *p, char_u *escaped)
508{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100509 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100510 int n;
511
512 while (*p != NUL)
513 {
514 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
515 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100516 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100517 p += n;
518 l -= n;
519 }
520}
521
522/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200523 * Load library "name".
524 */
525 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000526vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200527{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200528 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200529
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200530 // No need to load any library when registering OLE.
531 if (found_register_arg)
532 return dll;
533
Bram Moolenaar0f873732019-12-05 20:28:46 +0100534 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
535 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200536 if (exe_path == NULL)
537 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200538 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200539 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200540 WCHAR old_dirw[MAXPATHL];
541
542 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
543 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100544 // Change directory to where the executable is, both to make
545 // sure we find a .dll there and to avoid looking for a .dll
546 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100547 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200548 dll = LoadLibrary(name);
549 SetCurrentDirectoryW(old_dirw);
550 return dll;
551 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200552 }
553 return dll;
554}
555
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200556#if defined(VIMDLL) || defined(PROTO)
557/*
558 * Check if the current executable file is for the GUI subsystem.
559 */
560 int
561mch_is_gui_executable(void)
562{
563 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
564 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
565 PIMAGE_NT_HEADERS pPE;
566
567 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
568 return FALSE;
569 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
570 if (pPE->Signature != IMAGE_NT_SIGNATURE)
571 return FALSE;
572 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
573 return TRUE;
574 return FALSE;
575}
576#endif
577
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000578#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
579 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100580/*
581 * Get related information about 'funcname' which is imported by 'hInst'.
582 * If 'info' is 0, return the function address.
583 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000584 * If 'info' is 2, hook the function with 'ptr', and return the original
585 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100586 */
587 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000588get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
589 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100590{
591 PBYTE pImage = (PBYTE)hInst;
592 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
593 PIMAGE_NT_HEADERS pPE;
594 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100595 PIMAGE_THUNK_DATA pIAT; // Import Address Table
596 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100597 PIMAGE_IMPORT_BY_NAME pImpName;
598
599 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
600 return NULL;
601 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
602 if (pPE->Signature != IMAGE_NT_SIGNATURE)
603 return NULL;
604 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
605 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
606 .VirtualAddress);
607 for (; pImpDesc->FirstThunk; ++pImpDesc)
608 {
609 if (!pImpDesc->OriginalFirstThunk)
610 continue;
611 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
612 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
613 for (; pIAT->u1.Function; ++pIAT, ++pINT)
614 {
615 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
616 continue;
617 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
618 + (UINT_PTR)(pINT->u1.AddressOfData));
619 if (strcmp((char *)pImpName->Name, funcname) == 0)
620 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000621 void *original;
622 DWORD old, new = PAGE_READWRITE;
623
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100624 switch (info)
625 {
626 case 0:
627 return (void *)pIAT->u1.Function;
628 case 1:
629 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000630 case 2:
631 original = (void *)pIAT->u1.Function;
632 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
633 new, &old);
634 pIAT->u1.Function = (UINT_PTR)ptr;
635 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
636 old, &new);
637 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100638 default:
639 return NULL;
640 }
641 }
642 }
643 }
644 return NULL;
645}
646
647/*
648 * Get the module handle which 'funcname' in 'hInst' is imported from.
649 */
650 HINSTANCE
651find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
652{
653 char *modulename;
654
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000655 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100656 if (modulename != NULL)
657 return GetModuleHandleA(modulename);
658 return NULL;
659}
660
661/*
662 * Get the address of 'funcname' which is imported by 'hInst' DLL.
663 */
664 void *
665get_dll_import_func(HINSTANCE hInst, const char *funcname)
666{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000667 return get_imported_func_info(hInst, funcname, 0, NULL);
668}
669
670/*
671 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
672 * and return the original function address.
673 */
674 void *
675hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
676{
677 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100678}
679#endif
680
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
682# ifndef GETTEXT_DLL
683# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200684# define GETTEXT_DLL_ALT1 "libintl-8.dll"
685# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000686# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100687// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000688static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200689static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000690static char *null_libintl_textdomain(const char *);
691static char *null_libintl_bindtextdomain(const char *, const char *);
692static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100693static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200695static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000696char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200697char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
698 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000699char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
700char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000701 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000702char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
703 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100704int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705
706 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100707dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708{
709 int i;
710 static struct
711 {
712 char *name;
713 FARPROC *ptr;
714 } libintl_entry[] =
715 {
716 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200717 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
719 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
720 {NULL, NULL}
721 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100722 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723
Bram Moolenaar7554c542018-10-06 15:03:15 +0200724 // No need to initialize twice.
725 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000726 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200727 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100728 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100729# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100730 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200731 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100732# endif
733# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200734 if (!hLibintlDLL)
735 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100736# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100737 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200739 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200741 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000742 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200743 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200745 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746 }
747 for (i = 0; libintl_entry[i].name != NULL
748 && libintl_entry[i].ptr != NULL; ++i)
749 {
K.Takata54119102022-02-03 13:33:03 +0000750 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751 libintl_entry[i].name)) == NULL)
752 {
753 dyn_libintl_end();
754 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000755 {
756 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000757 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000758 verbose_leave();
759 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760 return 0;
761 }
762 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000763
Bram Moolenaar0f873732019-12-05 20:28:46 +0100764 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100765 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
766 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000767 if (dyn_libintl_bind_textdomain_codeset == NULL)
768 dyn_libintl_bind_textdomain_codeset =
769 null_libintl_bind_textdomain_codeset;
770
Bram Moolenaar0f873732019-12-05 20:28:46 +0100771 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100772 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
773 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100774 dyn_libintl_wputenv = (int (*)(const wchar_t *))
775 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100776 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
777 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100778
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779 return 1;
780}
781
782 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100783dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784{
785 if (hLibintlDLL)
786 FreeLibrary(hLibintlDLL);
787 hLibintlDLL = NULL;
788 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200789 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790 dyn_libintl_textdomain = null_libintl_textdomain;
791 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000792 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100793 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794}
795
796 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000797null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798{
799 return (char*)msgid;
800}
801
802 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200803null_libintl_ngettext(
804 const char *msgid,
805 const char *msgid_plural,
806 unsigned long n)
807{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200808 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200809}
810
Bram Moolenaaree695f72016-08-03 22:08:45 +0200811 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100812null_libintl_bindtextdomain(
813 const char *domainname UNUSED,
814 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000815{
816 return NULL;
817}
818
819 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100820null_libintl_bind_textdomain_codeset(
821 const char *domainname UNUSED,
822 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000823{
824 return NULL;
825}
826
827 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100828null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829{
830 return NULL;
831}
832
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200833 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100834null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100835{
836 return 0;
837}
838
Bram Moolenaar0f873732019-12-05 20:28:46 +0100839#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840
Bram Moolenaar0f873732019-12-05 20:28:46 +0100841// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000842
843#ifndef VER_PLATFORM_WIN32_WINDOWS
844# define VER_PLATFORM_WIN32_WINDOWS 1
845#endif
846
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100848# ifndef PROTO
849# include <aclapi.h>
850# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200851# ifndef PROTECTED_DACL_SECURITY_INFORMATION
852# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
853# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854#endif
855
Bram Moolenaar27515922013-06-29 15:36:26 +0200856#ifdef HAVE_ACL
857/*
858 * Enables or disables the specified privilege.
859 */
860 static BOOL
861win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
862{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100863 BOOL bResult;
864 LUID luid;
865 HANDLE hToken;
866 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200867
868 if (!OpenProcessToken(GetCurrentProcess(),
869 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
870 return FALSE;
871
872 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
873 {
874 CloseHandle(hToken);
875 return FALSE;
876 }
877
Bram Moolenaar45500912014-07-09 20:51:07 +0200878 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200879 tokenPrivileges.Privileges[0].Luid = luid;
880 tokenPrivileges.Privileges[0].Attributes = bEnable ?
881 SE_PRIVILEGE_ENABLED : 0;
882
883 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
884 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
885
886 CloseHandle(hToken);
887
888 return bResult && GetLastError() == ERROR_SUCCESS;
889}
890#endif
891
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100892#ifdef _MSC_VER
893// Suppress the deprecation warning for using GetVersionEx().
894// It is needed for implementing "windowsversion()".
895# pragma warning(push)
896# pragma warning(disable: 4996)
897#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200899 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900 */
901 void
902PlatformId(void)
903{
904 static int done = FALSE;
905
906 if (!done)
907 {
908 OSVERSIONINFO ovi;
909
910 ovi.dwOSVersionInfoSize = sizeof(ovi);
911 GetVersionEx(&ovi);
912
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200913#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100914 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
915 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200916#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100917 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
918 || ovi.dwMajorVersion > 6)
919 win8_or_later = TRUE;
920
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100922 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200923 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924#endif
925 done = TRUE;
926 }
927}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100928#ifdef _MSC_VER
929# pragma warning(pop)
930#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200932#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100934# define SHIFT (SHIFT_PRESSED)
935# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
936# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
937# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938
939
Bram Moolenaar0f873732019-12-05 20:28:46 +0100940// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
941// We map function keys to their ANSI terminal equivalents, as produced
942// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
943// ANSI key with a value >= '\300' is nonstandard, but provided anyway
944// so that the user can have access to all SHIFT-, CTRL-, and ALT-
945// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000947static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948{
949 WORD wVirtKey;
950 BOOL fAnsiKey;
951 int chAlone;
952 int chShift;
953 int chCtrl;
954 int chAlt;
955} VirtKeyMap[] =
956{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200957// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
959
960 { VK_F1, TRUE, ';', 'T', '^', 'h', },
961 { VK_F2, TRUE, '<', 'U', '_', 'i', },
962 { VK_F3, TRUE, '=', 'V', '`', 'j', },
963 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
964 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
965 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
966 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
967 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
968 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
969 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200970 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
971 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200973 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
974 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
975 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
976 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
977 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
978 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
979 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
980 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
981 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
982 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100983 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000984
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200985 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100987# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200988 // Most people don't have F13-F20, but what the hell...
989 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
990 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
991 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
992 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
993 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
994 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
995 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
996 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100997# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200998 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
999 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1000 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1001 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001003 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1004 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1005 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1006 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1007 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1008 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1009 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1010 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1011 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1012 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001013 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014};
1015
1016
Bram Moolenaar0f873732019-12-05 20:28:46 +01001017/*
1018 * The return code indicates key code size.
1019 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001022 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023{
1024 UINT uMods = pker->dwControlKeyState;
1025 static int s_iIsDead = 0;
1026 static WORD awAnsiCode[2];
1027 static BYTE abKeystate[256];
1028
1029
1030 if (s_iIsDead == 2)
1031 {
K.Takata972db232022-02-04 10:45:38 +00001032 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033 s_iIsDead = 0;
1034 return 1;
1035 }
1036
K.Takata972db232022-02-04 10:45:38 +00001037 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038 return 1;
1039
Bram Moolenaara80faa82020-04-12 19:37:17 +02001040 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041
Bram Moolenaar0f873732019-12-05 20:28:46 +01001042 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001043 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044
1045 if (uMods & SHIFT_PRESSED)
1046 abKeystate[VK_SHIFT] = 0x80;
1047 if (uMods & CAPSLOCK_ON)
1048 abKeystate[VK_CAPITAL] = 1;
1049
1050 if ((uMods & ALT_GR) == ALT_GR)
1051 {
1052 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1053 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1054 }
1055
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001056 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1057 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058
1059 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001060 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061
1062 return s_iIsDead;
1063}
1064
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065static BOOL g_fJustGotFocus = FALSE;
1066
1067/*
1068 * Decode a KEY_EVENT into one or two keystrokes
1069 */
1070 static BOOL
1071decode_key_event(
1072 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001073 WCHAR *pch,
1074 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001076 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077{
1078 int i;
1079 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1080
1081 *pch = *pch2 = NUL;
1082 g_fJustGotFocus = FALSE;
1083
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 if (!pker->bKeyDown)
1086 return FALSE;
1087
Bram Moolenaar0f873732019-12-05 20:28:46 +01001088 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001089 switch (pker->wVirtualKeyCode)
1090 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001091 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 case VK_SHIFT:
1093 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001094 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095 return FALSE;
1096
1097 default:
1098 break;
1099 }
1100
Bram Moolenaar0f873732019-12-05 20:28:46 +01001101 // special cases
K.Takata972db232022-02-04 10:45:38 +00001102 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1103 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001105 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 if (pker->wVirtualKeyCode == '6')
1107 {
1108 *pch = Ctrl_HAT;
1109 return TRUE;
1110 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001111 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112 else if (pker->wVirtualKeyCode == '2')
1113 {
1114 *pch = NUL;
1115 return TRUE;
1116 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001117 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 else if (pker->wVirtualKeyCode == 0xBD)
1119 {
1120 *pch = Ctrl__;
1121 return TRUE;
1122 }
1123 }
1124
Bram Moolenaar0f873732019-12-05 20:28:46 +01001125 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1127 {
1128 *pch = K_NUL;
1129 *pch2 = '\017';
1130 return TRUE;
1131 }
1132
K.Takataeeec2542021-06-02 13:28:16 +02001133 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134 {
1135 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1136 {
1137 if (nModifs == 0)
1138 *pch = VirtKeyMap[i].chAlone;
1139 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1140 *pch = VirtKeyMap[i].chShift;
1141 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1142 *pch = VirtKeyMap[i].chCtrl;
1143 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1144 *pch = VirtKeyMap[i].chAlt;
1145
1146 if (*pch != 0)
1147 {
1148 if (VirtKeyMap[i].fAnsiKey)
1149 {
1150 *pch2 = *pch;
1151 *pch = K_NUL;
1152 }
1153
1154 return TRUE;
1155 }
1156 }
1157 }
1158
1159 i = win32_kbd_patch_key(pker);
1160
1161 if (i < 0)
1162 *pch = NUL;
1163 else
1164 {
K.Takata972db232022-02-04 10:45:38 +00001165 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166
1167 if (pmodifiers != NULL)
1168 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001169 // Pass on the ALT key as a modifier, but only when not combined
1170 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1172 *pmodifiers |= MOD_MASK_ALT;
1173
Bram Moolenaar0f873732019-12-05 20:28:46 +01001174 // Pass on SHIFT only for special keys, because we don't know when
1175 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001176 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1177 *pmodifiers |= MOD_MASK_SHIFT;
1178
Bram Moolenaar0f873732019-12-05 20:28:46 +01001179 // Pass on CTRL only for non-special keys, because we don't know
1180 // when it's already included with the character. And not when
1181 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001182 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1183 && *pch >= 0x20 && *pch < 0x80)
1184 *pmodifiers |= MOD_MASK_CTRL;
1185 }
1186 }
1187
1188 return (*pch != NUL);
1189}
1190
Bram Moolenaar0f873732019-12-05 20:28:46 +01001191#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192
1193
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194/*
1195 * For the GUI the mouse handling is in gui_w32.c.
1196 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001197#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001199mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200{
1201}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001202#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001203static int g_fMouseAvail = FALSE; // mouse present
1204static int g_fMouseActive = FALSE; // mouse enabled
1205static int g_nMouseClick = -1; // mouse status
1206static int g_xMouse; // mouse x coordinate
1207static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001208static DWORD g_cmodein = 0; // Original console input mode
1209static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210
1211/*
1212 * Enable or disable mouse input
1213 */
1214 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001215mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216{
1217 DWORD cmodein;
1218
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001219# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001220 if (gui.in_use)
1221 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001222# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223 if (!g_fMouseAvail)
1224 return;
1225
1226 g_fMouseActive = on;
1227 GetConsoleMode(g_hConIn, &cmodein);
1228
1229 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001230 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001232 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1233 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001235 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001237 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1238 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001239
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001240 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241}
1242
Bram Moolenaar157d8132018-03-06 17:09:20 +01001243
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001244# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001245/*
1246 * Called when 'balloonevalterm' changed.
1247 */
1248 void
1249mch_bevalterm_changed(void)
1250{
1251 mch_setmouse(g_fMouseActive);
1252}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001253# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001254
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255/*
1256 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1257 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1258 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1259 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1260 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1261 * and we return the mouse position in g_xMouse and g_yMouse.
1262 *
1263 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1264 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1265 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1266 *
1267 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1268 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1269 *
1270 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1271 * moves, even if it stays within the same character cell. We ignore
1272 * all MOUSE_MOVED messages if the position hasn't really changed, and
1273 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1274 * we're only interested in MOUSE_DRAG).
1275 *
1276 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1277 * 2-button mouses by pressing the left & right buttons simultaneously.
1278 * In practice, it's almost impossible to click both at the same time,
1279 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1280 * in such cases, if the user is clicking quickly.
1281 */
1282 static BOOL
1283decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001284 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285{
1286 static int s_nOldButton = -1;
1287 static int s_nOldMouseClick = -1;
1288 static int s_xOldMouse = -1;
1289 static int s_yOldMouse = -1;
1290 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001291# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001293# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294 static int s_cClicks = 1;
1295 static BOOL s_fReleased = TRUE;
1296 static DWORD s_dwLastClickTime = 0;
1297 static BOOL s_fNextIsMiddle = FALSE;
1298
Bram Moolenaar0f873732019-12-05 20:28:46 +01001299 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001300
1301 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1302 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1303 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1304 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1305
1306 int nButton;
1307
1308 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1309 cButtons = 2;
1310
1311 if (!g_fMouseAvail || !g_fMouseActive)
1312 {
1313 g_nMouseClick = -1;
1314 return FALSE;
1315 }
1316
Bram Moolenaar0f873732019-12-05 20:28:46 +01001317 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318 if (g_fJustGotFocus)
1319 {
1320 g_fJustGotFocus = FALSE;
1321 return FALSE;
1322 }
1323
Bram Moolenaar0f873732019-12-05 20:28:46 +01001324 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325 if (g_nMouseClick != -1)
1326 return TRUE;
1327
1328 nButton = -1;
1329 g_xMouse = pmer->dwMousePosition.X;
1330 g_yMouse = pmer->dwMousePosition.Y;
1331
1332 if (pmer->dwEventFlags == MOUSE_MOVED)
1333 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001334 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1335 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001336 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1337 return FALSE;
1338 }
1339
Bram Moolenaar0f873732019-12-05 20:28:46 +01001340 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1342 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001343 nButton = MOUSE_RELEASE;
1344
Bram Moolenaar0f873732019-12-05 20:28:46 +01001345 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001346 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001347 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001348# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001349 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001350 if (p_bevalterm)
1351 nButton = MOUSE_DRAG;
1352 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001353# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001354 return FALSE;
1355 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356
Bram Moolenaar071d4272004-06-13 20:20:40 +00001357 s_fReleased = TRUE;
1358 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001359 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001360 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001361 // on a 2-button mouse, hold down left and right buttons
1362 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001363
1364 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1365 {
1366 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1367
Bram Moolenaar0f873732019-12-05 20:28:46 +01001368 // if either left or right button only is pressed, see if the
1369 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370 if (dwLR == LEFT || dwLR == RIGHT)
1371 {
1372 for (;;)
1373 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001374 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001375 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1376 != WAIT_OBJECT_0)
1377 break;
1378 else
1379 {
1380 DWORD cRecords = 0;
1381 INPUT_RECORD ir;
1382 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1383
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001384 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001385
1386 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1387 || !(pmer2->dwButtonState & LEFT_RIGHT))
1388 break;
1389 else
1390 {
1391 if (pmer2->dwEventFlags != MOUSE_MOVED)
1392 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001393 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001394
1395 return decode_mouse_event(pmer2);
1396 }
1397 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1398 s_yOldMouse == pmer2->dwMousePosition.Y)
1399 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001400 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001401 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402
Bram Moolenaar0f873732019-12-05 20:28:46 +01001403 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001404 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405
1406 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1407 break;
1408 }
1409 else
1410 break;
1411 }
1412 }
1413 }
1414 }
1415 }
1416
1417 if (s_fNextIsMiddle)
1418 {
1419 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1420 ? MOUSE_DRAG : MOUSE_MIDDLE;
1421 s_fNextIsMiddle = FALSE;
1422 }
1423 else if (cButtons == 2 &&
1424 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1425 {
1426 nButton = MOUSE_MIDDLE;
1427
1428 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1429 {
1430 s_fNextIsMiddle = TRUE;
1431 nButton = MOUSE_RELEASE;
1432 }
1433 }
1434 else if ((pmer->dwButtonState & LEFT) == LEFT)
1435 nButton = MOUSE_LEFT;
1436 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1437 nButton = MOUSE_MIDDLE;
1438 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1439 nButton = MOUSE_RIGHT;
1440
1441 if (! s_fReleased && ! s_fNextIsMiddle
1442 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1443 return FALSE;
1444
1445 s_fReleased = s_fNextIsMiddle;
1446 }
1447
1448 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1449 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001450 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451 if (nButton != -1 && nButton != MOUSE_RELEASE)
1452 {
1453 DWORD dwCurrentTime = GetTickCount();
1454
1455 if (s_xOldMouse != g_xMouse
1456 || s_yOldMouse != g_yMouse
1457 || s_nOldButton != nButton
1458 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001459# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001461# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1463 {
1464 s_cClicks = 1;
1465 }
1466 else if (++s_cClicks > 4)
1467 {
1468 s_cClicks = 1;
1469 }
1470
1471 s_dwLastClickTime = dwCurrentTime;
1472 }
1473 }
1474 else if (pmer->dwEventFlags == MOUSE_MOVED)
1475 {
1476 if (nButton != -1 && nButton != MOUSE_RELEASE)
1477 nButton = MOUSE_DRAG;
1478
1479 s_cClicks = 1;
1480 }
1481
1482 if (nButton == -1)
1483 return FALSE;
1484
1485 if (nButton != MOUSE_RELEASE)
1486 s_nOldButton = nButton;
1487
1488 g_nMouseClick = nButton;
1489
1490 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1491 g_nMouseClick |= MOUSE_SHIFT;
1492 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1493 g_nMouseClick |= MOUSE_CTRL;
1494 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1495 g_nMouseClick |= MOUSE_ALT;
1496
1497 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1498 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1499
Bram Moolenaar0f873732019-12-05 20:28:46 +01001500 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501 if (s_xOldMouse == g_xMouse
1502 && s_yOldMouse == g_yMouse
1503 && s_nOldMouseClick == g_nMouseClick)
1504 {
1505 g_nMouseClick = -1;
1506 return FALSE;
1507 }
1508
1509 s_xOldMouse = g_xMouse;
1510 s_yOldMouse = g_yMouse;
1511 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001512# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515 s_nOldMouseClick = g_nMouseClick;
1516
1517 return TRUE;
1518}
1519
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001520#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521
1522
1523#ifdef MCH_CURSOR_SHAPE
1524/*
1525 * Set the shape of the cursor.
1526 * 'thickness' can be from 1 (thin) to 99 (block)
1527 */
1528 static void
1529mch_set_cursor_shape(int thickness)
1530{
1531 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1532 ConsoleCursorInfo.dwSize = thickness;
1533 ConsoleCursorInfo.bVisible = s_cursor_visible;
1534
1535 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1536 if (s_cursor_visible)
1537 SetConsoleCursorPosition(g_hConOut, g_coord);
1538}
1539
1540 void
1541mch_update_cursor(void)
1542{
1543 int idx;
1544 int thickness;
1545
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001546# ifdef VIMDLL
1547 if (gui.in_use)
1548 return;
1549# endif
1550
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551 /*
1552 * How the cursor is drawn depends on the current mode.
1553 */
1554 idx = get_shape_idx(FALSE);
1555
1556 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001557 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558 else
1559 thickness = shape_table[idx].percentage;
1560 mch_set_cursor_shape(thickness);
1561}
1562#endif
1563
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001564#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565/*
1566 * Handle FOCUS_EVENT.
1567 */
1568 static void
1569handle_focus_event(INPUT_RECORD ir)
1570{
1571 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1572 ui_focus_change((int)g_fJustGotFocus);
1573}
1574
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001575static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1576
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577/*
1578 * Wait until console input from keyboard or mouse is available,
1579 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001580 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581 * Return TRUE if something is available FALSE if not.
1582 */
1583 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001584WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585{
1586 DWORD dwNow = 0, dwEndTime = 0;
1587 INPUT_RECORD ir;
1588 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001589 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001590# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001591 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001592# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593
1594 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001595 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596 dwEndTime = GetTickCount() + msec;
1597 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001598 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 dwEndTime = INFINITE;
1600
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001601 // We need to loop until the end of the time period, because
1602 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 for (;;)
1604 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001605 // Only process messages when waiting.
1606 if (msec != 0)
1607 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001608# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001609 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001610# endif
1611# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001612 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001613# endif
1614# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001615 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001616# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001617 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001618
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001619 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001620# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001621 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001622# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623 )
1624 return TRUE;
1625
1626 if (msec > 0)
1627 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001628 // If the specified wait time has passed, return. Beware that
1629 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001631 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001632 break;
1633 }
1634 if (msec != 0)
1635 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001636 DWORD dwWaitTime = dwEndTime - dwNow;
1637
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001638 // Don't wait for more than 11 msec to avoid dropping characters,
1639 // check channel while waiting for input and handle a callback from
1640 // 'balloonexpr'.
1641 if (dwWaitTime > 11)
1642 dwWaitTime = 11;
1643
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001644# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001645 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001646 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001647# endif
1648# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001649 // When waiting very briefly don't trigger timers.
1650 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001651 {
1652 long due_time;
1653
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001654 // Trigger timers and then get the time in msec until the next
1655 // one is due. Wait up to that time.
1656 due_time = check_due_timer();
1657 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001658 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001659 // timer may have used feedkeys().
1660 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001661 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001662 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1663 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001664 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001665# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001666 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001667# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001668 // Wait for either an event on the console input or a
1669 // message in the client-server window.
1670 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1671 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001672# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001673 wait_for_single_object(g_hConIn, dwWaitTime)
1674 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001675# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001676 )
1677 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678 }
1679
1680 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001681 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001683# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001684 // May have to redraw if the cursor ends up in the wrong place.
1685 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001686 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687 {
1688 CONSOLE_SCREEN_BUFFER_INFO csbi;
1689
1690 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1691 {
1692 if (csbi.dwCursorPosition.Y != msg_row)
1693 {
matveyte08795e2021-05-07 15:00:17 +02001694 // The screen is now messed up, must redraw the command
1695 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001696 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001697 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698 redrawcmd();
1699 }
1700 }
1701 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001702# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001703
1704 if (cRecords > 0)
1705 {
1706 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1707 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001708# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001709 // Windows IME sends two '\n's with only one 'ENTER'. First:
1710 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001711 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1713 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001714 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715 continue;
1716 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1719 NULL, FALSE))
1720 return TRUE;
1721 }
1722
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001723 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724
1725 if (ir.EventType == FOCUS_EVENT)
1726 handle_focus_event(ir);
1727 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001728 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001729 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1730
Bram Moolenaar36698e32019-12-11 22:57:40 +01001731 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001732 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001733 if (dwSize.X != Columns || dwSize.Y != Rows)
1734 {
1735 CONSOLE_SCREEN_BUFFER_INFO csbi;
1736 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001737 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001738 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001739 if (dwSize.X != Columns || dwSize.Y != Rows)
1740 {
1741 ResizeConBuf(g_hConOut, dwSize);
1742 shell_resized();
1743 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001744 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 else if (ir.EventType == MOUSE_EVENT
1747 && decode_mouse_event(&ir.Event.MouseEvent))
1748 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 }
1750 else if (msec == 0)
1751 break;
1752 }
1753
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001754# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001755 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756 if (input_available())
1757 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001758# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001759
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 return FALSE;
1761}
1762
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763/*
1764 * return non-zero if a character is available
1765 */
1766 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001767mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001769# ifdef VIMDLL
1770 if (gui.in_use)
1771 return TRUE;
1772# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001773 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001774}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001775
1776# if defined(FEAT_TERMINAL) || defined(PROTO)
1777/*
1778 * Check for any pending input or messages.
1779 */
1780 int
1781mch_check_messages(void)
1782{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001783# ifdef VIMDLL
1784 if (gui.in_use)
1785 return TRUE;
1786# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001787 return WaitForChar(0L, TRUE);
1788}
1789# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001790
1791/*
1792 * Create the console input. Used when reading stdin doesn't work.
1793 */
1794 static void
1795create_conin(void)
1796{
1797 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1798 FILE_SHARE_READ|FILE_SHARE_WRITE,
1799 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001800 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 did_create_conin = TRUE;
1802}
1803
1804/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001805 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001807 static WCHAR
1808tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001810 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811
1812 for (;;)
1813 {
1814 INPUT_RECORD ir;
1815 DWORD cRecords = 0;
1816
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001817# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001818 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 if (input_available())
1820 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 if (g_nMouseClick != -1)
1822 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001823# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001824 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 {
1826 if (did_create_conin)
1827 read_error_exit();
1828 create_conin();
1829 continue;
1830 }
1831
1832 if (ir.EventType == KEY_EVENT)
1833 {
1834 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1835 pmodifiers, TRUE))
1836 return ch;
1837 }
1838 else if (ir.EventType == FOCUS_EVENT)
1839 handle_focus_event(ir);
1840 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1841 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001842 else if (ir.EventType == MOUSE_EVENT)
1843 {
1844 if (decode_mouse_event(&ir.Event.MouseEvent))
1845 return 0;
1846 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 }
1848}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001849#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850
1851
1852/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001853 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 * Get one or more characters from the keyboard or the mouse.
1855 * If time == 0, do not wait for characters.
1856 * If time == n, wait a short time for characters.
1857 * If time == -1, wait forever for characters.
1858 * Returns the number of characters read into buf.
1859 */
1860 int
1861mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001862 char_u *buf UNUSED,
1863 int maxlen UNUSED,
1864 long time UNUSED,
1865 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001866{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001867#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868
1869 int len;
1870 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001871# ifdef VIMDLL
1872// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1873# define TYPEAHEADSPACE 6
1874# else
1875# define TYPEAHEADSPACE 0
1876# endif
1877# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001878 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 static int typeaheadlen = 0;
1880
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001881# ifdef VIMDLL
1882 if (gui.in_use)
1883 return 0;
1884# endif
1885
Bram Moolenaar0f873732019-12-05 20:28:46 +01001886 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 if (typeaheadlen > 0)
1888 goto theend;
1889
Bram Moolenaar071d4272004-06-13 20:20:40 +00001890 if (time >= 0)
1891 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001892 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001895 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001896 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001897 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001898
Bram Moolenaar3918c952005-03-15 22:34:55 +00001899 /*
1900 * If there is no character available within 2 seconds (default)
1901 * write the autoscript file to disk. Or cause the CursorHold event
1902 * to be triggered.
1903 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001904 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001906 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001908 buf[0] = K_SPECIAL;
1909 buf[1] = KS_EXTRA;
1910 buf[2] = (int)KE_CURSORHOLD;
1911 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001913 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914 }
1915 }
1916
1917 /*
1918 * Try to read as many characters as there are, until the buffer is full.
1919 */
1920
Bram Moolenaar0f873732019-12-05 20:28:46 +01001921 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 g_fCBrkPressed = FALSE;
1923
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001924# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925 if (fdDump)
1926 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001927# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928
Bram Moolenaar0f873732019-12-05 20:28:46 +01001929 // Keep looping until there is something in the typeahead buffer and more
1930 // to get and still room in the buffer (up to two bytes for a char and
1931 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001932 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001933 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934 {
1935 if (typebuf_changed(tb_change_cnt))
1936 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001937 // "buf" may be invalid now if a client put something in the
1938 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 typeaheadlen = 0;
1940 break;
1941 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 if (g_nMouseClick != -1)
1943 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001944# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 if (fdDump)
1946 fprintf(fdDump, "{%02x @ %d, %d}",
1947 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001948# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 typeahead[typeaheadlen++] = ESC + 128;
1950 typeahead[typeaheadlen++] = 'M';
1951 typeahead[typeaheadlen++] = g_nMouseClick;
1952 typeahead[typeaheadlen++] = g_xMouse + '!';
1953 typeahead[typeaheadlen++] = g_yMouse + '!';
1954 g_nMouseClick = -1;
1955 }
1956 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001958 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959 int modifiers = 0;
1960
1961 c = tgetch(&modifiers, &ch2);
1962
1963 if (typebuf_changed(tb_change_cnt))
1964 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001965 // "buf" may be invalid now if a client put something in the
1966 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967 typeaheadlen = 0;
1968 break;
1969 }
1970
1971 if (c == Ctrl_C && ctrl_c_interrupts)
1972 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001973# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001975# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 got_int = TRUE;
1977 }
1978
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980 {
1981 int n = 1;
1982
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001983 if (ch2 == NUL)
1984 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001985 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001986 char_u *p;
1987 WCHAR ch[2];
1988
1989 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001990 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001991 {
1992 ch[1] = tgetch(&modifiers, &ch2);
1993 n++;
1994 }
1995 p = utf16_to_enc(ch, &n);
1996 if (p != NULL)
1997 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001998 for (i = 0, j = 0; i < n; i++)
1999 {
2000 typeahead[typeaheadlen + j++] = p[i];
2001# ifdef VIMDLL
2002 if (p[i] == CSI)
2003 {
2004 typeahead[typeaheadlen + j++] = KS_EXTRA;
2005 typeahead[typeaheadlen + j++] = KE_CSI;
2006 }
2007# endif
2008 }
2009 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002010 vim_free(p);
2011 }
2012 }
2013 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002014 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002015 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002016# ifdef VIMDLL
2017 if (c == CSI)
2018 {
2019 typeahead[typeaheadlen + 1] = KS_EXTRA;
2020 typeahead[typeaheadlen + 2] = KE_CSI;
2021 n = 3;
2022 }
2023# endif
2024 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 if (ch2 != NUL)
2026 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002027 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002028 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002029 switch (ch2)
2030 {
2031 case (WCHAR)'\324': // SHIFT+Insert
2032 case (WCHAR)'\325': // CTRL+Insert
2033 case (WCHAR)'\327': // SHIFT+Delete
2034 case (WCHAR)'\330': // CTRL+Delete
2035 typeahead[typeaheadlen + n] = (char_u)ch2;
2036 n++;
2037 break;
2038
2039 default:
2040 typeahead[typeaheadlen + n] = 3;
2041 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2042 n += 2;
2043 break;
2044 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002045 }
2046 else
2047 {
2048 typeahead[typeaheadlen + n] = 3;
2049 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2050 n += 2;
2051 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002052 }
2053
Bram Moolenaar0f873732019-12-05 20:28:46 +01002054 // Use the ALT key to set the 8th bit of the character
2055 // when it's one byte, the 8th bit isn't set yet and not
2056 // using a double-byte encoding (would become a lead
2057 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 if ((modifiers & MOD_MASK_ALT)
2059 && n == 1
2060 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 )
2063 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002064 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2065 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 modifiers &= ~MOD_MASK_ALT;
2067 }
2068
2069 if (modifiers != 0)
2070 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002071 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 mch_memmove(typeahead + typeaheadlen + 3,
2073 typeahead + typeaheadlen, n);
2074 typeahead[typeaheadlen++] = K_SPECIAL;
2075 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2076 typeahead[typeaheadlen++] = modifiers;
2077 }
2078
2079 typeaheadlen += n;
2080
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002081# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082 if (fdDump)
2083 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002084# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002085 }
2086 }
2087 }
2088
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002089# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 if (fdDump)
2091 {
2092 fputs("]\n", fdDump);
2093 fflush(fdDump);
2094 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002095# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002098 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 len = 0;
2100 while (len < maxlen && typeaheadlen > 0)
2101 {
2102 buf[len++] = typeahead[0];
2103 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2104 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002105# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002106 if (len > 0)
2107 {
2108 buf[len] = NUL;
2109 ch_log(NULL, "raw key input: \"%s\"", buf);
2110 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002111# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 return len;
2113
Bram Moolenaar0f873732019-12-05 20:28:46 +01002114#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002116#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117}
2118
Bram Moolenaar82881492012-11-20 16:53:39 +01002119#ifndef PROTO
2120# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002121# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002122# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002123#endif
2124
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002125/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002126 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002127 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2128 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002129 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002130 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002132executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133{
LemonBoy40fd7e62022-05-05 20:18:16 +01002134 int attrs = win32_getattrs((char_u *)name);
2135
2136 // The file doesn't exist or is a folder.
2137 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2138 return FALSE;
2139 // Check if the file is an AppExecLink, a special alias used by Windows
2140 // Store for its apps.
2141 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002142 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002143 char_u *res = resolve_appexeclink((char_u *)name);
2144 if (res == NULL)
2145 return FALSE;
2146 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002147 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002148 *path = res;
2149 else
2150 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002151 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002152 else if (path != NULL)
2153 *path = FullName_save((char_u *)name, FALSE);
2154 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002155}
2156
2157/*
2158 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2159 * If "use_path" is FALSE: Return TRUE if "name" exists.
2160 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2161 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2162 * the allocated memory.
2163 */
2164 static int
2165executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2166{
2167 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2168 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2169 // UTF-8.
2170 char_u buf[_MAX_PATH * 3];
2171 size_t len = STRLEN(name);
2172 size_t tmplen;
2173 char_u *p, *e, *e2;
2174 char_u *pathbuf = NULL;
2175 char_u *pathext = NULL;
2176 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002177 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002178 int noext = FALSE;
2179 int retval = FALSE;
2180
2181 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002182 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002183
2184 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002185 shname = gettail(p_sh);
2186 if (strstr((char *)shname, "sh") != NULL &&
2187 !(strstr((char *)shname, "powershell") != NULL
2188 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002189 noext = TRUE;
2190
2191 if (use_pathext)
2192 {
2193 pathext = mch_getenv("PATHEXT");
2194 if (pathext == NULL)
2195 pathext = (char_u *)".com;.exe;.bat;.cmd";
2196
2197 if (noext == FALSE)
2198 {
2199 /*
2200 * Loop over all extensions in $PATHEXT.
2201 * Check "name" ends with extension.
2202 */
2203 p = pathext;
2204 while (*p)
2205 {
2206 if (p[0] == ';'
2207 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2208 {
2209 // Skip empty or single ".".
2210 ++p;
2211 continue;
2212 }
2213 e = vim_strchr(p, ';');
2214 if (e == NULL)
2215 e = p + STRLEN(p);
2216 tmplen = e - p;
2217
2218 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2219 {
2220 noext = TRUE;
2221 break;
2222 }
2223
2224 p = e;
2225 }
2226 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002227 }
2228
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002229 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002230 if (pathext == NULL)
2231 pathext = (char_u *)".";
2232 else if (noext == TRUE)
2233 {
2234 if (pathextbuf == NULL)
2235 pathextbuf = alloc(STRLEN(pathext) + 3);
2236 if (pathextbuf == NULL)
2237 {
2238 retval = FALSE;
2239 goto theend;
2240 }
2241 STRCPY(pathextbuf, ".;");
2242 STRCAT(pathextbuf, pathext);
2243 pathext = pathextbuf;
2244 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002245
Bram Moolenaar95da1362020-05-30 18:37:55 +02002246 // Use $PATH when "use_path" is TRUE and "name" is basename.
2247 if (use_path && gettail((char_u *)name) == (char_u *)name)
2248 {
2249 p = mch_getenv("PATH");
2250 if (p != NULL)
2251 {
2252 pathbuf = alloc(STRLEN(p) + 3);
2253 if (pathbuf == NULL)
2254 {
2255 retval = FALSE;
2256 goto theend;
2257 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002258
2259 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2260 STRCPY(pathbuf, ".;");
2261 else
2262 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002263 STRCAT(pathbuf, p);
2264 }
2265 }
2266
2267 /*
2268 * Walk through all entries in $PATH to check if "name" exists there and
2269 * is an executable file.
2270 */
2271 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2272 while (*p)
2273 {
2274 if (*p == ';') // Skip empty entry
2275 {
2276 ++p;
2277 continue;
2278 }
2279 e = vim_strchr(p, ';');
2280 if (e == NULL)
2281 e = p + STRLEN(p);
2282
2283 if (e - p + len + 2 > sizeof(buf))
2284 {
2285 retval = FALSE;
2286 goto theend;
2287 }
2288 // A single "." that means current dir.
2289 if (e - p == 1 && *p == '.')
2290 STRCPY(buf, name);
2291 else
2292 {
2293 vim_strncpy(buf, p, e - p);
2294 add_pathsep(buf);
2295 STRCAT(buf, name);
2296 }
2297 tmplen = STRLEN(buf);
2298
2299 /*
2300 * Loop over all extensions in $PATHEXT.
2301 * Check "name" with extension added.
2302 */
2303 p = pathext;
2304 while (*p)
2305 {
2306 if (*p == ';')
2307 {
2308 // Skip empty entry
2309 ++p;
2310 continue;
2311 }
2312 e2 = vim_strchr(p, (int)';');
2313 if (e2 == NULL)
2314 e2 = p + STRLEN(p);
2315
2316 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2317 {
2318 // Not a single "." that means no extension is added.
2319 if (e2 - p + tmplen + 1 > sizeof(buf))
2320 {
2321 retval = FALSE;
2322 goto theend;
2323 }
2324 vim_strncpy(buf + tmplen, p, e2 - p);
2325 }
2326 if (executable_file((char *)buf, path))
2327 {
2328 retval = TRUE;
2329 goto theend;
2330 }
2331
2332 p = e2;
2333 }
2334
2335 p = e;
2336 }
2337
2338theend:
2339 free(pathextbuf);
2340 free(pathbuf);
2341 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002342}
2343
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002344#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2345 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002346/*
2347 * Bad parameter handler.
2348 *
2349 * Certain MS CRT functions will intentionally crash when passed invalid
2350 * parameters to highlight possible security holes. Setting this function as
2351 * the bad parameter handler will prevent the crash.
2352 *
2353 * In debug builds the parameters contain CRT information that might help track
2354 * down the source of a problem, but in non-debug builds the arguments are all
2355 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2356 * worth allowing these to make debugging of issues easier.
2357 */
2358 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002359bad_param_handler(const wchar_t *expression UNUSED,
2360 const wchar_t *function UNUSED,
2361 const wchar_t *file UNUSED,
2362 unsigned int line UNUSED,
2363 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002364{
2365}
2366
2367# define SET_INVALID_PARAM_HANDLER \
2368 ((void)_set_invalid_parameter_handler(bad_param_handler))
2369#else
2370# define SET_INVALID_PARAM_HANDLER
2371#endif
2372
Bram Moolenaar4f974752019-02-17 17:44:42 +01002373#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374
2375/*
2376 * GUI version of mch_init().
2377 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002378 static void
2379mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002381# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002383# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384
Bram Moolenaar0f873732019-12-05 20:28:46 +01002385 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002386 SET_INVALID_PARAM_HANDLER;
2387
Bram Moolenaar0f873732019-12-05 20:28:46 +01002388 // Let critical errors result in a failure, not in a dialog box. Required
2389 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390 SetErrorMode(SEM_FAILCRITICALERRORS);
2391
Bram Moolenaar0f873732019-12-05 20:28:46 +01002392 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393
Bram Moolenaar0f873732019-12-05 20:28:46 +01002394 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395 Rows = 25;
2396 Columns = 80;
2397
Bram Moolenaar0f873732019-12-05 20:28:46 +01002398 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 {
2400 char_u vimrun_location[_MAX_PATH + 4];
2401
Bram Moolenaar0f873732019-12-05 20:28:46 +01002402 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002403 STRCPY(vimrun_location, exe_name);
2404 STRCPY(gettail(vimrun_location), "vimrun.exe");
2405 if (mch_getperm(vimrun_location) >= 0)
2406 {
2407 if (*skiptowhite(vimrun_location) != NUL)
2408 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002409 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002410 mch_memmove(vimrun_location + 1, vimrun_location,
2411 STRLEN(vimrun_location) + 1);
2412 *vimrun_location = '"';
2413 STRCPY(gettail(vimrun_location), "vimrun\" ");
2414 }
2415 else
2416 STRCPY(gettail(vimrun_location), "vimrun ");
2417
2418 vimrun_path = (char *)vim_strsave(vimrun_location);
2419 s_dont_use_vimrun = FALSE;
2420 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002421 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 s_dont_use_vimrun = FALSE;
2423
Bram Moolenaar0f873732019-12-05 20:28:46 +01002424 // Don't give the warning for a missing vimrun.exe right now, but only
2425 // when vimrun was supposed to be used. Don't bother people that do
2426 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427 if (s_dont_use_vimrun)
2428 need_vimrun_warning = TRUE;
2429 }
2430
2431 /*
2432 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2433 * Otherwise the default "findstr /n" is used.
2434 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002435 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002436 set_option_value_give_err((char_u *)"grepprg",
2437 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002439# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002440 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002441# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002442
2443 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444}
2445
2446
Bram Moolenaar0f873732019-12-05 20:28:46 +01002447#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002448
2449#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002451# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2452# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453
2454/*
2455 * ClearConsoleBuffer()
2456 * Description:
2457 * Clears the entire contents of the console screen buffer, using the
2458 * specified attribute.
2459 * Returns:
2460 * TRUE on success
2461 */
2462 static BOOL
2463ClearConsoleBuffer(WORD wAttribute)
2464{
2465 CONSOLE_SCREEN_BUFFER_INFO csbi;
2466 COORD coord;
2467 DWORD NumCells, dummy;
2468
2469 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2470 return FALSE;
2471
2472 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2473 coord.X = 0;
2474 coord.Y = 0;
2475 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2476 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2479 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481
2482 return TRUE;
2483}
2484
2485/*
2486 * FitConsoleWindow()
2487 * Description:
2488 * Checks if the console window will fit within given buffer dimensions.
2489 * Also, if requested, will shrink the window to fit.
2490 * Returns:
2491 * TRUE on success
2492 */
2493 static BOOL
2494FitConsoleWindow(
2495 COORD dwBufferSize,
2496 BOOL WantAdjust)
2497{
2498 CONSOLE_SCREEN_BUFFER_INFO csbi;
2499 COORD dwWindowSize;
2500 BOOL NeedAdjust = FALSE;
2501
2502 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2503 {
2504 /*
2505 * A buffer resize will fail if the current console window does
2506 * not lie completely within that buffer. To avoid this, we might
2507 * have to move and possibly shrink the window.
2508 */
2509 if (csbi.srWindow.Right >= dwBufferSize.X)
2510 {
2511 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2512 if (dwWindowSize.X > dwBufferSize.X)
2513 dwWindowSize.X = dwBufferSize.X;
2514 csbi.srWindow.Right = dwBufferSize.X - 1;
2515 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2516 NeedAdjust = TRUE;
2517 }
2518 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2519 {
2520 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2521 if (dwWindowSize.Y > dwBufferSize.Y)
2522 dwWindowSize.Y = dwBufferSize.Y;
2523 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2524 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2525 NeedAdjust = TRUE;
2526 }
2527 if (NeedAdjust && WantAdjust)
2528 {
2529 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2530 return FALSE;
2531 }
2532 return TRUE;
2533 }
2534
2535 return FALSE;
2536}
2537
2538typedef struct ConsoleBufferStruct
2539{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002540 BOOL IsValid;
2541 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002542 PCHAR_INFO Buffer;
2543 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002544 PSMALL_RECT Regions;
2545 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546} ConsoleBuffer;
2547
2548/*
2549 * SaveConsoleBuffer()
2550 * Description:
2551 * Saves important information about the console buffer, including the
2552 * actual buffer contents. The saved information is suitable for later
2553 * restoration by RestoreConsoleBuffer().
2554 * Returns:
2555 * TRUE if all information was saved; FALSE otherwise
2556 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2557 */
2558 static BOOL
2559SaveConsoleBuffer(
2560 ConsoleBuffer *cb)
2561{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002562 DWORD NumCells;
2563 COORD BufferCoord;
2564 SMALL_RECT ReadRegion;
2565 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002566 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002567
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568 if (cb == NULL)
2569 return FALSE;
2570
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002571 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 {
2573 cb->IsValid = FALSE;
2574 return FALSE;
2575 }
2576 cb->IsValid = TRUE;
2577
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002578 /*
2579 * Allocate a buffer large enough to hold the entire console screen
2580 * buffer. If this ConsoleBuffer structure has already been initialized
2581 * with a buffer of the correct size, then just use that one.
2582 */
2583 if (!cb->IsValid || cb->Buffer == NULL ||
2584 cb->BufferSize.X != cb->Info.dwSize.X ||
2585 cb->BufferSize.Y != cb->Info.dwSize.Y)
2586 {
2587 cb->BufferSize.X = cb->Info.dwSize.X;
2588 cb->BufferSize.Y = cb->Info.dwSize.Y;
2589 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2590 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002591 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002592 if (cb->Buffer == NULL)
2593 return FALSE;
2594 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595
2596 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002597 * We will now copy the console screen buffer into our buffer.
2598 * ReadConsoleOutput() seems to be limited as far as how much you
2599 * can read at a time. Empirically, this number seems to be about
2600 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2601 * in chunks until it is all copied. The chunks will all have the
2602 * same horizontal characteristics, so initialize them now. The
2603 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002605 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002606 ReadRegion.Left = 0;
2607 ReadRegion.Right = cb->Info.dwSize.X - 1;
2608 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002609
2610 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2611 if (cb->Regions == NULL || numregions != cb->NumRegions)
2612 {
2613 cb->NumRegions = numregions;
2614 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002615 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002616 if (cb->Regions == NULL)
2617 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002618 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002619 return FALSE;
2620 }
2621 }
2622
2623 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002625 /*
2626 * Read into position (0, Y) in our buffer.
2627 */
2628 BufferCoord.Y = Y;
2629 /*
2630 * Read the region whose top left corner is (0, Y) and whose bottom
2631 * right corner is (width - 1, Y + Y_incr - 1). This should define
2632 * a region of size width by Y_incr. Don't worry if this region is
2633 * too large for the remaining buffer; it will be cropped.
2634 */
2635 ReadRegion.Top = Y;
2636 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002637 if (!ReadConsoleOutputW(g_hConOut, // output handle
2638 cb->Buffer, // our buffer
2639 cb->BufferSize, // dimensions of our buffer
2640 BufferCoord, // offset in our buffer
2641 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002642 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002643 VIM_CLEAR(cb->Buffer);
2644 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002645 return FALSE;
2646 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002647 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648 }
2649
2650 return TRUE;
2651}
2652
2653/*
2654 * RestoreConsoleBuffer()
2655 * Description:
2656 * Restores important information about the console buffer, including the
2657 * actual buffer contents, if desired. The information to restore is in
2658 * the same format used by SaveConsoleBuffer().
2659 * Returns:
2660 * TRUE on success
2661 */
2662 static BOOL
2663RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002664 ConsoleBuffer *cb,
2665 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002667 COORD BufferCoord;
2668 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002669 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670
2671 if (cb == NULL || !cb->IsValid)
2672 return FALSE;
2673
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002674 /*
2675 * Before restoring the buffer contents, clear the current buffer, and
2676 * restore the cursor position and window information. Doing this now
2677 * prevents old buffer contents from "flashing" onto the screen.
2678 */
2679 if (RestoreScreen)
2680 ClearConsoleBuffer(cb->Info.wAttributes);
2681
2682 FitConsoleWindow(cb->Info.dwSize, TRUE);
2683 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2684 return FALSE;
2685 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2686 return FALSE;
2687
2688 if (!RestoreScreen)
2689 {
2690 /*
2691 * No need to restore the screen buffer contents, so we're done.
2692 */
2693 return TRUE;
2694 }
2695
2696 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2697 return FALSE;
2698 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2699 return FALSE;
2700
2701 /*
2702 * Restore the screen buffer contents.
2703 */
2704 if (cb->Buffer != NULL)
2705 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002706 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002707 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002708 BufferCoord.X = cb->Regions[i].Left;
2709 BufferCoord.Y = cb->Regions[i].Top;
2710 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002711 if (!WriteConsoleOutputW(g_hConOut, // output handle
2712 cb->Buffer, // our buffer
2713 cb->BufferSize, // dimensions of our buffer
2714 BufferCoord, // offset in our buffer
2715 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002716 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002717 }
2718 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719
2720 return TRUE;
2721}
2722
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002723# define FEAT_RESTORE_ORIG_SCREEN
2724# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002725static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002726# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727static ConsoleBuffer g_cbNonTermcap = { 0 };
2728static ConsoleBuffer g_cbTermcap = { 0 };
2729
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002731HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732static HICON g_hOrigIconSmall = NULL;
2733static HICON g_hOrigIcon = NULL;
2734static HICON g_hVimIcon = NULL;
2735static BOOL g_fCanChangeIcon = FALSE;
2736
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737/*
2738 * GetConsoleIcon()
2739 * Description:
2740 * Attempts to retrieve the small icon and/or the big icon currently in
2741 * use by a given window.
2742 * Returns:
2743 * TRUE on success
2744 */
2745 static BOOL
2746GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002747 HWND hWnd,
2748 HICON *phIconSmall,
2749 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750{
2751 if (hWnd == NULL)
2752 return FALSE;
2753
2754 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002755 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2756 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002758 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2759 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002760 return TRUE;
2761}
2762
2763/*
2764 * SetConsoleIcon()
2765 * Description:
2766 * Attempts to change the small icon and/or the big icon currently in
2767 * use by a given window.
2768 * Returns:
2769 * TRUE on success
2770 */
2771 static BOOL
2772SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002773 HWND hWnd,
2774 HICON hIconSmall,
2775 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777 if (hWnd == NULL)
2778 return FALSE;
2779
2780 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002781 SendMessage(hWnd, WM_SETICON,
2782 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002784 SendMessage(hWnd, WM_SETICON,
2785 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786 return TRUE;
2787}
2788
2789/*
2790 * SaveConsoleTitleAndIcon()
2791 * Description:
2792 * Saves the current console window title in g_szOrigTitle, for later
2793 * restoration. Also, attempts to obtain a handle to the console window,
2794 * and use it to save the small and big icons currently in use by the
2795 * console window. This is not always possible on some versions of Windows;
2796 * nor is it possible when running Vim remotely using Telnet (since the
2797 * console window the user sees is owned by a remote process).
2798 */
2799 static void
2800SaveConsoleTitleAndIcon(void)
2801{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002802 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2804 return;
2805
2806 /*
2807 * Obtain a handle to the console window using GetConsoleWindow() from
2808 * KERNEL32.DLL; we need to handle in order to change the window icon.
2809 * This function only exists on NT-based Windows, starting with Windows
2810 * 2000. On older operating systems, we can't change the window icon
2811 * anyway.
2812 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002813 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814 if (g_hWnd == NULL)
2815 return;
2816
Bram Moolenaar0f873732019-12-05 20:28:46 +01002817 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002818 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2819 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2820 return;
2821
Bram Moolenaar0f873732019-12-05 20:28:46 +01002822 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002823 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002824 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825 if (g_hVimIcon != NULL)
2826 g_fCanChangeIcon = TRUE;
2827}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828
2829static int g_fWindInitCalled = FALSE;
2830static int g_fTermcapMode = FALSE;
2831static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832
2833/*
2834 * non-GUI version of mch_init().
2835 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002836 static void
2837mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002839# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002840 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002841# endif
2842# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002844# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845
Bram Moolenaar0f873732019-12-05 20:28:46 +01002846 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002847 SET_INVALID_PARAM_HANDLER;
2848
Bram Moolenaar0f873732019-12-05 20:28:46 +01002849 // Let critical errors result in a failure, not in a dialog box. Required
2850 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851 SetErrorMode(SEM_FAILCRITICALERRORS);
2852
Bram Moolenaar0f873732019-12-05 20:28:46 +01002853 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854 out_flush();
2855
Bram Moolenaar0f873732019-12-05 20:28:46 +01002856 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857 if (read_cmd_fd == 0)
2858 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2859 else
2860 create_conin();
2861 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2862
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002863# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002864 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002865 SaveConsoleBuffer(&g_cbOrig);
2866 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002867# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002868 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002869 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2870 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002871# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872 if (cterm_normal_fg_color == 0)
2873 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2874 if (cterm_normal_bg_color == 0)
2875 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2876
Bram Moolenaarbdace832019-03-02 10:13:42 +01002877 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002878 g_color_index_fg = g_attrDefault & 0xf;
2879 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2880
Bram Moolenaar0f873732019-12-05 20:28:46 +01002881 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002882 update_tcap(g_attrCurrent);
2883
2884 GetConsoleCursorInfo(g_hConOut, &g_cci);
2885 GetConsoleMode(g_hConIn, &g_cmodein);
2886 GetConsoleMode(g_hConOut, &g_cmodeout);
2887
Bram Moolenaar071d4272004-06-13 20:20:40 +00002888 SaveConsoleTitleAndIcon();
2889 /*
2890 * Set both the small and big icons of the console window to Vim's icon.
2891 * Note that Vim presently only has one size of icon (32x32), but it
2892 * automatically gets scaled down to 16x16 when setting the small icon.
2893 */
2894 if (g_fCanChangeIcon)
2895 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896
2897 ui_get_shellsize();
2898
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002899# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900 fdDump = fopen("dump", "wt");
2901
2902 if (fdDump)
2903 {
2904 time_t t;
2905
2906 time(&t);
2907 fputs(ctime(&t), fdDump);
2908 fflush(fdDump);
2909 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002910# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911
2912 g_fWindInitCalled = TRUE;
2913
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002916# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002917 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002918# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002919
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002920 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002921 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002922 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923}
2924
2925/*
2926 * non-GUI version of mch_exit().
2927 * Shut down and exit with status `r'
2928 * Careful: mch_exit() may be called before mch_init()!
2929 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002930 static void
2931mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002933 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002935 vtp_exit();
2936
Bram Moolenaar955f1982017-02-05 15:10:51 +01002937 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002938 if (g_fWindInitCalled)
2939 settmode(TMODE_COOK);
2940
Bram Moolenaar0f873732019-12-05 20:28:46 +01002941 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942
2943 if (g_fWindInitCalled)
2944 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002945 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 /*
2947 * Restore both the small and big icons of the console window to
2948 * what they were at startup. Don't do this when the window is
2949 * closed, Vim would hang here.
2950 */
2951 if (g_fCanChangeIcon && !g_fForceExit)
2952 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002954# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955 if (fdDump)
2956 {
2957 time_t t;
2958
2959 time(&t);
2960 fputs(ctime(&t), fdDump);
2961 fclose(fdDump);
2962 }
2963 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002964# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965 }
2966
2967 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002968 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 SetConsoleMode(g_hConOut, g_cmodeout);
2970
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002971# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002973# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974
2975 exit(r);
2976}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002977#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002979 void
2980mch_init(void)
2981{
2982#ifdef VIMDLL
2983 if (gui.starting)
2984 mch_init_g();
2985 else
2986 mch_init_c();
2987#elif defined(FEAT_GUI_MSWIN)
2988 mch_init_g();
2989#else
2990 mch_init_c();
2991#endif
2992}
2993
2994 void
2995mch_exit(int r)
2996{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002997#ifdef FEAT_NETBEANS_INTG
2998 netbeans_send_disconnect();
2999#endif
3000
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003001#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003002 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003003 mch_exit_g(r);
3004 else
3005 mch_exit_c(r);
3006#elif defined(FEAT_GUI_MSWIN)
3007 mch_exit_g(r);
3008#else
3009 mch_exit_c(r);
3010#endif
3011}
3012
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013/*
3014 * Do we have an interactive window?
3015 */
3016 int
3017mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003018 int argc UNUSED,
3019 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020{
3021 get_exe_name();
3022
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003023#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003024 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003026# ifdef VIMDLL
3027 if (gui.in_use)
3028 return OK;
3029# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 if (isatty(1))
3031 return OK;
3032 return FAIL;
3033#endif
3034}
3035
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003036/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003037 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 * When "len" is > 0, also expand short to long filenames.
3039 */
3040 void
3041fname_case(
3042 char_u *name,
3043 int len)
3044{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003045 int flen;
3046 WCHAR *p;
3047 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003049 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003050 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 return;
3052
3053 slash_adjust(name);
3054
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003055 p = enc_to_utf16(name, NULL);
3056 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003057 return;
3058
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003059 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003061 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003063 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003065 if (len > 0 || flen >= (int)STRLEN(q))
3066 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3067 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068 }
3069 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003070 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071}
3072
3073
3074/*
3075 * Insert user name in s[len].
3076 */
3077 int
3078mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003079 char_u *s,
3080 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003082 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003083 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003085 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003086 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003087 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003088
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003089 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003090 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003091 vim_strncpy(s, p, len - 1);
3092 vim_free(p);
3093 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003094 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003095 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096 s[0] = NUL;
3097 return FAIL;
3098}
3099
3100
3101/*
3102 * Insert host name in s[len].
3103 */
3104 void
3105mch_get_host_name(
3106 char_u *s,
3107 int len)
3108{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003109 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003110 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003112 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003113 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003114 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003115
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003116 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003117 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003118 vim_strncpy(s, p, len - 1);
3119 vim_free(p);
3120 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003121 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003122 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123}
3124
3125
3126/*
3127 * return process ID
3128 */
3129 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003130mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131{
3132 return (long)GetCurrentProcessId();
3133}
3134
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003135/*
3136 * return TRUE if process "pid" is still running
3137 */
3138 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003139mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003140{
3141 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3142 DWORD status = 0;
3143 int ret = FALSE;
3144
3145 if (hProcess == NULL)
3146 return FALSE; // might not have access
3147 if (GetExitCodeProcess(hProcess, &status) )
3148 ret = status == STILL_ACTIVE;
3149 CloseHandle(hProcess);
3150 return ret;
3151}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152
3153/*
3154 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3155 * Return OK for success, FAIL for failure.
3156 */
3157 int
3158mch_dirname(
3159 char_u *buf,
3160 int len)
3161{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003162 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003163
Bram Moolenaar071d4272004-06-13 20:20:40 +00003164 /*
3165 * Originally this was:
3166 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3167 * But the Win32s known bug list says that getcwd() doesn't work
3168 * so use the Win32 system call instead. <Negri>
3169 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003170 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003172 WCHAR wcbuf[_MAX_PATH + 1];
3173 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003175 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003176 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003177 p = utf16_to_enc(wcbuf, NULL);
3178 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003179 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003180 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003182 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183 }
3184 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003185 if (p == NULL)
3186 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003187
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003188 if (p != NULL)
3189 {
3190 vim_strncpy(buf, p, len - 1);
3191 vim_free(p);
3192 return OK;
3193 }
3194 }
3195 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196}
3197
3198/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003199 * Get file permissions for "name".
3200 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 */
3202 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003203mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003205 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003206 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003208 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003209 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210}
3211
3212
3213/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003214 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003215 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003216 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217 */
3218 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003219mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003220{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003221 long n;
3222 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003223
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003224 p = enc_to_utf16(name, NULL);
3225 if (p == NULL)
3226 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003227
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003228 n = _wchmod(p, perm);
3229 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003230 if (n == -1)
3231 return FAIL;
3232
3233 win32_set_archive(name);
3234
3235 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236}
3237
3238/*
3239 * Set hidden flag for "name".
3240 */
3241 void
3242mch_hide(char_u *name)
3243{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003244 int attrs = win32_getattrs(name);
3245 if (attrs == -1)
3246 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003248 attrs |= FILE_ATTRIBUTE_HIDDEN;
3249 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250}
3251
3252/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003253 * Return TRUE if file "name" exists and is hidden.
3254 */
3255 int
3256mch_ishidden(char_u *name)
3257{
3258 int f = win32_getattrs(name);
3259
3260 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003261 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003262
3263 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3264}
3265
3266/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003267 * return TRUE if "name" is a directory
3268 * return FALSE if "name" is not a directory or upon error
3269 */
3270 int
3271mch_isdir(char_u *name)
3272{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003273 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003274
3275 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003276 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003277
3278 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3279}
3280
3281/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003282 * return TRUE if "name" is a directory, NOT a symlink to a directory
3283 * return FALSE if "name" is not a directory
3284 * return FALSE for error
3285 */
3286 int
3287mch_isrealdir(char_u *name)
3288{
3289 return mch_isdir(name) && !mch_is_symbolic_link(name);
3290}
3291
3292/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003293 * Create directory "name".
3294 * Return 0 on success, -1 on error.
3295 */
3296 int
3297mch_mkdir(char_u *name)
3298{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003299 WCHAR *p;
3300 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003301
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003302 p = enc_to_utf16(name, NULL);
3303 if (p == NULL)
3304 return -1;
3305 retval = _wmkdir(p);
3306 vim_free(p);
3307 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003308}
3309
3310/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003311 * Delete directory "name".
3312 * Return 0 on success, -1 on error.
3313 */
3314 int
3315mch_rmdir(char_u *name)
3316{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003317 WCHAR *p;
3318 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003319
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003320 p = enc_to_utf16(name, NULL);
3321 if (p == NULL)
3322 return -1;
3323 retval = _wrmdir(p);
3324 vim_free(p);
3325 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003326}
3327
3328/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003329 * Return TRUE if file "fname" has more than one link.
3330 */
3331 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003332mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003333{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003334 BY_HANDLE_FILE_INFORMATION info;
3335
3336 return win32_fileinfo(fname, &info) == FILEINFO_OK
3337 && info.nNumberOfLinks > 1;
3338}
3339
3340/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003341 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003342 */
3343 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003344mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003345{
3346 HANDLE hFind;
3347 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003348 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003349 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003350 WIN32_FIND_DATAW findDataW;
3351
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003352 wn = enc_to_utf16(name, NULL);
3353 if (wn == NULL)
3354 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003355
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003356 hFind = FindFirstFileW(wn, &findDataW);
3357 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003358 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003359 {
3360 fileFlags = findDataW.dwFileAttributes;
3361 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003362 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003363 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003364
3365 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003366 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3367 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003368 res = TRUE;
3369
3370 return res;
3371}
3372
3373/*
3374 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3375 * link.
3376 */
3377 int
3378mch_is_linked(char_u *fname)
3379{
3380 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3381 return TRUE;
3382 return FALSE;
3383}
3384
3385/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003386 * Get the by-handle-file-information for "fname".
3387 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003388 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003389 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3390 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3391 */
3392 int
3393win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3394{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003395 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003396 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003397 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003398
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003399 wn = enc_to_utf16(fname, NULL);
3400 if (wn == NULL)
3401 return FILEINFO_ENC_FAIL;
3402
3403 hFile = CreateFileW(wn, // file name
3404 GENERIC_READ, // access mode
3405 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3406 NULL, // security descriptor
3407 OPEN_EXISTING, // creation disposition
3408 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3409 NULL); // handle to template file
3410 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003411
3412 if (hFile != INVALID_HANDLE_VALUE)
3413 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003414 if (GetFileInformationByHandle(hFile, info) != 0)
3415 res = FILEINFO_OK;
3416 else
3417 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003418 CloseHandle(hFile);
3419 }
3420
Bram Moolenaar03f48552006-02-28 23:52:23 +00003421 return res;
3422}
3423
3424/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003425 * get file attributes for `name'
3426 * -1 : error
3427 * else FILE_ATTRIBUTE_* defined in winnt.h
3428 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003429 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003430win32_getattrs(char_u *name)
3431{
3432 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003433 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003434
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003435 p = enc_to_utf16(name, NULL);
3436 if (p == NULL)
3437 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003438
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003439 attr = GetFileAttributesW(p);
3440 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003441
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003442 return attr;
3443}
3444
3445/*
3446 * set file attributes for `name' to `attrs'
3447 *
3448 * return -1 for failure, 0 otherwise
3449 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003450 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003451win32_setattrs(char_u *name, int attrs)
3452{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003453 int res;
3454 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003455
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003456 p = enc_to_utf16(name, NULL);
3457 if (p == NULL)
3458 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003459
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003460 res = SetFileAttributesW(p, attrs);
3461 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003462
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003463 return res ? 0 : -1;
3464}
3465
3466/*
3467 * Set archive flag for "name".
3468 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003469 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003470win32_set_archive(char_u *name)
3471{
3472 int attrs = win32_getattrs(name);
3473 if (attrs == -1)
3474 return -1;
3475
3476 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3477 return win32_setattrs(name, attrs);
3478}
3479
3480/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481 * Return TRUE if file or directory "name" is writable (not readonly).
3482 * Strange semantics of Win32: a readonly directory is writable, but you can't
3483 * delete a file. Let's say this means it is writable.
3484 */
3485 int
3486mch_writable(char_u *name)
3487{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003488 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003490 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3491 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492}
3493
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003495 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003496 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003497 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3498 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499 */
3500 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003501mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003503 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505
3506/*
3507 * Check what "name" is:
3508 * NODE_NORMAL: file or directory (or doesn't exist)
3509 * NODE_WRITABLE: writable device, socket, fifo, etc.
3510 * NODE_OTHER: non-writable things
3511 */
3512 int
3513mch_nodetype(char_u *name)
3514{
3515 HANDLE hFile;
3516 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003517 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518
Bram Moolenaar0f873732019-12-05 20:28:46 +01003519 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3520 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3521 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003522 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3523 return NODE_WRITABLE;
3524
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003525 wn = enc_to_utf16(name, NULL);
3526 if (wn == NULL)
3527 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003528
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003529 hFile = CreateFileW(wn, // file name
3530 GENERIC_WRITE, // access mode
3531 0, // share mode
3532 NULL, // security descriptor
3533 OPEN_EXISTING, // creation disposition
3534 0, // file attributes
3535 NULL); // handle to template file
3536 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537 if (hFile == INVALID_HANDLE_VALUE)
3538 return NODE_NORMAL;
3539
3540 type = GetFileType(hFile);
3541 CloseHandle(hFile);
3542 if (type == FILE_TYPE_CHAR)
3543 return NODE_WRITABLE;
3544 if (type == FILE_TYPE_DISK)
3545 return NODE_NORMAL;
3546 return NODE_OTHER;
3547}
3548
3549#ifdef HAVE_ACL
3550struct my_acl
3551{
3552 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3553 PSID pSidOwner;
3554 PSID pSidGroup;
3555 PACL pDacl;
3556 PACL pSacl;
3557};
3558#endif
3559
3560/*
3561 * Return a pointer to the ACL of file "fname" in allocated memory.
3562 * Return NULL if the ACL is not available for whatever reason.
3563 */
3564 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003565mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566{
3567#ifndef HAVE_ACL
3568 return (vim_acl_T)NULL;
3569#else
3570 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003571 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003573 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003574 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003576 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003577
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003578 wn = enc_to_utf16(fname, NULL);
3579 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003580 {
3581 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003582 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003583 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003584
3585 // Try to retrieve the entire security descriptor.
3586 err = GetNamedSecurityInfoW(
3587 wn, // Abstract filename
3588 SE_FILE_OBJECT, // File Object
3589 OWNER_SECURITY_INFORMATION |
3590 GROUP_SECURITY_INFORMATION |
3591 DACL_SECURITY_INFORMATION |
3592 SACL_SECURITY_INFORMATION,
3593 &p->pSidOwner, // Ownership information.
3594 &p->pSidGroup, // Group membership.
3595 &p->pDacl, // Discretionary information.
3596 &p->pSacl, // For auditing purposes.
3597 &p->pSecurityDescriptor);
3598 if (err == ERROR_ACCESS_DENIED ||
3599 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003600 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003601 // Retrieve only DACL.
3602 (void)GetNamedSecurityInfoW(
3603 wn,
3604 SE_FILE_OBJECT,
3605 DACL_SECURITY_INFORMATION,
3606 NULL,
3607 NULL,
3608 &p->pDacl,
3609 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003610 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003611 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003612 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003613 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003614 mch_free_acl((vim_acl_T)p);
3615 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003617 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618 }
3619
3620 return (vim_acl_T)p;
3621#endif
3622}
3623
Bram Moolenaar27515922013-06-29 15:36:26 +02003624#ifdef HAVE_ACL
3625/*
3626 * Check if "acl" contains inherited ACE.
3627 */
3628 static BOOL
3629is_acl_inherited(PACL acl)
3630{
3631 DWORD i;
3632 ACL_SIZE_INFORMATION acl_info;
3633 PACCESS_ALLOWED_ACE ace;
3634
3635 acl_info.AceCount = 0;
3636 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3637 for (i = 0; i < acl_info.AceCount; i++)
3638 {
3639 GetAce(acl, i, (LPVOID *)&ace);
3640 if (ace->Header.AceFlags & INHERITED_ACE)
3641 return TRUE;
3642 }
3643 return FALSE;
3644}
3645#endif
3646
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647/*
3648 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3649 * Errors are ignored.
3650 * This must only be called with "acl" equal to what mch_get_acl() returned.
3651 */
3652 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003653mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003654{
3655#ifdef HAVE_ACL
3656 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003657 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003658 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003659
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003660 if (p == NULL)
3661 return;
3662
3663 wn = enc_to_utf16(fname, NULL);
3664 if (wn == NULL)
3665 return;
3666
3667 // Set security flags
3668 if (p->pSidOwner)
3669 sec_info |= OWNER_SECURITY_INFORMATION;
3670 if (p->pSidGroup)
3671 sec_info |= GROUP_SECURITY_INFORMATION;
3672 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003673 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003674 sec_info |= DACL_SECURITY_INFORMATION;
3675 // Do not inherit its parent's DACL.
3676 // If the DACL is inherited, Cygwin permissions would be changed.
3677 if (!is_acl_inherited(p->pDacl))
3678 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003679 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003680 if (p->pSacl)
3681 sec_info |= SACL_SECURITY_INFORMATION;
3682
3683 (void)SetNamedSecurityInfoW(
3684 wn, // Abstract filename
3685 SE_FILE_OBJECT, // File Object
3686 sec_info,
3687 p->pSidOwner, // Ownership information.
3688 p->pSidGroup, // Group membership.
3689 p->pDacl, // Discretionary information.
3690 p->pSacl // For auditing purposes.
3691 );
3692 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693#endif
3694}
3695
3696 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003697mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698{
3699#ifdef HAVE_ACL
3700 struct my_acl *p = (struct my_acl *)acl;
3701
3702 if (p != NULL)
3703 {
3704 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3705 vim_free(p);
3706 }
3707#endif
3708}
3709
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003710#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711
3712/*
3713 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3714 */
3715 static BOOL WINAPI
3716handler_routine(
3717 DWORD dwCtrlType)
3718{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003719 INPUT_RECORD ir;
3720 DWORD out;
3721
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722 switch (dwCtrlType)
3723 {
3724 case CTRL_C_EVENT:
3725 if (ctrl_c_interrupts)
3726 g_fCtrlCPressed = TRUE;
3727 return TRUE;
3728
3729 case CTRL_BREAK_EVENT:
3730 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003731 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003732 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003733 ir.EventType = KEY_EVENT;
3734 ir.Event.KeyEvent.bKeyDown = TRUE;
3735 ir.Event.KeyEvent.wRepeatCount = 1;
3736 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3737 ir.Event.KeyEvent.wVirtualScanCode = 0;
3738 ir.Event.KeyEvent.dwControlKeyState = 0;
3739 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3740 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 return TRUE;
3742
Bram Moolenaar0f873732019-12-05 20:28:46 +01003743 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744 case CTRL_CLOSE_EVENT:
3745 case CTRL_LOGOFF_EVENT:
3746 case CTRL_SHUTDOWN_EVENT:
3747 windgoto((int)Rows - 1, 0);
3748 g_fForceExit = TRUE;
3749
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003750 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751 (dwCtrlType == CTRL_CLOSE_EVENT
3752 ? _("close")
3753 : dwCtrlType == CTRL_LOGOFF_EVENT
3754 ? _("logoff")
3755 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003756# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003758# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003759
Bram Moolenaar0f873732019-12-05 20:28:46 +01003760 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761
Bram Moolenaar0f873732019-12-05 20:28:46 +01003762 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003763
3764 default:
3765 return FALSE;
3766 }
3767}
3768
3769
3770/*
3771 * set the tty in (raw) ? "raw" : "cooked" mode
3772 */
3773 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003774mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775{
3776 DWORD cmodein;
3777 DWORD cmodeout;
3778 BOOL bEnableHandler;
3779
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003780# ifdef VIMDLL
3781 if (gui.in_use)
3782 return;
3783# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784 GetConsoleMode(g_hConIn, &cmodein);
3785 GetConsoleMode(g_hConOut, &cmodeout);
3786 if (tmode == TMODE_RAW)
3787 {
3788 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3789 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003791 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003793 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3794 }
3795 else
3796 {
3797 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3798 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003799 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003800# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003801 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3802 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003803 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003804# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003805 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003806# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003807 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808 bEnableHandler = TRUE;
3809 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003810 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811 {
3812 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3813 ENABLE_ECHO_INPUT);
3814 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3815 bEnableHandler = FALSE;
3816 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003817 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 SetConsoleMode(g_hConOut, cmodeout);
3819 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3820
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003821# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 if (fdDump)
3823 {
3824 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3825 tmode == TMODE_RAW ? "raw" :
3826 tmode == TMODE_COOK ? "cooked" : "normal",
3827 cmodein, cmodeout);
3828 fflush(fdDump);
3829 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003830# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831}
3832
3833
3834/*
3835 * Get the size of the current window in `Rows' and `Columns'
3836 * Return OK when size could be determined, FAIL otherwise.
3837 */
3838 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003839mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840{
3841 CONSOLE_SCREEN_BUFFER_INFO csbi;
3842
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003843# ifdef VIMDLL
3844 if (gui.in_use)
3845 return OK;
3846# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3848 {
3849 /*
3850 * For some reason, we are trying to get the screen dimensions
3851 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3852 * variables are really intended to mean the size of Vim screen
3853 * while in termcap mode.
3854 */
3855 Rows = g_cbTermcap.Info.dwSize.Y;
3856 Columns = g_cbTermcap.Info.dwSize.X;
3857 }
3858 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3859 {
3860 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3861 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3862 }
3863 else
3864 {
3865 Rows = 25;
3866 Columns = 80;
3867 }
3868 return OK;
3869}
3870
3871/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003872 * Resize console buffer to 'COORD'
3873 */
3874 static void
3875ResizeConBuf(
3876 HANDLE hConsole,
3877 COORD coordScreen)
3878{
3879 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3880 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003881# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003882 if (fdDump)
3883 {
3884 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3885 GetLastError());
3886 fflush(fdDump);
3887 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003888# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003889 }
3890}
3891
3892/*
3893 * Resize console window size to 'srWindowRect'
3894 */
3895 static void
3896ResizeWindow(
3897 HANDLE hConsole,
3898 SMALL_RECT srWindowRect)
3899{
3900 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3901 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003902# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003903 if (fdDump)
3904 {
3905 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3906 GetLastError());
3907 fflush(fdDump);
3908 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003909# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003910 }
3911}
3912
3913/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914 * Set a console window to `xSize' * `ySize'
3915 */
3916 static void
3917ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003918 HANDLE hConsole,
3919 int xSize,
3920 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003922 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3923 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003925 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003926 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003927
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003928# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929 if (fdDump)
3930 {
3931 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3932 fflush(fdDump);
3933 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003934# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935
Bram Moolenaar0f873732019-12-05 20:28:46 +01003936 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937 coordScreen = GetLargestConsoleWindowSize(hConsole);
3938
Bram Moolenaar0f873732019-12-05 20:28:46 +01003939 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003940 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3941 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3942 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3943
3944 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3945 {
3946 int sx, sy;
3947
3948 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3949 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3950 if (sy < ySize || sx < xSize)
3951 {
3952 /*
3953 * Increasing number of lines/columns, do buffer first.
3954 * Use the maximal size in x and y direction.
3955 */
3956 if (sy < ySize)
3957 coordScreen.Y = ySize;
3958 else
3959 coordScreen.Y = sy;
3960 if (sx < xSize)
3961 coordScreen.X = xSize;
3962 else
3963 coordScreen.X = sx;
3964 SetConsoleScreenBufferSize(hConsole, coordScreen);
3965 }
3966 }
3967
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003968 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003969 coordScreen.X = xSize;
3970 coordScreen.Y = ySize;
3971
Bram Moolenaar2551c032018-08-23 22:38:31 +02003972 // In the new console call API, only the first time in reverse order
3973 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003975 ResizeWindow(hConsole, srWindowRect);
3976 ResizeConBuf(hConsole, coordScreen);
3977 }
3978 else
3979 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003980 // Workaround for a Windows 10 bug
3981 cursor.X = srWindowRect.Left;
3982 cursor.Y = srWindowRect.Top;
3983 SetConsoleCursorPosition(hConsole, cursor);
3984
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003985 ResizeConBuf(hConsole, coordScreen);
3986 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003987 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988 }
3989}
3990
3991
3992/*
3993 * Set the console window to `Rows' * `Columns'
3994 */
3995 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003996mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003997{
3998 COORD coordScreen;
3999
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004000# ifdef VIMDLL
4001 if (gui.in_use)
4002 return;
4003# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004004 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004005 if (suppress_winsize != 0)
4006 {
4007 suppress_winsize = 2;
4008 return;
4009 }
4010
4011 if (term_console)
4012 {
4013 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4014
Bram Moolenaar0f873732019-12-05 20:28:46 +01004015 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004016 if (Rows > coordScreen.Y)
4017 Rows = coordScreen.Y;
4018 if (Columns > coordScreen.X)
4019 Columns = coordScreen.X;
4020
4021 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4022 }
4023}
4024
4025/*
4026 * Rows and/or Columns has changed.
4027 */
4028 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004029mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004031# ifdef VIMDLL
4032 if (gui.in_use)
4033 return;
4034# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4036}
4037
4038
4039/*
4040 * Called when started up, to set the winsize that was delayed.
4041 */
4042 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004043mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004044{
4045 if (suppress_winsize == 2)
4046 {
4047 suppress_winsize = 0;
4048 mch_set_shellsize();
4049 shell_resized();
4050 }
4051 suppress_winsize = 0;
4052}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004053#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004055 static BOOL
4056vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004057 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004058 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004059 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004060 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004061 PROCESS_INFORMATION *pi,
4062 LPVOID *env,
4063 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004064{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004065 BOOL ret = FALSE;
4066 WCHAR *wcmd, *wcwd = NULL;
4067
4068 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4069 if (wcmd == NULL)
4070 return FALSE;
4071 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004072 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004073 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4074 if (wcwd == NULL)
4075 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004076 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004077
4078 ret = CreateProcessW(
4079 NULL, // Executable name
4080 wcmd, // Command to execute
4081 NULL, // Process security attributes
4082 NULL, // Thread security attributes
4083 inherit_handles, // Inherit handles
4084 flags, // Creation flags
4085 env, // Environment
4086 wcwd, // Current directory
4087 (LPSTARTUPINFOW)si, // Startup information
4088 pi); // Process information
4089theend:
4090 vim_free(wcmd);
4091 vim_free(wcwd);
4092 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004093}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004094
4095
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004096 static HINSTANCE
4097vim_shell_execute(
4098 char *cmd,
4099 INT n_show_cmd)
4100{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004101 HINSTANCE ret;
4102 WCHAR *wcmd;
4103
4104 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4105 if (wcmd == NULL)
4106 return (HINSTANCE) 0;
4107
4108 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4109 vim_free(wcmd);
4110 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004111}
4112
4113
Bram Moolenaar4f974752019-02-17 17:44:42 +01004114#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115
4116/*
4117 * Specialised version of system() for Win32 GUI mode.
4118 * This version proceeds as follows:
4119 * 1. Create a console window for use by the subprocess
4120 * 2. Run the subprocess (it gets the allocated console by default)
4121 * 3. Wait for the subprocess to terminate and get its exit code
4122 * 4. Prompt the user to press a key to close the console window
4123 */
4124 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004125mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126{
4127 STARTUPINFO si;
4128 PROCESS_INFORMATION pi;
4129 DWORD ret = 0;
4130 HWND hwnd = GetFocus();
4131
4132 si.cb = sizeof(si);
4133 si.lpReserved = NULL;
4134 si.lpDesktop = NULL;
4135 si.lpTitle = NULL;
4136 si.dwFlags = STARTF_USESHOWWINDOW;
4137 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004138 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004139 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004141 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004142 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 else
4144 si.wShowWindow = SW_SHOWNORMAL;
4145 si.cbReserved2 = 0;
4146 si.lpReserved2 = NULL;
4147
Bram Moolenaar0f873732019-12-05 20:28:46 +01004148 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004149 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004150 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4151 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152
Bram Moolenaar0f873732019-12-05 20:28:46 +01004153 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004155# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 int delay = 1;
4157
Bram Moolenaar0f873732019-12-05 20:28:46 +01004158 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 for (;;)
4160 {
4161 MSG msg;
4162
K.Takatab7057bd2022-01-21 11:37:07 +00004163 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 {
4165 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004166 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004167 delay = 1;
4168 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169 }
4170 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4171 break;
4172
Bram Moolenaar0f873732019-12-05 20:28:46 +01004173 // We start waiting for a very short time and then increase it, so
4174 // that we respond quickly when the process is quick, and don't
4175 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176 if (delay < 50)
4177 delay += 10;
4178 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004179# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004180 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004181# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004182
Bram Moolenaar0f873732019-12-05 20:28:46 +01004183 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004184 GetExitCodeProcess(pi.hProcess, &ret);
4185 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186
Bram Moolenaar0f873732019-12-05 20:28:46 +01004187 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004188 CloseHandle(pi.hThread);
4189 CloseHandle(pi.hProcess);
4190
Bram Moolenaar0f873732019-12-05 20:28:46 +01004191 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4193
4194 return ret;
4195}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004196
4197/*
4198 * Thread launched by the gui to send the current buffer data to the
4199 * process. This way avoid to hang up vim totally if the children
4200 * process take a long time to process the lines.
4201 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004202 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004203sub_process_writer(LPVOID param)
4204{
4205 HANDLE g_hChildStd_IN_Wr = param;
4206 linenr_T lnum = curbuf->b_op_start.lnum;
4207 DWORD len = 0;
4208 DWORD l;
4209 char_u *lp = ml_get(lnum);
4210 char_u *s;
4211 int written = 0;
4212
4213 for (;;)
4214 {
4215 l = (DWORD)STRLEN(lp + written);
4216 if (l == 0)
4217 len = 0;
4218 else if (lp[written] == NL)
4219 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004220 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004221 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4222 }
4223 else
4224 {
4225 s = vim_strchr(lp + written, NL);
4226 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4227 s == NULL ? l : (DWORD)(s - (lp + written)),
4228 &len, NULL);
4229 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004230 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004231 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004232 // Finished a line, add a NL, unless this line should not have
4233 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004234 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004235 || (!curbuf->b_p_bin
4236 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004237 || (lnum != curbuf->b_no_eol_lnum
4238 && (lnum != curbuf->b_ml.ml_line_count
4239 || curbuf->b_p_eol)))
4240 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004241 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4242 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004243 }
4244
4245 ++lnum;
4246 if (lnum > curbuf->b_op_end.lnum)
4247 break;
4248
4249 lp = ml_get(lnum);
4250 written = 0;
4251 }
4252 else if (len > 0)
4253 written += len;
4254 }
4255
Bram Moolenaar0f873732019-12-05 20:28:46 +01004256 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004257 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004258 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004259}
4260
4261
Bram Moolenaar0f873732019-12-05 20:28:46 +01004262# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004263
4264/*
4265 * This function read from the children's stdout and write the
4266 * data on screen or in the buffer accordingly.
4267 */
4268 static void
4269dump_pipe(int options,
4270 HANDLE g_hChildStd_OUT_Rd,
4271 garray_T *ga,
4272 char_u buffer[],
4273 DWORD *buffer_off)
4274{
4275 DWORD availableBytes = 0;
4276 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004277 int ret;
4278 DWORD len;
4279 DWORD toRead;
4280 int repeatCount;
4281
Bram Moolenaar0f873732019-12-05 20:28:46 +01004282 // we query the pipe to see if there is any data to read
4283 // to avoid to perform a blocking read
4284 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4285 NULL, // optional buffer
4286 0, // buffer size
4287 NULL, // number of read bytes
4288 &availableBytes, // available bytes total
4289 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004290
4291 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004292 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004293 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004294 {
4295 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004296 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004297 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004298 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004299
Bram Moolenaar0f873732019-12-05 20:28:46 +01004300 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004301 if (len == 0)
4302 break;
4303
4304 availableBytes -= len;
4305
4306 if (options & SHELL_READ)
4307 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004308 // Do NUL -> NL translation, append NL separated
4309 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004310 for (i = 0; i < len; ++i)
4311 {
4312 if (buffer[i] == NL)
4313 append_ga_line(ga);
4314 else if (buffer[i] == NUL)
4315 ga_append(ga, NL);
4316 else
4317 ga_append(ga, buffer[i]);
4318 }
4319 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004320 else if (has_mbyte)
4321 {
4322 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004323 int c;
4324 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004325
4326 len += *buffer_off;
4327 buffer[len] = NUL;
4328
Bram Moolenaar0f873732019-12-05 20:28:46 +01004329 // Check if the last character in buffer[] is
4330 // incomplete, keep these bytes for the next
4331 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004332 for (p = buffer; p < buffer + len; p += l)
4333 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004334 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004335 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004336 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004337 else if (MB_BYTE2LEN(*p) != l)
4338 break;
4339 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004340 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004341 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004342 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004343 if (len >= 12)
4344 ++p;
4345 else
4346 {
4347 *buffer_off = len;
4348 return;
4349 }
4350 }
4351 c = *p;
4352 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004353 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004354 if (p < buffer + len)
4355 {
4356 *p = c;
4357 *buffer_off = (DWORD)((buffer + len) - p);
4358 mch_memmove(buffer, p, *buffer_off);
4359 return;
4360 }
4361 *buffer_off = 0;
4362 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004363 else
4364 {
4365 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004366 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004367 }
4368
4369 windgoto(msg_row, msg_col);
4370 cursor_on();
4371 out_flush();
4372 }
4373}
4374
4375/*
4376 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4377 * for communication and doesn't open any new window.
4378 */
4379 static int
4380mch_system_piped(char *cmd, int options)
4381{
4382 STARTUPINFO si;
4383 PROCESS_INFORMATION pi;
4384 DWORD ret = 0;
4385
4386 HANDLE g_hChildStd_IN_Rd = NULL;
4387 HANDLE g_hChildStd_IN_Wr = NULL;
4388 HANDLE g_hChildStd_OUT_Rd = NULL;
4389 HANDLE g_hChildStd_OUT_Wr = NULL;
4390
Bram Moolenaar0f873732019-12-05 20:28:46 +01004391 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004392 DWORD len;
4393
Bram Moolenaar0f873732019-12-05 20:28:46 +01004394 // buffer used to receive keys
4395 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4396 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004397
4398 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004399 int noread_cnt = 0;
4400 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004401 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004402 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004403 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004404
4405 SECURITY_ATTRIBUTES saAttr;
4406
Bram Moolenaar0f873732019-12-05 20:28:46 +01004407 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004408 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4409 saAttr.bInheritHandle = TRUE;
4410 saAttr.lpSecurityDescriptor = NULL;
4411
4412 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004413 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004414 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004415 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004417 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004418 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004419 {
4420 CloseHandle(g_hChildStd_IN_Rd);
4421 CloseHandle(g_hChildStd_IN_Wr);
4422 CloseHandle(g_hChildStd_OUT_Rd);
4423 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004424 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004425 }
4426
4427 si.cb = sizeof(si);
4428 si.lpReserved = NULL;
4429 si.lpDesktop = NULL;
4430 si.lpTitle = NULL;
4431 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4432
Bram Moolenaar0f873732019-12-05 20:28:46 +01004433 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004434 si.hStdError = g_hChildStd_OUT_Wr;
4435 si.hStdOutput = g_hChildStd_OUT_Wr;
4436 si.hStdInput = g_hChildStd_IN_Rd;
4437 si.wShowWindow = SW_HIDE;
4438 si.cbReserved2 = 0;
4439 si.lpReserved2 = NULL;
4440
4441 if (options & SHELL_READ)
4442 ga_init2(&ga, 1, BUFLEN);
4443
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004444 if (cmd != NULL)
4445 {
4446 p = (char *)vim_strsave((char_u *)cmd);
4447 if (p != NULL)
4448 unescape_shellxquote((char_u *)p, p_sxe);
4449 else
4450 p = cmd;
4451 }
4452
Bram Moolenaar0f873732019-12-05 20:28:46 +01004453 // Now, run the command.
4454 // About "Inherit handles" being TRUE: this command can be litigious,
4455 // handle inheritance was deactivated for pending temp file, but, if we
4456 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004457 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4458 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004459
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004460 if (p != cmd)
4461 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004462
Bram Moolenaar0f873732019-12-05 20:28:46 +01004463 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004464 CloseHandle(g_hChildStd_IN_Rd);
4465 CloseHandle(g_hChildStd_OUT_Wr);
4466
4467 if (options & SHELL_WRITE)
4468 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004469 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004470 _beginthreadex(NULL, // security attributes
4471 0, // default stack size
4472 sub_process_writer, // function to be executed
4473 g_hChildStd_IN_Wr, // parameter
4474 0, // creation flag, start immediately
4475 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004476 CloseHandle(thread);
4477 g_hChildStd_IN_Wr = NULL;
4478 }
4479
Bram Moolenaar0f873732019-12-05 20:28:46 +01004480 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004481 for (;;)
4482 {
4483 MSG msg;
4484
K.Takatab7057bd2022-01-21 11:37:07 +00004485 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004486 {
4487 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004488 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004489 }
4490
Bram Moolenaar0f873732019-12-05 20:28:46 +01004491 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004492 if ((options & (SHELL_READ|SHELL_WRITE))
4493# ifdef FEAT_GUI
4494 || gui.in_use
4495# endif
4496 )
4497 {
4498 len = 0;
4499 if (!(options & SHELL_EXPAND)
4500 && ((options &
4501 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4502 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4503# ifdef FEAT_GUI
4504 || gui.in_use
4505# endif
4506 )
4507 && (ta_len > 0 || noread_cnt > 4))
4508 {
4509 if (ta_len == 0)
4510 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004511 // Get extra characters when we don't have any. Reset the
4512 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004513 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004514 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4515 }
4516 if (ta_len > 0 || len > 0)
4517 {
4518 /*
4519 * For pipes: Check for CTRL-C: send interrupt signal to
4520 * child. Check for CTRL-D: EOF, close pipe to child.
4521 */
4522 if (len == 1 && cmd != NULL)
4523 {
4524 if (ta_buf[ta_len] == Ctrl_C)
4525 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004526 // Learn what exit code is expected, for
4527 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004528 TerminateProcess(pi.hProcess, 9);
4529 }
4530 if (ta_buf[ta_len] == Ctrl_D)
4531 {
4532 CloseHandle(g_hChildStd_IN_Wr);
4533 g_hChildStd_IN_Wr = NULL;
4534 }
4535 }
4536
Bram Moolenaarf4140482020-02-15 23:06:45 +01004537 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004538
4539 /*
4540 * For pipes: echo the typed characters. For a pty this
4541 * does not seem to work.
4542 */
4543 for (i = ta_len; i < ta_len + len; ++i)
4544 {
4545 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4546 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004547 else if (has_mbyte)
4548 {
4549 int l = (*mb_ptr2len)(ta_buf + i);
4550
4551 msg_outtrans_len(ta_buf + i, l);
4552 i += l - 1;
4553 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004554 else
4555 msg_outtrans_len(ta_buf + i, 1);
4556 }
4557 windgoto(msg_row, msg_col);
4558 out_flush();
4559
4560 ta_len += len;
4561
4562 /*
4563 * Write the characters to the child, unless EOF has been
4564 * typed for pipes. Write one character at a time, to
4565 * avoid losing too much typeahead. When writing buffer
4566 * lines, drop the typed characters (only check for
4567 * CTRL-C).
4568 */
4569 if (options & SHELL_WRITE)
4570 ta_len = 0;
4571 else if (g_hChildStd_IN_Wr != NULL)
4572 {
4573 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4574 1, &len, NULL);
4575 // if we are typing in, we want to keep things reactive
4576 delay = 1;
4577 if (len > 0)
4578 {
4579 ta_len -= len;
4580 mch_memmove(ta_buf, ta_buf + len, ta_len);
4581 }
4582 }
4583 }
4584 }
4585 }
4586
4587 if (ta_len)
4588 ui_inchar_undo(ta_buf, ta_len);
4589
4590 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4591 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004592 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004593 break;
4594 }
4595
4596 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004597 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004598
Bram Moolenaar0f873732019-12-05 20:28:46 +01004599 // We start waiting for a very short time and then increase it, so
4600 // that we respond quickly when the process is quick, and don't
4601 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004602 if (delay < 50)
4603 delay += 10;
4604 }
4605
Bram Moolenaar0f873732019-12-05 20:28:46 +01004606 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004607 CloseHandle(g_hChildStd_OUT_Rd);
4608 if (g_hChildStd_IN_Wr != NULL)
4609 CloseHandle(g_hChildStd_IN_Wr);
4610
4611 WaitForSingleObject(pi.hProcess, INFINITE);
4612
Bram Moolenaar0f873732019-12-05 20:28:46 +01004613 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004614 GetExitCodeProcess(pi.hProcess, &ret);
4615
4616 if (options & SHELL_READ)
4617 {
4618 if (ga.ga_len > 0)
4619 {
4620 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004621 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004622 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4623 }
4624 else
4625 curbuf->b_no_eol_lnum = 0;
4626 ga_clear(&ga);
4627 }
4628
Bram Moolenaar0f873732019-12-05 20:28:46 +01004629 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004630 CloseHandle(pi.hThread);
4631 CloseHandle(pi.hProcess);
4632
4633 return ret;
4634}
4635
4636 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004637mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004638{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004639 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004640 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004641 return mch_system_piped(cmd, options);
4642 else
4643 return mch_system_classic(cmd, options);
4644}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004645#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004646
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004647#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004648 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004649mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004650{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004651 int ret;
4652 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004653 char_u *buf;
4654 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004655
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004656 // If the command starts and ends with double quotes, enclose the command
4657 // in parentheses.
4658 len = STRLEN(cmd);
4659 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4660 {
4661 len += 3;
4662 buf = alloc(len);
4663 if (buf == NULL)
4664 return -1;
4665 vim_snprintf((char *)buf, len, "(%s)", cmd);
4666 wcmd = enc_to_utf16(buf, NULL);
4667 free(buf);
4668 }
4669 else
4670 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4671
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004672 if (wcmd == NULL)
4673 return -1;
4674
4675 ret = _wsystem(wcmd);
4676 vim_free(wcmd);
4677 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004678}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004679
4680#endif
4681
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004682 static int
4683mch_system(char *cmd, int options)
4684{
4685#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004686 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004687 return mch_system_g(cmd, options);
4688 else
4689 return mch_system_c(cmd, options);
4690#elif defined(FEAT_GUI_MSWIN)
4691 return mch_system_g(cmd, options);
4692#else
4693 return mch_system_c(cmd, options);
4694#endif
4695}
4696
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004697#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4698/*
4699 * Use a terminal window to run a shell command in.
4700 */
4701 static int
4702mch_call_shell_terminal(
4703 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004704 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004705{
4706 jobopt_T opt;
4707 char_u *newcmd = NULL;
4708 typval_T argvar[2];
4709 long_u cmdlen;
4710 int retval = -1;
4711 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004712 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004713 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004714 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004715
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004716 if (cmd == NULL)
4717 cmdlen = STRLEN(p_sh) + 1;
4718 else
4719 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004720 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004721 if (newcmd == NULL)
4722 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004723 if (cmd == NULL)
4724 {
4725 STRCPY(newcmd, p_sh);
4726 ch_log(NULL, "starting terminal to run a shell");
4727 }
4728 else
4729 {
4730 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4731 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4732 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004733
4734 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004735
4736 argvar[0].v_type = VAR_STRING;
4737 argvar[0].vval.v_string = newcmd;
4738 argvar[1].v_type = VAR_UNKNOWN;
4739 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004740 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004741 {
4742 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004743 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004744 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004745
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004746 job = term_getjob(buf->b_term);
4747 ++job->jv_refcount;
4748
Bram Moolenaar0f873732019-12-05 20:28:46 +01004749 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004750 aucmd_prepbuf(&aco, buf);
4751
4752 clear_oparg(&oa);
4753 while (term_use_loop())
4754 {
4755 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4756 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004757 // If terminal_loop() returns OK we got a key that is handled
4758 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004759 if (terminal_loop(TRUE) == OK)
4760 normal_cmd(&oa, TRUE);
4761 }
4762 else
4763 normal_cmd(&oa, TRUE);
4764 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004765 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004766 ch_log(NULL, "system command finished");
4767
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004768 job_unref(job);
4769
Bram Moolenaar0f873732019-12-05 20:28:46 +01004770 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004771 aucmd_restbuf(&aco);
4772
4773 wait_return(TRUE);
4774 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4775
4776 vim_free(newcmd);
4777 return retval;
4778}
4779#endif
4780
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781/*
4782 * Either execute a command by calling the shell or start a new shell
4783 */
4784 int
4785mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004786 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004787 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788{
4789 int x = 0;
4790 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004791 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004792
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004793#ifdef FEAT_JOB_CHANNEL
4794 ch_log(NULL, "executing shell command: %s", cmd);
4795#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004796 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004797 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004798 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004799 if (cmd == NULL)
4800 wcscat(szShellTitle, L" :sh");
4801 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004802 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004803 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004804
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004805 if (wn != NULL)
4806 {
4807 wcscat(szShellTitle, L" - !");
4808 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004809 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004810 wcscat(szShellTitle, wn);
4811 SetConsoleTitleW(szShellTitle);
4812 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004813 }
4814 }
4815 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816
4817 out_flush();
4818
4819#ifdef MCH_WRITE_DUMP
4820 if (fdDump)
4821 {
4822 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4823 fflush(fdDump);
4824 }
4825#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004826#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004827 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004828 if (
4829# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004830 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004831# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004832 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004833 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4834 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004835 char_u *cmdbase = cmd;
4836
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004837 if (cmdbase != NULL)
4838 // Skip a leading quote and (.
4839 while (*cmdbase == '"' || *cmdbase == '(')
4840 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004841
4842 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004843 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4844 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004845 {
4846 // Use a terminal window to run the command in.
4847 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004848 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004849 return x;
4850 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004851 }
4852#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004853
4854 /*
4855 * Catch all deadly signals while running the external command, because a
4856 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4857 */
4858 signal(SIGINT, SIG_IGN);
4859#if defined(__GNUC__) && !defined(__MINGW32__)
4860 signal(SIGKILL, SIG_IGN);
4861#else
4862 signal(SIGBREAK, SIG_IGN);
4863#endif
4864 signal(SIGILL, SIG_IGN);
4865 signal(SIGFPE, SIG_IGN);
4866 signal(SIGSEGV, SIG_IGN);
4867 signal(SIGTERM, SIG_IGN);
4868 signal(SIGABRT, SIG_IGN);
4869
4870 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004871 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872
4873 if (cmd == NULL)
4874 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004875 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004876 }
4877 else
4878 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004879 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004880 char_u *newcmd = NULL;
4881 char_u *cmdbase = cmd;
4882 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004883
Bram Moolenaar0f873732019-12-05 20:28:46 +01004884 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004885 if (*cmdbase == '"' )
4886 ++cmdbase;
4887 if (*cmdbase == '(')
4888 ++cmdbase;
4889
Bram Moolenaar1c465442017-03-12 20:10:05 +01004890 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004891 {
4892 STARTUPINFO si;
4893 PROCESS_INFORMATION pi;
4894 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004895 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004896 char_u *p;
4897
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004898 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004899 si.cb = sizeof(si);
4900 si.lpReserved = NULL;
4901 si.lpDesktop = NULL;
4902 si.lpTitle = NULL;
4903 si.dwFlags = 0;
4904 si.cbReserved2 = 0;
4905 si.lpReserved2 = NULL;
4906
4907 cmdbase = skipwhite(cmdbase + 5);
4908 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004909 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004910 {
4911 cmdbase = skipwhite(cmdbase + 4);
4912 si.dwFlags = STARTF_USESHOWWINDOW;
4913 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004914 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004915 }
4916 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004917 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004918 {
4919 cmdbase = skipwhite(cmdbase + 2);
4920 flags = CREATE_NO_WINDOW;
4921 si.dwFlags = STARTF_USESTDHANDLES;
4922 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004923 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004924 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004925 NULL, // Security att.
4926 OPEN_EXISTING, // Open flags
4927 FILE_ATTRIBUTE_NORMAL, // File att.
4928 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004929 si.hStdOutput = si.hStdInput;
4930 si.hStdError = si.hStdInput;
4931 }
4932
Bram Moolenaar0f873732019-12-05 20:28:46 +01004933 // Remove a trailing ", ) and )" if they have a match
4934 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004935 if (cmdbase > cmd)
4936 {
4937 p = cmdbase + STRLEN(cmdbase);
4938 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4939 *--p = NUL;
4940 if (p > cmdbase && p[-1] == ')'
4941 && (*cmd =='(' || cmd[1] == '('))
4942 *--p = NUL;
4943 }
4944
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004945 newcmd = cmdbase;
4946 unescape_shellxquote(cmdbase, p_sxe);
4947
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004948 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004949 * If creating new console, arguments are passed to the
4950 * 'cmd.exe' as-is. If it's not, arguments are not treated
4951 * correctly for current 'cmd.exe'. So unescape characters in
4952 * shellxescape except '|' for avoiding to be treated as
4953 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004954 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004955 if (flags != CREATE_NEW_CONSOLE)
4956 {
4957 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004958 char_u *cmd_shell = mch_getenv("COMSPEC");
4959
4960 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004961 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004962
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004963 subcmd = vim_strsave_escaped_ext(cmdbase,
4964 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004965 if (subcmd != NULL)
4966 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004967 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004968 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004969 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004970 if (newcmd != NULL)
4971 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004972 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004973 else
4974 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004975 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004976 }
4977 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004978
4979 /*
4980 * Now, start the command as a process, so that it doesn't
4981 * inherit our handles which causes unpleasant dangling swap
4982 * files if we exit before the spawned process
4983 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004984 if (vim_create_process((char *)newcmd, FALSE, flags,
4985 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004986 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004987 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4988 > (HINSTANCE)32)
4989 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004990 else
4991 {
4992 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004993#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004994# ifdef VIMDLL
4995 if (gui.in_use)
4996# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00004997 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004998#endif
4999 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005000
5001 if (newcmd != cmdbase)
5002 vim_free(newcmd);
5003
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005004 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005005 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005006 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005007 CloseHandle(si.hStdInput);
5008 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005009 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005010 CloseHandle(pi.hThread);
5011 CloseHandle(pi.hProcess);
5012 }
5013 else
5014 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005015 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005016#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005017 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005018 (!s_dont_use_vimrun && p_stmp ?
5019 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5020 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005022 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005023
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005024 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005025 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005026 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005027#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005028 if (
5029# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005030 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005031# endif
5032 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005033 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005034 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5035 "External commands will not pause after completion.\n"
5036 "See :help win32-vimrun for more information.");
5037 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005038 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5039 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005040
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005041 if (wmsg != NULL && wtitle != NULL)
5042 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5043 vim_free(wmsg);
5044 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045 need_vimrun_warning = FALSE;
5046 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005047 if (
5048# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005049 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005050# endif
5051 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005052 // Use vimrun to execute the command. It opens a console
5053 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005054 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005055 vimrun_path,
5056 (msg_silent != 0 || (options & SHELL_DOOUT))
5057 ? "-s " : "",
5058 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005059 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005060# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005061 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005062# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005063 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005064 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005065 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5066 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005067 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005068#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005069 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005070 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005071 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005072 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005073 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005074 }
5075 }
5076
5077 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005078 {
5079 // The shell may have messed with the mode, always set it.
5080 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005081 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005082 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005083
Bram Moolenaar0f873732019-12-05 20:28:46 +01005084 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005085 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005086#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005087 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005088 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005089#endif
5090 )
5091 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005092 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005093 msg_putchar('\n');
5094 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005095 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005096
5097 signal(SIGINT, SIG_DFL);
5098#if defined(__GNUC__) && !defined(__MINGW32__)
5099 signal(SIGKILL, SIG_DFL);
5100#else
5101 signal(SIGBREAK, SIG_DFL);
5102#endif
5103 signal(SIGILL, SIG_DFL);
5104 signal(SIGFPE, SIG_DFL);
5105 signal(SIGSEGV, SIG_DFL);
5106 signal(SIGTERM, SIG_DFL);
5107 signal(SIGABRT, SIG_DFL);
5108
5109 return x;
5110}
5111
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005112#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005113 static HANDLE
5114job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005115 char_u *fname,
5116 DWORD dwDesiredAccess,
5117 DWORD dwShareMode,
5118 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5119 DWORD dwCreationDisposition,
5120 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005121{
5122 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005123 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005124
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005125 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005126 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005127 return INVALID_HANDLE_VALUE;
5128
5129 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5130 lpSecurityAttributes, dwCreationDisposition,
5131 dwFlagsAndAttributes, NULL);
5132 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005133 return h;
5134}
5135
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005136/*
5137 * Turn the dictionary "env" into a NUL separated list that can be used as the
5138 * environment argument of vim_create_process().
5139 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005140 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005141win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005142{
5143 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005144 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005145 LPVOID base = GetEnvironmentStringsW();
5146
Bram Moolenaar0f873732019-12-05 20:28:46 +01005147 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005148 if (ga_grow(gap, 1) == FAIL)
5149 return;
5150
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005151 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005152 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005153 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005154 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005155 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005156 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005157 typval_T *item = &dict_lookup(hi)->di_tv;
5158 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005159 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005160 --todo;
5161 if (wkey != NULL && wval != NULL)
5162 {
5163 size_t n;
5164 size_t lkey = wcslen(wkey);
5165 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005166
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005167 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5168 continue;
5169 for (n = 0; n < lkey; n++)
5170 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5171 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5172 for (n = 0; n < lval; n++)
5173 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5174 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5175 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005176 vim_free(wkey);
5177 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005178 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005179 }
5180 }
5181
Bram Moolenaar355757a2020-02-10 22:06:32 +01005182 if (base)
5183 {
5184 WCHAR *p = (WCHAR*) base;
5185
5186 // for last \0
5187 if (ga_grow(gap, 1) == FAIL)
5188 return;
5189
5190 while (*p != 0 || *(p + 1) != 0)
5191 {
5192 if (ga_grow(gap, 1) == OK)
5193 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5194 p++;
5195 }
5196 FreeEnvironmentStrings(base);
5197 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5198 }
5199
Bram Moolenaar493359e2018-06-12 20:25:52 +02005200# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005201 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005202# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005203 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005204 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005205# endif
5206# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005207 char_u *version = get_vim_var_str(VV_VERSION);
5208 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005209# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005210 // size of "VIM_SERVERNAME=" and value,
5211 // plus "VIM_TERMINAL=" and value,
5212 // plus two terminating NULs
5213 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005214# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005215 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005216# endif
5217# ifdef FEAT_TERMINAL
5218 + 13 + version_len + 2
5219# endif
5220 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005221
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005222 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005223 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005224# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005225 for (n = 0; n < 15; n++)
5226 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5227 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005228 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005229 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5230 (WCHAR)servername[n];
5231 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005232# endif
5233# ifdef FEAT_TERMINAL
5234 if (is_terminal)
5235 {
5236 for (n = 0; n < 13; n++)
5237 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5238 (WCHAR)"VIM_TERMINAL="[n];
5239 for (n = 0; n < version_len; n++)
5240 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5241 (WCHAR)version[n];
5242 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5243 }
5244# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005245 }
5246 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005247# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005248}
5249
Bram Moolenaarb091f302019-01-19 14:37:00 +01005250/*
5251 * Create a pair of pipes.
5252 * Return TRUE for success, FALSE for failure.
5253 */
5254 static BOOL
5255create_pipe_pair(HANDLE handles[2])
5256{
5257 static LONG s;
5258 char name[64];
5259 SECURITY_ATTRIBUTES sa;
5260
5261 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5262 GetCurrentProcessId(),
5263 InterlockedIncrement(&s));
5264
5265 // Create named pipe. Max size of named pipe is 65535.
5266 handles[1] = CreateNamedPipe(
5267 name,
5268 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5269 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005270 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005271
5272 if (handles[1] == INVALID_HANDLE_VALUE)
5273 return FALSE;
5274
5275 sa.nLength = sizeof(sa);
5276 sa.bInheritHandle = TRUE;
5277 sa.lpSecurityDescriptor = NULL;
5278
5279 handles[0] = CreateFile(name,
5280 FILE_GENERIC_READ,
5281 FILE_SHARE_READ, &sa,
5282 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5283
5284 if (handles[0] == INVALID_HANDLE_VALUE)
5285 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005286 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005287 return FALSE;
5288 }
5289
5290 return TRUE;
5291}
5292
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005293 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005294mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005295{
5296 STARTUPINFO si;
5297 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005298 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005299 SECURITY_ATTRIBUTES saAttr;
5300 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005301 HANDLE ifd[2];
5302 HANDLE ofd[2];
5303 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005304 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005305
5306 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5307 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5308 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5309 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5310 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5311 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5312 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5313
5314 if (use_out_for_err && use_null_for_out)
5315 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005316
5317 ifd[0] = INVALID_HANDLE_VALUE;
5318 ifd[1] = INVALID_HANDLE_VALUE;
5319 ofd[0] = INVALID_HANDLE_VALUE;
5320 ofd[1] = INVALID_HANDLE_VALUE;
5321 efd[0] = INVALID_HANDLE_VALUE;
5322 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005323 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005324
Bram Moolenaar14207f42016-10-27 21:13:10 +02005325 jo = CreateJobObject(NULL, NULL);
5326 if (jo == NULL)
5327 {
5328 job->jv_status = JOB_FAILED;
5329 goto failed;
5330 }
5331
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005332 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005333 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005334
Bram Moolenaar76467df2016-02-12 19:30:26 +01005335 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005336 ZeroMemory(&si, sizeof(si));
5337 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005338 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005339 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005340
Bram Moolenaard8070362016-02-15 21:56:54 +01005341 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5342 saAttr.bInheritHandle = TRUE;
5343 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005344
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005345 if (use_file_for_in)
5346 {
5347 char_u *fname = options->jo_io_name[PART_IN];
5348
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005349 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5350 FILE_SHARE_READ | FILE_SHARE_WRITE,
5351 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5352 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005353 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005354 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005355 goto failed;
5356 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005357 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005358 else if (!use_null_for_in
5359 && (!create_pipe_pair(ifd)
5360 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005361 goto failed;
5362
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005363 if (use_file_for_out)
5364 {
5365 char_u *fname = options->jo_io_name[PART_OUT];
5366
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005367 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5368 FILE_SHARE_READ | FILE_SHARE_WRITE,
5369 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5370 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005371 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005372 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005373 goto failed;
5374 }
5375 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005376 else if (!use_null_for_out &&
5377 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005378 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005379 goto failed;
5380
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005381 if (use_file_for_err)
5382 {
5383 char_u *fname = options->jo_io_name[PART_ERR];
5384
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005385 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5386 FILE_SHARE_READ | FILE_SHARE_WRITE,
5387 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5388 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005389 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005390 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005391 goto failed;
5392 }
5393 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005394 else if (!use_out_for_err && !use_null_for_err &&
5395 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005396 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005397 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005398
Bram Moolenaard8070362016-02-15 21:56:54 +01005399 si.dwFlags |= STARTF_USESTDHANDLES;
5400 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005401 si.hStdOutput = ofd[1];
5402 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5403
5404 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5405 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005406 if (options->jo_set & JO_CHANNEL)
5407 {
5408 channel = options->jo_channel;
5409 if (channel != NULL)
5410 ++channel->ch_refcount;
5411 }
5412 else
5413 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005414 if (channel == NULL)
5415 goto failed;
5416 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005417
5418 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005419 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005420 CREATE_DEFAULT_ERROR_MODE |
5421 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005422 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005423 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005424 &si, &pi,
5425 ga.ga_data,
5426 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005427 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005428 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005429 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005430 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005431 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005432
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005433 ga_clear(&ga);
5434
Bram Moolenaar14207f42016-10-27 21:13:10 +02005435 if (!AssignProcessToJobObject(jo, pi.hProcess))
5436 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005437 // if failing, switch the way to terminate
5438 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005439 CloseHandle(jo);
5440 jo = NULL;
5441 }
5442 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005443 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005444 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005445 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005446 job->jv_status = JOB_STARTED;
5447
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005448 CloseHandle(ifd[0]);
5449 CloseHandle(ofd[1]);
5450 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005451 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005452
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005453 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005454 if (channel != NULL)
5455 {
5456 channel_set_pipes(channel,
5457 use_file_for_in || use_null_for_in
5458 ? INVALID_FD : (sock_T)ifd[1],
5459 use_file_for_out || use_null_for_out
5460 ? INVALID_FD : (sock_T)ofd[0],
5461 use_out_for_err || use_file_for_err || use_null_for_err
5462 ? INVALID_FD : (sock_T)efd[0]);
5463 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005464 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005465 return;
5466
5467failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005468 CloseHandle(ifd[0]);
5469 CloseHandle(ofd[0]);
5470 CloseHandle(efd[0]);
5471 CloseHandle(ifd[1]);
5472 CloseHandle(ofd[1]);
5473 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005474 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005475 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005476}
5477
5478 char *
5479mch_job_status(job_T *job)
5480{
5481 DWORD dwExitCode = 0;
5482
Bram Moolenaar76467df2016-02-12 19:30:26 +01005483 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5484 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005485 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005486 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005487 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005488 {
5489 ch_log(job->jv_channel, "Job ended");
5490 job->jv_status = JOB_ENDED;
5491 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005492 return "dead";
5493 }
5494 return "run";
5495}
5496
Bram Moolenaar97792de2016-10-15 18:36:49 +02005497 job_T *
5498mch_detect_ended_job(job_T *job_list)
5499{
5500 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5501 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5502 job_T *job = job_list;
5503
5504 while (job != NULL)
5505 {
5506 DWORD n;
5507 DWORD result;
5508
5509 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5510 && job != NULL; job = job->jv_next)
5511 {
5512 if (job->jv_status == JOB_STARTED)
5513 {
5514 jobHandles[n] = job->jv_proc_info.hProcess;
5515 jobArray[n] = job;
5516 ++n;
5517 }
5518 }
5519 if (n == 0)
5520 continue;
5521 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5522 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5523 {
5524 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5525
5526 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5527 return wait_job;
5528 }
5529 }
5530 return NULL;
5531}
5532
Bram Moolenaarfb630902016-10-29 14:55:00 +02005533 static BOOL
5534terminate_all(HANDLE process, int code)
5535{
5536 PROCESSENTRY32 pe;
5537 HANDLE h = INVALID_HANDLE_VALUE;
5538 DWORD pid = GetProcessId(process);
5539
5540 if (pid != 0)
5541 {
5542 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5543 if (h != INVALID_HANDLE_VALUE)
5544 {
5545 pe.dwSize = sizeof(PROCESSENTRY32);
5546 if (!Process32First(h, &pe))
5547 goto theend;
5548
5549 do
5550 {
5551 if (pe.th32ParentProcessID == pid)
5552 {
5553 HANDLE ph = OpenProcess(
5554 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5555 if (ph != NULL)
5556 {
5557 terminate_all(ph, code);
5558 CloseHandle(ph);
5559 }
5560 }
5561 } while (Process32Next(h, &pe));
5562
5563 CloseHandle(h);
5564 }
5565 }
5566
5567theend:
5568 return TerminateProcess(process, code);
5569}
5570
5571/*
5572 * Send a (deadly) signal to "job".
5573 * Return FAIL if it didn't work.
5574 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005575 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005576mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005577{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005578 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005579
Bram Moolenaar923d9262016-02-25 20:56:01 +01005580 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005581 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005582 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005583 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005584 {
5585 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5586 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005587 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005588 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005589 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005590 }
5591
5592 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5593 return FAIL;
5594 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005595 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5596 job->jv_proc_info.dwProcessId)
5597 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005598 FreeConsole();
5599 return ret;
5600}
5601
5602/*
5603 * Clear the data related to "job".
5604 */
5605 void
5606mch_clear_job(job_T *job)
5607{
5608 if (job->jv_status != JOB_FAILED)
5609 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005610 if (job->jv_job_object != NULL)
5611 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005612 CloseHandle(job->jv_proc_info.hProcess);
5613 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005614}
5615#endif
5616
Bram Moolenaar071d4272004-06-13 20:20:40 +00005617
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005618#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619
5620/*
5621 * Start termcap mode
5622 */
5623 static void
5624termcap_mode_start(void)
5625{
5626 DWORD cmodein;
5627
5628 if (g_fTermcapMode)
5629 return;
5630
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005631 if (!p_rs && USE_VTP)
5632 vtp_printf("\033[?1049h");
5633
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634 SaveConsoleBuffer(&g_cbNonTermcap);
5635
5636 if (g_cbTermcap.IsValid)
5637 {
5638 /*
5639 * We've been in termcap mode before. Restore certain screen
5640 * characteristics, including the buffer size and the window
5641 * size. Since we will be redrawing the screen, we don't need
5642 * to restore the actual contents of the buffer.
5643 */
5644 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005645 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5647 Rows = g_cbTermcap.Info.dwSize.Y;
5648 Columns = g_cbTermcap.Info.dwSize.X;
5649 }
5650 else
5651 {
5652 /*
5653 * This is our first time entering termcap mode. Clear the console
5654 * screen buffer, and resize the buffer to match the current window
5655 * size. We will use this as the size of our editing environment.
5656 */
5657 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005658 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005659 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5660 }
5661
Bram Moolenaar071d4272004-06-13 20:20:40 +00005662 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663
5664 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005665 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005666 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005668 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5669 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005670 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005671 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005673 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005675 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005676 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005677
5678 redraw_later_clear();
5679 g_fTermcapMode = TRUE;
5680}
5681
5682
5683/*
5684 * End termcap mode
5685 */
5686 static void
5687termcap_mode_end(void)
5688{
5689 DWORD cmodein;
5690 ConsoleBuffer *cb;
5691 COORD coord;
5692 DWORD dwDummy;
5693
5694 if (!g_fTermcapMode)
5695 return;
5696
5697 SaveConsoleBuffer(&g_cbTermcap);
5698
5699 GetConsoleMode(g_hConIn, &cmodein);
5700 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005701 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5702 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005704# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005705 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005706# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005708# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005709 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005710 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711 SetConsoleCursorInfo(g_hConOut, &g_cci);
5712
5713 if (p_rs || exiting)
5714 {
5715 /*
5716 * Clear anything that happens to be on the current line.
5717 */
5718 coord.X = 0;
5719 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5720 FillConsoleOutputCharacter(g_hConOut, ' ',
5721 cb->Info.dwSize.X, coord, &dwDummy);
5722 /*
5723 * The following is just for aesthetics. If we are exiting without
5724 * restoring the screen, then we want to have a prompt string
5725 * appear at the bottom line. However, the command interpreter
5726 * seems to always advance the cursor one line before displaying
5727 * the prompt string, which causes the screen to scroll. To
5728 * counter this, move the cursor up one line before exiting.
5729 */
5730 if (exiting && !p_rs)
5731 coord.Y--;
5732 /*
5733 * Position the cursor at the leftmost column of the desired row.
5734 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005735 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005736 }
5737
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005738 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005739 vtp_printf("\033[?1049l");
5740
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741 g_fTermcapMode = FALSE;
5742}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005743#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005744
5745
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005746#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005747 void
5748mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005749 char_u *s UNUSED,
5750 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005751{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005752 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005753}
5754
5755#else
5756
5757/*
5758 * clear `n' chars, starting from `coord'
5759 */
5760 static void
5761clear_chars(
5762 COORD coord,
5763 DWORD n)
5764{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005765 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005766 {
5767 DWORD dwDummy;
5768
5769 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5770 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5771 &dwDummy);
5772 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005773 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005774 {
5775 set_console_color_rgb();
5776 gotoxy(coord.X + 1, coord.Y + 1);
5777 vtp_printf("\033[%dX", n);
5778 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779}
5780
5781
5782/*
5783 * Clear the screen
5784 */
5785 static void
5786clear_screen(void)
5787{
5788 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005789
5790 if (!USE_VTP)
5791 clear_chars(g_coord, Rows * Columns);
5792 else
5793 {
5794 set_console_color_rgb();
5795 gotoxy(1, 1);
5796 vtp_printf("\033[2J");
5797 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798}
5799
5800
5801/*
5802 * Clear to end of display
5803 */
5804 static void
5805clear_to_end_of_display(void)
5806{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005807 COORD save = g_coord;
5808
5809 if (!USE_VTP)
5810 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005812 else
5813 {
5814 set_console_color_rgb();
5815 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5816 vtp_printf("\033[0J");
5817
5818 gotoxy(save.X + 1, save.Y + 1);
5819 g_coord = save;
5820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821}
5822
5823
5824/*
5825 * Clear to end of line
5826 */
5827 static void
5828clear_to_end_of_line(void)
5829{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005830 COORD save = g_coord;
5831
5832 if (!USE_VTP)
5833 clear_chars(g_coord, Columns - g_coord.X);
5834 else
5835 {
5836 set_console_color_rgb();
5837 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5838 vtp_printf("\033[0K");
5839
5840 gotoxy(save.X + 1, save.Y + 1);
5841 g_coord = save;
5842 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843}
5844
5845
5846/*
5847 * Scroll the scroll region up by `cLines' lines
5848 */
5849 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005850scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851{
5852 COORD oldcoord = g_coord;
5853
5854 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5855 delete_lines(cLines);
5856
5857 g_coord = oldcoord;
5858}
5859
5860
5861/*
5862 * Set the scroll region
5863 */
5864 static void
5865set_scroll_region(
5866 unsigned left,
5867 unsigned top,
5868 unsigned right,
5869 unsigned bottom)
5870{
5871 if (left >= right
5872 || top >= bottom
5873 || right > (unsigned) Columns - 1
5874 || bottom > (unsigned) Rows - 1)
5875 return;
5876
5877 g_srScrollRegion.Left = left;
5878 g_srScrollRegion.Top = top;
5879 g_srScrollRegion.Right = right;
5880 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005881}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005882
Bram Moolenaar6982f422019-02-16 16:48:01 +01005883 static void
5884set_scroll_region_tb(
5885 unsigned top,
5886 unsigned bottom)
5887{
5888 if (top >= bottom || bottom > (unsigned)Rows - 1)
5889 return;
5890
5891 g_srScrollRegion.Top = top;
5892 g_srScrollRegion.Bottom = bottom;
5893}
5894
5895 static void
5896set_scroll_region_lr(
5897 unsigned left,
5898 unsigned right)
5899{
5900 if (left >= right || right > (unsigned)Columns - 1)
5901 return;
5902
5903 g_srScrollRegion.Left = left;
5904 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005905}
5906
5907
5908/*
5909 * Insert `cLines' lines at the current cursor position
5910 */
5911 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005912insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005913{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005914 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915 COORD dest;
5916 CHAR_INFO fill;
5917
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005918 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5919
Bram Moolenaar6982f422019-02-16 16:48:01 +01005920 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921 dest.Y = g_coord.Y + cLines;
5922
Bram Moolenaar6982f422019-02-16 16:48:01 +01005923 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924 source.Top = g_coord.Y;
5925 source.Right = g_srScrollRegion.Right;
5926 source.Bottom = g_srScrollRegion.Bottom - cLines;
5927
Bram Moolenaar6982f422019-02-16 16:48:01 +01005928 clip.Left = g_srScrollRegion.Left;
5929 clip.Top = g_coord.Y;
5930 clip.Right = g_srScrollRegion.Right;
5931 clip.Bottom = g_srScrollRegion.Bottom;
5932
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005933 fill.Char.AsciiChar = ' ';
5934 if (!USE_VTP)
5935 fill.Attributes = g_attrCurrent;
5936 else
5937 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005938
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005939 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005940
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005941 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5942
Bram Moolenaar6982f422019-02-16 16:48:01 +01005943 // Here we have to deal with a win32 console flake: If the scroll
5944 // region looks like abc and we scroll c to a and fill with d we get
5945 // cbd... if we scroll block c one line at a time to a, we get cdd...
5946 // vim expects cdd consistently... So we have to deal with that
5947 // here... (this also occurs scrolling the same way in the other
5948 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949
5950 if (source.Bottom < dest.Y)
5951 {
5952 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005953 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005954
Bram Moolenaar6982f422019-02-16 16:48:01 +01005955 coord.X = source.Left;
5956 for (i = clip.Top; i < dest.Y; ++i)
5957 {
5958 coord.Y = i;
5959 clear_chars(coord, source.Right - source.Left + 1);
5960 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005962
5963 if (USE_WT)
5964 {
5965 COORD coord;
5966 int i;
5967
5968 coord.X = source.Left;
5969 for (i = source.Top; i < dest.Y; ++i)
5970 {
5971 coord.Y = i;
5972 clear_chars(coord, source.Right - source.Left + 1);
5973 }
5974 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975}
5976
5977
5978/*
5979 * Delete `cLines' lines at the current cursor position
5980 */
5981 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005982delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005983{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005984 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005985 COORD dest;
5986 CHAR_INFO fill;
5987 int nb;
5988
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005989 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5990
Bram Moolenaar6982f422019-02-16 16:48:01 +01005991 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992 dest.Y = g_coord.Y;
5993
Bram Moolenaar6982f422019-02-16 16:48:01 +01005994 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005995 source.Top = g_coord.Y + cLines;
5996 source.Right = g_srScrollRegion.Right;
5997 source.Bottom = g_srScrollRegion.Bottom;
5998
Bram Moolenaar6982f422019-02-16 16:48:01 +01005999 clip.Left = g_srScrollRegion.Left;
6000 clip.Top = g_coord.Y;
6001 clip.Right = g_srScrollRegion.Right;
6002 clip.Bottom = g_srScrollRegion.Bottom;
6003
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006004 fill.Char.AsciiChar = ' ';
6005 if (!USE_VTP)
6006 fill.Attributes = g_attrCurrent;
6007 else
6008 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006010 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006011
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006012 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6013
Bram Moolenaar6982f422019-02-16 16:48:01 +01006014 // Here we have to deal with a win32 console flake; See insert_lines()
6015 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006016
6017 nb = dest.Y + (source.Bottom - source.Top) + 1;
6018
6019 if (nb < source.Top)
6020 {
6021 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006022 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006023
Bram Moolenaar6982f422019-02-16 16:48:01 +01006024 coord.X = source.Left;
6025 for (i = nb; i < clip.Bottom; ++i)
6026 {
6027 coord.Y = i;
6028 clear_chars(coord, source.Right - source.Left + 1);
6029 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006031
6032 if (USE_WT)
6033 {
6034 COORD coord;
6035 int i;
6036
6037 coord.X = source.Left;
6038 for (i = nb; i <= source.Bottom; ++i)
6039 {
6040 coord.Y = i;
6041 clear_chars(coord, source.Right - source.Left + 1);
6042 }
6043 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044}
6045
6046
6047/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006048 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049 */
6050 static void
6051gotoxy(
6052 unsigned x,
6053 unsigned y)
6054{
6055 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6056 return;
6057
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006058 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006059 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006060 // There are reports of double-width characters not displayed
6061 // correctly. This workaround should fix it, similar to how it's done
6062 // for VTP.
6063 g_coord.X = 0;
6064 SetConsoleCursorPosition(g_hConOut, g_coord);
6065
Bram Moolenaar2313b612019-09-27 14:14:32 +02006066 // external cursor coords are 1-based; internal are 0-based
6067 g_coord.X = x - 1;
6068 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006069 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006070 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006071 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006072 {
6073 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006074 // destruction. Insider build bug. Always enabled because it's cheap
6075 // and avoids mistakes with recognizing the build.
6076 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006077
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006078 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006079
6080 g_coord.X = x - 1;
6081 g_coord.Y = y - 1;
6082 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083}
6084
6085
6086/*
6087 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006088 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006089 */
6090 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006091textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006093 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094
6095 SetConsoleTextAttribute(g_hConOut, wAttr);
6096}
6097
6098
6099 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006100textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006101{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006102 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006104 if (!USE_VTP)
6105 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6106 else
6107 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108}
6109
6110
6111 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006112textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006114 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006116 if (!USE_VTP)
6117 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6118 else
6119 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006120}
6121
6122
6123/*
6124 * restore the default text attribute (whatever we started with)
6125 */
6126 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006127normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006129 if (!USE_VTP)
6130 textattr(g_attrDefault);
6131 else
6132 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133}
6134
6135
6136static WORD g_attrPreStandout = 0;
6137
6138/*
6139 * Make the text standout, by brightening it
6140 */
6141 static void
6142standout(void)
6143{
6144 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006145
Bram Moolenaar071d4272004-06-13 20:20:40 +00006146 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6147}
6148
6149
6150/*
6151 * Turn off standout mode
6152 */
6153 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006154standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155{
6156 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006158
6159 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006160}
6161
6162
6163/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006164 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165 */
6166 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006167mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168{
6169 char_u *p;
6170 int n;
6171
6172 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6173 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006174 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006175# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006176 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006177# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006178 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179 {
6180 p = T_ME + 2;
6181 n = getdigits(&p);
6182 if (*p == 'm' && n > 0)
6183 {
6184 cterm_normal_fg_color = (n & 0xf) + 1;
6185 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6186 }
6187 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006188# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006189 cterm_normal_fg_gui_color = INVALCOLOR;
6190 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006191# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006192}
6193
6194
6195/*
6196 * visual bell: flash the screen
6197 */
6198 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006199visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006200{
6201 COORD coordOrigin = {0, 0};
6202 WORD attrFlash = ~g_attrCurrent & 0xff;
6203
6204 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006205 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206
6207 if (oldattrs == NULL)
6208 return;
6209 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6210 coordOrigin, &dwDummy);
6211 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6212 coordOrigin, &dwDummy);
6213
Bram Moolenaar0f873732019-12-05 20:28:46 +01006214 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006215 if (!USE_VTP)
6216 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217 coordOrigin, &dwDummy);
6218 vim_free(oldattrs);
6219}
6220
6221
6222/*
6223 * Make the cursor visible or invisible
6224 */
6225 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006226cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227{
6228 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006229
6230 if (USE_VTP)
6231 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6232
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006233# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006235# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236}
6237
6238
6239/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006240 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006241 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006243 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006245 char_u *pchBuf,
6246 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006248 COORD coord = g_coord;
6249 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006250 DWORD n, cchwritten;
6251 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006252 static WCHAR *unicodebuf = NULL;
6253 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006254 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006255 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006256 static WCHAR *utf8spbuf = NULL;
6257 static int utf8splength;
6258 static DWORD utf8spcells;
6259 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006261 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006262 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006263 utf8usingbuf = &unicodebuf;
6264 do
6265 {
6266 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6267 unicodebuf, unibuflen);
6268 if (length && length <= unibuflen)
6269 break;
6270 vim_free(unicodebuf);
6271 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6272 unibuflen = unibuflen ? 0 : length;
6273 } while(1);
6274 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006275 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006276 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6277 {
6278 if (utf8usingbuf != &utf8spbuf)
6279 {
6280 if (utf8spbuf == NULL)
6281 {
6282 cells = mb_string2cells((char_u *)" ", 1);
6283 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6284 utf8spbuf = LALLOC_MULT(WCHAR, length);
6285 if (utf8spbuf != NULL)
6286 {
6287 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6288 utf8usingbuf = &utf8spbuf;
6289 utf8splength = length;
6290 utf8spcells = cells;
6291 }
6292 }
6293 else
6294 {
6295 utf8usingbuf = &utf8spbuf;
6296 length = utf8splength;
6297 cells = utf8spcells;
6298 }
6299 }
6300 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006301
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006302 if (!USE_VTP)
6303 {
6304 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6305 coord, &written);
6306 // When writing fails or didn't write a single character, pretend one
6307 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006308 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006309 coord, &cchwritten) == 0
6310 || cchwritten == 0 || cchwritten == (DWORD)-1)
6311 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006312 }
6313 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006314 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006315 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006316 NULL) == 0 || cchwritten == 0)
6317 cchwritten = 1;
6318 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006319
K.Takata135e1522022-01-29 15:27:58 +00006320 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006321 {
6322 written = cbToWrite;
6323 g_coord.X += (SHORT)cells;
6324 }
6325 else
6326 {
6327 char_u *p = pchBuf;
6328 for (n = 0; n < cchwritten; n++)
6329 MB_CPTR_ADV(p);
6330 written = p - pchBuf;
6331 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006332 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333
6334 while (g_coord.X > g_srScrollRegion.Right)
6335 {
6336 g_coord.X -= (SHORT) Columns;
6337 if (g_coord.Y < g_srScrollRegion.Bottom)
6338 g_coord.Y++;
6339 }
6340
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006341 // Cursor under VTP is always in the correct position, no need to reset.
6342 if (!USE_VTP)
6343 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344
6345 return written;
6346}
6347
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006348 static char_u *
6349get_seq(
6350 int *args,
6351 int *count,
6352 char_u *head)
6353{
6354 int argc;
6355 char_u *p;
6356
6357 if (head == NULL || *head != '\033')
6358 return NULL;
6359
6360 argc = 0;
6361 p = head;
6362 ++p;
6363 do
6364 {
6365 ++p;
6366 args[argc] = getdigits(&p);
6367 argc += (argc < 15) ? 1 : 0;
6368 } while (*p == ';');
6369 *count = argc;
6370
6371 return p;
6372}
6373
6374 static char_u *
6375get_sgr(
6376 int *args,
6377 int *count,
6378 char_u *head)
6379{
6380 char_u *p = get_seq(args, count, head);
6381
6382 return (p && *p == 'm') ? ++p : NULL;
6383}
6384
6385/*
6386 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6387 */
6388 static char_u *
6389sgrn2(
6390 char_u *head,
6391 int n)
6392{
6393 int argc;
6394 int args[16];
6395 char_u *p = get_sgr(args, &argc, head);
6396
6397 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6398}
6399
6400/*
6401 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6402 */
6403 static char_u *
6404sgrnc(
6405 char_u *head,
6406 int n)
6407{
6408 int argc;
6409 int args[16];
6410 char_u *p = get_sgr(args, &argc, head);
6411
6412 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6413 ? p : NULL;
6414}
6415
6416 static char_u *
6417skipblank(char_u *q)
6418{
6419 char_u *p = q;
6420
6421 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6422 ++p;
6423 return p;
6424}
6425
6426/*
6427 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6428 * NULL.
6429 */
6430 static char_u *
6431sgrn2c(
6432 char_u *head,
6433 int n)
6434{
6435 char_u *p = sgrn2(head, n);
6436
6437 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6438}
6439
6440/*
6441 * If there is only a newline between the sequence immediately following it,
6442 * a pointer to the character following the newline is returned.
6443 * Otherwise NULL.
6444 */
6445 static char_u *
6446sgrn2cn(
6447 char_u *head,
6448 int n)
6449{
6450 char_u *p = sgrn2(head, n);
6451
6452 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6453}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454
6455/*
6456 * mch_write(): write the output buffer to the screen, translating ESC
6457 * sequences into calls to console output routines.
6458 */
6459 void
6460mch_write(
6461 char_u *s,
6462 int len)
6463{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006464 char_u *end = s + len;
6465
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006466# ifdef VIMDLL
6467 if (gui.in_use)
6468 return;
6469# endif
6470
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471 if (!term_console)
6472 {
6473 write(1, s, (unsigned)len);
6474 return;
6475 }
6476
Bram Moolenaar0f873732019-12-05 20:28:46 +01006477 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006478 while (len--)
6479 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006480 int prefix = -1;
6481 char_u ch;
6482
6483 // While processing a sequence, on rare occasions it seems that another
6484 // sequence may be inserted asynchronously.
6485 if (len < 0)
6486 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006487 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006488 return;
6489 }
6490
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006491 while (s + ++prefix < end)
6492 {
6493 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006494 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6495 && ch != '\a' && ch != '\033'))
6496 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498
6499 if (p_wd)
6500 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006501 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502 if (prefix != 0)
6503 prefix = 1;
6504 }
6505
6506 if (prefix != 0)
6507 {
6508 DWORD nWritten;
6509
6510 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006511# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512 if (fdDump)
6513 {
6514 fputc('>', fdDump);
6515 fwrite(s, sizeof(char_u), nWritten, fdDump);
6516 fputs("<\n", fdDump);
6517 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006518# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 len -= (nWritten - 1);
6520 s += nWritten;
6521 }
6522 else if (s[0] == '\n')
6523 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006524 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525 if (g_coord.Y == g_srScrollRegion.Bottom)
6526 {
6527 scroll(1);
6528 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6529 }
6530 else
6531 {
6532 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6533 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006534# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 if (fdDump)
6536 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006537# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538 s++;
6539 }
6540 else if (s[0] == '\r')
6541 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006542 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006544# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545 if (fdDump)
6546 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006547# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 s++;
6549 }
6550 else if (s[0] == '\b')
6551 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006552 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553 if (g_coord.X > g_srScrollRegion.Left)
6554 g_coord.X--;
6555 else if (g_coord.Y > g_srScrollRegion.Top)
6556 {
6557 g_coord.X = g_srScrollRegion.Right;
6558 g_coord.Y--;
6559 }
6560 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006561# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562 if (fdDump)
6563 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006564# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 s++;
6566 }
6567 else if (s[0] == '\a')
6568 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006569 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006571# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572 if (fdDump)
6573 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006574# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575 s++;
6576 }
6577 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6578 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006579# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006580 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006581# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006582 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006583 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006584 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585
6586 switch (s[2])
6587 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006588 case '0': case '1': case '2': case '3': case '4':
6589 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006590 if (*(p = get_seq(args, &argc, s)) != 'm')
6591 goto notsgr;
6592
6593 p = s;
6594
6595 // Handling frequent optional sequences. Output to the screen
6596 // takes too long, so do not output as much as possible.
6597
6598 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6599 // resetFG,FG,BG are omitted.
6600 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006601 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006602 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6603 len = len + 1 - (int)(p - s);
6604 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006606 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006608 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6609 // omitted.
6610 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6611 p = sp;
6612
6613 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6614 // omitted.
6615 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6616 p = sp;
6617
6618 // If BG,BG of SGR are connected, the first BG can be omitted.
6619 if (sgrn2((sp = sgrn2(p, 48)), 48))
6620 p = sp;
6621
6622 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006623 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006624 if (sgrn2((sp = sgrnc(p, 39)), 38))
6625 p = sp;
6626
6627 p = get_seq(args, &argc, p);
6628
6629notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006630 arg1 = args[0];
6631 arg2 = args[1];
6632 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006634 if (argc == 1 && args[0] == 0)
6635 normvideo();
6636 else if (argc == 1)
6637 {
6638 if (USE_VTP)
6639 textcolor((WORD) arg1);
6640 else
6641 textattr((WORD) arg1);
6642 }
6643 else if (USE_VTP)
6644 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006646 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006648 gotoxy(arg2, arg1);
6649 }
6650 else if (argc == 2 && *p == 'r')
6651 {
6652 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6653 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006654 else if (argc == 2 && *p == 'R')
6655 {
6656 set_scroll_region_tb(arg1, arg2);
6657 }
6658 else if (argc == 2 && *p == 'V')
6659 {
6660 set_scroll_region_lr(arg1, arg2);
6661 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006662 else if (argc == 1 && *p == 'A')
6663 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664 gotoxy(g_coord.X + 1,
6665 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6666 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006667 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 {
6669 textbackground((WORD) arg1);
6670 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006671 else if (argc == 1 && *p == 'C')
6672 {
6673 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6674 g_coord.Y + 1);
6675 }
6676 else if (argc == 1 && *p == 'f')
6677 {
6678 textcolor((WORD) arg1);
6679 }
6680 else if (argc == 1 && *p == 'H')
6681 {
6682 gotoxy(1, arg1);
6683 }
6684 else if (argc == 1 && *p == 'L')
6685 {
6686 insert_lines(arg1);
6687 }
6688 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689 {
6690 delete_lines(arg1);
6691 }
6692
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006693 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 s = p + 1;
6695 break;
6696
Bram Moolenaar071d4272004-06-13 20:20:40 +00006697 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698 gotoxy(g_coord.X + 1,
6699 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6700 goto got3;
6701
6702 case 'B':
6703 visual_bell();
6704 goto got3;
6705
6706 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6708 g_coord.Y + 1);
6709 goto got3;
6710
6711 case 'E':
6712 termcap_mode_end();
6713 goto got3;
6714
6715 case 'F':
6716 standout();
6717 goto got3;
6718
6719 case 'f':
6720 standend();
6721 goto got3;
6722
6723 case 'H':
6724 gotoxy(1, 1);
6725 goto got3;
6726
6727 case 'j':
6728 clear_to_end_of_display();
6729 goto got3;
6730
6731 case 'J':
6732 clear_screen();
6733 goto got3;
6734
6735 case 'K':
6736 clear_to_end_of_line();
6737 goto got3;
6738
6739 case 'L':
6740 insert_lines(1);
6741 goto got3;
6742
6743 case 'M':
6744 delete_lines(1);
6745 goto got3;
6746
6747 case 'S':
6748 termcap_mode_start();
6749 goto got3;
6750
6751 case 'V':
6752 cursor_visible(TRUE);
6753 goto got3;
6754
6755 case 'v':
6756 cursor_visible(FALSE);
6757 goto got3;
6758
6759 got3:
6760 s += 3;
6761 len -= 2;
6762 }
6763
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006764# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765 if (fdDump)
6766 {
6767 fputs("ESC | ", fdDump);
6768 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6769 fputc('\n', fdDump);
6770 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006771# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 }
6773 else
6774 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006775 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776 DWORD nWritten;
6777
6778 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006779# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780 if (fdDump)
6781 {
6782 fputc('>', fdDump);
6783 fwrite(s, sizeof(char_u), nWritten, fdDump);
6784 fputs("<\n", fdDump);
6785 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006786# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006787
6788 len -= (nWritten - 1);
6789 s += nWritten;
6790 }
6791 }
6792
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006793# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794 if (fdDump)
6795 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006796# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797}
6798
Bram Moolenaar0f873732019-12-05 20:28:46 +01006799#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800
6801
6802/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006803 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804 */
6805 void
6806mch_delay(
6807 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006808 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006810#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006811 Sleep((int)msec); // never wait for input
6812#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006813# ifdef VIMDLL
6814 if (gui.in_use)
6815 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006816 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006817 return;
6818 }
6819# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006820 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006821# ifdef FEAT_MZSCHEME
6822 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6823 {
6824 int towait = p_mzq;
6825
Bram Moolenaar0f873732019-12-05 20:28:46 +01006826 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006827 while (msec > 0)
6828 {
6829 mzvim_check_threads();
6830 if (msec < towait)
6831 towait = msec;
6832 Sleep(towait);
6833 msec -= towait;
6834 }
6835 }
6836 else
6837# endif
6838 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006839 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006840 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006841#endif
6842}
6843
6844
6845/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006846 * This version of remove is not scared by a readonly (backup) file.
6847 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006848 * Return 0 for success, -1 for failure.
6849 */
6850 int
6851mch_remove(char_u *name)
6852{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006853 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854 int n;
6855
Bram Moolenaar203258c2016-01-17 22:15:16 +01006856 /*
6857 * On Windows, deleting a directory's symbolic link is done by
6858 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6859 */
6860 if (mch_isdir(name) && mch_is_symbolic_link(name))
6861 return mch_rmdir(name);
6862
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006863 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6864
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006865 wn = enc_to_utf16(name, NULL);
6866 if (wn == NULL)
6867 return -1;
6868
6869 n = DeleteFileW(wn) ? 0 : -1;
6870 vim_free(wn);
6871 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872}
6873
6874
6875/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006876 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877 */
6878 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006879mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006880{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006881#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6882# ifdef VIMDLL
6883 if (!gui.in_use)
6884# endif
6885 if (g_fCtrlCPressed || g_fCBrkPressed)
6886 {
6887 ctrl_break_was_pressed = g_fCBrkPressed;
6888 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6889 got_int = TRUE;
6890 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891#endif
6892}
6893
Bram Moolenaar0f873732019-12-05 20:28:46 +01006894// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006895#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006896
6897/*
6898 * How much main memory in KiB that can be used by VIM.
6899 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006900 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006901mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006902{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006903 MEMORYSTATUSEX ms;
6904
Bram Moolenaar0f873732019-12-05 20:28:46 +01006905 // Need to use GlobalMemoryStatusEx() when there is more memory than
6906 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006907 ms.dwLength = sizeof(MEMORYSTATUSEX);
6908 GlobalMemoryStatusEx(&ms);
6909 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006910 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006911 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006912 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006913 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006914 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006915 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006916 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006917 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006918 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006919 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006920 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006921}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006924 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6926 * file whose short file name is "FOO.BAR" (its long file name will
6927 * be correct: "foo.bar~"). Because a file can be accessed by
6928 * either its SFN or its LFN, "foo.bar" has effectively been
6929 * renamed to "foo.bar", which is not at all what was wanted. This
6930 * seems to happen only when renaming files with three-character
6931 * extensions by appending a suffix that does not include ".".
6932 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6933 *
6934 * There is another problem, which isn't really a bug but isn't right either:
6935 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6936 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6937 * service pack 6. Doesn't seem to happen on Windows 98.
6938 *
6939 * Like rename(), returns 0 upon success, non-zero upon failure.
6940 * Should probably set errno appropriately when errors occur.
6941 */
6942 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006943mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006945 WCHAR *p;
6946 int i;
6947 WCHAR szTempFile[_MAX_PATH + 1];
6948 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006951 // No need to play tricks unless the file name contains a "~" as the
6952 // seventh character.
6953 p = wold;
6954 for (i = 0; wold[i] != NUL; ++i)
6955 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6956 && wold[i + 1] != 0)
6957 p = wold + i + 1;
6958 if ((int)(wold + i - p) < 8 || p[6] != '~')
6959 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006960
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006961 // Get base path of new file name. Undocumented feature: If pszNewFile is
6962 // a directory, no error is returned and pszFilePart will be NULL.
6963 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006965 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006967 // Get (and create) a unique temporary file name in directory of new file
6968 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 return -2;
6970
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006971 // blow the temp file away
6972 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006973 return -3;
6974
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006975 // rename old file to the temp file
6976 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977 return -4;
6978
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006979 // now create an empty file called pszOldFile; this prevents the operating
6980 // system using pszOldFile as an alias (SFN) if we're renaming within the
6981 // same directory. For example, we're editing a file called
6982 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6983 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6984 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6985 // cause all sorts of problems later in buf_write(). So, we create an
6986 // empty file called filena~1.txt and the system will have to find some
6987 // other SFN for filena~1.txt~, such as filena~2.txt
6988 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006989 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6990 return -5;
6991 if (!CloseHandle(hf))
6992 return -6;
6993
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006994 // rename the temp file to the new file
6995 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006996 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006997 // Renaming failed. Rename the file back to its old name, so that it
6998 // looks like nothing happened.
6999 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007000 return -7;
7001 }
7002
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007003 // Seems to be left around on Novell filesystems
7004 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007005
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007006 // finally, remove the empty old file
7007 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008 return -8;
7009
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007010 return 0;
7011}
7012
7013
7014/*
7015 * Converts the filenames to UTF-16, then call mch_wrename().
7016 * Like rename(), returns 0 upon success, non-zero upon failure.
7017 */
7018 int
7019mch_rename(
7020 const char *pszOldFile,
7021 const char *pszNewFile)
7022{
7023 WCHAR *wold = NULL;
7024 WCHAR *wnew = NULL;
7025 int retval = -1;
7026
7027 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7028 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7029 if (wold != NULL && wnew != NULL)
7030 retval = mch_wrename(wold, wnew);
7031 vim_free(wold);
7032 vim_free(wnew);
7033 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034}
7035
7036/*
7037 * Get the default shell for the current hardware platform
7038 */
7039 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007040default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007042 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007043}
7044
7045/*
7046 * mch_access() extends access() to do more detailed check on network drives.
7047 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7048 */
7049 int
7050mch_access(char *n, int p)
7051{
7052 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007053 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007054 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007056 wn = enc_to_utf16((char_u *)n, NULL);
7057 if (wn == NULL)
7058 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007060 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007062 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063
7064 if (p & R_OK)
7065 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007066 // Read check is performed by seeing if we can do a find file on
7067 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007068 int i;
7069 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007071 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7072 TempNameW[i] = wn[i];
7073 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7074 TempNameW[i++] = '\\';
7075 TempNameW[i++] = '*';
7076 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007078 hFile = FindFirstFileW(TempNameW, &d);
7079 if (hFile == INVALID_HANDLE_VALUE)
7080 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007081 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083 }
7084
7085 if (p & W_OK)
7086 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007087 // Trying to create a temporary file in the directory should catch
7088 // directories on read-only network shares. However, in
7089 // directories whose ACL allows writes but denies deletes will end
7090 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007091 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7092 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007093 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007094 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095 }
7096 }
7097 else
7098 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007099 // Don't consider a file read-only if another process has opened it.
7100 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7101
Bram Moolenaar0f873732019-12-05 20:28:46 +01007102 // Trying to open the file for the required access does ACL, read-only
7103 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007104 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7105 | ((p & R_OK) ? GENERIC_READ : 0);
7106
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007107 hFile = CreateFileW(wn, access_mode, share_mode,
7108 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007109 if (hFile == INVALID_HANDLE_VALUE)
7110 goto getout;
7111 CloseHandle(hFile);
7112 }
7113
Bram Moolenaar0f873732019-12-05 20:28:46 +01007114 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007115getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117 return retval;
7118}
7119
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007121 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122 */
7123 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007124mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125{
7126 WCHAR *wn;
7127 int f;
7128
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007129 wn = enc_to_utf16((char_u *)name, NULL);
7130 if (wn == NULL)
7131 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007133 f = _wopen(wn, flags, mode);
7134 vim_free(wn);
7135 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136}
7137
7138/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007139 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 */
7141 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007142mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143{
7144 WCHAR *wn, *wm;
7145 FILE *f = NULL;
7146
Bram Moolenaara12a1612019-01-24 16:39:02 +01007147#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007148 // Work around an annoying assertion in the Microsoft debug CRT
7149 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007150 char newMode = mode[strlen(mode) - 1];
7151 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007152
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007153 _get_fmode(&oldMode);
7154 if (newMode == 't')
7155 _set_fmode(_O_TEXT);
7156 else if (newMode == 'b')
7157 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007158#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007159 wn = enc_to_utf16((char_u *)name, NULL);
7160 wm = enc_to_utf16((char_u *)mode, NULL);
7161 if (wn != NULL && wm != NULL)
7162 f = _wfopen(wn, wm);
7163 vim_free(wn);
7164 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007165
Bram Moolenaara12a1612019-01-24 16:39:02 +01007166#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007167 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007168#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007169 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171
Bram Moolenaar071d4272004-06-13 20:20:40 +00007172/*
7173 * SUB STREAM (aka info stream) handling:
7174 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007175 * NTFS can have sub streams for each file. The normal contents of a file is
7176 * stored in the main stream, and extra contents (author information, title and
7177 * so on) can be stored in a sub stream. After Windows 2000, the user can
7178 * access and store this information in sub streams via an explorer's property
7179 * menu item in the right click menu. This information in sub streams was lost
7180 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007181 *
7182 * Incomplete explanation:
7183 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7184 * More useful info and an example:
7185 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7186 */
7187
7188/*
7189 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7190 * and write to stream "substream" of file "to".
7191 * Errors are ignored.
7192 */
7193 static void
7194copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7195{
7196 HANDLE hTo;
7197 WCHAR *to_name;
7198
7199 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7200 wcscpy(to_name, to);
7201 wcscat(to_name, substream);
7202
7203 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7204 FILE_ATTRIBUTE_NORMAL, NULL);
7205 if (hTo != INVALID_HANDLE_VALUE)
7206 {
7207 long done;
7208 DWORD todo;
7209 DWORD readcnt, written;
7210 char buf[4096];
7211
Bram Moolenaar0f873732019-12-05 20:28:46 +01007212 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213 for (done = 0; done < len; done += written)
7214 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007215 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007216 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7217 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7219 FALSE, FALSE, context)
7220 || readcnt != todo
7221 || !WriteFile(hTo, buf, todo, &written, NULL)
7222 || written != todo)
7223 break;
7224 }
7225 CloseHandle(hTo);
7226 }
7227
7228 free(to_name);
7229}
7230
7231/*
7232 * Copy info streams from file "from" to file "to".
7233 */
7234 static void
7235copy_infostreams(char_u *from, char_u *to)
7236{
7237 WCHAR *fromw;
7238 WCHAR *tow;
7239 HANDLE sh;
7240 WIN32_STREAM_ID sid;
7241 int headersize;
7242 WCHAR streamname[_MAX_PATH];
7243 DWORD readcount;
7244 void *context = NULL;
7245 DWORD lo, hi;
7246 int len;
7247
Bram Moolenaar0f873732019-12-05 20:28:46 +01007248 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007249 fromw = enc_to_utf16(from, NULL);
7250 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 if (fromw != NULL && tow != NULL)
7252 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007253 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7255 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7256 if (sh != INVALID_HANDLE_VALUE)
7257 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007258 // Use BackupRead() to find the info streams. Repeat until we
7259 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260 for (;;)
7261 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007262 // Get the header to find the length of the stream name. If
7263 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007264 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007265 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7267 &readcount, FALSE, FALSE, &context)
7268 || readcount == 0)
7269 break;
7270
Bram Moolenaar0f873732019-12-05 20:28:46 +01007271 // We only deal with streams that have a name. The normal
7272 // file data appears to be without a name, even though docs
7273 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007274 if (sid.dwStreamNameSize > 0)
7275 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007276 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007277 if (!BackupRead(sh, (LPBYTE)streamname,
7278 sid.dwStreamNameSize,
7279 &readcount, FALSE, FALSE, &context))
7280 break;
7281
Bram Moolenaar0f873732019-12-05 20:28:46 +01007282 // Copy an info stream with a name ":anything:$DATA".
7283 // Skip "::$DATA", it has no stream name (examples suggest
7284 // it might be used for the normal file contents).
7285 // Note that BackupRead() counts bytes, but the name is in
7286 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007287 len = readcount / sizeof(WCHAR);
7288 streamname[len] = 0;
7289 if (len > 7 && wcsicmp(streamname + len - 6,
7290 L":$DATA") == 0)
7291 {
7292 streamname[len - 6] = 0;
7293 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007294 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007295 }
7296 }
7297
Bram Moolenaar0f873732019-12-05 20:28:46 +01007298 // Advance to the next stream. We might try seeking too far,
7299 // but BackupSeek() doesn't skip over stream borders, thus
7300 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007301 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302 &lo, &hi, &context);
7303 }
7304
Bram Moolenaar0f873732019-12-05 20:28:46 +01007305 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7307
7308 CloseHandle(sh);
7309 }
7310 }
7311 vim_free(fromw);
7312 vim_free(tow);
7313}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007314
7315/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007316 * ntdll.dll definitions
7317 */
7318#define FileEaInformation 7
7319#ifndef STATUS_SUCCESS
7320# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7321#endif
7322
7323typedef struct _FILE_FULL_EA_INFORMATION_ {
7324 ULONG NextEntryOffset;
7325 UCHAR Flags;
7326 UCHAR EaNameLength;
7327 USHORT EaValueLength;
7328 CHAR EaName[1];
7329} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7330
7331typedef struct _FILE_EA_INFORMATION_ {
7332 ULONG EaSize;
7333} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7334
Paul Ollis65745772022-06-05 16:55:54 +01007335#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007336typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7337 PHANDLE FileHandle,
7338 ACCESS_MASK DesiredAccess,
7339 POBJECT_ATTRIBUTES ObjectAttributes,
7340 PIO_STATUS_BLOCK IoStatusBlock,
7341 ULONG ShareAccess,
7342 ULONG OpenOptions);
7343typedef NTSTATUS (NTAPI *PfnNtClose)(
7344 HANDLE Handle);
7345typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007346 HANDLE FileHandle,
7347 PIO_STATUS_BLOCK IoStatusBlock,
7348 PVOID Buffer,
7349 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007350typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7351 HANDLE FileHandle,
7352 PIO_STATUS_BLOCK IoStatusBlock,
7353 PVOID Buffer,
7354 ULONG Length,
7355 BOOLEAN ReturnSingleEntry,
7356 PVOID EaList,
7357 ULONG EaListLength,
7358 PULONG EaIndex,
7359 BOOLEAN RestartScan);
7360typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007361 HANDLE FileHandle,
7362 PIO_STATUS_BLOCK IoStatusBlock,
7363 PVOID FileInformation,
7364 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007365 FILE_INFORMATION_CLASS FileInformationClass);
7366typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7367 PUNICODE_STRING DestinationString,
7368 PCWSTR SourceString);
7369
7370PfnNtOpenFile pNtOpenFile = NULL;
7371PfnNtClose pNtClose = NULL;
7372PfnNtSetEaFile pNtSetEaFile = NULL;
7373PfnNtQueryEaFile pNtQueryEaFile = NULL;
7374PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7375PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007376#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007377
7378/*
7379 * Load ntdll.dll functions.
7380 */
7381 static BOOL
7382load_ntdll(void)
7383{
7384 static int loaded = -1;
7385
7386 if (loaded == -1)
7387 {
7388 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7389 if (hNtdll != NULL)
7390 {
7391 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7392 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7393 pNtSetEaFile = (PfnNtSetEaFile)
7394 GetProcAddress(hNtdll, "NtSetEaFile");
7395 pNtQueryEaFile = (PfnNtQueryEaFile)
7396 GetProcAddress(hNtdll, "NtQueryEaFile");
7397 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7398 GetProcAddress(hNtdll, "NtQueryInformationFile");
7399 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7400 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7401 }
7402 if (pNtOpenFile == NULL
7403 || pNtClose == NULL
7404 || pNtSetEaFile == NULL
7405 || pNtQueryEaFile == NULL
7406 || pNtQueryInformationFile == NULL
7407 || pRtlInitUnicodeString == NULL)
7408 loaded = FALSE;
7409 else
7410 loaded = TRUE;
7411 }
7412 return (BOOL) loaded;
7413}
7414
7415/*
7416 * Copy extended attributes (EA) from file "from" to file "to".
7417 */
7418 static void
7419copy_extattr(char_u *from, char_u *to)
7420{
7421 char_u *fromf = NULL;
7422 char_u *tof = NULL;
7423 WCHAR *fromw = NULL;
7424 WCHAR *tow = NULL;
7425 UNICODE_STRING u;
7426 HANDLE h;
7427 OBJECT_ATTRIBUTES oa;
7428 IO_STATUS_BLOCK iosb;
7429 FILE_EA_INFORMATION_ eainfo = {0};
7430 void *ea = NULL;
7431
7432 if (!load_ntdll())
7433 return;
7434
7435 // Convert the file names to the fully qualified object names.
7436 fromf = alloc(STRLEN(from) + 5);
7437 tof = alloc(STRLEN(to) + 5);
7438 if (fromf == NULL || tof == NULL)
7439 goto theend;
7440 STRCPY(fromf, "\\??\\");
7441 STRCAT(fromf, from);
7442 STRCPY(tof, "\\??\\");
7443 STRCAT(tof, to);
7444
7445 // Convert the names to wide characters.
7446 fromw = enc_to_utf16(fromf, NULL);
7447 tow = enc_to_utf16(tof, NULL);
7448 if (fromw == NULL || tow == NULL)
7449 goto theend;
7450
7451 // Get the EA.
7452 pRtlInitUnicodeString(&u, fromw);
7453 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7454 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7455 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7456 goto theend;
7457 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7458 FileEaInformation);
7459 if (eainfo.EaSize != 0)
7460 {
7461 ea = alloc(eainfo.EaSize);
7462 if (ea != NULL)
7463 {
7464 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7465 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7466 {
7467 vim_free(ea);
7468 ea = NULL;
7469 }
7470 }
7471 }
7472 pNtClose(h);
7473
7474 // Set the EA.
7475 if (ea != NULL)
7476 {
7477 pRtlInitUnicodeString(&u, tow);
7478 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7479 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7480 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7481 goto theend;
7482
7483 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7484 pNtClose(h);
7485 }
7486
7487theend:
7488 vim_free(fromf);
7489 vim_free(tof);
7490 vim_free(fromw);
7491 vim_free(tow);
7492 vim_free(ea);
7493}
7494
7495/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496 * Copy file attributes from file "from" to file "to".
7497 * For Windows NT and later we copy info streams.
7498 * Always returns zero, errors are ignored.
7499 */
7500 int
7501mch_copy_file_attribute(char_u *from, char_u *to)
7502{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007503 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007504 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007505 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 return 0;
7507}
7508
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007509
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007510/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007511 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007512 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007513static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007514static LPWSTR *ArglistW = NULL;
7515static int global_argc = 0;
7516static char **global_argv;
7517
Bram Moolenaar0f873732019-12-05 20:28:46 +01007518static int used_file_argc = 0; // last argument in global_argv[] used
7519 // for the argument list.
7520static int *used_file_indexes = NULL; // indexes in global_argv[] for
7521 // command line arguments added to
7522 // the argument list
7523static int used_file_count = 0; // nr of entries in used_file_indexes
7524static int used_file_literal = FALSE; // take file names literally
7525static int used_file_full_path = FALSE; // file name was full path
7526static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007527static int used_alist_count = 0;
7528
7529
7530/*
7531 * Get the command line arguments. Unicode version.
7532 * Returns argc. Zero when something fails.
7533 */
7534 int
7535get_cmd_argsW(char ***argvp)
7536{
7537 char **argv = NULL;
7538 int argc = 0;
7539 int i;
7540
Bram Moolenaar14993322014-09-09 12:25:33 +02007541 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007542 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7543 if (ArglistW != NULL)
7544 {
7545 argv = malloc((nArgsW + 1) * sizeof(char *));
7546 if (argv != NULL)
7547 {
7548 argc = nArgsW;
7549 argv[argc] = NULL;
7550 for (i = 0; i < argc; ++i)
7551 {
7552 int len;
7553
K.Takatadc73b4b2021-06-08 18:32:36 +02007554 // Convert each Unicode argument to UTF-8.
7555 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007556 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007557 (LPSTR *)&argv[i], &len, 0, 0);
7558 if (argv[i] == NULL)
7559 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007560 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007561 while (i > 0)
7562 free(argv[--i]);
7563 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007564 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007565 argc = 0;
7566 }
7567 }
7568 }
7569 }
7570
7571 global_argc = argc;
7572 global_argv = argv;
7573 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007574 {
7575 if (used_file_indexes != NULL)
7576 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007577 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007578 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007579
7580 if (argvp != NULL)
7581 *argvp = argv;
7582 return argc;
7583}
7584
7585 void
7586free_cmd_argsW(void)
7587{
7588 if (ArglistW != NULL)
7589 {
7590 GlobalFree(ArglistW);
7591 ArglistW = NULL;
7592 }
7593}
7594
7595/*
7596 * Remember "name" is an argument that was added to the argument list.
7597 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7598 * is called.
7599 */
7600 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007601used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007602{
7603 int i;
7604
7605 if (used_file_indexes == NULL)
7606 return;
7607 for (i = used_file_argc + 1; i < global_argc; ++i)
7608 if (STRCMP(global_argv[i], name) == 0)
7609 {
7610 used_file_argc = i;
7611 used_file_indexes[used_file_count++] = i;
7612 break;
7613 }
7614 used_file_literal = literal;
7615 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007616 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007617}
7618
7619/*
7620 * Remember the length of the argument list as it was. If it changes then we
7621 * leave it alone when 'encoding' is set.
7622 */
7623 void
7624set_alist_count(void)
7625{
7626 used_alist_count = GARGCOUNT;
7627}
7628
7629/*
7630 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007631 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007632 * and convert them to 'encoding'.
7633 */
7634 void
7635fix_arg_enc(void)
7636{
7637 int i;
7638 int idx;
7639 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007640 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007641
Bram Moolenaar0f873732019-12-05 20:28:46 +01007642 // Safety checks:
7643 // - if argument count differs between the wide and non-wide argument
7644 // list, something must be wrong.
7645 // - the file name arguments must have been located.
7646 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007647 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007648 || ArglistW == NULL
7649 || used_file_indexes == NULL
7650 || used_file_count == 0
7651 || used_alist_count != GARGCOUNT)
7652 return;
7653
Bram Moolenaar0f873732019-12-05 20:28:46 +01007654 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007655 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007656 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007657 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007658 for (i = 0; i < GARGCOUNT; ++i)
7659 fnum_list[i] = GARGLIST[i].ae_fnum;
7660
Bram Moolenaar0f873732019-12-05 20:28:46 +01007661 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007662 alist_clear(&global_alist);
7663 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007664 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007665
7666 for (i = 0; i < used_file_count; ++i)
7667 {
7668 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007669 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007670 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007671 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007672 int literal = used_file_literal;
7673
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007674#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007675 // When using diff mode may need to concatenate file name to
7676 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007677 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7678 && !mch_isdir(alist_name(&GARGLIST[0])))
7679 {
7680 char_u *r;
7681
7682 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7683 if (r != NULL)
7684 {
7685 vim_free(str);
7686 str = r;
7687 }
7688 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007689#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007690 // Re-use the old buffer by renaming it. When not using literal
7691 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007692 if (used_file_literal)
7693 buf_set_name(fnum_list[i], str);
7694
Bram Moolenaar0f873732019-12-05 20:28:46 +01007695 // Check backtick literal. backtick literal is already expanded in
7696 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007697 if (literal == FALSE)
7698 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007699 size_t len = STRLEN(str);
7700
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007701 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7702 literal = TRUE;
7703 }
7704 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007705 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007706 }
7707
7708 if (!used_file_literal)
7709 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007710 // Now expand wildcards in the arguments.
7711 // Temporarily add '(' and ')' to 'isfname'. These are valid
7712 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007713 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007714 // Also, unset wildignore to not be influenced by this option.
7715 // The arguments specified in command-line should be kept even if
7716 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007717 // Use :legacy so that it also works when in Vim9 script.
7718 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7719 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007720 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007721 do_cmdline_cmd(
7722 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7723 do_cmdline_cmd(
7724 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007725 }
7726
Bram Moolenaar0f873732019-12-05 20:28:46 +01007727 // If wildcard expansion failed, we are editing the first file of the
7728 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007729 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7730 {
7731 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007732 if (GARGCOUNT == 1 && used_file_full_path
7733 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7734 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007735 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007736
7737 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007738}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007739
7740 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007741mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007742{
7743 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007744 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007745
Bram Moolenaar964b3742019-05-24 18:54:09 +02007746 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007747 if (envbuf == NULL)
7748 return -1;
7749
7750 sprintf((char *)envbuf, "%s=%s", var, value);
7751
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007752 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007753
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007754 vim_free(envbuf);
7755 if (p == NULL)
7756 return -1;
7757 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007758#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007759 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007760#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007761 // Unlike Un*x systems, we can free the string for _wputenv().
7762 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007763
7764 return 0;
7765}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007766
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007767/*
7768 * Support for 256 colors and 24-bit colors was added in Windows 10
7769 * version 1703 (Creators update).
7770 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007771#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7772
7773/*
7774 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007775 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007776 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007777#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007778
7779/*
7780 * ConPTY differences between versions, need different logic.
7781 * version 1903 (May 2019 update).
7782 */
7783#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7784
7785/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007786 * version 1909 (November 2019 update).
7787 */
7788#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7789
7790/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007791 * Stay ahead of the next update, and when it's done, fix this.
7792 * version ? (2020 update, temporarily use the build number of insider preview)
7793 */
7794#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7795
7796/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007797 * Confirm until this version. Also the logic changes.
7798 * insider preview.
7799 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007800#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007801
7802/*
7803 * Not stable now.
7804 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007805#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007806
7807 static void
7808vtp_flag_init(void)
7809{
7810 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007811#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007812 DWORD mode;
7813 HANDLE out;
7814
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007815# ifdef VIMDLL
7816 if (!gui.in_use)
7817# endif
7818 {
7819 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007820
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007821 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7822 GetConsoleMode(out, &mode);
7823 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7824 if (SetConsoleMode(out, mode) == 0)
7825 vtp_working = 0;
7826 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007827#endif
7828
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007829 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007830 conpty_working = 1;
7831 if (ver >= CONPTY_STABLE_BUILD)
7832 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007833
Bram Moolenaar57da6982019-09-13 22:30:11 +02007834 if (ver <= CONPTY_INSIDER_BUILD)
7835 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007836 if (ver <= CONPTY_1909_BUILD)
7837 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007838 if (ver <= CONPTY_1903_BUILD)
7839 conpty_type = 2;
7840 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7841 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007842
7843 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7844 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007845}
7846
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007847#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007848
7849 static void
7850vtp_init(void)
7851{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007852 HMODULE hKerneldll;
7853 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007854# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007855 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007856# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007857
Bram Moolenaar0f873732019-12-05 20:28:46 +01007858 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007859 hKerneldll = GetModuleHandle("kernel32.dll");
7860 if (hKerneldll != NULL)
7861 {
7862 pGetConsoleScreenBufferInfoEx =
7863 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7864 hKerneldll, "GetConsoleScreenBufferInfoEx");
7865 pSetConsoleScreenBufferInfoEx =
7866 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7867 hKerneldll, "SetConsoleScreenBufferInfoEx");
7868 if (pGetConsoleScreenBufferInfoEx != NULL
7869 && pSetConsoleScreenBufferInfoEx != NULL)
7870 has_csbiex = TRUE;
7871 }
7872
7873 csbi.cbSize = sizeof(csbi);
7874 if (has_csbiex)
7875 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007876 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7877 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007878 store_console_bg_rgb = save_console_bg_rgb;
7879 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007880
7881# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01007882 if (!USE_WT)
7883 {
7884 COLORREF bg;
7885 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7886 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7887 default_console_color_bg = bg;
7888 }
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007889 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007890 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007891 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007892# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007893
7894 set_console_color_rgb();
7895}
7896
7897 static void
7898vtp_exit(void)
7899{
Bram Moolenaardf543822020-01-30 11:53:59 +01007900 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007901}
7902
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007903 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007904vtp_printf(
7905 char *format,
7906 ...)
7907{
7908 char_u buf[100];
7909 va_list list;
7910 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007911 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007912
7913 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007914 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007915 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007916 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007917 return (int)result;
7918}
7919
7920 static void
7921vtp_sgr_bulk(
7922 int arg)
7923{
7924 int args[1];
7925
7926 args[0] = arg;
7927 vtp_sgr_bulks(1, args);
7928}
7929
K.Takata6e1d31e2022-02-03 13:05:32 +00007930# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007931 if ((*p-- = "0123456789"[(n = x % 10)]) \
7932 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7933 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7934
K.Takata6e1d31e2022-02-03 13:05:32 +00007935# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007936 case x: \
7937 FAST256(newargs[x - 1]);
7938
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007939 static void
7940vtp_sgr_bulks(
7941 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007942 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007943{
K.Takata6e1d31e2022-02-03 13:05:32 +00007944# define MAXSGR 16
7945# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007946 char_u buf[SGRBUFSIZE];
7947 char_u *p;
7948 int in, out;
7949 int newargs[16];
7950 static int sgrfgr = -1, sgrfgg, sgrfgb;
7951 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007952
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007953 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007954 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007955 sgrfgr = sgrbgr = -1;
7956 vtp_printf("033[m");
7957 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007958 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007959
7960 in = out = 0;
7961 while (in < argc)
7962 {
7963 int s = args[in];
7964 int copylen = 1;
7965
7966 if (s == 38)
7967 {
7968 if (argc - in >= 5 && args[in + 1] == 2)
7969 {
7970 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7971 && sgrfgb == args[in + 4])
7972 {
7973 in += 5;
7974 copylen = 0;
7975 }
7976 else
7977 {
7978 sgrfgr = args[in + 2];
7979 sgrfgg = args[in + 3];
7980 sgrfgb = args[in + 4];
7981 copylen = 5;
7982 }
7983 }
7984 else if (argc - in >= 3 && args[in + 1] == 5)
7985 {
7986 sgrfgr = -1;
7987 copylen = 3;
7988 }
7989 }
7990 else if (s == 48)
7991 {
7992 if (argc - in >= 5 && args[in + 1] == 2)
7993 {
7994 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
7995 && sgrbgb == args[in + 4])
7996 {
7997 in += 5;
7998 copylen = 0;
7999 }
8000 else
8001 {
8002 sgrbgr = args[in + 2];
8003 sgrbgg = args[in + 3];
8004 sgrbgb = args[in + 4];
8005 copylen = 5;
8006 }
8007 }
8008 else if (argc - in >= 3 && args[in + 1] == 5)
8009 {
8010 sgrbgr = -1;
8011 copylen = 3;
8012 }
8013 }
8014 else if (30 <= s && s <= 39)
8015 sgrfgr = -1;
8016 else if (90 <= s && s <= 97)
8017 sgrfgr = -1;
8018 else if (40 <= s && s <= 49)
8019 sgrbgr = -1;
8020 else if (100 <= s && s <= 107)
8021 sgrbgr = -1;
8022 else if (s == 0)
8023 sgrfgr = sgrbgr = -1;
8024
8025 while (copylen--)
8026 newargs[out++] = args[in++];
8027 }
8028
8029 p = &buf[sizeof(buf) - 1];
8030 *p-- = 'm';
8031
8032 switch (out)
8033 {
8034 int n, m;
8035 DWORD r;
8036
8037 FAST256CASE(16);
8038 *p-- = ';';
8039 FAST256CASE(15);
8040 *p-- = ';';
8041 FAST256CASE(14);
8042 *p-- = ';';
8043 FAST256CASE(13);
8044 *p-- = ';';
8045 FAST256CASE(12);
8046 *p-- = ';';
8047 FAST256CASE(11);
8048 *p-- = ';';
8049 FAST256CASE(10);
8050 *p-- = ';';
8051 FAST256CASE(9);
8052 *p-- = ';';
8053 FAST256CASE(8);
8054 *p-- = ';';
8055 FAST256CASE(7);
8056 *p-- = ';';
8057 FAST256CASE(6);
8058 *p-- = ';';
8059 FAST256CASE(5);
8060 *p-- = ';';
8061 FAST256CASE(4);
8062 *p-- = ';';
8063 FAST256CASE(3);
8064 *p-- = ';';
8065 FAST256CASE(2);
8066 *p-- = ';';
8067 FAST256CASE(1);
8068 *p-- = '[';
8069 *p = '\033';
8070 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8071 default:
8072 break;
8073 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008074}
8075
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008076 static void
8077wt_init(void)
8078{
8079 wt_working = (mch_getenv("WT_SESSION") != NULL);
8080}
8081
8082 int
8083use_wt(void)
8084{
8085 return USE_WT;
8086}
8087
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008088# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008089 static int
8090ctermtoxterm(
8091 int cterm)
8092{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008093 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008094
8095 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8096 return (((int)r << 16) | ((int)g << 8) | (int)b);
8097}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008098# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008099
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008100 static void
8101set_console_color_rgb(void)
8102{
8103# ifdef FEAT_TERMGUICOLORS
8104 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008105 guicolor_T fg, bg;
8106 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008107
8108 if (!USE_VTP)
8109 return;
8110
Bram Moolenaara050b942019-12-02 21:35:31 +01008111 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8112
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008113 if (USE_WT)
8114 {
8115 term_fg_rgb_color(fg);
8116 term_bg_rgb_color(bg);
8117 return;
8118 }
8119
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008120 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8121 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8122
8123 csbi.cbSize = sizeof(csbi);
8124 if (has_csbiex)
8125 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8126
8127 csbi.cbSize = sizeof(csbi);
8128 csbi.srWindow.Right += 1;
8129 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008130 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8131 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008132 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8133 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008134 if (has_csbiex)
8135 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8136# endif
8137}
8138
Bram Moolenaara050b942019-12-02 21:35:31 +01008139# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8140 void
8141get_default_console_color(
8142 int *cterm_fg,
8143 int *cterm_bg,
8144 guicolor_T *gui_fg,
8145 guicolor_T *gui_bg)
8146{
8147 int id;
8148 guicolor_T guifg = INVALCOLOR;
8149 guicolor_T guibg = INVALCOLOR;
8150 int ctermfg = 0;
8151 int ctermbg = 0;
8152
8153 id = syn_name2id((char_u *)"Normal");
8154 if (id > 0 && p_tgc)
8155 syn_id2colors(id, &guifg, &guibg);
8156 if (guifg == INVALCOLOR)
8157 {
8158 ctermfg = -1;
8159 if (id > 0)
8160 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8161 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8162 : default_console_color_fg;
8163 cterm_normal_fg_gui_color = guifg;
8164 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8165 }
8166 if (guibg == INVALCOLOR)
8167 {
8168 ctermbg = -1;
8169 if (id > 0)
8170 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008171 if (!USE_WT)
8172 {
8173 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8174 : default_console_color_bg;
8175 cterm_normal_bg_gui_color = guibg;
8176 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8177 }
8178 else
8179 {
8180 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008181 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008182 if (ctermbg < 0)
8183 ctermbg = 0;
8184 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008185 }
8186
8187 *cterm_fg = ctermfg;
8188 *cterm_bg = ctermbg;
8189 *gui_fg = guifg;
8190 *gui_bg = guibg;
8191}
8192# endif
8193
Bram Moolenaardf543822020-01-30 11:53:59 +01008194/*
8195 * Set the console colors to the original colors or the last set colors.
8196 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008197 static void
8198reset_console_color_rgb(void)
8199{
8200# ifdef FEAT_TERMGUICOLORS
8201 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8202
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008203 if (USE_WT)
8204 return;
8205
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008206 csbi.cbSize = sizeof(csbi);
8207 if (has_csbiex)
8208 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8209
8210 csbi.cbSize = sizeof(csbi);
8211 csbi.srWindow.Right += 1;
8212 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008213 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8214 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8215 if (has_csbiex)
8216 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8217# endif
8218}
8219
8220/*
8221 * Set the console colors to the original colors.
8222 */
8223 static void
8224restore_console_color_rgb(void)
8225{
8226# ifdef FEAT_TERMGUICOLORS
8227 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8228
8229 csbi.cbSize = sizeof(csbi);
8230 if (has_csbiex)
8231 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8232
8233 csbi.cbSize = sizeof(csbi);
8234 csbi.srWindow.Right += 1;
8235 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008236 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8237 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008238 if (has_csbiex)
8239 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8240# endif
8241}
8242
8243 void
8244control_console_color_rgb(void)
8245{
8246 if (USE_VTP)
8247 set_console_color_rgb();
8248 else
8249 reset_console_color_rgb();
8250}
8251
8252 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008253use_vtp(void)
8254{
8255 return USE_VTP;
8256}
8257
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008258 int
8259is_term_win32(void)
8260{
8261 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8262}
8263
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008264 int
8265has_vtp_working(void)
8266{
8267 return vtp_working;
8268}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008269
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008270#endif
8271
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008272 int
8273has_conpty_working(void)
8274{
8275 return conpty_working;
8276}
8277
8278 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008279get_conpty_type(void)
8280{
8281 return conpty_type;
8282}
8283
8284 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008285is_conpty_stable(void)
8286{
8287 return conpty_stable;
8288}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008289
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008290 int
8291get_conpty_fix_type(void)
8292{
8293 return conpty_fix_type;
8294}
8295
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008296#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008297 void
8298resize_console_buf(void)
8299{
8300 CONSOLE_SCREEN_BUFFER_INFO csbi;
8301 COORD coord;
8302 SMALL_RECT newsize;
8303
8304 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8305 {
8306 coord.X = SRWIDTH(csbi.srWindow);
8307 coord.Y = SRHEIGHT(csbi.srWindow);
8308 SetConsoleScreenBufferSize(g_hConOut, coord);
8309
8310 newsize.Left = 0;
8311 newsize.Top = 0;
8312 newsize.Right = coord.X - 1;
8313 newsize.Bottom = coord.Y - 1;
8314 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8315
8316 SetConsoleScreenBufferSize(g_hConOut, coord);
8317 }
8318}
8319#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008320
8321 char *
8322GetWin32Error(void)
8323{
K.Takatad68b2fc2022-02-12 11:18:37 +00008324 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008325 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008326
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008327 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8328 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008329 if (oldmsg != NULL)
8330 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008331 if (msg != NULL)
8332 {
8333 // remove trailing \r\n
8334 char *pcrlf = strstr(msg, "\r\n");
8335 if (pcrlf != NULL)
8336 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008337 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008338 }
8339 return msg;
8340}
Paul Ollis65745772022-06-05 16:55:54 +01008341
8342#if defined(FEAT_RELTIME) || defined(PROTO)
8343static HANDLE timer_handle;
8344static int timer_active = FALSE;
8345
8346/*
8347 * Calls to start_timeout alternate the return value pointer between the two
8348 * entries in timeout_flags. If the previously active timeout is very close to
8349 * expiring when start_timeout() is called then a race condition means that the
8350 * set_flag() function may still be invoked after the previous timer is
8351 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8352 * timeouts.
8353 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008354static sig_atomic_t timeout_flags[2];
8355static int timeout_flag_idx = 0;
8356static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008357
8358
8359 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008360set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008361{
8362 int *timeout_flag = (int *)param;
8363
8364 *timeout_flag = TRUE;
8365}
8366
8367/*
8368 * Stop any active timeout.
8369 */
8370 void
8371stop_timeout(void)
8372{
8373 if (timer_active)
8374 {
8375 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
8376 timer_active = FALSE;
8377 if (!ret && GetLastError() != ERROR_IO_PENDING)
8378 {
8379 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8380 }
8381 }
8382 *timeout_flag = FALSE;
8383}
8384
8385/*
8386 * Start the timeout timer.
8387 *
8388 * The period is defined in milliseconds.
8389 *
8390 * The return value is a pointer to a flag that is initialised to 0. If the
8391 * timeout expires, the flag is set to 1. This will only return pointers to
8392 * static memory; i.e. any pointer returned by this function may always be
8393 * safely dereferenced.
8394 *
8395 * This function is not expected to fail, but if it does it still returns a
8396 * valid flag pointer; the flag will remain stuck at zero.
8397 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008398 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008399start_timeout(long msec)
8400{
Paul Ollis65745772022-06-05 16:55:54 +01008401 BOOL ret;
8402
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008403 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008404
8405 stop_timeout();
8406 ret = CreateTimerQueueTimer(
8407 &timer_handle, NULL, set_flag, timeout_flag,
8408 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8409 if (!ret)
8410 {
8411 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8412 }
8413 else
8414 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008415 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008416 timer_active = TRUE;
8417 *timeout_flag = FALSE;
8418 }
8419 return timeout_flag;
8420}
8421#endif