blob: e5351b1ce1d056094292d8fc85a18e0e835c0461 [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 *
Nir Lichtman563e8ec2024-09-30 19:42:28 +020015 * Win32 system-dependent routines.
Bram Moolenaar071d4272004-06-13 20:20:40 +000016 * 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 Moolenaar071d4272004-06-13 20:20:40 +000037# include <direct.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
Bram Moolenaar651fca82021-11-29 20:39:38 +000039# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010040# include <shellapi.h>
41# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000042
K.Takata56f587b2024-06-19 19:56:03 +020043# ifdef FEAT_JOB_CHANNEL
44# include <tlhelp32.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000045# endif
46#endif
47
Bram Moolenaar0f873732019-12-05 20:28:46 +010048// Record all output and all keyboard & mouse input
49// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000050
51#ifdef MCH_WRITE_DUMP
52FILE* fdDump = NULL;
53#endif
54
55/*
56 * When generating prototypes for Win32 on Unix, these lines make the syntax
57 * errors disappear. They do not need to be correct.
58 */
59#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010060# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000061typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000062typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000063typedef int ACCESS_MASK;
64typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +010065typedef int BOOLEAN;
66typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +000067typedef int COLORREF;
68typedef int CONSOLE_CURSOR_INFO;
69typedef int COORD;
70typedef int DWORD;
71typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +010072typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000073typedef int HDC;
74typedef int HFONT;
75typedef int HICON;
76typedef int HINSTANCE;
77typedef int HWND;
78typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +020079typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +000080typedef int KEY_EVENT_RECORD;
81typedef int LOGFONT;
82typedef int LPBOOL;
83typedef int LPCTSTR;
84typedef int LPDWORD;
85typedef int LPSTR;
86typedef int LPTSTR;
87typedef int LPVOID;
88typedef int MOUSE_EVENT_RECORD;
89typedef int PACL;
90typedef int PDWORD;
91typedef int PHANDLE;
92typedef int PRINTDLG;
93typedef int PSECURITY_DESCRIPTOR;
94typedef int PSID;
95typedef int SECURITY_INFORMATION;
96typedef int SHORT;
97typedef int SMALL_RECT;
98typedef int TEXTMETRIC;
99typedef int TOKEN_INFORMATION_CLASS;
100typedef int TRUSTEE;
101typedef int WORD;
102typedef int WCHAR;
103typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100104typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200105typedef int SE_OBJECT_TYPE;
106typedef int PSNSECINFO;
107typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100108typedef int STARTUPINFO;
109typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200110typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100111# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000112#endif
113
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200114#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100115// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
117static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
118
Bram Moolenaar0f873732019-12-05 20:28:46 +0100119// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000120static SMALL_RECT g_srScrollRegion;
Saleem Abdulrasool38bea302023-12-27 18:57:12 +0100121// This is explicitly initialised to work around a LTCG issue on Windows ARM64
122// (at least of 19.39.33321). This pushes this into the `.data` rather than
123// `.bss` which corrects code generation in `write_chars` (#13453).
124static COORD g_coord = {0, 0}; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000125
Bram Moolenaar0f873732019-12-05 20:28:46 +0100126// The attribute of the screen when the editor was started
127static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000128static WORD g_attrCurrent;
129
Bram Moolenaar0f873732019-12-05 20:28:46 +0100130static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
131static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
132static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000133
Bram Moolenaar071d4272004-06-13 20:20:40 +0000134static void scroll(unsigned cLines);
135static void set_scroll_region(unsigned left, unsigned top,
136 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100137static void set_scroll_region_tb(unsigned top, unsigned bottom);
138static void set_scroll_region_lr(unsigned left, unsigned right);
139static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140static void delete_lines(unsigned cLines);
141static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000143static int s_cursor_visible = TRUE;
144static int did_create_conin = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000145// The 'input_record_buffer' is an internal dynamic fifo queue of MS-Windows
146// console INPUT_RECORD events that are normally read from the console input
147// buffer. This provides an injection point for testing the low-level handling
148// of INPUT_RECORDs.
149typedef struct input_record_buffer_node_S
150{
151 INPUT_RECORD ir;
152 struct input_record_buffer_node_S *next;
153} input_record_buffer_node_T;
154typedef struct input_record_buffer_S
155{
156 input_record_buffer_node_T *head;
157 input_record_buffer_node_T *tail;
158 int length;
159} input_record_buffer_T;
160static input_record_buffer_T input_record_buffer;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000161static int read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength);
162static int write_input_record_buffer(INPUT_RECORD* irEvents, int nLength);
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200163#endif
164#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000165static int s_dont_use_vimrun = TRUE;
166static int need_vimrun_warning = FALSE;
167static char *vimrun_path = "vimrun ";
168#endif
169
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200170static int win32_getattrs(char_u *name);
171static int win32_setattrs(char_u *name, int attrs);
172static int win32_set_archive(char_u *name);
173
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100174static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200175static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100176static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200177static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100178static void vtp_flag_init();
179
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100181static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100182static void vtp_init();
183static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100184static void vtp_sgr_bulk(int arg);
185static void vtp_sgr_bulks(int argc, int *argv);
186
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200187static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000188static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200189
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200190static int g_color_index_bg = 0;
191static int g_color_index_fg = 7;
192
193# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000194static guicolor_T save_console_bg_rgb;
195static guicolor_T save_console_fg_rgb;
196static guicolor_T store_console_bg_rgb;
197static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100198static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200199static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +0000200# define USE_VTP (vtp_working && is_term_win32() \
201 && (p_tgc || t_colors >= 256))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200202# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100203# else
204# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200205# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100206# endif
207
208static void set_console_color_rgb(void);
209static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100210static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000211#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100212
Bram Moolenaar0f873732019-12-05 20:28:46 +0100213// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100214#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
215# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
216#endif
217
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200218#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100219static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000220#endif
221
K.Takatace3189d2023-02-15 19:13:43 +0000222static WCHAR *exe_pathw = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200223
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100224static BOOL win8_or_later = FALSE;
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000225static BOOL win10_22H2_or_later = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000226#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000227static BOOL use_alternate_screen_buffer = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000228#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100229
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100230/*
231 * Get version number including build number
232 */
233typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100234#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100235 (((major) << 24) | ((minor) << 16) | (build))
236
237 static DWORD
238get_build_number(void)
239{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100240 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100241 HMODULE hNtdll;
242 PfnRtlGetVersion pRtlGetVersion;
243 DWORD ver = MAKE_VER(0, 0, 0);
244
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100245 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246 hNtdll = GetModuleHandle("ntdll.dll");
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000247 if (hNtdll == NULL)
248 return ver;
249
250 pRtlGetVersion =
251 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
252 pRtlGetVersion(&osver);
253 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
254 min(osver.dwMinorVersion, 255),
255 min(osver.dwBuildNumber, 32767));
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100256 return ver;
257}
258
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200259#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200260 static BOOL
261is_ambiwidth_event(
262 INPUT_RECORD *ir)
263{
264 return ir->EventType == KEY_EVENT
265 && ir->Event.KeyEvent.bKeyDown
266 && ir->Event.KeyEvent.wRepeatCount == 1
267 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
268 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000269 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200270 && ir->Event.KeyEvent.dwControlKeyState == 2;
271}
272
273 static void
274make_ambiwidth_event(
275 INPUT_RECORD *down,
276 INPUT_RECORD *up)
277{
278 down->Event.KeyEvent.wVirtualKeyCode = 0;
279 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000280 down->Event.KeyEvent.uChar.UnicodeChar
281 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200282 down->Event.KeyEvent.dwControlKeyState = 0;
283}
284
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285/*
286 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100287 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288 */
289 static BOOL
290read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100291 HANDLE hInput,
292 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100293 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100295{
296 enum
297 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301 static DWORD s_dwIndex = 0;
302 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100304 int head;
305 int tail;
306 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200307 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100308
Christopher Plewright20b795e2022-12-20 20:01:58 +0000309 if (s_dwMax == 0 && input_record_buffer.length > 0)
310 {
311 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
312 s_dwIndex = 0;
313 s_dwMax = dwEvents;
314 }
315
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200316 if (nLength == -2)
317 return (s_dwMax > 0) ? TRUE : FALSE;
318
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 if (!win8_or_later)
320 {
321 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200322 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
323 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100324 }
325
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 if (s_dwMax == 0)
327 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000328 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200329 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200330 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
331 if (dwEvents == 0 && nLength == -1)
332 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
333 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 s_dwIndex = 0;
335 s_dwMax = dwEvents;
336 if (dwEvents == 0)
337 {
338 *lpEvents = 0;
339 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100340 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100341
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200342 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
343 if (is_ambiwidth_event(&s_irCache[i]))
344 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
345
Bram Moolenaardd415a62014-02-05 14:02:27 +0100346 if (s_dwMax > 1)
347 {
348 head = 0;
349 tail = s_dwMax - 1;
350 while (head != tail)
351 {
352 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
353 && s_irCache[head + 1].EventType
354 == WINDOW_BUFFER_SIZE_EVENT)
355 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100356 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100357 for (i = head; i < tail; ++i)
358 s_irCache[i] = s_irCache[i + 1];
359 --tail;
360 continue;
361 }
362 head++;
363 }
364 s_dwMax = tail + 1;
365 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100366 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100367
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200368 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
369 {
370 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
371 {
372 s_irPseudo = s_irCache[s_dwIndex];
373 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
374 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
375 *lpBuffer = s_irPseudo;
376 *lpEvents = 1;
377 return TRUE;
378 }
379 }
380
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100381 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200382 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100383 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100384 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100385 return TRUE;
386}
387
388/*
389 * Version of PeekConsoleInput() that works with IME.
390 */
391 static BOOL
392peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100393 HANDLE hInput,
394 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200395 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100396 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100397{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100398 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100399}
400
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100401# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200402 static DWORD
403msg_wait_for_multiple_objects(
404 DWORD nCount,
405 LPHANDLE pHandles,
406 BOOL fWaitAll,
407 DWORD dwMilliseconds,
408 DWORD dwWakeMask)
409{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100410 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200411 return WAIT_OBJECT_0;
412 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
413 dwMilliseconds, dwWakeMask);
414}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100415# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200416
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100417# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200418 static DWORD
419wait_for_single_object(
420 HANDLE hHandle,
421 DWORD dwMilliseconds)
422{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100423 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200424 return WAIT_OBJECT_0;
425 return WaitForSingleObject(hHandle, dwMilliseconds);
426}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100427# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000428#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200429
K.Takatace3189d2023-02-15 19:13:43 +0000430 void
431mch_get_exe_name(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100433 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
K.Takataf741e3e2023-05-15 16:41:40 +0100434 // as the maximum length that works. Add 1 for a NUL byte and 5 for
435 // "PATH=".
436#define MAX_ENV_PATH_LEN (8191 + 1 + 5)
437 WCHAR temp[MAX_ENV_PATH_LEN];
K.Takatace3189d2023-02-15 19:13:43 +0000438 WCHAR buf[MAX_PATH];
439 int updated = FALSE;
440 static int enc_prev = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441
K.Takatace3189d2023-02-15 19:13:43 +0000442 if (exe_name == NULL || exe_pathw == NULL || enc_prev != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100444 // store the name of the executable, may be used for $VIM
K.Takatace3189d2023-02-15 19:13:43 +0000445 GetModuleFileNameW(NULL, buf, MAX_PATH);
446 if (*buf != NUL)
447 {
448 if (enc_codepage == -1)
449 enc_codepage = GetACP();
K.Takataf741e3e2023-05-15 16:41:40 +0100450 vim_free(exe_name);
K.Takatace3189d2023-02-15 19:13:43 +0000451 exe_name = utf16_to_enc(buf, NULL);
452 enc_prev = enc_codepage;
453
454 WCHAR *wp = wcsrchr(buf, '\\');
455 if (wp != NULL)
456 *wp = NUL;
K.Takataf741e3e2023-05-15 16:41:40 +0100457 vim_free(exe_pathw);
K.Takatace3189d2023-02-15 19:13:43 +0000458 exe_pathw = _wcsdup(buf);
459 updated = TRUE;
460 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000461 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000462
K.Takatace3189d2023-02-15 19:13:43 +0000463 if (exe_pathw == NULL || !updated)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000464 return;
465
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000466 // Append our starting directory to $PATH, so that when doing
467 // "!xxd" it's found in our starting directory. Needed because
468 // SearchPath() also looks there.
K.Takataf741e3e2023-05-15 16:41:40 +0100469 WCHAR *p = _wgetenv(L"PATH");
470 if (p == NULL || wcslen(p) + wcslen(exe_pathw) + 2 + 5 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000471 {
K.Takataf741e3e2023-05-15 16:41:40 +0100472 wcscpy(temp, L"PATH=");
473
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000474 if (p == NULL || *p == NUL)
K.Takataf741e3e2023-05-15 16:41:40 +0100475 wcscat(temp, exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000476 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000477 {
K.Takataf741e3e2023-05-15 16:41:40 +0100478 wcscat(temp, p);
479
480 // Check if exe_path is already included in $PATH.
481 if (wcsstr(temp, exe_pathw) == NULL)
482 {
483 // Append ';' if $PATH doesn't end with it.
484 size_t len = wcslen(temp);
485 if (temp[len - 1] != L';')
486 wcscat(temp, L";");
487
488 wcscat(temp, exe_pathw);
489 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000490 }
K.Takataf741e3e2023-05-15 16:41:40 +0100491 _wputenv(temp);
492#ifdef libintl_wputenv
493 libintl_wputenv(temp);
494#endif
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496}
497
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100499 * Unescape characters in "p" that appear in "escaped".
500 */
501 static void
502unescape_shellxquote(char_u *p, char_u *escaped)
503{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100504 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100505 int n;
506
507 while (*p != NUL)
508 {
509 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
510 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100511 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100512 p += n;
513 l -= n;
514 }
515}
516
517/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200518 * Load library "name".
519 */
520 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000521vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200522{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200523 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200524
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200525 // No need to load any library when registering OLE.
526 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000527 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200528
Bram Moolenaar0f873732019-12-05 20:28:46 +0100529 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
530 // vimLoadLib() recursively, which causes a stack overflow.
K.Takatace3189d2023-02-15 19:13:43 +0000531 if (exe_pathw == NULL)
K.Takataf741e3e2023-05-15 16:41:40 +0100532 {
K.Takatace3189d2023-02-15 19:13:43 +0000533 mch_get_exe_name();
K.Takataf741e3e2023-05-15 16:41:40 +0100534 if (exe_pathw == NULL)
535 return NULL;
536 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000537
538 WCHAR old_dirw[MAXPATHL];
539
540 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
541 return NULL;
542
543 // Change directory to where the executable is, both to make
544 // sure we find a .dll there and to avoid looking for a .dll
545 // in the current directory.
K.Takatace3189d2023-02-15 19:13:43 +0000546 SetCurrentDirectoryW(exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000547 dll = LoadLibrary(name);
548 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200549 return dll;
550}
551
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200552#if defined(VIMDLL) || defined(PROTO)
553/*
554 * Check if the current executable file is for the GUI subsystem.
555 */
556 int
557mch_is_gui_executable(void)
558{
559 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
560 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
561 PIMAGE_NT_HEADERS pPE;
562
563 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
564 return FALSE;
565 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
566 if (pPE->Signature != IMAGE_NT_SIGNATURE)
567 return FALSE;
568 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
569 return TRUE;
570 return FALSE;
571}
572#endif
573
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000574#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
575 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100576/*
577 * Get related information about 'funcname' which is imported by 'hInst'.
578 * If 'info' is 0, return the function address.
579 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000580 * If 'info' is 2, hook the function with 'ptr', and return the original
581 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100582 */
583 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000584get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
585 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100586{
587 PBYTE pImage = (PBYTE)hInst;
588 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
589 PIMAGE_NT_HEADERS pPE;
590 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100591 PIMAGE_THUNK_DATA pIAT; // Import Address Table
592 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100593 PIMAGE_IMPORT_BY_NAME pImpName;
Ken Takata119fdd92023-10-04 20:05:05 +0200594 DWORD ImpVA;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100595
596 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
597 return NULL;
598 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
599 if (pPE->Signature != IMAGE_NT_SIGNATURE)
600 return NULL;
Ken Takata119fdd92023-10-04 20:05:05 +0200601
602 ImpVA = pPE->OptionalHeader
603 .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
604 if (ImpVA == 0)
605 return NULL; // No Import Table
606 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage + ImpVA);
607
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100608 for (; pImpDesc->FirstThunk; ++pImpDesc)
609 {
610 if (!pImpDesc->OriginalFirstThunk)
611 continue;
612 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
613 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
614 for (; pIAT->u1.Function; ++pIAT, ++pINT)
615 {
616 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
617 continue;
618 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
619 + (UINT_PTR)(pINT->u1.AddressOfData));
620 if (strcmp((char *)pImpName->Name, funcname) == 0)
621 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000622 void *original;
623 DWORD old, new = PAGE_READWRITE;
624
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100625 switch (info)
626 {
627 case 0:
628 return (void *)pIAT->u1.Function;
629 case 1:
630 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000631 case 2:
632 original = (void *)pIAT->u1.Function;
633 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
634 new, &old);
635 pIAT->u1.Function = (UINT_PTR)ptr;
636 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
637 old, &new);
638 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100639 default:
640 return NULL;
641 }
642 }
643 }
644 }
645 return NULL;
646}
647
648/*
649 * Get the module handle which 'funcname' in 'hInst' is imported from.
650 */
651 HINSTANCE
652find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
653{
654 char *modulename;
655
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000656 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100657 if (modulename != NULL)
658 return GetModuleHandleA(modulename);
659 return NULL;
660}
661
662/*
663 * Get the address of 'funcname' which is imported by 'hInst' DLL.
664 */
665 void *
666get_dll_import_func(HINSTANCE hInst, const char *funcname)
667{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000668 return get_imported_func_info(hInst, funcname, 0, NULL);
669}
670
671/*
672 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
673 * and return the original function address.
674 */
675 void *
676hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
677{
678 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100679}
680#endif
681
Ken Takata119fdd92023-10-04 20:05:05 +0200682#if defined(FEAT_PYTHON3) || defined(PROTO)
683/*
684 * Check if the specified DLL is a function forwarder.
685 * If yes, return the instance of the forwarded DLL.
686 * If no, return the specified DLL.
687 * If error, return NULL.
688 * This assumes that the DLL forwards all the function to a single DLL.
689 */
690 HINSTANCE
691get_forwarded_dll(HINSTANCE hInst)
692{
693 PBYTE pImage = (PBYTE)hInst;
694 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
695 PIMAGE_NT_HEADERS pPE;
696 PIMAGE_EXPORT_DIRECTORY pExpDir;
697 DWORD ExpVA;
698 DWORD ExpSize;
699 LPDWORD pFunctionTable;
700
701 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
702 return NULL;
703 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
704 if (pPE->Signature != IMAGE_NT_SIGNATURE)
705 return NULL;
706
707 ExpVA = pPE->OptionalHeader
708 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
709 ExpSize = pPE->OptionalHeader
710 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
711 if (ExpVA == 0)
712 return hInst; // No Export Directory
713 pExpDir = (PIMAGE_EXPORT_DIRECTORY)(pImage + ExpVA);
714 pFunctionTable = (LPDWORD)(pImage + pExpDir->AddressOfFunctions);
715
716 if (pExpDir->NumberOfNames == 0)
717 return hInst; // No export names.
718
719 // Check only the first entry.
720 if ((pFunctionTable[0] < ExpVA) || (pFunctionTable[0] >= ExpVA + ExpSize))
721 // The first entry is not a function forwarder.
722 return hInst;
723
724 // The first entry is a function forwarder.
725 // The name is represented as "DllName.FunctionName".
726 const char *name = (const char *)(pImage + pFunctionTable[0]);
727 const char *p = strchr(name, '.');
728 if (p == NULL)
729 return hInst;
730
731 // Extract DllName.
732 char buf[MAX_PATH];
733 if (p - name + 1 > sizeof(buf))
734 return NULL;
735 strncpy(buf, name, p - name);
736 buf[p - name] = '\0';
737 return GetModuleHandleA(buf);
738}
739#endif
740
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
742# ifndef GETTEXT_DLL
743# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200744# define GETTEXT_DLL_ALT1 "libintl-8.dll"
745# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100747// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000748static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200749static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000750static char *null_libintl_textdomain(const char *);
751static char *null_libintl_bindtextdomain(const char *, const char *);
752static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100753static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200755static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000756char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200757char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
758 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000759char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
760char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000762char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
763 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100764int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765
766 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100767dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768{
769 int i;
770 static struct
771 {
772 char *name;
773 FARPROC *ptr;
774 } libintl_entry[] =
775 {
776 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200777 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
779 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
780 {NULL, NULL}
781 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100782 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000783
Bram Moolenaar7554c542018-10-06 15:03:15 +0200784 // No need to initialize twice.
785 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200787 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100788 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100789# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100790 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200791 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100792# endif
793# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200794 if (!hLibintlDLL)
795 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100796# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100797 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200799 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200801 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000802 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200803 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000804 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200805 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000806 }
807 for (i = 0; libintl_entry[i].name != NULL
808 && libintl_entry[i].ptr != NULL; ++i)
809 {
K.Takata54119102022-02-03 13:33:03 +0000810 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811 libintl_entry[i].name)) == NULL)
812 {
813 dyn_libintl_end();
814 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000815 {
816 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000817 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000818 verbose_leave();
819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820 return 0;
821 }
822 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000823
Bram Moolenaar0f873732019-12-05 20:28:46 +0100824 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100825 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
826 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000827 if (dyn_libintl_bind_textdomain_codeset == NULL)
828 dyn_libintl_bind_textdomain_codeset =
829 null_libintl_bind_textdomain_codeset;
830
Bram Moolenaar0f873732019-12-05 20:28:46 +0100831 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100832 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
833 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100834 dyn_libintl_wputenv = (int (*)(const wchar_t *))
835 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100836 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
837 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100838
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839 return 1;
840}
841
842 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100843dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844{
845 if (hLibintlDLL)
846 FreeLibrary(hLibintlDLL);
847 hLibintlDLL = NULL;
848 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200849 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850 dyn_libintl_textdomain = null_libintl_textdomain;
851 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000852 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100853 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854}
855
856 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000857null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858{
859 return (char*)msgid;
860}
861
862 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200863null_libintl_ngettext(
864 const char *msgid,
865 const char *msgid_plural,
866 unsigned long n)
867{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200868 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200869}
870
Bram Moolenaaree695f72016-08-03 22:08:45 +0200871 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100872null_libintl_bindtextdomain(
873 const char *domainname UNUSED,
874 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875{
876 return NULL;
877}
878
879 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100880null_libintl_bind_textdomain_codeset(
881 const char *domainname UNUSED,
882 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000883{
884 return NULL;
885}
886
887 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100888null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889{
890 return NULL;
891}
892
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200893 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100894null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100895{
896 return 0;
897}
898
Bram Moolenaar0f873732019-12-05 20:28:46 +0100899#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900
Bram Moolenaar0f873732019-12-05 20:28:46 +0100901// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902
903#ifndef VER_PLATFORM_WIN32_WINDOWS
904# define VER_PLATFORM_WIN32_WINDOWS 1
905#endif
906
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100908# ifndef PROTO
909# include <aclapi.h>
910# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200911# ifndef PROTECTED_DACL_SECURITY_INFORMATION
912# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
913# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914#endif
915
Bram Moolenaar27515922013-06-29 15:36:26 +0200916#ifdef HAVE_ACL
917/*
918 * Enables or disables the specified privilege.
919 */
920 static BOOL
921win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
922{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100923 BOOL bResult;
924 LUID luid;
925 HANDLE hToken;
926 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200927
928 if (!OpenProcessToken(GetCurrentProcess(),
929 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
930 return FALSE;
931
932 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
933 {
934 CloseHandle(hToken);
935 return FALSE;
936 }
937
Bram Moolenaar45500912014-07-09 20:51:07 +0200938 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200939 tokenPrivileges.Privileges[0].Luid = luid;
940 tokenPrivileges.Privileges[0].Attributes = bEnable ?
941 SE_PRIVILEGE_ENABLED : 0;
942
943 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
944 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
945
946 CloseHandle(hToken);
947
948 return bResult && GetLastError() == ERROR_SUCCESS;
949}
950#endif
951
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100952#ifdef _MSC_VER
953// Suppress the deprecation warning for using GetVersionEx().
954// It is needed for implementing "windowsversion()".
955# pragma warning(push)
956# pragma warning(disable: 4996)
957#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200959 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 */
961 void
962PlatformId(void)
963{
964 static int done = FALSE;
965
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000966 if (done)
967 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000969 OSVERSIONINFO ovi;
970
971 ovi.dwOSVersionInfoSize = sizeof(ovi);
972 GetVersionEx(&ovi);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200974#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000975 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
976 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200977#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000978 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
979 || ovi.dwMajorVersion > 6)
980 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100981
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000982 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
983 || ovi.dwMajorVersion > 10)
984 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000985
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000987 // Enable privilege for getting or setting SACLs.
988 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000990 done = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100992#ifdef _MSC_VER
993# pragma warning(pop)
994#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200996#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100998# define SHIFT (SHIFT_PRESSED)
999# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
1000# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
1001# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002
1003
Bram Moolenaar0f873732019-12-05 20:28:46 +01001004// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
1005// We map function keys to their ANSI terminal equivalents, as produced
1006// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
1007// ANSI key with a value >= '\300' is nonstandard, but provided anyway
1008// so that the user can have access to all SHIFT-, CTRL-, and ALT-
1009// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010
Bram Moolenaard6f676d2005-06-01 21:51:55 +00001011static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012{
1013 WORD wVirtKey;
1014 BOOL fAnsiKey;
1015 int chAlone;
1016 int chShift;
1017 int chCtrl;
1018 int chAlt;
1019} VirtKeyMap[] =
1020{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001021// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
1023
1024 { VK_F1, TRUE, ';', 'T', '^', 'h', },
1025 { VK_F2, TRUE, '<', 'U', '_', 'i', },
1026 { VK_F3, TRUE, '=', 'V', '`', 'j', },
1027 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
1028 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
1029 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
1030 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
1031 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
1032 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
1033 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001034 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
1035 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001037 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
1038 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
1039 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
1040 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
1041 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
1042 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
1043 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
1044 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
1045 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
1046 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001047 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001049 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001051# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001052 // Most people don't have F13-F20, but what the hell...
1053 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
1054 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
1055 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1056 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1057 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1058 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1059 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1060 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001061# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001062 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1063 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1064 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1065 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001067 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1068 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1069 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1070 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1071 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1072 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1073 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1074 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1075 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1076 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001077 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001078};
1079
1080
Bram Moolenaar0f873732019-12-05 20:28:46 +01001081/*
1082 * The return code indicates key code size.
1083 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001086 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087{
1088 UINT uMods = pker->dwControlKeyState;
1089 static int s_iIsDead = 0;
1090 static WORD awAnsiCode[2];
1091 static BYTE abKeystate[256];
1092
1093
1094 if (s_iIsDead == 2)
1095 {
K.Takata972db232022-02-04 10:45:38 +00001096 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 s_iIsDead = 0;
1098 return 1;
1099 }
1100
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001101 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001102 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103 return 1;
1104
Bram Moolenaara80faa82020-04-12 19:37:17 +02001105 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106
Bram Moolenaar0f873732019-12-05 20:28:46 +01001107 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001108 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109
1110 if (uMods & SHIFT_PRESSED)
1111 abKeystate[VK_SHIFT] = 0x80;
1112 if (uMods & CAPSLOCK_ON)
1113 abKeystate[VK_CAPITAL] = 1;
1114
1115 if ((uMods & ALT_GR) == ALT_GR)
1116 {
1117 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1118 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1119 }
1120
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001121 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1122 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123
1124 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001125 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126
1127 return s_iIsDead;
1128}
1129
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130static BOOL g_fJustGotFocus = FALSE;
1131
1132/*
1133 * Decode a KEY_EVENT into one or two keystrokes
1134 */
1135 static BOOL
1136decode_key_event(
1137 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001138 WCHAR *pch,
1139 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001141 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142{
1143 int i;
1144 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1145
1146 *pch = *pch2 = NUL;
1147 g_fJustGotFocus = FALSE;
1148
Bram Moolenaar0f873732019-12-05 20:28:46 +01001149 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 if (!pker->bKeyDown)
1151 return FALSE;
1152
Bram Moolenaar0f873732019-12-05 20:28:46 +01001153 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154 switch (pker->wVirtualKeyCode)
1155 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001156 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 case VK_SHIFT:
1158 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001159 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160 return FALSE;
1161
1162 default:
1163 break;
1164 }
1165
Bram Moolenaar0f873732019-12-05 20:28:46 +01001166 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1168 {
1169 *pch = K_NUL;
1170 *pch2 = '\017';
1171 return TRUE;
1172 }
1173
K.Takataeeec2542021-06-02 13:28:16 +02001174 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175 {
1176 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1177 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001178 *pch = VirtKeyMap[i].chAlone;
1179 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180 *pch = VirtKeyMap[i].chShift;
1181 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1182 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001183 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001184 *pch = VirtKeyMap[i].chAlt;
1185
1186 if (*pch != 0)
1187 {
1188 if (VirtKeyMap[i].fAnsiKey)
1189 {
1190 *pch2 = *pch;
1191 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001192 if (pmodifiers)
1193 {
1194 if (pker->wVirtualKeyCode >= VK_F1
1195 && pker->wVirtualKeyCode <= VK_F12)
1196 {
1197 if ((nModifs & ALT) != 0)
1198 {
1199 *pmodifiers |= MOD_MASK_ALT;
1200 if ((nModifs & SHIFT) == 0)
1201 *pch2 = VirtKeyMap[i].chAlone;
1202 }
1203 if ((nModifs & CTRL) != 0)
1204 {
1205 *pmodifiers |= MOD_MASK_CTRL;
1206 if ((nModifs & SHIFT) == 0)
1207 *pch2 = VirtKeyMap[i].chAlone;
1208 }
1209 }
1210 else if (pker->wVirtualKeyCode >= VK_END
1211 && pker->wVirtualKeyCode <= VK_DOWN)
1212 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001213 // (0x23 - 0x28): VK_END, VK_HOME,
1214 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1215
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001216 *pmodifiers = 0;
1217 *pch2 = VirtKeyMap[i].chAlone;
1218 if ((nModifs & SHIFT) != 0
1219 && (nModifs & ~SHIFT) == 0)
1220 {
1221 *pch2 = VirtKeyMap[i].chShift;
1222 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001223 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001224 && (nModifs & ~CTRL) == 0)
1225 {
1226 *pch2 = VirtKeyMap[i].chCtrl;
1227 if (pker->wVirtualKeyCode == VK_UP
1228 || pker->wVirtualKeyCode == VK_DOWN)
1229 {
1230 *pmodifiers |= MOD_MASK_CTRL;
1231 *pch2 = VirtKeyMap[i].chAlone;
1232 }
1233 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001234 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001235 && (nModifs & CTRL) != 0)
1236 {
1237 *pmodifiers |= MOD_MASK_CTRL;
1238 *pch2 = VirtKeyMap[i].chShift;
1239 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001240 if ((nModifs & ALT) != 0)
1241 {
1242 *pch2 = VirtKeyMap[i].chAlt;
1243 *pmodifiers |= MOD_MASK_ALT;
1244 if ((nModifs & ~ALT) == 0)
1245 {
1246 *pch2 = VirtKeyMap[i].chAlone;
1247 }
1248 else if ((nModifs & SHIFT) != 0)
1249 {
1250 *pch2 = VirtKeyMap[i].chShift;
1251 }
1252 else if ((nModifs & CTRL) != 0)
1253 {
1254 if (pker->wVirtualKeyCode == VK_UP
1255 || pker->wVirtualKeyCode == VK_DOWN)
1256 {
1257 *pmodifiers |= MOD_MASK_CTRL;
1258 *pch2 = VirtKeyMap[i].chAlone;
1259 }
1260 else
1261 {
1262 *pch2 = VirtKeyMap[i].chCtrl;
1263 }
1264 }
1265 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001266 }
Christopher Plewrightf5f69e82024-08-04 19:57:44 +02001267 else if (pker->wVirtualKeyCode == VK_INSERT
1268 && (nModifs & SHIFT) != 0
1269 && (nModifs & ~SHIFT) == 0)
1270 {
1271 *pmodifiers = 0;
1272 *pch2 = VirtKeyMap[i].chShift;
1273 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001274 else
1275 {
1276 *pch2 = VirtKeyMap[i].chAlone;
1277 if ((nModifs & SHIFT) != 0)
1278 *pmodifiers |= MOD_MASK_SHIFT;
1279 if ((nModifs & CTRL) != 0)
1280 *pmodifiers |= MOD_MASK_CTRL;
1281 if ((nModifs & ALT) != 0)
1282 *pmodifiers |= MOD_MASK_ALT;
1283 }
1284 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285 }
1286
1287 return TRUE;
1288 }
1289 }
1290 }
1291
1292 i = win32_kbd_patch_key(pker);
1293
1294 if (i < 0)
1295 *pch = NUL;
1296 else
1297 {
K.Takata972db232022-02-04 10:45:38 +00001298 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299
1300 if (pmodifiers != NULL)
1301 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001302 // Pass on the ALT key as a modifier, but only when not combined
1303 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1305 *pmodifiers |= MOD_MASK_ALT;
1306
Bram Moolenaar0f873732019-12-05 20:28:46 +01001307 // Pass on SHIFT only for special keys, because we don't know when
1308 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001309 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1310 *pmodifiers |= MOD_MASK_SHIFT;
1311
Bram Moolenaar0f873732019-12-05 20:28:46 +01001312 // Pass on CTRL only for non-special keys, because we don't know
1313 // when it's already included with the character. And not when
1314 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001315 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1316 && *pch >= 0x20 && *pch < 0x80)
1317 *pmodifiers |= MOD_MASK_CTRL;
1318 }
1319 }
1320
1321 return (*pch != NUL);
1322}
1323
Christopher Plewright20b795e2022-12-20 20:01:58 +00001324# if defined(FEAT_EVAL)
1325 static int
1326encode_key_event(dict_T *args, INPUT_RECORD *ir)
1327{
1328 static int s_dwMods = 0;
1329
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001330 char_u *action = dict_get_string(args, "event", TRUE);
1331 if (action && (STRICMP(action, "keydown") == 0
1332 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001333 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001334 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001335 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1336 if (vkCode <= 0 || vkCode >= 0xFF)
1337 {
1338 semsg(_(e_invalid_argument_nr), (long)vkCode);
1339 return FALSE;
1340 }
1341
1342 ir->EventType = KEY_EVENT;
1343 KEY_EVENT_RECORD ker;
1344 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001345 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001346 ker.wRepeatCount = 1;
1347 ker.wVirtualScanCode = 0;
1348 ker.dwControlKeyState = 0;
1349 int mods = (int)dict_get_number(args, "modifiers");
1350 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1351 if (mods)
1352 {
1353 // If "modifiers" is explicitly set in the args, then we reset any
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00001354 // remembered modifier key state that may have been set from
1355 // earlier mod-key-down events, even if they are not yet unset by
1356 // earlier mod-key-up events.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001357 s_dwMods = 0;
1358 if (mods & MOD_MASK_SHIFT)
1359 ker.dwControlKeyState |= SHIFT_PRESSED;
1360 if (mods & MOD_MASK_CTRL)
1361 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1362 if (mods & MOD_MASK_ALT)
1363 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1364 }
1365
1366 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1367 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001368 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001369 s_dwMods |= SHIFT_PRESSED;
1370 else
1371 s_dwMods &= ~SHIFT_PRESSED;
1372 }
1373 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1374 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001375 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001376 s_dwMods |= LEFT_CTRL_PRESSED;
1377 else
1378 s_dwMods &= ~LEFT_CTRL_PRESSED;
1379 }
1380 else if (vkCode == VK_RCONTROL)
1381 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001382 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001383 s_dwMods |= RIGHT_CTRL_PRESSED;
1384 else
1385 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1386 }
1387 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1388 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001389 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001390 s_dwMods |= LEFT_ALT_PRESSED;
1391 else
1392 s_dwMods &= ~LEFT_ALT_PRESSED;
1393 }
1394 else if (vkCode == VK_RMENU)
1395 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001396 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001397 s_dwMods |= RIGHT_ALT_PRESSED;
1398 else
1399 s_dwMods &= ~RIGHT_ALT_PRESSED;
1400 }
1401 ker.dwControlKeyState |= s_dwMods;
1402 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001403 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001404 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001405 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001406 }
1407 else
1408 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001409 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001410 {
1411 semsg(_(e_missing_argument_str), "event");
1412 }
1413 else
1414 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001415 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1416 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001417 }
1418 return FALSE;
1419 }
1420 return TRUE;
1421}
1422# endif // FEAT_EVAL
1423#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001424
1425
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426/*
1427 * For the GUI the mouse handling is in gui_w32.c.
1428 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001429#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001431mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432{
1433}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001434#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001435static int g_fMouseAvail = FALSE; // mouse present
1436static int g_fMouseActive = FALSE; // mouse enabled
1437static int g_nMouseClick = -1; // mouse status
1438static int g_xMouse; // mouse x coordinate
1439static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001440static DWORD g_cmodein = 0; // Original console input mode
1441static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001442
1443/*
1444 * Enable or disable mouse input
1445 */
1446 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001447mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448{
1449 DWORD cmodein;
1450
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001451# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001452 if (gui.in_use)
1453 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001454# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 if (!g_fMouseAvail)
1456 return;
1457
1458 g_fMouseActive = on;
1459 GetConsoleMode(g_hConIn, &cmodein);
1460
1461 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001462 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001463 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001464 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1465 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001467 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001469 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1470 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001472 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473}
1474
Bram Moolenaar157d8132018-03-06 17:09:20 +01001475
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001476# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001477/*
1478 * Called when 'balloonevalterm' changed.
1479 */
1480 void
1481mch_bevalterm_changed(void)
1482{
1483 mch_setmouse(g_fMouseActive);
1484}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001485# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001486
Christopher Plewright2a46f812022-10-16 19:47:45 +01001487/*
1488 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001489 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001490 *
1491 * This encodes the mouse scroll direction and keyboard modifiers into
1492 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1493 *
1494 * The direction of the scroll is decoded from two fields of the win32 console
1495 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001496 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001497 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1498 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001499 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001500 * - If the high word of the dwButtonState member contains a positive
1501 * value, the wheel was rotated to the right.
1502 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001503 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001504 * - If the high word of the dwButtonState member contains a positive value,
1505 * the wheel was rotated forward, away from the user.
1506 * - Otherwise, the wheel was rotated backward, toward the user.
1507 */
1508 static void
1509decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1510{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001511 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1512 int zDelta = pmer->dwButtonState;
1513
1514 g_xMouse = pmer->dwMousePosition.X;
1515 g_yMouse = pmer->dwMousePosition.Y;
1516
K.Takata161b6ac2022-11-14 15:31:07 +00001517# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001518 int lcol = g_xMouse;
1519 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001520 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001521 if (wp != NULL && popup_is_popup(wp))
1522 {
1523 g_nMouseClick = -1;
1524 cmdarg_T cap;
1525 oparg_T oa;
1526 CLEAR_FIELD(cap);
1527 clear_oparg(&oa);
1528 cap.oap = &oa;
1529 if (horizontal)
1530 {
1531 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1532 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1533 }
1534 else
1535 {
1536 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1537 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1538 }
1539
1540 // Mouse hovers over popup window, scroll it if possible.
1541 mouse_row = wp->w_winrow;
1542 mouse_col = wp->w_wincol;
1543 nv_mousescroll(&cap);
1544 update_screen(0);
1545 setcursor();
1546 out_flush();
1547 return;
1548 }
K.Takata161b6ac2022-11-14 15:31:07 +00001549# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001550 mouse_col = g_xMouse;
1551 mouse_row = g_yMouse;
1552
1553 char_u modifiers = 0;
1554 char_u direction = 0;
1555
1556 // Decode the direction into an event that Vim can process
1557 if (horizontal)
1558 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1559 else
1560 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1561
dundargocc57b5bc2022-11-02 13:30:51 +00001562 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001563 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001564 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001565 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001566 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001567 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1568 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1569
1570 // add (bitwise or) the scroll direction and the key modifier chars
1571 // together.
1572 g_nMouseClick = ((direction << 8) | modifiers);
1573
1574 return;
1575}
1576
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577/*
1578 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1579 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1580 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1581 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1582 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1583 * and we return the mouse position in g_xMouse and g_yMouse.
1584 *
1585 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1586 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1587 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1588 *
1589 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1590 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1591 *
1592 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1593 * moves, even if it stays within the same character cell. We ignore
1594 * all MOUSE_MOVED messages if the position hasn't really changed, and
1595 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1596 * we're only interested in MOUSE_DRAG).
1597 *
1598 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1599 * 2-button mouses by pressing the left & right buttons simultaneously.
1600 * In practice, it's almost impossible to click both at the same time,
1601 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1602 * in such cases, if the user is clicking quickly.
1603 */
1604 static BOOL
1605decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001606 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607{
1608 static int s_nOldButton = -1;
1609 static int s_nOldMouseClick = -1;
1610 static int s_xOldMouse = -1;
1611 static int s_yOldMouse = -1;
1612 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001613# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001615# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616 static int s_cClicks = 1;
1617 static BOOL s_fReleased = TRUE;
1618 static DWORD s_dwLastClickTime = 0;
1619 static BOOL s_fNextIsMiddle = FALSE;
1620
Bram Moolenaar0f873732019-12-05 20:28:46 +01001621 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622
1623 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1624 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1625 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1626 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1627
1628 int nButton;
1629
1630 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1631 cButtons = 2;
1632
1633 if (!g_fMouseAvail || !g_fMouseActive)
1634 {
1635 g_nMouseClick = -1;
1636 return FALSE;
1637 }
1638
Bram Moolenaar0f873732019-12-05 20:28:46 +01001639 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 if (g_fJustGotFocus)
1641 {
1642 g_fJustGotFocus = FALSE;
1643 return FALSE;
1644 }
1645
Christopher Plewright605d02a2022-10-19 11:54:46 +01001646 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647 if (g_nMouseClick != -1)
1648 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001649
Christopher Plewright2a46f812022-10-16 19:47:45 +01001650 if (pmer->dwEventFlags == MOUSE_WHEELED
1651 || pmer->dwEventFlags == MOUSE_HWHEELED)
1652 {
1653 decode_mouse_wheel(pmer);
1654 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1655 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001656
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657 nButton = -1;
1658 g_xMouse = pmer->dwMousePosition.X;
1659 g_yMouse = pmer->dwMousePosition.Y;
1660
1661 if (pmer->dwEventFlags == MOUSE_MOVED)
1662 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001663 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1664 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1666 return FALSE;
1667 }
1668
Bram Moolenaar0f873732019-12-05 20:28:46 +01001669 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1671 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001672 nButton = MOUSE_RELEASE;
1673
Bram Moolenaar0f873732019-12-05 20:28:46 +01001674 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001676 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001677# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001678 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001679 if (p_bevalterm)
1680 nButton = MOUSE_DRAG;
1681 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001682# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001683 return FALSE;
1684 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 s_fReleased = TRUE;
1687 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001688 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001690 // on a 2-button mouse, hold down left and right buttons
1691 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692
1693 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1694 {
1695 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1696
Bram Moolenaar0f873732019-12-05 20:28:46 +01001697 // if either left or right button only is pressed, see if the
1698 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699 if (dwLR == LEFT || dwLR == RIGHT)
1700 {
1701 for (;;)
1702 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001703 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1705 != WAIT_OBJECT_0)
1706 break;
1707 else
1708 {
1709 DWORD cRecords = 0;
1710 INPUT_RECORD ir;
1711 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1712
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001713 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714
1715 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1716 || !(pmer2->dwButtonState & LEFT_RIGHT))
1717 break;
1718 else
1719 {
1720 if (pmer2->dwEventFlags != MOUSE_MOVED)
1721 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001722 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723
1724 return decode_mouse_event(pmer2);
1725 }
1726 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1727 s_yOldMouse == pmer2->dwMousePosition.Y)
1728 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001729 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001730 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731
Bram Moolenaar0f873732019-12-05 20:28:46 +01001732 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001733 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734
1735 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1736 break;
1737 }
1738 else
1739 break;
1740 }
1741 }
1742 }
1743 }
1744 }
1745
1746 if (s_fNextIsMiddle)
1747 {
1748 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1749 ? MOUSE_DRAG : MOUSE_MIDDLE;
1750 s_fNextIsMiddle = FALSE;
1751 }
1752 else if (cButtons == 2 &&
1753 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1754 {
1755 nButton = MOUSE_MIDDLE;
1756
1757 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1758 {
1759 s_fNextIsMiddle = TRUE;
1760 nButton = MOUSE_RELEASE;
1761 }
1762 }
1763 else if ((pmer->dwButtonState & LEFT) == LEFT)
1764 nButton = MOUSE_LEFT;
1765 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1766 nButton = MOUSE_MIDDLE;
1767 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1768 nButton = MOUSE_RIGHT;
1769
1770 if (! s_fReleased && ! s_fNextIsMiddle
1771 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1772 return FALSE;
1773
1774 s_fReleased = s_fNextIsMiddle;
1775 }
1776
1777 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1778 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001779 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001780 if (nButton != -1 && nButton != MOUSE_RELEASE)
1781 {
1782 DWORD dwCurrentTime = GetTickCount();
1783
1784 if (s_xOldMouse != g_xMouse
1785 || s_yOldMouse != g_yMouse
1786 || s_nOldButton != nButton
1787 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001788# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001790# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1792 {
1793 s_cClicks = 1;
1794 }
1795 else if (++s_cClicks > 4)
1796 {
1797 s_cClicks = 1;
1798 }
1799
1800 s_dwLastClickTime = dwCurrentTime;
1801 }
1802 }
1803 else if (pmer->dwEventFlags == MOUSE_MOVED)
1804 {
1805 if (nButton != -1 && nButton != MOUSE_RELEASE)
1806 nButton = MOUSE_DRAG;
1807
1808 s_cClicks = 1;
1809 }
1810
1811 if (nButton == -1)
1812 return FALSE;
1813
1814 if (nButton != MOUSE_RELEASE)
1815 s_nOldButton = nButton;
1816
1817 g_nMouseClick = nButton;
1818
1819 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1820 g_nMouseClick |= MOUSE_SHIFT;
1821 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1822 g_nMouseClick |= MOUSE_CTRL;
1823 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1824 g_nMouseClick |= MOUSE_ALT;
1825
1826 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1827 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1828
Bram Moolenaar0f873732019-12-05 20:28:46 +01001829 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830 if (s_xOldMouse == g_xMouse
1831 && s_yOldMouse == g_yMouse
1832 && s_nOldMouseClick == g_nMouseClick)
1833 {
1834 g_nMouseClick = -1;
1835 return FALSE;
1836 }
1837
1838 s_xOldMouse = g_xMouse;
1839 s_yOldMouse = g_yMouse;
1840 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001841# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001842 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001843# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 s_nOldMouseClick = g_nMouseClick;
1845
1846 return TRUE;
1847}
1848
Christopher Plewright20b795e2022-12-20 20:01:58 +00001849# ifdef FEAT_EVAL
1850 static int
1851encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1852{
1853 int button;
1854 int row;
1855 int col;
1856 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001857 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001858 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859
Christopher Plewright20b795e2022-12-20 20:01:58 +00001860 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1861 return FALSE;
1862
1863 // Note: "move" is optional, requires fewer arguments
1864 move = (int)dict_get_bool(args, "move", FALSE);
1865 if (!move && (!dict_has_key(args, "button")
1866 || !dict_has_key(args, "multiclick")
1867 || !dict_has_key(args, "modifiers")))
1868 return FALSE;
1869
1870 row = (int)dict_get_number(args, "row") - 1;
1871 col = (int)dict_get_number(args, "col") - 1;
1872
1873 ir->EventType = MOUSE_EVENT;
1874 MOUSE_EVENT_RECORD mer;
1875 ZeroMemory(&mer, sizeof(mer));
1876 mer.dwMousePosition.X = col;
1877 mer.dwMousePosition.Y = row;
1878
1879 if (move)
1880 {
1881 mer.dwButtonState = 0;
1882 mer.dwEventFlags = MOUSE_MOVED;
1883 }
1884 else
1885 {
1886 button = (int)dict_get_number(args, "button");
1887 repeated_click = (int)dict_get_number(args, "multiclick");
1888 mods = (int)dict_get_number(args, "modifiers");
1889 // Reset the scroll values to known values.
1890 // XXX: Remove this when/if the scroll step is made configurable.
1891 mouse_set_hor_scroll_step(6);
1892 mouse_set_vert_scroll_step(3);
1893
1894 switch (button)
1895 {
1896 case MOUSE_LEFT:
1897 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1898 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1899 break;
1900 case MOUSE_MIDDLE:
1901 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1902 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1903 break;
1904 case MOUSE_RIGHT:
1905 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1906 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1907 break;
1908 case MOUSE_RELEASE:
1909 // umm? Assume Left Release?
1910 mer.dwEventFlags = 0;
1911
1912 case MOUSE_MOVE:
1913 mer.dwButtonState = 0;
1914 mer.dwEventFlags = MOUSE_MOVED;
1915 break;
1916 case MOUSE_X1:
1917 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1918 break;
1919 case MOUSE_X2:
1920 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1921 break;
1922 case MOUSE_4: // KE_MOUSEDOWN;
1923 mer.dwButtonState = -1;
1924 mer.dwEventFlags = MOUSE_WHEELED;
1925 break;
1926 case MOUSE_5: // KE_MOUSEUP;
1927 mer.dwButtonState = +1;
1928 mer.dwEventFlags = MOUSE_WHEELED;
1929 break;
1930 case MOUSE_6: // KE_MOUSELEFT;
1931 mer.dwButtonState = -1;
1932 mer.dwEventFlags = MOUSE_HWHEELED;
1933 break;
1934 case MOUSE_7: // KE_MOUSERIGHT;
1935 mer.dwButtonState = +1;
1936 mer.dwEventFlags = MOUSE_HWHEELED;
1937 break;
1938 default:
1939 semsg(_(e_invalid_argument_str), "button");
1940 return FALSE;
1941 }
1942 }
1943
1944 mer.dwControlKeyState = 0;
1945 if (mods != 0)
1946 {
1947 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1948 if (mods & MOUSE_SHIFT)
1949 mer.dwControlKeyState |= SHIFT_PRESSED;
1950 if (mods & MOUSE_CTRL)
1951 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1952 if (mods & MOUSE_ALT)
1953 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1954 }
1955 ir->Event.MouseEvent = mer;
1956 return TRUE;
1957}
1958# endif // FEAT_EVAL
1959
1960 static int
1961write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1962{
1963 int nCount = 0;
1964 while (nCount < nLength)
1965 {
1966 input_record_buffer.length++;
1967 input_record_buffer_node_T *event_node =
1968 malloc(sizeof(input_record_buffer_node_T));
1969 event_node->ir = irEvents[nCount++];
1970 event_node->next = NULL;
1971 if (input_record_buffer.tail == NULL)
1972 {
1973 input_record_buffer.head = event_node;
1974 input_record_buffer.tail = event_node;
1975 }
1976 else
1977 {
1978 input_record_buffer.tail->next = event_node;
1979 input_record_buffer.tail = input_record_buffer.tail->next;
1980 }
1981 }
1982 return nCount;
1983}
1984
1985 static int
1986read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1987{
1988 int nCount = 0;
1989 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1990 {
1991 input_record_buffer.length--;
1992 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1993 irEvents[nCount++] = pop_head->ir;
1994 input_record_buffer.head = pop_head->next;
1995 vim_free(pop_head);
1996 if (input_record_buffer.length == 0)
1997 input_record_buffer.tail = NULL;
1998 }
1999 return nCount;
2000}
Christopher Plewright20b795e2022-12-20 20:01:58 +00002001#endif // !FEAT_GUI_MSWIN || VIMDLL
2002
2003#ifdef FEAT_EVAL
2004/*
2005 * The 'test_mswin_event' function is for testing Vim's low-level handling of
2006 * user input events. ie, this manages the encoding of INPUT_RECORD events
2007 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
2008 * consoles.
2009 *
2010 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
2011 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
2012 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
2013 *
2014 * When the Windows console is running, the arguments; 'event' and 'args', are
2015 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
2016 * events are encoded as INPUT_RECORD events.
2017 *
2018 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
2019 * GUI sends MSG structs instead.
2020 */
2021 int
2022test_mswin_event(char_u *event, dict_T *args)
2023{
2024 int lpEventsWritten = 0;
2025
2026# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
2027 if (gui.in_use)
2028 return test_gui_w32_sendevent(event, args);
2029# endif
2030
2031# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
2032
2033// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
2034// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
2035// Maybe also: MENU_EVENT
2036
2037 INPUT_RECORD ir;
2038 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002039 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002040 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002041 {
2042 execute = dict_get_bool(args, "execute", FALSE);
2043 if (dict_has_key(args, "event"))
2044 input_encoded = encode_key_event(args, &ir);
2045 else if (!execute)
2046 {
2047 semsg(_(e_missing_argument_str), "event");
2048 return FALSE;
2049 }
2050 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002051 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002052 {
2053 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002054 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002055 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002056 else
2057 {
2058 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
2059 return FALSE;
2060 }
2061
2062 // Ideally, WriteConsoleInput would be used to inject these low-level
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002063 // events. But, this doesn't work well in the CI test environment. So
Christopher Plewright20b795e2022-12-20 20:01:58 +00002064 // implementing an input_record_buffer instead.
2065 if (input_encoded)
2066 lpEventsWritten = write_input_record_buffer(&ir, 1);
2067
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002068 // Set flags to execute the event, ie. like feedkeys mode X.
2069 if (execute)
2070 {
2071 int save_msg_scroll = msg_scroll;
2072 // Avoid a 1 second delay when the keys start Insert mode.
2073 msg_scroll = FALSE;
2074 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002075 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002076 msg_scroll |= save_msg_scroll;
2077 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002078
2079# endif
2080 return lpEventsWritten;
2081}
2082#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083
2084#ifdef MCH_CURSOR_SHAPE
2085/*
2086 * Set the shape of the cursor.
2087 * 'thickness' can be from 1 (thin) to 99 (block)
2088 */
2089 static void
2090mch_set_cursor_shape(int thickness)
2091{
Christopher Plewright38804d62022-11-09 23:55:52 +00002092 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002093 {
2094 if (*T_CSI == NUL)
2095 {
2096 // If 't_SI' is not set, use the default cursor styles.
2097 if (thickness < 50)
2098 vtp_printf("\033[3 q"); // underline
2099 else
2100 vtp_printf("\033[0 q"); // default
2101 }
2102 }
2103 else
2104 {
2105 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2106 ConsoleCursorInfo.dwSize = thickness;
2107 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108
K.Takatadf5320c2022-09-01 13:20:16 +01002109 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2110 if (s_cursor_visible)
2111 SetConsoleCursorPosition(g_hConOut, g_coord);
2112 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113}
2114
2115 void
2116mch_update_cursor(void)
2117{
2118 int idx;
2119 int thickness;
2120
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002121# ifdef VIMDLL
2122 if (gui.in_use)
2123 return;
2124# endif
2125
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 /*
2127 * How the cursor is drawn depends on the current mode.
2128 */
2129 idx = get_shape_idx(FALSE);
2130
2131 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002132 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133 else
2134 thickness = shape_table[idx].percentage;
2135 mch_set_cursor_shape(thickness);
2136}
2137#endif
2138
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002139#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140/*
2141 * Handle FOCUS_EVENT.
2142 */
2143 static void
2144handle_focus_event(INPUT_RECORD ir)
2145{
2146 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2147 ui_focus_change((int)g_fJustGotFocus);
2148}
2149
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002150static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2151
Bram Moolenaar071d4272004-06-13 20:20:40 +00002152/*
2153 * Wait until console input from keyboard or mouse is available,
2154 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002155 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002156 * Return TRUE if something is available FALSE if not.
2157 */
2158 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002159WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002160{
2161 DWORD dwNow = 0, dwEndTime = 0;
2162 INPUT_RECORD ir;
2163 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002164 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002165# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002166 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002167# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002168
2169 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002170 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 dwEndTime = GetTickCount() + msec;
2172 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002173 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 dwEndTime = INFINITE;
2175
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002176 // We need to loop until the end of the time period, because
2177 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002178 for (;;)
2179 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002180 // Only process messages when waiting.
2181 if (msec != 0)
2182 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002183# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002184 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002185# endif
2186# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002187 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002188# endif
2189# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002190 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002191# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002192 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002193
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002194 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002195# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002196 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002197# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 )
2199 return TRUE;
2200
2201 if (msec > 0)
2202 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002203 // If the specified wait time has passed, return. Beware that
2204 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002206 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002207 break;
2208 }
2209 if (msec != 0)
2210 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002211 DWORD dwWaitTime = dwEndTime - dwNow;
2212
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002213 // Don't wait for more than 11 msec to avoid dropping characters,
2214 // check channel while waiting for input and handle a callback from
2215 // 'balloonexpr'.
2216 if (dwWaitTime > 11)
2217 dwWaitTime = 11;
2218
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002219# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002220 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002221 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002222# endif
2223# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002224 // When waiting very briefly don't trigger timers.
2225 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002226 {
2227 long due_time;
2228
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002229 // Trigger timers and then get the time in msec until the next
2230 // one is due. Wait up to that time.
2231 due_time = check_due_timer();
2232 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002233 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002234 // timer may have used feedkeys().
2235 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002236 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002237 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2238 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002239 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002240# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002241 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002242# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002243 // Wait for either an event on the console input or a
2244 // message in the client-server window.
2245 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2246 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002247# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002248 wait_for_single_object(g_hConIn, dwWaitTime)
2249 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002250# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002251 )
2252 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002253 }
2254
2255 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002256 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002258# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002259 // May have to redraw if the cursor ends up in the wrong place.
2260 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002261 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262 {
2263 CONSOLE_SCREEN_BUFFER_INFO csbi;
2264
2265 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2266 {
2267 if (csbi.dwCursorPosition.Y != msg_row)
2268 {
matveyte08795e2021-05-07 15:00:17 +02002269 // The screen is now messed up, must redraw the command
2270 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002271 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002272 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 redrawcmd();
2274 }
2275 }
2276 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002277# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278
2279 if (cRecords > 0)
2280 {
2281 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2282 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002283# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002284 // Windows IME sends two '\n's with only one 'ENTER'. First:
2285 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002286 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2288 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002289 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290 continue;
2291 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002292# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002293 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2294 NULL, FALSE))
2295 return TRUE;
2296 }
2297
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002298 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299
2300 if (ir.EventType == FOCUS_EVENT)
2301 handle_focus_event(ir);
2302 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002303 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002304 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2305
Bram Moolenaar36698e32019-12-11 22:57:40 +01002306 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002307 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002308 if (dwSize.X != Columns || dwSize.Y != Rows)
2309 {
2310 CONSOLE_SCREEN_BUFFER_INFO csbi;
2311 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002312 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002313 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002314 if (dwSize.X != Columns || dwSize.Y != Rows)
2315 {
2316 ResizeConBuf(g_hConOut, dwSize);
2317 shell_resized();
2318 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002319 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002320 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 else if (ir.EventType == MOUSE_EVENT
2322 && decode_mouse_event(&ir.Event.MouseEvent))
2323 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324 }
2325 else if (msec == 0)
2326 break;
2327 }
2328
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002329# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002330 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 if (input_available())
2332 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002333# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002334
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 return FALSE;
2336}
2337
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338/*
2339 * return non-zero if a character is available
2340 */
2341 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002342mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002343{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002344# ifdef VIMDLL
2345 if (gui.in_use)
2346 return TRUE;
2347# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002348 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002350
2351# if defined(FEAT_TERMINAL) || defined(PROTO)
2352/*
2353 * Check for any pending input or messages.
2354 */
2355 int
2356mch_check_messages(void)
2357{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002358# ifdef VIMDLL
2359 if (gui.in_use)
2360 return TRUE;
2361# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002362 return WaitForChar(0L, TRUE);
2363}
2364# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365
2366/*
2367 * Create the console input. Used when reading stdin doesn't work.
2368 */
2369 static void
2370create_conin(void)
2371{
2372 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2373 FILE_SHARE_READ|FILE_SHARE_WRITE,
2374 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002375 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376 did_create_conin = TRUE;
2377}
2378
2379/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002380 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002382 static WCHAR
2383tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002385 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386
2387 for (;;)
2388 {
2389 INPUT_RECORD ir;
2390 DWORD cRecords = 0;
2391
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002392# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002393 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394 if (input_available())
2395 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 if (g_nMouseClick != -1)
2397 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002398# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002399 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400 {
2401 if (did_create_conin)
2402 read_error_exit();
2403 create_conin();
2404 continue;
2405 }
2406
2407 if (ir.EventType == KEY_EVENT)
2408 {
2409 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2410 pmodifiers, TRUE))
2411 return ch;
2412 }
2413 else if (ir.EventType == FOCUS_EVENT)
2414 handle_focus_event(ir);
2415 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2416 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417 else if (ir.EventType == MOUSE_EVENT)
2418 {
2419 if (decode_mouse_event(&ir.Event.MouseEvent))
2420 return 0;
2421 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 }
2423}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002424#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425
2426
2427/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002428 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429 * Get one or more characters from the keyboard or the mouse.
2430 * If time == 0, do not wait for characters.
2431 * If time == n, wait a short time for characters.
2432 * If time == -1, wait forever for characters.
2433 * Returns the number of characters read into buf.
2434 */
2435 int
2436mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002437 char_u *buf UNUSED,
2438 int maxlen UNUSED,
2439 long time UNUSED,
2440 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002442#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443
2444 int len;
2445 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002446# ifdef VIMDLL
2447// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2448# define TYPEAHEADSPACE 6
2449# else
2450# define TYPEAHEADSPACE 0
2451# endif
2452# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002453 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 static int typeaheadlen = 0;
2455
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002456# ifdef VIMDLL
2457 if (gui.in_use)
2458 return 0;
2459# endif
2460
Bram Moolenaar0f873732019-12-05 20:28:46 +01002461 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462 if (typeaheadlen > 0)
2463 goto theend;
2464
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465 if (time >= 0)
2466 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002467 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002468 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002470 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002472 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473
Bram Moolenaar3918c952005-03-15 22:34:55 +00002474 /*
2475 * If there is no character available within 2 seconds (default)
2476 * write the autoscript file to disk. Or cause the CursorHold event
2477 * to be triggered.
2478 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002479 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002481 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002483 buf[0] = K_SPECIAL;
2484 buf[1] = KS_EXTRA;
2485 buf[2] = (int)KE_CURSORHOLD;
2486 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002488 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002489 }
2490 }
2491
2492 /*
2493 * Try to read as many characters as there are, until the buffer is full.
2494 */
2495
Bram Moolenaar0f873732019-12-05 20:28:46 +01002496 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 g_fCBrkPressed = FALSE;
2498
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002499# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 if (fdDump)
2501 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002502# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503
Bram Moolenaar0f873732019-12-05 20:28:46 +01002504 // Keep looping until there is something in the typeahead buffer and more
2505 // to get and still room in the buffer (up to two bytes for a char and
2506 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002507 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002508 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509 {
2510 if (typebuf_changed(tb_change_cnt))
2511 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002512 // "buf" may be invalid now if a client put something in the
2513 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 typeaheadlen = 0;
2515 break;
2516 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 if (g_nMouseClick != -1)
2518 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002519# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 if (fdDump)
2521 fprintf(fdDump, "{%02x @ %d, %d}",
2522 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002523# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002524 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2525 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2526
2527 if (scroll_dir == KE_MOUSEDOWN
2528 || scroll_dir == KE_MOUSEUP
2529 || scroll_dir == KE_MOUSELEFT
2530 || scroll_dir == KE_MOUSERIGHT)
2531 {
2532 if (modifiers > 0)
2533 {
Christopher Plewright03193062022-11-22 12:58:27 +00002534 // use K_SPECIAL instead of CSI to make mappings work
2535 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002536 typeahead[typeaheadlen++] = KS_MODIFIER;
2537 typeahead[typeaheadlen++] = modifiers;
2538 }
2539 typeahead[typeaheadlen++] = CSI;
2540 typeahead[typeaheadlen++] = KS_EXTRA;
2541 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002542 }
2543 else
2544 {
2545 typeahead[typeaheadlen++] = ESC + 128;
2546 typeahead[typeaheadlen++] = 'M';
2547 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002548 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002549
2550 // Pass the pointer coordinates of the mouse event in 2 bytes,
2551 // allowing for > 223 columns. Both for click and scroll events.
2552 // This is the same as what is used for the GUI.
2553 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2554 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2555 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2556 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2557
2558 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559 }
2560 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002562 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563 int modifiers = 0;
2564
2565 c = tgetch(&modifiers, &ch2);
2566
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002567 c = simplify_key(c, &modifiers);
2568
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002569 // Some chars need adjustment when the Ctrl modifier is used.
2570 ++no_reduce_keys;
2571 c = may_adjust_key_for_ctrl(modifiers, c);
2572 --no_reduce_keys;
2573
2574 // remove the SHIFT modifier for keys where it's already included,
2575 // e.g., '(' and '*'
2576 modifiers = may_remove_shift_modifier(modifiers, c);
2577
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 if (typebuf_changed(tb_change_cnt))
2579 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002580 // "buf" may be invalid now if a client put something in the
2581 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 typeaheadlen = 0;
2583 break;
2584 }
2585
2586 if (c == Ctrl_C && ctrl_c_interrupts)
2587 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002588# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002590# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 got_int = TRUE;
2592 }
2593
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 {
2596 int n = 1;
2597
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002598 if (ch2 == NUL)
2599 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002600 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002601 char_u *p;
2602 WCHAR ch[2];
2603
2604 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002605 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002606 {
2607 ch[1] = tgetch(&modifiers, &ch2);
2608 n++;
2609 }
2610 p = utf16_to_enc(ch, &n);
2611 if (p != NULL)
2612 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002613 for (i = 0, j = 0; i < n; i++)
2614 {
2615 typeahead[typeaheadlen + j++] = p[i];
2616# ifdef VIMDLL
2617 if (p[i] == CSI)
2618 {
2619 typeahead[typeaheadlen + j++] = KS_EXTRA;
2620 typeahead[typeaheadlen + j++] = KE_CSI;
2621 }
2622# endif
2623 }
2624 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002625 vim_free(p);
2626 }
2627 }
2628 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002629 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002630 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002631# ifdef VIMDLL
2632 if (c == CSI)
2633 {
2634 typeahead[typeaheadlen + 1] = KS_EXTRA;
2635 typeahead[typeaheadlen + 2] = KE_CSI;
2636 n = 3;
2637 }
2638# endif
2639 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002640 if (ch2 != NUL)
2641 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002642 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002643 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002644 switch (ch2)
2645 {
2646 case (WCHAR)'\324': // SHIFT+Insert
2647 case (WCHAR)'\325': // CTRL+Insert
2648 case (WCHAR)'\327': // SHIFT+Delete
2649 case (WCHAR)'\330': // CTRL+Delete
2650 typeahead[typeaheadlen + n] = (char_u)ch2;
2651 n++;
2652 break;
2653
2654 default:
2655 typeahead[typeaheadlen + n] = 3;
2656 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2657 n += 2;
2658 break;
2659 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002660 }
2661 else
2662 {
2663 typeahead[typeaheadlen + n] = 3;
2664 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2665 n += 2;
2666 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002667 }
2668
Bram Moolenaar0f873732019-12-05 20:28:46 +01002669 // Use the ALT key to set the 8th bit of the character
2670 // when it's one byte, the 8th bit isn't set yet and not
2671 // using a double-byte encoding (would become a lead
2672 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002673 if ((modifiers & MOD_MASK_ALT)
2674 && n == 1
2675 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002677 )
2678 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002679 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2680 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002681 modifiers &= ~MOD_MASK_ALT;
2682 }
2683
2684 if (modifiers != 0)
2685 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002686 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687 mch_memmove(typeahead + typeaheadlen + 3,
2688 typeahead + typeaheadlen, n);
2689 typeahead[typeaheadlen++] = K_SPECIAL;
2690 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2691 typeahead[typeaheadlen++] = modifiers;
2692 }
2693
2694 typeaheadlen += n;
2695
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002696# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002697 if (fdDump)
2698 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002699# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700 }
2701 }
2702 }
2703
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002704# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705 if (fdDump)
2706 {
2707 fputs("]\n", fdDump);
2708 fflush(fdDump);
2709 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002710# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002713 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 len = 0;
2715 while (len < maxlen && typeaheadlen > 0)
2716 {
2717 buf[len++] = typeahead[0];
2718 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2719 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002720# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002721 if (len > 0)
2722 {
2723 buf[len] = NUL;
2724 ch_log(NULL, "raw key input: \"%s\"", buf);
2725 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002726# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727 return len;
2728
Bram Moolenaar0f873732019-12-05 20:28:46 +01002729#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002731#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732}
2733
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002734/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002735 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002736 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2737 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002738 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002739 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002741executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742{
LemonBoy40fd7e62022-05-05 20:18:16 +01002743 int attrs = win32_getattrs((char_u *)name);
2744
2745 // The file doesn't exist or is a folder.
2746 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2747 return FALSE;
2748 // Check if the file is an AppExecLink, a special alias used by Windows
2749 // Store for its apps.
2750 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002751 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002752 char_u *res = resolve_appexeclink((char_u *)name);
2753 if (res == NULL)
AmberArrf5d0f542023-08-20 20:03:45 +02002754 res = resolve_reparse_point((char_u *)name);
2755 if (res == NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002756 return FALSE;
2757 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002758 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002759 *path = res;
2760 else
2761 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002762 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002763 else if (path != NULL)
2764 *path = FullName_save((char_u *)name, FALSE);
2765 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002766}
2767
2768/*
2769 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2770 * If "use_path" is FALSE: Return TRUE if "name" exists.
2771 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2772 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2773 * the allocated memory.
2774 */
2775 static int
2776executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2777{
2778 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2779 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2780 // UTF-8.
2781 char_u buf[_MAX_PATH * 3];
2782 size_t len = STRLEN(name);
2783 size_t tmplen;
2784 char_u *p, *e, *e2;
2785 char_u *pathbuf = NULL;
2786 char_u *pathext = NULL;
2787 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002788 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002789 int noext = FALSE;
2790 int retval = FALSE;
2791
2792 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002793 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002794
2795 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002796 shname = gettail(p_sh);
2797 if (strstr((char *)shname, "sh") != NULL &&
2798 !(strstr((char *)shname, "powershell") != NULL
2799 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002800 noext = TRUE;
2801
2802 if (use_pathext)
2803 {
2804 pathext = mch_getenv("PATHEXT");
2805 if (pathext == NULL)
2806 pathext = (char_u *)".com;.exe;.bat;.cmd";
2807
2808 if (noext == FALSE)
2809 {
2810 /*
2811 * Loop over all extensions in $PATHEXT.
2812 * Check "name" ends with extension.
2813 */
2814 p = pathext;
2815 while (*p)
2816 {
2817 if (p[0] == ';'
2818 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2819 {
2820 // Skip empty or single ".".
2821 ++p;
2822 continue;
2823 }
2824 e = vim_strchr(p, ';');
2825 if (e == NULL)
2826 e = p + STRLEN(p);
2827 tmplen = e - p;
2828
2829 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2830 {
2831 noext = TRUE;
2832 break;
2833 }
2834
2835 p = e;
2836 }
2837 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002838 }
2839
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002840 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002841 if (pathext == NULL)
2842 pathext = (char_u *)".";
2843 else if (noext == TRUE)
2844 {
2845 if (pathextbuf == NULL)
2846 pathextbuf = alloc(STRLEN(pathext) + 3);
2847 if (pathextbuf == NULL)
2848 {
2849 retval = FALSE;
2850 goto theend;
2851 }
2852 STRCPY(pathextbuf, ".;");
2853 STRCAT(pathextbuf, pathext);
2854 pathext = pathextbuf;
2855 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002856
Bram Moolenaar95da1362020-05-30 18:37:55 +02002857 // Use $PATH when "use_path" is TRUE and "name" is basename.
2858 if (use_path && gettail((char_u *)name) == (char_u *)name)
2859 {
2860 p = mch_getenv("PATH");
2861 if (p != NULL)
2862 {
2863 pathbuf = alloc(STRLEN(p) + 3);
2864 if (pathbuf == NULL)
2865 {
2866 retval = FALSE;
2867 goto theend;
2868 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002869
2870 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2871 STRCPY(pathbuf, ".;");
2872 else
2873 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002874 STRCAT(pathbuf, p);
2875 }
2876 }
2877
2878 /*
2879 * Walk through all entries in $PATH to check if "name" exists there and
2880 * is an executable file.
2881 */
2882 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2883 while (*p)
2884 {
2885 if (*p == ';') // Skip empty entry
2886 {
2887 ++p;
2888 continue;
2889 }
2890 e = vim_strchr(p, ';');
2891 if (e == NULL)
2892 e = p + STRLEN(p);
2893
2894 if (e - p + len + 2 > sizeof(buf))
2895 {
2896 retval = FALSE;
2897 goto theend;
2898 }
2899 // A single "." that means current dir.
2900 if (e - p == 1 && *p == '.')
2901 STRCPY(buf, name);
2902 else
2903 {
2904 vim_strncpy(buf, p, e - p);
2905 add_pathsep(buf);
2906 STRCAT(buf, name);
2907 }
2908 tmplen = STRLEN(buf);
2909
2910 /*
2911 * Loop over all extensions in $PATHEXT.
2912 * Check "name" with extension added.
2913 */
2914 p = pathext;
2915 while (*p)
2916 {
2917 if (*p == ';')
2918 {
2919 // Skip empty entry
2920 ++p;
2921 continue;
2922 }
2923 e2 = vim_strchr(p, (int)';');
2924 if (e2 == NULL)
2925 e2 = p + STRLEN(p);
2926
2927 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2928 {
2929 // Not a single "." that means no extension is added.
2930 if (e2 - p + tmplen + 1 > sizeof(buf))
2931 {
2932 retval = FALSE;
2933 goto theend;
2934 }
2935 vim_strncpy(buf + tmplen, p, e2 - p);
2936 }
2937 if (executable_file((char *)buf, path))
2938 {
2939 retval = TRUE;
2940 goto theend;
2941 }
2942
2943 p = e2;
2944 }
2945
2946 p = e;
2947 }
2948
2949theend:
2950 free(pathextbuf);
2951 free(pathbuf);
2952 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953}
2954
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002955#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2956 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002957/*
2958 * Bad parameter handler.
2959 *
2960 * Certain MS CRT functions will intentionally crash when passed invalid
2961 * parameters to highlight possible security holes. Setting this function as
2962 * the bad parameter handler will prevent the crash.
2963 *
2964 * In debug builds the parameters contain CRT information that might help track
2965 * down the source of a problem, but in non-debug builds the arguments are all
2966 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2967 * worth allowing these to make debugging of issues easier.
2968 */
2969 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002970bad_param_handler(const wchar_t *expression UNUSED,
2971 const wchar_t *function UNUSED,
2972 const wchar_t *file UNUSED,
2973 unsigned int line UNUSED,
2974 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002975{
2976}
2977
2978# define SET_INVALID_PARAM_HANDLER \
2979 ((void)_set_invalid_parameter_handler(bad_param_handler))
2980#else
2981# define SET_INVALID_PARAM_HANDLER
2982#endif
2983
Bram Moolenaar4f974752019-02-17 17:44:42 +01002984#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985
2986/*
2987 * GUI version of mch_init().
2988 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002989 static void
2990mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002992# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002994# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995
Bram Moolenaar0f873732019-12-05 20:28:46 +01002996 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002997 SET_INVALID_PARAM_HANDLER;
2998
Bram Moolenaar0f873732019-12-05 20:28:46 +01002999 // Let critical errors result in a failure, not in a dialog box. Required
3000 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003001 SetErrorMode(SEM_FAILCRITICALERRORS);
3002
Bram Moolenaar0f873732019-12-05 20:28:46 +01003003 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003004
Bram Moolenaar0f873732019-12-05 20:28:46 +01003005 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00003006 Rows = 25;
3007 Columns = 80;
3008
Bram Moolenaar0f873732019-12-05 20:28:46 +01003009 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010 {
3011 char_u vimrun_location[_MAX_PATH + 4];
3012
Bram Moolenaar0f873732019-12-05 20:28:46 +01003013 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014 STRCPY(vimrun_location, exe_name);
3015 STRCPY(gettail(vimrun_location), "vimrun.exe");
3016 if (mch_getperm(vimrun_location) >= 0)
3017 {
3018 if (*skiptowhite(vimrun_location) != NUL)
3019 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003020 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021 mch_memmove(vimrun_location + 1, vimrun_location,
3022 STRLEN(vimrun_location) + 1);
3023 *vimrun_location = '"';
3024 STRCPY(gettail(vimrun_location), "vimrun\" ");
3025 }
3026 else
3027 STRCPY(gettail(vimrun_location), "vimrun ");
3028
3029 vimrun_path = (char *)vim_strsave(vimrun_location);
3030 s_dont_use_vimrun = FALSE;
3031 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02003032 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033 s_dont_use_vimrun = FALSE;
3034
Bram Moolenaar0f873732019-12-05 20:28:46 +01003035 // Don't give the warning for a missing vimrun.exe right now, but only
3036 // when vimrun was supposed to be used. Don't bother people that do
3037 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 if (s_dont_use_vimrun)
3039 need_vimrun_warning = TRUE;
3040 }
3041
3042 /*
3043 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
3044 * Otherwise the default "findstr /n" is used.
3045 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02003046 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003047 set_option_value_give_err((char_u *)"grepprg",
3048 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003050# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003051 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003052# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003053
3054 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055}
3056
3057
Bram Moolenaar0f873732019-12-05 20:28:46 +01003058#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003059
3060#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003062# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3063# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064
3065/*
3066 * ClearConsoleBuffer()
3067 * Description:
3068 * Clears the entire contents of the console screen buffer, using the
3069 * specified attribute.
3070 * Returns:
3071 * TRUE on success
3072 */
3073 static BOOL
3074ClearConsoleBuffer(WORD wAttribute)
3075{
3076 CONSOLE_SCREEN_BUFFER_INFO csbi;
3077 COORD coord;
3078 DWORD NumCells, dummy;
3079
3080 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3081 return FALSE;
3082
3083 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3084 coord.X = 0;
3085 coord.Y = 0;
3086 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3087 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3090 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092
3093 return TRUE;
3094}
3095
3096/*
3097 * FitConsoleWindow()
3098 * Description:
3099 * Checks if the console window will fit within given buffer dimensions.
3100 * Also, if requested, will shrink the window to fit.
3101 * Returns:
3102 * TRUE on success
3103 */
3104 static BOOL
3105FitConsoleWindow(
3106 COORD dwBufferSize,
3107 BOOL WantAdjust)
3108{
3109 CONSOLE_SCREEN_BUFFER_INFO csbi;
3110 COORD dwWindowSize;
3111 BOOL NeedAdjust = FALSE;
3112
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003113 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3114 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003116 /*
3117 * A buffer resize will fail if the current console window does
3118 * not lie completely within that buffer. To avoid this, we might
3119 * have to move and possibly shrink the window.
3120 */
3121 if (csbi.srWindow.Right >= dwBufferSize.X)
3122 {
3123 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3124 if (dwWindowSize.X > dwBufferSize.X)
3125 dwWindowSize.X = dwBufferSize.X;
3126 csbi.srWindow.Right = dwBufferSize.X - 1;
3127 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3128 NeedAdjust = TRUE;
3129 }
3130 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3131 {
3132 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3133 if (dwWindowSize.Y > dwBufferSize.Y)
3134 dwWindowSize.Y = dwBufferSize.Y;
3135 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3136 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3137 NeedAdjust = TRUE;
3138 }
3139 if (NeedAdjust && WantAdjust)
3140 {
3141 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3142 return FALSE;
3143 }
3144 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145}
3146
3147typedef struct ConsoleBufferStruct
3148{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003149 BOOL IsValid;
3150 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003151 PCHAR_INFO Buffer;
3152 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003153 PSMALL_RECT Regions;
3154 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155} ConsoleBuffer;
3156
3157/*
3158 * SaveConsoleBuffer()
3159 * Description:
3160 * Saves important information about the console buffer, including the
3161 * actual buffer contents. The saved information is suitable for later
3162 * restoration by RestoreConsoleBuffer().
3163 * Returns:
3164 * TRUE if all information was saved; FALSE otherwise
3165 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3166 */
3167 static BOOL
3168SaveConsoleBuffer(
3169 ConsoleBuffer *cb)
3170{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003171 DWORD NumCells;
3172 COORD BufferCoord;
3173 SMALL_RECT ReadRegion;
3174 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003175 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003176
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 if (cb == NULL)
3178 return FALSE;
3179
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003180 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181 {
3182 cb->IsValid = FALSE;
3183 return FALSE;
3184 }
3185 cb->IsValid = TRUE;
3186
Christopher Plewright1140b512022-11-12 18:46:05 +00003187 // VTP uses alternate screen buffer.
3188 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003189 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003190 return TRUE;
3191
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003192 /*
3193 * Allocate a buffer large enough to hold the entire console screen
3194 * buffer. If this ConsoleBuffer structure has already been initialized
3195 * with a buffer of the correct size, then just use that one.
3196 */
3197 if (!cb->IsValid || cb->Buffer == NULL ||
3198 cb->BufferSize.X != cb->Info.dwSize.X ||
3199 cb->BufferSize.Y != cb->Info.dwSize.Y)
3200 {
3201 cb->BufferSize.X = cb->Info.dwSize.X;
3202 cb->BufferSize.Y = cb->Info.dwSize.Y;
3203 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3204 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003205 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003206 if (cb->Buffer == NULL)
3207 return FALSE;
3208 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003209
3210 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003211 * We will now copy the console screen buffer into our buffer.
3212 * ReadConsoleOutput() seems to be limited as far as how much you
3213 * can read at a time. Empirically, this number seems to be about
3214 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3215 * in chunks until it is all copied. The chunks will all have the
3216 * same horizontal characteristics, so initialize them now. The
3217 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003219 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003220 ReadRegion.Left = 0;
3221 ReadRegion.Right = cb->Info.dwSize.X - 1;
3222 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003223
3224 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3225 if (cb->Regions == NULL || numregions != cb->NumRegions)
3226 {
3227 cb->NumRegions = numregions;
3228 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003229 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003230 if (cb->Regions == NULL)
3231 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003232 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003233 return FALSE;
3234 }
3235 }
3236
3237 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003239 /*
3240 * Read into position (0, Y) in our buffer.
3241 */
3242 BufferCoord.Y = Y;
3243 /*
3244 * Read the region whose top left corner is (0, Y) and whose bottom
3245 * right corner is (width - 1, Y + Y_incr - 1). This should define
3246 * a region of size width by Y_incr. Don't worry if this region is
3247 * too large for the remaining buffer; it will be cropped.
3248 */
3249 ReadRegion.Top = Y;
3250 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003251 if (!ReadConsoleOutputW(g_hConOut, // output handle
3252 cb->Buffer, // our buffer
3253 cb->BufferSize, // dimensions of our buffer
3254 BufferCoord, // offset in our buffer
3255 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003256 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003257 VIM_CLEAR(cb->Buffer);
3258 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003259 return FALSE;
3260 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003261 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 }
3263
3264 return TRUE;
3265}
3266
3267/*
3268 * RestoreConsoleBuffer()
3269 * Description:
3270 * Restores important information about the console buffer, including the
3271 * actual buffer contents, if desired. The information to restore is in
3272 * the same format used by SaveConsoleBuffer().
3273 * Returns:
3274 * TRUE on success
3275 */
3276 static BOOL
3277RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003278 ConsoleBuffer *cb,
3279 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003281 COORD BufferCoord;
3282 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003283 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003284
Christopher Plewright1140b512022-11-12 18:46:05 +00003285 // VTP uses alternate screen buffer.
3286 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003287 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003288 return TRUE;
3289
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290 if (cb == NULL || !cb->IsValid)
3291 return FALSE;
3292
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003293 /*
3294 * Before restoring the buffer contents, clear the current buffer, and
3295 * restore the cursor position and window information. Doing this now
3296 * prevents old buffer contents from "flashing" onto the screen.
3297 */
3298 if (RestoreScreen)
3299 ClearConsoleBuffer(cb->Info.wAttributes);
3300
3301 FitConsoleWindow(cb->Info.dwSize, TRUE);
3302 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3303 return FALSE;
3304 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3305 return FALSE;
3306
3307 if (!RestoreScreen)
3308 {
3309 /*
3310 * No need to restore the screen buffer contents, so we're done.
3311 */
3312 return TRUE;
3313 }
3314
3315 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3316 return FALSE;
3317 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3318 return FALSE;
3319
3320 /*
3321 * Restore the screen buffer contents.
3322 */
3323 if (cb->Buffer != NULL)
3324 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003325 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003326 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003327 BufferCoord.X = cb->Regions[i].Left;
3328 BufferCoord.Y = cb->Regions[i].Top;
3329 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003330 if (!WriteConsoleOutputW(g_hConOut, // output handle
3331 cb->Buffer, // our buffer
3332 cb->BufferSize, // dimensions of our buffer
3333 BufferCoord, // offset in our buffer
3334 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003335 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003336 }
3337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338
3339 return TRUE;
3340}
3341
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003342# define FEAT_RESTORE_ORIG_SCREEN
3343# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003344static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003345# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003346static ConsoleBuffer g_cbNonTermcap = { 0 };
3347static ConsoleBuffer g_cbTermcap = { 0 };
3348
Bram Moolenaar071d4272004-06-13 20:20:40 +00003349char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003350HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003351static HICON g_hOrigIconSmall = NULL;
3352static HICON g_hOrigIcon = NULL;
3353static HICON g_hVimIcon = NULL;
3354static BOOL g_fCanChangeIcon = FALSE;
3355
Bram Moolenaar071d4272004-06-13 20:20:40 +00003356/*
3357 * GetConsoleIcon()
3358 * Description:
3359 * Attempts to retrieve the small icon and/or the big icon currently in
3360 * use by a given window.
3361 * Returns:
3362 * TRUE on success
3363 */
3364 static BOOL
3365GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003366 HWND hWnd,
3367 HICON *phIconSmall,
3368 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369{
3370 if (hWnd == NULL)
3371 return FALSE;
3372
3373 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003374 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3375 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003377 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3378 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 return TRUE;
3380}
3381
3382/*
3383 * SetConsoleIcon()
3384 * Description:
3385 * Attempts to change the small icon and/or the big icon currently in
3386 * use by a given window.
3387 * Returns:
3388 * TRUE on success
3389 */
3390 static BOOL
3391SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003392 HWND hWnd,
3393 HICON hIconSmall,
3394 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003396 if (hWnd == NULL)
3397 return FALSE;
3398
3399 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003400 SendMessage(hWnd, WM_SETICON,
3401 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003402 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003403 SendMessage(hWnd, WM_SETICON,
3404 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003405 return TRUE;
3406}
3407
3408/*
3409 * SaveConsoleTitleAndIcon()
3410 * Description:
3411 * Saves the current console window title in g_szOrigTitle, for later
3412 * restoration. Also, attempts to obtain a handle to the console window,
3413 * and use it to save the small and big icons currently in use by the
3414 * console window. This is not always possible on some versions of Windows;
3415 * nor is it possible when running Vim remotely using Telnet (since the
3416 * console window the user sees is owned by a remote process).
3417 */
3418 static void
3419SaveConsoleTitleAndIcon(void)
3420{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003421 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003422 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3423 return;
3424
3425 /*
3426 * Obtain a handle to the console window using GetConsoleWindow() from
3427 * KERNEL32.DLL; we need to handle in order to change the window icon.
3428 * This function only exists on NT-based Windows, starting with Windows
3429 * 2000. On older operating systems, we can't change the window icon
3430 * anyway.
3431 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003432 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 if (g_hWnd == NULL)
3434 return;
3435
Bram Moolenaar0f873732019-12-05 20:28:46 +01003436 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3438 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3439 return;
3440
Bram Moolenaar0f873732019-12-05 20:28:46 +01003441 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003442 if (
3443# ifdef FEAT_LIBCALL
3444 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3445# endif
3446 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003447 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448 if (g_hVimIcon != NULL)
3449 g_fCanChangeIcon = TRUE;
3450}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451
3452static int g_fWindInitCalled = FALSE;
3453static int g_fTermcapMode = FALSE;
3454static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003455
3456/*
3457 * non-GUI version of mch_init().
3458 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003459 static void
3460mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003462# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003463 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003464# endif
3465# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003467# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003468
Bram Moolenaar0f873732019-12-05 20:28:46 +01003469 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003470 SET_INVALID_PARAM_HANDLER;
3471
Bram Moolenaar0f873732019-12-05 20:28:46 +01003472 // Let critical errors result in a failure, not in a dialog box. Required
3473 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474 SetErrorMode(SEM_FAILCRITICALERRORS);
3475
Bram Moolenaar0f873732019-12-05 20:28:46 +01003476 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477 out_flush();
3478
Bram Moolenaar0f873732019-12-05 20:28:46 +01003479 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003480 if (read_cmd_fd == 0)
3481 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3482 else
3483 create_conin();
3484 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3485
Christopher Plewright38804d62022-11-09 23:55:52 +00003486 wt_init();
3487 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003488# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003489 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003490 SaveConsoleBuffer(&g_cbOrig);
3491 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003492# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003493 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003494 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3495 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003496# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497 if (cterm_normal_fg_color == 0)
3498 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3499 if (cterm_normal_bg_color == 0)
3500 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3501
Bram Moolenaarbdace832019-03-02 10:13:42 +01003502 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003503 g_color_index_fg = g_attrDefault & 0xf;
3504 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3505
Bram Moolenaar0f873732019-12-05 20:28:46 +01003506 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003507 update_tcap(g_attrCurrent);
3508
3509 GetConsoleCursorInfo(g_hConOut, &g_cci);
3510 GetConsoleMode(g_hConIn, &g_cmodein);
3511 GetConsoleMode(g_hConOut, &g_cmodeout);
3512
Bram Moolenaar071d4272004-06-13 20:20:40 +00003513 SaveConsoleTitleAndIcon();
3514 /*
3515 * Set both the small and big icons of the console window to Vim's icon.
3516 * Note that Vim presently only has one size of icon (32x32), but it
3517 * automatically gets scaled down to 16x16 when setting the small icon.
3518 */
3519 if (g_fCanChangeIcon)
3520 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003521
3522 ui_get_shellsize();
3523
Christopher Plewrightd343c602023-01-22 18:58:30 +00003524 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003525 // Switch to a new alternate screen buffer.
3526 if (use_alternate_screen_buffer)
3527 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003528
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003529# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003530 fdDump = fopen("dump", "wt");
3531
3532 if (fdDump)
3533 {
3534 time_t t;
3535
3536 time(&t);
3537 fputs(ctime(&t), fdDump);
3538 fflush(fdDump);
3539 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003540# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003541
3542 g_fWindInitCalled = TRUE;
3543
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003546# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003547 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003548# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549}
3550
3551/*
3552 * non-GUI version of mch_exit().
3553 * Shut down and exit with status `r'
3554 * Careful: mch_exit() may be called before mch_init()!
3555 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003556 static void
3557mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003558{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003559 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003560
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003561 vtp_exit();
3562
Bram Moolenaar955f1982017-02-05 15:10:51 +01003563 stoptermcap();
Ken Takata568cbc92024-08-07 21:18:24 +02003564 // Switch back to main screen buffer.
3565 if (use_alternate_screen_buffer)
3566 vtp_printf("\033[?1049l");
3567
Bram Moolenaar071d4272004-06-13 20:20:40 +00003568 if (g_fWindInitCalled)
3569 settmode(TMODE_COOK);
3570
Bram Moolenaar0f873732019-12-05 20:28:46 +01003571 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572
3573 if (g_fWindInitCalled)
3574 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003575 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003576 /*
3577 * Restore both the small and big icons of the console window to
3578 * what they were at startup. Don't do this when the window is
3579 * closed, Vim would hang here.
3580 */
3581 if (g_fCanChangeIcon && !g_fForceExit)
3582 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003584# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585 if (fdDump)
3586 {
3587 time_t t;
3588
3589 time(&t);
3590 fputs(ctime(&t), fdDump);
3591 fclose(fdDump);
3592 }
3593 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 }
3596
3597 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003598 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599 SetConsoleMode(g_hConOut, g_cmodeout);
3600
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003601# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003603# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604
3605 exit(r);
3606}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003607#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003609 void
3610mch_init(void)
3611{
3612#ifdef VIMDLL
3613 if (gui.starting)
3614 mch_init_g();
3615 else
3616 mch_init_c();
3617#elif defined(FEAT_GUI_MSWIN)
3618 mch_init_g();
3619#else
3620 mch_init_c();
3621#endif
3622}
3623
3624 void
3625mch_exit(int r)
3626{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003627#ifdef FEAT_NETBEANS_INTG
3628 netbeans_send_disconnect();
3629#endif
3630
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003631#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003632 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003633 mch_exit_g(r);
3634 else
3635 mch_exit_c(r);
3636#elif defined(FEAT_GUI_MSWIN)
3637 mch_exit_g(r);
3638#else
3639 mch_exit_c(r);
3640#endif
3641}
3642
Bram Moolenaar071d4272004-06-13 20:20:40 +00003643/*
3644 * Do we have an interactive window?
3645 */
3646 int
3647mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003648 int argc UNUSED,
3649 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650{
K.Takatace3189d2023-02-15 19:13:43 +00003651 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003653#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003654 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003656# ifdef VIMDLL
3657 if (gui.in_use)
3658 return OK;
3659# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003660 if (isatty(1))
3661 return OK;
3662 return FAIL;
3663#endif
3664}
3665
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003666/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003667 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668 * When "len" is > 0, also expand short to long filenames.
3669 */
3670 void
3671fname_case(
3672 char_u *name,
3673 int len)
3674{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003675 int flen;
3676 WCHAR *p;
3677 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003678
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003679 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003680 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003681 return;
3682
3683 slash_adjust(name);
3684
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003685 p = enc_to_utf16(name, NULL);
3686 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003687 return;
3688
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003689 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003691 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003693 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003694 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003695 if (len > 0 || flen >= (int)STRLEN(q))
3696 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3697 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698 }
3699 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003700 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701}
3702
3703
3704/*
3705 * Insert user name in s[len].
3706 */
3707 int
3708mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003709 char_u *s,
3710 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003712 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003713 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003715 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003716 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003717 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003718
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003719 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003720 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003721 vim_strncpy(s, p, len - 1);
3722 vim_free(p);
3723 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003724 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003725 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 s[0] = NUL;
3727 return FAIL;
3728}
3729
3730
3731/*
3732 * Insert host name in s[len].
3733 */
3734 void
3735mch_get_host_name(
3736 char_u *s,
3737 int len)
3738{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003739 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003740 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003742 if (!GetComputerNameW(wszHostName, &wcch))
3743 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003744
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003745 char_u *p = utf16_to_enc(wszHostName, NULL);
3746 if (p == NULL)
3747 return;
3748
3749 vim_strncpy(s, p, len - 1);
3750 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751}
3752
3753
3754/*
3755 * return process ID
3756 */
3757 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003758mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003759{
3760 return (long)GetCurrentProcessId();
3761}
3762
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003763/*
3764 * return TRUE if process "pid" is still running
3765 */
3766 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003767mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003768{
3769 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3770 DWORD status = 0;
3771 int ret = FALSE;
3772
3773 if (hProcess == NULL)
3774 return FALSE; // might not have access
3775 if (GetExitCodeProcess(hProcess, &status) )
3776 ret = status == STILL_ACTIVE;
3777 CloseHandle(hProcess);
3778 return ret;
3779}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780
3781/*
3782 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3783 * Return OK for success, FAIL for failure.
3784 */
3785 int
3786mch_dirname(
3787 char_u *buf,
3788 int len)
3789{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003790 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003791
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792 /*
3793 * Originally this was:
3794 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3795 * But the Win32s known bug list says that getcwd() doesn't work
3796 * so use the Win32 system call instead. <Negri>
3797 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003798 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3799 return FAIL;
3800
3801 WCHAR wcbuf[_MAX_PATH + 1];
3802 char_u *p = NULL;
3803
3804 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003805 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003806 p = utf16_to_enc(wcbuf, NULL);
3807 if (STRLEN(p) >= (size_t)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003809 // long path name is too long, fall back to short one
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00003810 VIM_CLEAR(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003811 }
3812 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003813 if (p == NULL)
3814 p = utf16_to_enc(wbuf, NULL);
3815
3816 if (p == NULL)
3817 return FAIL;
3818
3819 vim_strncpy(buf, p, len - 1);
3820 vim_free(p);
3821 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822}
3823
3824/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003825 * Get file permissions for "name".
3826 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827 */
3828 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003829mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003831 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003832 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003833
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003834 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003835 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836}
3837
3838
3839/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003840 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003841 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003842 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003843 */
3844 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003845mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003846{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003847 long n;
3848 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003849
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003850 p = enc_to_utf16(name, NULL);
3851 if (p == NULL)
3852 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003853
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003854 n = _wchmod(p, perm);
3855 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003856 if (n == -1)
3857 return FAIL;
3858
3859 win32_set_archive(name);
3860
3861 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003862}
3863
3864/*
3865 * Set hidden flag for "name".
3866 */
3867 void
3868mch_hide(char_u *name)
3869{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003870 int attrs = win32_getattrs(name);
3871 if (attrs == -1)
3872 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003874 attrs |= FILE_ATTRIBUTE_HIDDEN;
3875 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876}
3877
3878/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003879 * Return TRUE if file "name" exists and is hidden.
3880 */
3881 int
3882mch_ishidden(char_u *name)
3883{
3884 int f = win32_getattrs(name);
3885
3886 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003887 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003888
3889 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3890}
3891
3892/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003893 * return TRUE if "name" is a directory
3894 * return FALSE if "name" is not a directory or upon error
3895 */
3896 int
3897mch_isdir(char_u *name)
3898{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003899 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003900
3901 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003902 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903
3904 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3905}
3906
3907/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003908 * return TRUE if "name" is a directory, NOT a symlink to a directory
3909 * return FALSE if "name" is not a directory
3910 * return FALSE for error
3911 */
3912 int
3913mch_isrealdir(char_u *name)
3914{
3915 return mch_isdir(name) && !mch_is_symbolic_link(name);
3916}
3917
3918/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003919 * Create directory "name".
3920 * Return 0 on success, -1 on error.
3921 */
3922 int
3923mch_mkdir(char_u *name)
3924{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003925 WCHAR *p;
3926 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003927
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003928 p = enc_to_utf16(name, NULL);
3929 if (p == NULL)
3930 return -1;
3931 retval = _wmkdir(p);
3932 vim_free(p);
3933 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003934}
3935
3936/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003937 * Delete directory "name".
3938 * Return 0 on success, -1 on error.
3939 */
3940 int
3941mch_rmdir(char_u *name)
3942{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003943 WCHAR *p;
3944 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003945
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003946 p = enc_to_utf16(name, NULL);
3947 if (p == NULL)
3948 return -1;
3949 retval = _wrmdir(p);
3950 vim_free(p);
3951 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003952}
3953
3954/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003955 * Return TRUE if file "fname" has more than one link.
3956 */
3957 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003958mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003959{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003960 BY_HANDLE_FILE_INFORMATION info;
3961
3962 return win32_fileinfo(fname, &info) == FILEINFO_OK
3963 && info.nNumberOfLinks > 1;
3964}
3965
3966/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003967 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003968 */
3969 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003970mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003971{
3972 HANDLE hFind;
3973 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003974 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003975 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003976 WIN32_FIND_DATAW findDataW;
3977
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003978 wn = enc_to_utf16(name, NULL);
3979 if (wn == NULL)
3980 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003981
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003982 hFind = FindFirstFileW(wn, &findDataW);
3983 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003984 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003985 {
3986 fileFlags = findDataW.dwFileAttributes;
3987 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003988 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003989 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003990
3991 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003992 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3993 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003994 res = TRUE;
3995
3996 return res;
3997}
3998
3999/*
4000 * Return TRUE if file "fname" has more than one link or if it is a symbolic
4001 * link.
4002 */
4003 int
4004mch_is_linked(char_u *fname)
4005{
4006 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
4007 return TRUE;
4008 return FALSE;
4009}
4010
4011/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004012 * Get the by-handle-file-information for "fname".
4013 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004014 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004015 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
4016 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
4017 */
4018 int
4019win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
4020{
Bram Moolenaar03f48552006-02-28 23:52:23 +00004021 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004022 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004023 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00004024
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004025 wn = enc_to_utf16(fname, NULL);
4026 if (wn == NULL)
4027 return FILEINFO_ENC_FAIL;
4028
4029 hFile = CreateFileW(wn, // file name
4030 GENERIC_READ, // access mode
4031 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
4032 NULL, // security descriptor
4033 OPEN_EXISTING, // creation disposition
4034 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
4035 NULL); // handle to template file
4036 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004037
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004038 if (hFile == INVALID_HANDLE_VALUE)
4039 return FILEINFO_READ_FAIL;
4040
4041 if (GetFileInformationByHandle(hFile, info) != 0)
4042 res = FILEINFO_OK;
4043 else
4044 res = FILEINFO_INFO_FAIL;
4045 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004046
Bram Moolenaar03f48552006-02-28 23:52:23 +00004047 return res;
4048}
4049
4050/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004051 * get file attributes for `name'
4052 * -1 : error
4053 * else FILE_ATTRIBUTE_* defined in winnt.h
4054 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004055 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004056win32_getattrs(char_u *name)
4057{
4058 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004059 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004060
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004061 p = enc_to_utf16(name, NULL);
4062 if (p == NULL)
4063 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004064
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004065 attr = GetFileAttributesW(p);
4066 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004067
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004068 return attr;
4069}
4070
4071/*
4072 * set file attributes for `name' to `attrs'
4073 *
4074 * return -1 for failure, 0 otherwise
4075 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004076 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004077win32_setattrs(char_u *name, int attrs)
4078{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004079 int res;
4080 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004081
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004082 p = enc_to_utf16(name, NULL);
4083 if (p == NULL)
4084 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004085
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004086 res = SetFileAttributesW(p, attrs);
4087 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004088
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004089 return res ? 0 : -1;
4090}
4091
4092/*
4093 * Set archive flag for "name".
4094 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004095 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004096win32_set_archive(char_u *name)
4097{
4098 int attrs = win32_getattrs(name);
4099 if (attrs == -1)
4100 return -1;
4101
4102 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4103 return win32_setattrs(name, attrs);
4104}
4105
4106/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004107 * Return TRUE if file or directory "name" is writable (not readonly).
4108 * Strange semantics of Win32: a readonly directory is writable, but you can't
4109 * delete a file. Let's say this means it is writable.
4110 */
4111 int
4112mch_writable(char_u *name)
4113{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004114 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004116 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4117 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118}
4119
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004121 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004122 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004123 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4124 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125 */
4126 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004127mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004128{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004129 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131
4132/*
4133 * Check what "name" is:
4134 * NODE_NORMAL: file or directory (or doesn't exist)
4135 * NODE_WRITABLE: writable device, socket, fifo, etc.
4136 * NODE_OTHER: non-writable things
4137 */
4138 int
4139mch_nodetype(char_u *name)
4140{
4141 HANDLE hFile;
4142 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004143 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144
Bram Moolenaar0f873732019-12-05 20:28:46 +01004145 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4146 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4147 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004148 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4149 return NODE_WRITABLE;
4150
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004151 wn = enc_to_utf16(name, NULL);
4152 if (wn == NULL)
4153 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004154
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004155 hFile = CreateFileW(wn, // file name
4156 GENERIC_WRITE, // access mode
4157 0, // share mode
4158 NULL, // security descriptor
4159 OPEN_EXISTING, // creation disposition
4160 0, // file attributes
4161 NULL); // handle to template file
4162 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 if (hFile == INVALID_HANDLE_VALUE)
4164 return NODE_NORMAL;
4165
4166 type = GetFileType(hFile);
4167 CloseHandle(hFile);
4168 if (type == FILE_TYPE_CHAR)
4169 return NODE_WRITABLE;
4170 if (type == FILE_TYPE_DISK)
4171 return NODE_NORMAL;
4172 return NODE_OTHER;
4173}
4174
4175#ifdef HAVE_ACL
4176struct my_acl
4177{
4178 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4179 PSID pSidOwner;
4180 PSID pSidGroup;
4181 PACL pDacl;
4182 PACL pSacl;
4183};
4184#endif
4185
4186/*
4187 * Return a pointer to the ACL of file "fname" in allocated memory.
4188 * Return NULL if the ACL is not available for whatever reason.
4189 */
4190 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004191mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192{
4193#ifndef HAVE_ACL
4194 return (vim_acl_T)NULL;
4195#else
4196 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004197 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004199 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004200 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004202 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004203
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004204 wn = enc_to_utf16(fname, NULL);
4205 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004206 {
4207 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004208 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004209 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004210
4211 // Try to retrieve the entire security descriptor.
4212 err = GetNamedSecurityInfoW(
4213 wn, // Abstract filename
4214 SE_FILE_OBJECT, // File Object
4215 OWNER_SECURITY_INFORMATION |
4216 GROUP_SECURITY_INFORMATION |
4217 DACL_SECURITY_INFORMATION |
4218 SACL_SECURITY_INFORMATION,
4219 &p->pSidOwner, // Ownership information.
4220 &p->pSidGroup, // Group membership.
4221 &p->pDacl, // Discretionary information.
4222 &p->pSacl, // For auditing purposes.
4223 &p->pSecurityDescriptor);
4224 if (err == ERROR_ACCESS_DENIED ||
4225 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004226 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004227 // Retrieve only DACL.
4228 (void)GetNamedSecurityInfoW(
4229 wn,
4230 SE_FILE_OBJECT,
4231 DACL_SECURITY_INFORMATION,
4232 NULL,
4233 NULL,
4234 &p->pDacl,
4235 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004236 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004237 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004238 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004239 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004240 mch_free_acl((vim_acl_T)p);
4241 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004242 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004243 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004244 }
4245
4246 return (vim_acl_T)p;
4247#endif
4248}
4249
Bram Moolenaar27515922013-06-29 15:36:26 +02004250#ifdef HAVE_ACL
4251/*
4252 * Check if "acl" contains inherited ACE.
4253 */
4254 static BOOL
4255is_acl_inherited(PACL acl)
4256{
4257 DWORD i;
4258 ACL_SIZE_INFORMATION acl_info;
4259 PACCESS_ALLOWED_ACE ace;
4260
4261 acl_info.AceCount = 0;
4262 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4263 for (i = 0; i < acl_info.AceCount; i++)
4264 {
4265 GetAce(acl, i, (LPVOID *)&ace);
4266 if (ace->Header.AceFlags & INHERITED_ACE)
4267 return TRUE;
4268 }
4269 return FALSE;
4270}
4271#endif
4272
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273/*
4274 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4275 * Errors are ignored.
4276 * This must only be called with "acl" equal to what mch_get_acl() returned.
4277 */
4278 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004279mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280{
4281#ifdef HAVE_ACL
4282 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004283 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004284 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004286 if (p == NULL)
4287 return;
4288
4289 wn = enc_to_utf16(fname, NULL);
4290 if (wn == NULL)
4291 return;
4292
4293 // Set security flags
4294 if (p->pSidOwner)
4295 sec_info |= OWNER_SECURITY_INFORMATION;
4296 if (p->pSidGroup)
4297 sec_info |= GROUP_SECURITY_INFORMATION;
4298 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004299 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004300 sec_info |= DACL_SECURITY_INFORMATION;
4301 // Do not inherit its parent's DACL.
4302 // If the DACL is inherited, Cygwin permissions would be changed.
4303 if (!is_acl_inherited(p->pDacl))
4304 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004305 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004306 if (p->pSacl)
4307 sec_info |= SACL_SECURITY_INFORMATION;
4308
4309 (void)SetNamedSecurityInfoW(
4310 wn, // Abstract filename
4311 SE_FILE_OBJECT, // File Object
4312 sec_info,
4313 p->pSidOwner, // Ownership information.
4314 p->pSidGroup, // Group membership.
4315 p->pDacl, // Discretionary information.
4316 p->pSacl // For auditing purposes.
4317 );
4318 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319#endif
4320}
4321
4322 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004323mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324{
4325#ifdef HAVE_ACL
4326 struct my_acl *p = (struct my_acl *)acl;
4327
4328 if (p != NULL)
4329 {
4330 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4331 vim_free(p);
4332 }
4333#endif
4334}
4335
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004336#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337
4338/*
4339 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4340 */
4341 static BOOL WINAPI
4342handler_routine(
4343 DWORD dwCtrlType)
4344{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004345 INPUT_RECORD ir;
4346 DWORD out;
4347
Bram Moolenaar071d4272004-06-13 20:20:40 +00004348 switch (dwCtrlType)
4349 {
4350 case CTRL_C_EVENT:
4351 if (ctrl_c_interrupts)
4352 g_fCtrlCPressed = TRUE;
4353 return TRUE;
4354
4355 case CTRL_BREAK_EVENT:
4356 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004357 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004358 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004359 ir.EventType = KEY_EVENT;
4360 ir.Event.KeyEvent.bKeyDown = TRUE;
4361 ir.Event.KeyEvent.wRepeatCount = 1;
4362 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4363 ir.Event.KeyEvent.wVirtualScanCode = 0;
4364 ir.Event.KeyEvent.dwControlKeyState = 0;
4365 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4366 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004367 return TRUE;
4368
Bram Moolenaar0f873732019-12-05 20:28:46 +01004369 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370 case CTRL_CLOSE_EVENT:
4371 case CTRL_LOGOFF_EVENT:
4372 case CTRL_SHUTDOWN_EVENT:
4373 windgoto((int)Rows - 1, 0);
4374 g_fForceExit = TRUE;
4375
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004376 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004377 (dwCtrlType == CTRL_CLOSE_EVENT
4378 ? _("close")
4379 : dwCtrlType == CTRL_LOGOFF_EVENT
4380 ? _("logoff")
4381 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004382# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004384# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004385
Bram Moolenaar0f873732019-12-05 20:28:46 +01004386 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004387
Bram Moolenaar0f873732019-12-05 20:28:46 +01004388 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004389
4390 default:
4391 return FALSE;
4392 }
4393}
4394
4395
4396/*
4397 * set the tty in (raw) ? "raw" : "cooked" mode
4398 */
4399 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004400mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004401{
4402 DWORD cmodein;
4403 DWORD cmodeout;
4404 BOOL bEnableHandler;
4405
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004406# ifdef VIMDLL
4407 if (gui.in_use)
4408 return;
4409# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410 GetConsoleMode(g_hConIn, &cmodein);
4411 GetConsoleMode(g_hConOut, &cmodeout);
4412 if (tmode == TMODE_RAW)
4413 {
4414 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4415 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004417 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004419 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4420 }
4421 else
4422 {
4423 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4424 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004425 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004426# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004427 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4428 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004429 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004430# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004431 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004432# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004433 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434 bEnableHandler = TRUE;
4435 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004436 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437 {
4438 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4439 ENABLE_ECHO_INPUT);
4440 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4441 bEnableHandler = FALSE;
4442 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004443 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444 SetConsoleMode(g_hConOut, cmodeout);
4445 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4446
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004447# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448 if (fdDump)
4449 {
4450 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4451 tmode == TMODE_RAW ? "raw" :
4452 tmode == TMODE_COOK ? "cooked" : "normal",
4453 cmodein, cmodeout);
4454 fflush(fdDump);
4455 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004456# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457}
4458
4459
4460/*
4461 * Get the size of the current window in `Rows' and `Columns'
4462 * Return OK when size could be determined, FAIL otherwise.
4463 */
4464 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004465mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004466{
4467 CONSOLE_SCREEN_BUFFER_INFO csbi;
4468
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004469# ifdef VIMDLL
4470 if (gui.in_use)
4471 return OK;
4472# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004473 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4474 {
4475 /*
4476 * For some reason, we are trying to get the screen dimensions
4477 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4478 * variables are really intended to mean the size of Vim screen
4479 * while in termcap mode.
4480 */
4481 Rows = g_cbTermcap.Info.dwSize.Y;
4482 Columns = g_cbTermcap.Info.dwSize.X;
4483 }
4484 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4485 {
4486 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4487 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4488 }
4489 else
4490 {
4491 Rows = 25;
4492 Columns = 80;
4493 }
4494 return OK;
4495}
4496
4497/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004498 * Resize console buffer to 'COORD'
4499 */
4500 static void
4501ResizeConBuf(
4502 HANDLE hConsole,
4503 COORD coordScreen)
4504{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004505 if (use_alternate_screen_buffer)
4506 return;
4507
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004508 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4509 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004510# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004511 if (fdDump)
4512 {
4513 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4514 GetLastError());
4515 fflush(fdDump);
4516 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004517# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004518 }
4519}
4520
4521/*
4522 * Resize console window size to 'srWindowRect'
4523 */
4524 static void
4525ResizeWindow(
4526 HANDLE hConsole,
4527 SMALL_RECT srWindowRect)
4528{
4529 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4530 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004531# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004532 if (fdDump)
4533 {
4534 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4535 GetLastError());
4536 fflush(fdDump);
4537 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004538# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004539 }
4540}
4541
4542/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 * Set a console window to `xSize' * `ySize'
4544 */
4545 static void
4546ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004547 HANDLE hConsole,
4548 int xSize,
4549 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004551 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4552 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004553 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004554 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004555 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004557# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004558 if (fdDump)
4559 {
4560 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4561 fflush(fdDump);
4562 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004563# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004564
Bram Moolenaar0f873732019-12-05 20:28:46 +01004565 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566 coordScreen = GetLargestConsoleWindowSize(hConsole);
4567
Bram Moolenaar0f873732019-12-05 20:28:46 +01004568 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4570 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4571 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4572
4573 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4574 {
4575 int sx, sy;
4576
4577 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4578 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4579 if (sy < ySize || sx < xSize)
4580 {
4581 /*
4582 * Increasing number of lines/columns, do buffer first.
4583 * Use the maximal size in x and y direction.
4584 */
4585 if (sy < ySize)
4586 coordScreen.Y = ySize;
4587 else
4588 coordScreen.Y = sy;
4589 if (sx < xSize)
4590 coordScreen.X = xSize;
4591 else
4592 coordScreen.X = sx;
4593 SetConsoleScreenBufferSize(hConsole, coordScreen);
4594 }
4595 }
4596
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004597 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598 coordScreen.X = xSize;
4599 coordScreen.Y = ySize;
4600
Bram Moolenaar2551c032018-08-23 22:38:31 +02004601 // In the new console call API, only the first time in reverse order
4602 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004603 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004604 ResizeWindow(hConsole, srWindowRect);
4605 ResizeConBuf(hConsole, coordScreen);
4606 }
4607 else
4608 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004609 // Workaround for a Windows 10 bug
4610 cursor.X = srWindowRect.Left;
4611 cursor.Y = srWindowRect.Top;
4612 SetConsoleCursorPosition(hConsole, cursor);
4613
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004614 ResizeConBuf(hConsole, coordScreen);
4615 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004616 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004617 }
4618}
4619
4620
4621/*
4622 * Set the console window to `Rows' * `Columns'
4623 */
4624 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004625mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626{
4627 COORD coordScreen;
4628
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004629# ifdef VIMDLL
4630 if (gui.in_use)
4631 return;
4632# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004633 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 if (suppress_winsize != 0)
4635 {
4636 suppress_winsize = 2;
4637 return;
4638 }
4639
4640 if (term_console)
4641 {
4642 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4643
Bram Moolenaar0f873732019-12-05 20:28:46 +01004644 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004645 if (Rows > coordScreen.Y)
4646 Rows = coordScreen.Y;
4647 if (Columns > coordScreen.X)
4648 Columns = coordScreen.X;
4649
4650 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4651 }
4652}
4653
4654/*
4655 * Rows and/or Columns has changed.
4656 */
4657 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004658mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004659{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004660# ifdef VIMDLL
4661 if (gui.in_use)
4662 return;
4663# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4665}
4666
4667
4668/*
4669 * Called when started up, to set the winsize that was delayed.
4670 */
4671 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004672mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004673{
4674 if (suppress_winsize == 2)
4675 {
4676 suppress_winsize = 0;
4677 mch_set_shellsize();
4678 shell_resized();
4679 }
4680 suppress_winsize = 0;
4681}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004682#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004684 static BOOL
4685vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004686 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004687 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004688 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004689 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004690 PROCESS_INFORMATION *pi,
4691 LPVOID *env,
4692 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004693{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004694 BOOL ret = FALSE;
4695 WCHAR *wcmd, *wcwd = NULL;
4696
4697 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4698 if (wcmd == NULL)
4699 return FALSE;
4700 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004701 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004702 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4703 if (wcwd == NULL)
4704 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004705 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004706
4707 ret = CreateProcessW(
4708 NULL, // Executable name
4709 wcmd, // Command to execute
4710 NULL, // Process security attributes
4711 NULL, // Thread security attributes
4712 inherit_handles, // Inherit handles
4713 flags, // Creation flags
4714 env, // Environment
4715 wcwd, // Current directory
4716 (LPSTARTUPINFOW)si, // Startup information
4717 pi); // Process information
4718theend:
4719 vim_free(wcmd);
4720 vim_free(wcwd);
4721 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004722}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004723
4724
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004725 static HINSTANCE
4726vim_shell_execute(
4727 char *cmd,
4728 INT n_show_cmd)
4729{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004730 HINSTANCE ret;
4731 WCHAR *wcmd;
4732
4733 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4734 if (wcmd == NULL)
4735 return (HINSTANCE) 0;
4736
4737 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4738 vim_free(wcmd);
4739 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004740}
4741
4742
Bram Moolenaar4f974752019-02-17 17:44:42 +01004743#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744
4745/*
4746 * Specialised version of system() for Win32 GUI mode.
4747 * This version proceeds as follows:
4748 * 1. Create a console window for use by the subprocess
4749 * 2. Run the subprocess (it gets the allocated console by default)
4750 * 3. Wait for the subprocess to terminate and get its exit code
4751 * 4. Prompt the user to press a key to close the console window
4752 */
4753 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004754mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755{
4756 STARTUPINFO si;
4757 PROCESS_INFORMATION pi;
4758 DWORD ret = 0;
4759 HWND hwnd = GetFocus();
4760
4761 si.cb = sizeof(si);
4762 si.lpReserved = NULL;
4763 si.lpDesktop = NULL;
4764 si.lpTitle = NULL;
4765 si.dwFlags = STARTF_USESHOWWINDOW;
4766 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004767 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004768 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004770 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004771 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772 else
4773 si.wShowWindow = SW_SHOWNORMAL;
4774 si.cbReserved2 = 0;
4775 si.lpReserved2 = NULL;
4776
Bram Moolenaar0f873732019-12-05 20:28:46 +01004777 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004778 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004779 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4780 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781
Bram Moolenaar0f873732019-12-05 20:28:46 +01004782 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004784# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785 int delay = 1;
4786
Bram Moolenaar0f873732019-12-05 20:28:46 +01004787 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788 for (;;)
4789 {
4790 MSG msg;
4791
K.Takatab7057bd2022-01-21 11:37:07 +00004792 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004793 {
4794 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004795 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004796 delay = 1;
4797 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004798 }
4799 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4800 break;
4801
Bram Moolenaar0f873732019-12-05 20:28:46 +01004802 // We start waiting for a very short time and then increase it, so
4803 // that we respond quickly when the process is quick, and don't
4804 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805 if (delay < 50)
4806 delay += 10;
4807 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004808# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004810# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004811
Bram Moolenaar0f873732019-12-05 20:28:46 +01004812 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813 GetExitCodeProcess(pi.hProcess, &ret);
4814 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004815
Bram Moolenaar0f873732019-12-05 20:28:46 +01004816 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004817 CloseHandle(pi.hThread);
4818 CloseHandle(pi.hProcess);
4819
Bram Moolenaar0f873732019-12-05 20:28:46 +01004820 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4822
4823 return ret;
4824}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004825
4826/*
4827 * Thread launched by the gui to send the current buffer data to the
4828 * process. This way avoid to hang up vim totally if the children
4829 * process take a long time to process the lines.
4830 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004831 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004832sub_process_writer(LPVOID param)
4833{
4834 HANDLE g_hChildStd_IN_Wr = param;
4835 linenr_T lnum = curbuf->b_op_start.lnum;
4836 DWORD len = 0;
4837 DWORD l;
4838 char_u *lp = ml_get(lnum);
4839 char_u *s;
4840 int written = 0;
4841
4842 for (;;)
4843 {
4844 l = (DWORD)STRLEN(lp + written);
4845 if (l == 0)
4846 len = 0;
4847 else if (lp[written] == NL)
4848 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004849 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004850 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4851 }
4852 else
4853 {
4854 s = vim_strchr(lp + written, NL);
4855 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4856 s == NULL ? l : (DWORD)(s - (lp + written)),
4857 &len, NULL);
4858 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004859 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004860 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004861 // Finished a line, add a NL, unless this line should not have
4862 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004863 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004864 || (!curbuf->b_p_bin
4865 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004866 || (lnum != curbuf->b_no_eol_lnum
4867 && (lnum != curbuf->b_ml.ml_line_count
4868 || curbuf->b_p_eol)))
4869 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004870 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4871 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004872 }
4873
4874 ++lnum;
4875 if (lnum > curbuf->b_op_end.lnum)
4876 break;
4877
4878 lp = ml_get(lnum);
4879 written = 0;
4880 }
4881 else if (len > 0)
4882 written += len;
4883 }
4884
Bram Moolenaar0f873732019-12-05 20:28:46 +01004885 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004886 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004887 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004888}
4889
4890
Bram Moolenaar0f873732019-12-05 20:28:46 +01004891# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004892
4893/*
4894 * This function read from the children's stdout and write the
4895 * data on screen or in the buffer accordingly.
4896 */
4897 static void
4898dump_pipe(int options,
4899 HANDLE g_hChildStd_OUT_Rd,
4900 garray_T *ga,
4901 char_u buffer[],
4902 DWORD *buffer_off)
4903{
4904 DWORD availableBytes = 0;
4905 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004906 int ret;
4907 DWORD len;
4908 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004909
Bram Moolenaar0f873732019-12-05 20:28:46 +01004910 // we query the pipe to see if there is any data to read
4911 // to avoid to perform a blocking read
4912 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4913 NULL, // optional buffer
4914 0, // buffer size
4915 NULL, // number of read bytes
4916 &availableBytes, // available bytes total
4917 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004918
Bram Moolenaar0f873732019-12-05 20:28:46 +01004919 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004920 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004921 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004922 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004923 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004924 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004925
Bram Moolenaar0f873732019-12-05 20:28:46 +01004926 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004927 if (len == 0)
4928 break;
4929
4930 availableBytes -= len;
4931
4932 if (options & SHELL_READ)
4933 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004934 // Do NUL -> NL translation, append NL separated
4935 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004936 for (i = 0; i < len; ++i)
4937 {
4938 if (buffer[i] == NL)
4939 append_ga_line(ga);
4940 else if (buffer[i] == NUL)
4941 ga_append(ga, NL);
4942 else
4943 ga_append(ga, buffer[i]);
4944 }
4945 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004946 else if (has_mbyte)
4947 {
4948 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004949 int c;
4950 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004951
4952 len += *buffer_off;
4953 buffer[len] = NUL;
4954
Bram Moolenaar0f873732019-12-05 20:28:46 +01004955 // Check if the last character in buffer[] is
4956 // incomplete, keep these bytes for the next
4957 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004958 for (p = buffer; p < buffer + len; p += l)
4959 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004960 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004961 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004962 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004963 else if (MB_BYTE2LEN(*p) != l)
4964 break;
4965 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004966 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004967 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004968 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004969 if (len >= 12)
4970 ++p;
4971 else
4972 {
4973 *buffer_off = len;
4974 return;
4975 }
4976 }
4977 c = *p;
4978 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004979 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004980 if (p < buffer + len)
4981 {
4982 *p = c;
4983 *buffer_off = (DWORD)((buffer + len) - p);
4984 mch_memmove(buffer, p, *buffer_off);
4985 return;
4986 }
4987 *buffer_off = 0;
4988 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004989 else
4990 {
4991 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004992 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004993 }
4994
4995 windgoto(msg_row, msg_col);
4996 cursor_on();
4997 out_flush();
4998 }
4999}
5000
5001/*
5002 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
5003 * for communication and doesn't open any new window.
5004 */
5005 static int
5006mch_system_piped(char *cmd, int options)
5007{
5008 STARTUPINFO si;
5009 PROCESS_INFORMATION pi;
5010 DWORD ret = 0;
5011
5012 HANDLE g_hChildStd_IN_Rd = NULL;
5013 HANDLE g_hChildStd_IN_Wr = NULL;
5014 HANDLE g_hChildStd_OUT_Rd = NULL;
5015 HANDLE g_hChildStd_OUT_Wr = NULL;
5016
Bram Moolenaar0f873732019-12-05 20:28:46 +01005017 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005018 DWORD len;
5019
Bram Moolenaar0f873732019-12-05 20:28:46 +01005020 // buffer used to receive keys
5021 char_u ta_buf[BUFLEN + 1]; // TypeAHead
5022 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005023
5024 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005025 int noread_cnt = 0;
5026 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005027 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005028 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005029 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005030
5031 SECURITY_ATTRIBUTES saAttr;
5032
Bram Moolenaar0f873732019-12-05 20:28:46 +01005033 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005034 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5035 saAttr.bInheritHandle = TRUE;
5036 saAttr.lpSecurityDescriptor = NULL;
5037
5038 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005039 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005040 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005041 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005042 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005043 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005044 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005045 {
5046 CloseHandle(g_hChildStd_IN_Rd);
5047 CloseHandle(g_hChildStd_IN_Wr);
5048 CloseHandle(g_hChildStd_OUT_Rd);
5049 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005050 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005051 }
5052
5053 si.cb = sizeof(si);
5054 si.lpReserved = NULL;
5055 si.lpDesktop = NULL;
5056 si.lpTitle = NULL;
5057 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5058
Bram Moolenaar0f873732019-12-05 20:28:46 +01005059 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005060 si.hStdError = g_hChildStd_OUT_Wr;
5061 si.hStdOutput = g_hChildStd_OUT_Wr;
5062 si.hStdInput = g_hChildStd_IN_Rd;
5063 si.wShowWindow = SW_HIDE;
5064 si.cbReserved2 = 0;
5065 si.lpReserved2 = NULL;
5066
5067 if (options & SHELL_READ)
5068 ga_init2(&ga, 1, BUFLEN);
5069
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005070 if (cmd != NULL)
5071 {
5072 p = (char *)vim_strsave((char_u *)cmd);
5073 if (p != NULL)
5074 unescape_shellxquote((char_u *)p, p_sxe);
5075 else
5076 p = cmd;
5077 }
5078
Bram Moolenaar0f873732019-12-05 20:28:46 +01005079 // Now, run the command.
5080 // About "Inherit handles" being TRUE: this command can be litigious,
5081 // handle inheritance was deactivated for pending temp file, but, if we
5082 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005083 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5084 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005085
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005086 if (p != cmd)
5087 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005088
Bram Moolenaar0f873732019-12-05 20:28:46 +01005089 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005090 CloseHandle(g_hChildStd_IN_Rd);
5091 CloseHandle(g_hChildStd_OUT_Wr);
5092
5093 if (options & SHELL_WRITE)
5094 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005095 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005096 _beginthreadex(NULL, // security attributes
5097 0, // default stack size
5098 sub_process_writer, // function to be executed
5099 g_hChildStd_IN_Wr, // parameter
5100 0, // creation flag, start immediately
5101 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005102 CloseHandle(thread);
5103 g_hChildStd_IN_Wr = NULL;
5104 }
5105
Bram Moolenaar0f873732019-12-05 20:28:46 +01005106 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005107 for (;;)
5108 {
5109 MSG msg;
5110
K.Takatab7057bd2022-01-21 11:37:07 +00005111 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005112 {
5113 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005114 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005115 }
5116
Bram Moolenaar0f873732019-12-05 20:28:46 +01005117 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005118 if ((options & (SHELL_READ|SHELL_WRITE))
5119# ifdef FEAT_GUI
5120 || gui.in_use
5121# endif
5122 )
5123 {
5124 len = 0;
GuyBrush52ecc762024-02-21 20:16:38 +01005125 if (((options &
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005126 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5127 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5128# ifdef FEAT_GUI
5129 || gui.in_use
5130# endif
5131 )
5132 && (ta_len > 0 || noread_cnt > 4))
5133 {
5134 if (ta_len == 0)
5135 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005136 // Get extra characters when we don't have any. Reset the
5137 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005138 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005139 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5140 }
5141 if (ta_len > 0 || len > 0)
5142 {
5143 /*
5144 * For pipes: Check for CTRL-C: send interrupt signal to
GuyBrush1f13fcc2024-01-14 20:08:40 +01005145 * child.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005146 */
5147 if (len == 1 && cmd != NULL)
5148 {
5149 if (ta_buf[ta_len] == Ctrl_C)
5150 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005151 // Learn what exit code is expected, for
5152 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005153 TerminateProcess(pi.hProcess, 9);
5154 }
GuyBrush1f13fcc2024-01-14 20:08:40 +01005155 }
5156
5157 /*
5158 * Check for CTRL-D: EOF, close pipe to child.
5159 * Ctrl_D may be decorated by _OnChar()
5160 */
5161 if ((len == 1 || len == 4 ) && cmd != NULL)
5162 {
5163 if (ta_buf[0] == Ctrl_D
5164 || (ta_buf[0] == CSI
5165 && ta_buf[1] == KS_MODIFIER
5166 && ta_buf[3] == Ctrl_D))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005167 {
5168 CloseHandle(g_hChildStd_IN_Wr);
5169 g_hChildStd_IN_Wr = NULL;
GuyBrush1f13fcc2024-01-14 20:08:40 +01005170 len = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005171 }
5172 }
5173
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005174 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005175
5176 /*
5177 * For pipes: echo the typed characters. For a pty this
5178 * does not seem to work.
5179 */
5180 for (i = ta_len; i < ta_len + len; ++i)
5181 {
5182 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5183 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005184 else if (has_mbyte)
5185 {
5186 int l = (*mb_ptr2len)(ta_buf + i);
5187
5188 msg_outtrans_len(ta_buf + i, l);
5189 i += l - 1;
5190 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005191 else
5192 msg_outtrans_len(ta_buf + i, 1);
5193 }
5194 windgoto(msg_row, msg_col);
5195 out_flush();
5196
5197 ta_len += len;
5198
5199 /*
5200 * Write the characters to the child, unless EOF has been
5201 * typed for pipes. Write one character at a time, to
5202 * avoid losing too much typeahead. When writing buffer
5203 * lines, drop the typed characters (only check for
5204 * CTRL-C).
5205 */
5206 if (options & SHELL_WRITE)
5207 ta_len = 0;
5208 else if (g_hChildStd_IN_Wr != NULL)
5209 {
5210 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5211 1, &len, NULL);
5212 // if we are typing in, we want to keep things reactive
5213 delay = 1;
5214 if (len > 0)
5215 {
5216 ta_len -= len;
5217 mch_memmove(ta_buf, ta_buf + len, ta_len);
5218 }
5219 }
5220 }
5221 }
5222 }
5223
5224 if (ta_len)
5225 ui_inchar_undo(ta_buf, ta_len);
5226
5227 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5228 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005229 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005230 break;
5231 }
5232
5233 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005234 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005235
Bram Moolenaar0f873732019-12-05 20:28:46 +01005236 // We start waiting for a very short time and then increase it, so
5237 // that we respond quickly when the process is quick, and don't
5238 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005239 if (delay < 50)
5240 delay += 10;
5241 }
5242
Bram Moolenaar0f873732019-12-05 20:28:46 +01005243 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005244 CloseHandle(g_hChildStd_OUT_Rd);
5245 if (g_hChildStd_IN_Wr != NULL)
5246 CloseHandle(g_hChildStd_IN_Wr);
5247
5248 WaitForSingleObject(pi.hProcess, INFINITE);
5249
Bram Moolenaar0f873732019-12-05 20:28:46 +01005250 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005251 GetExitCodeProcess(pi.hProcess, &ret);
5252
5253 if (options & SHELL_READ)
5254 {
5255 if (ga.ga_len > 0)
5256 {
5257 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005258 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005259 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5260 }
5261 else
5262 curbuf->b_no_eol_lnum = 0;
5263 ga_clear(&ga);
5264 }
5265
Bram Moolenaar0f873732019-12-05 20:28:46 +01005266 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005267 CloseHandle(pi.hThread);
5268 CloseHandle(pi.hProcess);
5269
5270 return ret;
5271}
5272
5273 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005274mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005275{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005276 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005277 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005278 return mch_system_piped(cmd, options);
5279 else
5280 return mch_system_classic(cmd, options);
5281}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005282#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005283
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005284#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005285 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005286mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005287{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005288 int ret;
5289 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005290 char_u *buf;
5291 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005292
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005293 // If the command starts and ends with double quotes, enclose the command
5294 // in parentheses.
5295 len = STRLEN(cmd);
5296 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5297 {
5298 len += 3;
5299 buf = alloc(len);
5300 if (buf == NULL)
5301 return -1;
5302 vim_snprintf((char *)buf, len, "(%s)", cmd);
5303 wcmd = enc_to_utf16(buf, NULL);
5304 free(buf);
5305 }
5306 else
5307 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5308
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005309 if (wcmd == NULL)
5310 return -1;
5311
5312 ret = _wsystem(wcmd);
5313 vim_free(wcmd);
5314 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005315}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005316
5317#endif
5318
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005319 static int
5320mch_system(char *cmd, int options)
5321{
5322#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005323 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005324 return mch_system_g(cmd, options);
5325 else
5326 return mch_system_c(cmd, options);
5327#elif defined(FEAT_GUI_MSWIN)
5328 return mch_system_g(cmd, options);
5329#else
5330 return mch_system_c(cmd, options);
5331#endif
5332}
5333
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005334#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5335/*
5336 * Use a terminal window to run a shell command in.
5337 */
5338 static int
5339mch_call_shell_terminal(
5340 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005341 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005342{
5343 jobopt_T opt;
5344 char_u *newcmd = NULL;
5345 typval_T argvar[2];
5346 long_u cmdlen;
5347 int retval = -1;
5348 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005349 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005350 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005351 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005352
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005353 if (cmd == NULL)
5354 cmdlen = STRLEN(p_sh) + 1;
5355 else
5356 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005357 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005358 if (newcmd == NULL)
5359 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005360 if (cmd == NULL)
5361 {
5362 STRCPY(newcmd, p_sh);
5363 ch_log(NULL, "starting terminal to run a shell");
5364 }
5365 else
5366 {
5367 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5368 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5369 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005370
5371 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005372
5373 argvar[0].v_type = VAR_STRING;
5374 argvar[0].vval.v_string = newcmd;
5375 argvar[1].v_type = VAR_UNKNOWN;
5376 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005377 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005378 {
5379 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005380 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005381 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005382
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005383 job = term_getjob(buf->b_term);
5384 ++job->jv_refcount;
5385
Bram Moolenaar0f873732019-12-05 20:28:46 +01005386 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005387 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005388 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005389 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005390 // Only do this when a window was found for "buf".
5391 clear_oparg(&oa);
5392 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005393 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005394 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5395 {
5396 // If terminal_loop() returns OK we got a key that is handled
5397 // in Normal model. We don't do redrawing anyway.
5398 if (terminal_loop(TRUE) == OK)
5399 normal_cmd(&oa, TRUE);
5400 }
5401 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005402 normal_cmd(&oa, TRUE);
5403 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005404 retval = job->jv_exitval;
5405 ch_log(NULL, "system command finished");
5406
5407 job_unref(job);
5408
5409 // restore curwin/curbuf and a few other things
5410 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005411 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005412
5413 wait_return(TRUE);
5414 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5415
5416 vim_free(newcmd);
5417 return retval;
5418}
5419#endif
5420
Bram Moolenaar071d4272004-06-13 20:20:40 +00005421/*
5422 * Either execute a command by calling the shell or start a new shell
5423 */
5424 int
5425mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005426 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005427 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005428{
5429 int x = 0;
5430 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005431 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005432
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005433#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005434 ch_log(NULL, "executing shell command: %s", cmd);
5435#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005436 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005437 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005438 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005439 if (cmd == NULL)
5440 wcscat(szShellTitle, L" :sh");
5441 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005442 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005443 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005444
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005445 if (wn != NULL)
5446 {
5447 wcscat(szShellTitle, L" - !");
5448 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005449 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005450 wcscat(szShellTitle, wn);
5451 SetConsoleTitleW(szShellTitle);
5452 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005453 }
5454 }
5455 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005456
5457 out_flush();
5458
5459#ifdef MCH_WRITE_DUMP
5460 if (fdDump)
5461 {
5462 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5463 fflush(fdDump);
5464 }
5465#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005466#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005467 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005468 if (
5469# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005470 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005471# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005472 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005473 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5474 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005475 char_u *cmdbase = cmd;
5476
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005477 if (cmdbase != NULL)
5478 // Skip a leading quote and (.
5479 while (*cmdbase == '"' || *cmdbase == '(')
5480 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005481
5482 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005483 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5484 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005485 {
5486 // Use a terminal window to run the command in.
5487 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005488 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005489 return x;
5490 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005491 }
5492#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005493
5494 /*
5495 * Catch all deadly signals while running the external command, because a
5496 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5497 */
ichizok378447f2023-05-11 22:25:42 +01005498 mch_signal(SIGINT, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005499 mch_signal(SIGBREAK, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005500 mch_signal(SIGILL, SIG_IGN);
5501 mch_signal(SIGFPE, SIG_IGN);
5502 mch_signal(SIGSEGV, SIG_IGN);
5503 mch_signal(SIGTERM, SIG_IGN);
5504 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005505
5506 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005507 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005508
5509 if (cmd == NULL)
5510 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005511 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512 }
5513 else
5514 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005515 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005516 char_u *newcmd = NULL;
5517 char_u *cmdbase = cmd;
5518 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005519
Bram Moolenaar0f873732019-12-05 20:28:46 +01005520 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005521 if (*cmdbase == '"' )
5522 ++cmdbase;
5523 if (*cmdbase == '(')
5524 ++cmdbase;
5525
Bram Moolenaar1c465442017-03-12 20:10:05 +01005526 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005527 {
5528 STARTUPINFO si;
5529 PROCESS_INFORMATION pi;
5530 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005531 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005532 char_u *p;
5533
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005534 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005535 si.cb = sizeof(si);
5536 si.lpReserved = NULL;
5537 si.lpDesktop = NULL;
5538 si.lpTitle = NULL;
5539 si.dwFlags = 0;
5540 si.cbReserved2 = 0;
5541 si.lpReserved2 = NULL;
5542
5543 cmdbase = skipwhite(cmdbase + 5);
5544 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005545 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005546 {
5547 cmdbase = skipwhite(cmdbase + 4);
5548 si.dwFlags = STARTF_USESHOWWINDOW;
5549 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005550 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005551 }
5552 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005553 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005554 {
5555 cmdbase = skipwhite(cmdbase + 2);
5556 flags = CREATE_NO_WINDOW;
5557 si.dwFlags = STARTF_USESTDHANDLES;
5558 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005559 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005560 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005561 NULL, // Security att.
5562 OPEN_EXISTING, // Open flags
5563 FILE_ATTRIBUTE_NORMAL, // File att.
5564 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005565 si.hStdOutput = si.hStdInput;
5566 si.hStdError = si.hStdInput;
5567 }
5568
Bram Moolenaar0f873732019-12-05 20:28:46 +01005569 // Remove a trailing ", ) and )" if they have a match
5570 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005571 if (cmdbase > cmd)
5572 {
5573 p = cmdbase + STRLEN(cmdbase);
5574 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5575 *--p = NUL;
5576 if (p > cmdbase && p[-1] == ')'
5577 && (*cmd =='(' || cmd[1] == '('))
5578 *--p = NUL;
5579 }
5580
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005581 newcmd = cmdbase;
5582 unescape_shellxquote(cmdbase, p_sxe);
5583
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005584 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005585 * If creating new console, arguments are passed to the
5586 * 'cmd.exe' as-is. If it's not, arguments are not treated
5587 * correctly for current 'cmd.exe'. So unescape characters in
5588 * shellxescape except '|' for avoiding to be treated as
5589 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005590 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005591 if (flags != CREATE_NEW_CONSOLE)
5592 {
5593 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005594 char_u *cmd_shell = mch_getenv("COMSPEC");
5595
5596 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005597 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005598
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005599 subcmd = vim_strsave_escaped_ext(cmdbase,
5600 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005601 if (subcmd != NULL)
5602 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005603 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005604 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005605 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005606 if (newcmd != NULL)
5607 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005608 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005609 else
5610 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005611 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005612 }
5613 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005614
5615 /*
5616 * Now, start the command as a process, so that it doesn't
5617 * inherit our handles which causes unpleasant dangling swap
5618 * files if we exit before the spawned process
5619 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005620 if (vim_create_process((char *)newcmd, FALSE, flags,
5621 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005622 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005623 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5624 > (HINSTANCE)32)
5625 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005626 else
5627 {
5628 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005629#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005630# ifdef VIMDLL
5631 if (gui.in_use)
5632# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005633 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005634#endif
5635 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005636
5637 if (newcmd != cmdbase)
5638 vim_free(newcmd);
5639
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005640 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005641 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005642 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005643 CloseHandle(si.hStdInput);
5644 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005645 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005646 CloseHandle(pi.hThread);
5647 CloseHandle(pi.hProcess);
5648 }
5649 else
5650 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005651 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005652#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005653 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005654 (!s_dont_use_vimrun && p_stmp ?
5655 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5656 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005658 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005659
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005660 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005661 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005662 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005663#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005664 if (
5665# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005666 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005667# endif
5668 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005670 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5671 "External commands will not pause after completion.\n"
5672 "See :help win32-vimrun for more information.");
5673 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005674 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5675 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005676
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005677 if (wmsg != NULL && wtitle != NULL)
5678 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5679 vim_free(wmsg);
5680 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005681 need_vimrun_warning = FALSE;
5682 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005683 if (
5684# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005685 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005686# endif
5687 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005688 // Use vimrun to execute the command. It opens a console
5689 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005690 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691 vimrun_path,
5692 (msg_silent != 0 || (options & SHELL_DOOUT))
5693 ? "-s " : "",
5694 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005695 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005696# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005697 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005698# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005699 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005700 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005701 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5702 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005703 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005705 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005706 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005708 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005709 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710 }
5711 }
5712
5713 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005714 {
5715 // The shell may have messed with the mode, always set it.
5716 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005717 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005718 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719
Bram Moolenaar0f873732019-12-05 20:28:46 +01005720 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005722#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005723 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005724 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725#endif
5726 )
5727 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005728 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729 msg_putchar('\n');
5730 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005732
ichizok378447f2023-05-11 22:25:42 +01005733 mch_signal(SIGINT, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005734 mch_signal(SIGBREAK, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005735 mch_signal(SIGILL, SIG_DFL);
5736 mch_signal(SIGFPE, SIG_DFL);
5737 mch_signal(SIGSEGV, SIG_DFL);
5738 mch_signal(SIGTERM, SIG_DFL);
5739 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005740
5741 return x;
5742}
5743
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005744#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005745 static HANDLE
5746job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005747 char_u *fname,
5748 DWORD dwDesiredAccess,
5749 DWORD dwShareMode,
5750 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5751 DWORD dwCreationDisposition,
5752 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005753{
5754 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005755 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005756
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005757 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005758 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005759 return INVALID_HANDLE_VALUE;
5760
5761 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5762 lpSecurityAttributes, dwCreationDisposition,
5763 dwFlagsAndAttributes, NULL);
5764 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005765 return h;
5766}
5767
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005768/*
5769 * Turn the dictionary "env" into a NUL separated list that can be used as the
5770 * environment argument of vim_create_process().
5771 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005772 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005773win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005774{
5775 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005776 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005777 LPVOID base = GetEnvironmentStringsW();
5778
Bram Moolenaar0f873732019-12-05 20:28:46 +01005779 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005780 if (ga_grow(gap, 1) == FAIL)
5781 return;
5782
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005783 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005784 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005785 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005786 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005787 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005788 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005789 typval_T *item = &dict_lookup(hi)->di_tv;
5790 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005791 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005792 --todo;
5793 if (wkey != NULL && wval != NULL)
5794 {
5795 size_t n;
5796 size_t lkey = wcslen(wkey);
5797 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005798
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005799 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005800 continue;
5801 for (n = 0; n < lkey; n++)
5802 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5803 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5804 for (n = 0; n < lval; n++)
5805 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5806 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5807 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005808 vim_free(wkey);
5809 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005810 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005811 }
5812 }
5813
Bram Moolenaar355757a2020-02-10 22:06:32 +01005814 if (base)
5815 {
5816 WCHAR *p = (WCHAR*) base;
5817
5818 // for last \0
5819 if (ga_grow(gap, 1) == FAIL)
5820 return;
5821
5822 while (*p != 0 || *(p + 1) != 0)
5823 {
5824 if (ga_grow(gap, 1) == OK)
5825 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5826 p++;
5827 }
Ken Takataad29f6a2023-09-16 13:56:02 +02005828 FreeEnvironmentStringsW(base);
Bram Moolenaar355757a2020-02-10 22:06:32 +01005829 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5830 }
5831
Bram Moolenaar493359e2018-06-12 20:25:52 +02005832# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005833 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005834# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005835 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005836 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005837# endif
5838# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005839 char_u *version = get_vim_var_str(VV_VERSION);
5840 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005841# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005842 // size of "VIM_SERVERNAME=" and value,
5843 // plus "VIM_TERMINAL=" and value,
5844 // plus two terminating NULs
5845 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005846# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005847 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005848# endif
5849# ifdef FEAT_TERMINAL
5850 + 13 + version_len + 2
5851# endif
5852 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005853
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005854 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005855 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005856# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005857 for (n = 0; n < 15; n++)
5858 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5859 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005860 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005861 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5862 (WCHAR)servername[n];
5863 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005864# endif
5865# ifdef FEAT_TERMINAL
5866 if (is_terminal)
5867 {
5868 for (n = 0; n < 13; n++)
5869 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5870 (WCHAR)"VIM_TERMINAL="[n];
5871 for (n = 0; n < version_len; n++)
5872 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5873 (WCHAR)version[n];
5874 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5875 }
5876# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005877 }
5878 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005879# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005880}
5881
Bram Moolenaarb091f302019-01-19 14:37:00 +01005882/*
5883 * Create a pair of pipes.
5884 * Return TRUE for success, FALSE for failure.
5885 */
5886 static BOOL
5887create_pipe_pair(HANDLE handles[2])
5888{
5889 static LONG s;
5890 char name[64];
5891 SECURITY_ATTRIBUTES sa;
5892
5893 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5894 GetCurrentProcessId(),
5895 InterlockedIncrement(&s));
5896
5897 // Create named pipe. Max size of named pipe is 65535.
5898 handles[1] = CreateNamedPipe(
5899 name,
5900 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5901 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005902 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005903
5904 if (handles[1] == INVALID_HANDLE_VALUE)
5905 return FALSE;
5906
5907 sa.nLength = sizeof(sa);
5908 sa.bInheritHandle = TRUE;
5909 sa.lpSecurityDescriptor = NULL;
5910
5911 handles[0] = CreateFile(name,
5912 FILE_GENERIC_READ,
5913 FILE_SHARE_READ, &sa,
5914 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5915
5916 if (handles[0] == INVALID_HANDLE_VALUE)
5917 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005918 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005919 return FALSE;
5920 }
5921
5922 return TRUE;
5923}
5924
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005925 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005926mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005927{
5928 STARTUPINFO si;
5929 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005930 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005931 SECURITY_ATTRIBUTES saAttr;
5932 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005933 HANDLE ifd[2];
5934 HANDLE ofd[2];
5935 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005936 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005937
5938 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5939 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5940 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5941 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5942 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5943 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5944 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5945
5946 if (use_out_for_err && use_null_for_out)
5947 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005948
5949 ifd[0] = INVALID_HANDLE_VALUE;
5950 ifd[1] = INVALID_HANDLE_VALUE;
5951 ofd[0] = INVALID_HANDLE_VALUE;
5952 ofd[1] = INVALID_HANDLE_VALUE;
5953 efd[0] = INVALID_HANDLE_VALUE;
5954 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005955 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005956
Bram Moolenaar14207f42016-10-27 21:13:10 +02005957 jo = CreateJobObject(NULL, NULL);
5958 if (jo == NULL)
5959 {
5960 job->jv_status = JOB_FAILED;
5961 goto failed;
5962 }
5963
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005964 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005965 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005966
Bram Moolenaar76467df2016-02-12 19:30:26 +01005967 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005968 ZeroMemory(&si, sizeof(si));
5969 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005970 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005971 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005972
Bram Moolenaard8070362016-02-15 21:56:54 +01005973 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5974 saAttr.bInheritHandle = TRUE;
5975 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005976
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005977 if (use_file_for_in)
5978 {
5979 char_u *fname = options->jo_io_name[PART_IN];
5980
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005981 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5982 FILE_SHARE_READ | FILE_SHARE_WRITE,
5983 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5984 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005985 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005986 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005987 goto failed;
5988 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005989 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005990 else if (!use_null_for_in
5991 && (!create_pipe_pair(ifd)
5992 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005993 goto failed;
5994
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005995 if (use_file_for_out)
5996 {
5997 char_u *fname = options->jo_io_name[PART_OUT];
5998
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005999 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
6000 FILE_SHARE_READ | FILE_SHARE_WRITE,
6001 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6002 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006003 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006004 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006005 goto failed;
6006 }
6007 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006008 else if (!use_null_for_out &&
6009 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006010 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006011 goto failed;
6012
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006013 if (use_file_for_err)
6014 {
6015 char_u *fname = options->jo_io_name[PART_ERR];
6016
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006017 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
6018 FILE_SHARE_READ | FILE_SHARE_WRITE,
6019 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6020 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006021 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006022 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006023 goto failed;
6024 }
6025 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006026 else if (!use_out_for_err && !use_null_for_err &&
6027 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006028 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01006029 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006030
Bram Moolenaard8070362016-02-15 21:56:54 +01006031 si.dwFlags |= STARTF_USESTDHANDLES;
6032 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006033 si.hStdOutput = ofd[1];
6034 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
6035
6036 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
6037 {
Bram Moolenaarde279892016-03-11 22:19:44 +01006038 if (options->jo_set & JO_CHANNEL)
6039 {
6040 channel = options->jo_channel;
6041 if (channel != NULL)
6042 ++channel->ch_refcount;
6043 }
6044 else
6045 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006046 if (channel == NULL)
6047 goto failed;
6048 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006049
6050 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006051 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006052 CREATE_DEFAULT_ERROR_MODE |
6053 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006054 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006055 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006056 &si, &pi,
6057 ga.ga_data,
6058 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006059 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006060 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006061 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006062 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006063 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006064
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006065 ga_clear(&ga);
6066
Bram Moolenaar14207f42016-10-27 21:13:10 +02006067 if (!AssignProcessToJobObject(jo, pi.hProcess))
6068 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006069 // if failing, switch the way to terminate
6070 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006071 CloseHandle(jo);
6072 jo = NULL;
6073 }
6074 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006075 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006076 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006077 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006078 job->jv_status = JOB_STARTED;
6079
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006080 CloseHandle(ifd[0]);
6081 CloseHandle(ofd[1]);
6082 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006083 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006084
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006085 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006086 if (channel != NULL)
6087 {
6088 channel_set_pipes(channel,
6089 use_file_for_in || use_null_for_in
6090 ? INVALID_FD : (sock_T)ifd[1],
6091 use_file_for_out || use_null_for_out
6092 ? INVALID_FD : (sock_T)ofd[0],
6093 use_out_for_err || use_file_for_err || use_null_for_err
6094 ? INVALID_FD : (sock_T)efd[0]);
6095 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006096 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006097 return;
6098
6099failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006100 CloseHandle(ifd[0]);
6101 CloseHandle(ofd[0]);
6102 CloseHandle(efd[0]);
6103 CloseHandle(ifd[1]);
6104 CloseHandle(ofd[1]);
6105 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006106 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006107 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006108}
6109
6110 char *
6111mch_job_status(job_T *job)
6112{
6113 DWORD dwExitCode = 0;
6114
Bram Moolenaar76467df2016-02-12 19:30:26 +01006115 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6116 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006117 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006118 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006119 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006120 {
6121 ch_log(job->jv_channel, "Job ended");
6122 job->jv_status = JOB_ENDED;
6123 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006124 return "dead";
6125 }
6126 return "run";
6127}
6128
Bram Moolenaar97792de2016-10-15 18:36:49 +02006129 job_T *
6130mch_detect_ended_job(job_T *job_list)
6131{
6132 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6133 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6134 job_T *job = job_list;
6135
6136 while (job != NULL)
6137 {
6138 DWORD n;
6139 DWORD result;
6140
6141 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6142 && job != NULL; job = job->jv_next)
6143 {
6144 if (job->jv_status == JOB_STARTED)
6145 {
6146 jobHandles[n] = job->jv_proc_info.hProcess;
6147 jobArray[n] = job;
6148 ++n;
6149 }
6150 }
6151 if (n == 0)
6152 continue;
6153 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6154 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6155 {
6156 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6157
6158 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6159 return wait_job;
6160 }
6161 }
6162 return NULL;
6163}
6164
Bram Moolenaarfb630902016-10-29 14:55:00 +02006165 static BOOL
6166terminate_all(HANDLE process, int code)
6167{
6168 PROCESSENTRY32 pe;
6169 HANDLE h = INVALID_HANDLE_VALUE;
6170 DWORD pid = GetProcessId(process);
6171
6172 if (pid != 0)
6173 {
6174 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6175 if (h != INVALID_HANDLE_VALUE)
6176 {
6177 pe.dwSize = sizeof(PROCESSENTRY32);
6178 if (!Process32First(h, &pe))
6179 goto theend;
6180
6181 do
6182 {
6183 if (pe.th32ParentProcessID == pid)
6184 {
6185 HANDLE ph = OpenProcess(
6186 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6187 if (ph != NULL)
6188 {
6189 terminate_all(ph, code);
6190 CloseHandle(ph);
6191 }
6192 }
6193 } while (Process32Next(h, &pe));
6194
6195 CloseHandle(h);
6196 }
6197 }
6198
6199theend:
6200 return TerminateProcess(process, code);
6201}
6202
6203/*
6204 * Send a (deadly) signal to "job".
6205 * Return FAIL if it didn't work.
6206 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006207 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006208mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006209{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006210 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006211
Bram Moolenaar923d9262016-02-25 20:56:01 +01006212 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006213 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006214 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006215 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006216 {
6217 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6218 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006219 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006220 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006221 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006222 }
6223
6224 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6225 return FAIL;
6226 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006227 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6228 job->jv_proc_info.dwProcessId)
6229 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006230 FreeConsole();
6231 return ret;
6232}
6233
6234/*
6235 * Clear the data related to "job".
6236 */
6237 void
6238mch_clear_job(job_T *job)
6239{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006240 if (job->jv_status == JOB_FAILED)
6241 return;
6242
6243 if (job->jv_job_object != NULL)
6244 CloseHandle(job->jv_job_object);
6245 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006246}
6247#endif
6248
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006250#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251
6252/*
6253 * Start termcap mode
6254 */
6255 static void
6256termcap_mode_start(void)
6257{
6258 DWORD cmodein;
6259
6260 if (g_fTermcapMode)
6261 return;
6262
6263 SaveConsoleBuffer(&g_cbNonTermcap);
6264
6265 if (g_cbTermcap.IsValid)
6266 {
6267 /*
6268 * We've been in termcap mode before. Restore certain screen
6269 * characteristics, including the buffer size and the window
6270 * size. Since we will be redrawing the screen, we don't need
6271 * to restore the actual contents of the buffer.
6272 */
6273 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006274 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6276 Rows = g_cbTermcap.Info.dwSize.Y;
6277 Columns = g_cbTermcap.Info.dwSize.X;
6278 }
6279 else
6280 {
6281 /*
6282 * This is our first time entering termcap mode. Clear the console
6283 * screen buffer, and resize the buffer to match the current window
6284 * size. We will use this as the size of our editing environment.
6285 */
6286 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006287 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6289 }
6290
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006292
6293 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006295 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006296 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006297 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6298 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006300 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006302 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6303 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006305 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006306
6307 redraw_later_clear();
6308 g_fTermcapMode = TRUE;
6309}
6310
6311
6312/*
6313 * End termcap mode
6314 */
6315 static void
6316termcap_mode_end(void)
6317{
6318 DWORD cmodein;
6319 ConsoleBuffer *cb;
6320 COORD coord;
6321 DWORD dwDummy;
6322
6323 if (!g_fTermcapMode)
6324 return;
6325
6326 SaveConsoleBuffer(&g_cbTermcap);
6327
6328 GetConsoleMode(g_hConIn, &cmodein);
6329 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006330 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6331 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006333# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006334 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006335# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006337# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006338 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006339 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340
Christopher Plewright1140b512022-11-12 18:46:05 +00006341 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342 {
6343 /*
6344 * Clear anything that happens to be on the current line.
6345 */
6346 coord.X = 0;
6347 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006348 FillConsoleOutputCharacter(g_hConOut, ' ',
6349 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350 /*
6351 * The following is just for aesthetics. If we are exiting without
6352 * restoring the screen, then we want to have a prompt string
6353 * appear at the bottom line. However, the command interpreter
6354 * seems to always advance the cursor one line before displaying
6355 * the prompt string, which causes the screen to scroll. To
6356 * counter this, move the cursor up one line before exiting.
6357 */
6358 if (exiting && !p_rs)
6359 coord.Y--;
6360 /*
6361 * Position the cursor at the leftmost column of the desired row.
6362 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006363 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006365 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 g_fTermcapMode = FALSE;
6367}
Christopher Plewright38804d62022-11-09 23:55:52 +00006368#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369
6370
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006371#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372 void
6373mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006374 char_u *s UNUSED,
6375 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006377 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378}
6379
6380#else
6381
6382/*
6383 * clear `n' chars, starting from `coord'
6384 */
6385 static void
6386clear_chars(
6387 COORD coord,
6388 DWORD n)
6389{
Christopher Plewright38804d62022-11-09 23:55:52 +00006390 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006391 {
6392 DWORD dwDummy;
6393
6394 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6395 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6396 &dwDummy);
6397 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006398 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006399 {
6400 set_console_color_rgb();
6401 gotoxy(coord.X + 1, coord.Y + 1);
6402 vtp_printf("\033[%dX", n);
6403 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404}
6405
6406
6407/*
6408 * Clear the screen
6409 */
6410 static void
6411clear_screen(void)
6412{
6413 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006414
Christopher Plewright38804d62022-11-09 23:55:52 +00006415 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006416 clear_chars(g_coord, Rows * Columns);
6417 else
6418 {
6419 set_console_color_rgb();
6420 gotoxy(1, 1);
6421 vtp_printf("\033[2J");
6422 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006423}
6424
6425
6426/*
6427 * Clear to end of display
6428 */
6429 static void
6430clear_to_end_of_display(void)
6431{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006432 COORD save = g_coord;
6433
Christopher Plewright38804d62022-11-09 23:55:52 +00006434 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006435 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006436 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006437 else
6438 {
6439 set_console_color_rgb();
6440 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6441 vtp_printf("\033[0J");
6442
6443 gotoxy(save.X + 1, save.Y + 1);
6444 g_coord = save;
6445 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006446}
6447
6448
6449/*
6450 * Clear to end of line
6451 */
6452 static void
6453clear_to_end_of_line(void)
6454{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006455 COORD save = g_coord;
6456
Christopher Plewright38804d62022-11-09 23:55:52 +00006457 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006458 clear_chars(g_coord, Columns - g_coord.X);
6459 else
6460 {
6461 set_console_color_rgb();
6462 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6463 vtp_printf("\033[0K");
6464
6465 gotoxy(save.X + 1, save.Y + 1);
6466 g_coord = save;
6467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468}
6469
6470
6471/*
6472 * Scroll the scroll region up by `cLines' lines
6473 */
6474 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006475scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476{
6477 COORD oldcoord = g_coord;
6478
6479 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6480 delete_lines(cLines);
6481
6482 g_coord = oldcoord;
6483}
6484
6485
6486/*
6487 * Set the scroll region
6488 */
6489 static void
6490set_scroll_region(
6491 unsigned left,
6492 unsigned top,
6493 unsigned right,
6494 unsigned bottom)
6495{
6496 if (left >= right
6497 || top >= bottom
6498 || right > (unsigned) Columns - 1
6499 || bottom > (unsigned) Rows - 1)
6500 return;
6501
6502 g_srScrollRegion.Left = left;
6503 g_srScrollRegion.Top = top;
6504 g_srScrollRegion.Right = right;
6505 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006506}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006507
Bram Moolenaar6982f422019-02-16 16:48:01 +01006508 static void
6509set_scroll_region_tb(
6510 unsigned top,
6511 unsigned bottom)
6512{
6513 if (top >= bottom || bottom > (unsigned)Rows - 1)
6514 return;
6515
6516 g_srScrollRegion.Top = top;
6517 g_srScrollRegion.Bottom = bottom;
6518}
6519
6520 static void
6521set_scroll_region_lr(
6522 unsigned left,
6523 unsigned right)
6524{
6525 if (left >= right || right > (unsigned)Columns - 1)
6526 return;
6527
6528 g_srScrollRegion.Left = left;
6529 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530}
6531
6532
6533/*
6534 * Insert `cLines' lines at the current cursor position
6535 */
6536 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006537insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006539 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 COORD dest;
6541 CHAR_INFO fill;
6542
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006543 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6544
Bram Moolenaar6982f422019-02-16 16:48:01 +01006545 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546 dest.Y = g_coord.Y + cLines;
6547
Bram Moolenaar6982f422019-02-16 16:48:01 +01006548 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549 source.Top = g_coord.Y;
6550 source.Right = g_srScrollRegion.Right;
6551 source.Bottom = g_srScrollRegion.Bottom - cLines;
6552
Bram Moolenaar6982f422019-02-16 16:48:01 +01006553 clip.Left = g_srScrollRegion.Left;
6554 clip.Top = g_coord.Y;
6555 clip.Right = g_srScrollRegion.Right;
6556 clip.Bottom = g_srScrollRegion.Bottom;
6557
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006558 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006559 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006560 fill.Attributes = g_attrCurrent;
6561 else
6562 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006563
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006564 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006565
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006566 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6567
Bram Moolenaar6982f422019-02-16 16:48:01 +01006568 // Here we have to deal with a win32 console flake: If the scroll
6569 // region looks like abc and we scroll c to a and fill with d we get
6570 // cbd... if we scroll block c one line at a time to a, we get cdd...
6571 // vim expects cdd consistently... So we have to deal with that
6572 // here... (this also occurs scrolling the same way in the other
6573 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006574
6575 if (source.Bottom < dest.Y)
6576 {
6577 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006578 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579
Bram Moolenaar6982f422019-02-16 16:48:01 +01006580 coord.X = source.Left;
6581 for (i = clip.Top; i < dest.Y; ++i)
6582 {
6583 coord.Y = i;
6584 clear_chars(coord, source.Right - source.Left + 1);
6585 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006587
Christopher Plewright38804d62022-11-09 23:55:52 +00006588 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006589 {
6590 COORD coord;
6591 int i;
6592
6593 coord.X = source.Left;
6594 for (i = source.Top; i < dest.Y; ++i)
6595 {
6596 coord.Y = i;
6597 clear_chars(coord, source.Right - source.Left + 1);
6598 }
6599 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600}
6601
6602
6603/*
6604 * Delete `cLines' lines at the current cursor position
6605 */
6606 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006607delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006609 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006610 COORD dest;
6611 CHAR_INFO fill;
6612 int nb;
6613
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006614 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6615
Bram Moolenaar6982f422019-02-16 16:48:01 +01006616 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 dest.Y = g_coord.Y;
6618
Bram Moolenaar6982f422019-02-16 16:48:01 +01006619 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 source.Top = g_coord.Y + cLines;
6621 source.Right = g_srScrollRegion.Right;
6622 source.Bottom = g_srScrollRegion.Bottom;
6623
Bram Moolenaar6982f422019-02-16 16:48:01 +01006624 clip.Left = g_srScrollRegion.Left;
6625 clip.Top = g_coord.Y;
6626 clip.Right = g_srScrollRegion.Right;
6627 clip.Bottom = g_srScrollRegion.Bottom;
6628
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006629 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006630 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006631 fill.Attributes = g_attrCurrent;
6632 else
6633 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006635 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006636
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006637 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6638
Bram Moolenaar6982f422019-02-16 16:48:01 +01006639 // Here we have to deal with a win32 console flake; See insert_lines()
6640 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641
6642 nb = dest.Y + (source.Bottom - source.Top) + 1;
6643
6644 if (nb < source.Top)
6645 {
6646 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006647 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648
Bram Moolenaar6982f422019-02-16 16:48:01 +01006649 coord.X = source.Left;
6650 for (i = nb; i < clip.Bottom; ++i)
6651 {
6652 coord.Y = i;
6653 clear_chars(coord, source.Right - source.Left + 1);
6654 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006656
Christopher Plewright38804d62022-11-09 23:55:52 +00006657 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006658 {
6659 COORD coord;
6660 int i;
6661
6662 coord.X = source.Left;
6663 for (i = nb; i <= source.Bottom; ++i)
6664 {
6665 coord.Y = i;
6666 clear_chars(coord, source.Right - source.Left + 1);
6667 }
6668 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669}
6670
6671
6672/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006673 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674 */
6675 static void
6676gotoxy(
6677 unsigned x,
6678 unsigned y)
6679{
6680 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6681 return;
6682
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006683 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006684 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006685 // There are reports of double-width characters not displayed
6686 // correctly. This workaround should fix it, similar to how it's done
6687 // for VTP.
6688 g_coord.X = 0;
6689 SetConsoleCursorPosition(g_hConOut, g_coord);
6690
Bram Moolenaar2313b612019-09-27 14:14:32 +02006691 // external cursor coords are 1-based; internal are 0-based
6692 g_coord.X = x - 1;
6693 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006694 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006695 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006696 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006697 {
6698 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006699 // destruction. Insider build bug. Always enabled because it's cheap
6700 // and avoids mistakes with recognizing the build.
6701 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006702
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006703 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006704
6705 g_coord.X = x - 1;
6706 g_coord.Y = y - 1;
6707 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708}
6709
6710
6711/*
6712 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006713 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006714 */
6715 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006716textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006717{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006718 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719
6720 SetConsoleTextAttribute(g_hConOut, wAttr);
6721}
6722
6723
6724 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006725textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006727 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728
Christopher Plewright38804d62022-11-09 23:55:52 +00006729 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006730 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6731 else
6732 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733}
6734
6735
6736 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006737textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006739 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740
Christopher Plewright38804d62022-11-09 23:55:52 +00006741 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006742 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6743 else
6744 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745}
6746
6747
6748/*
6749 * restore the default text attribute (whatever we started with)
6750 */
6751 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006752normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753{
Christopher Plewright38804d62022-11-09 23:55:52 +00006754 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006755 textattr(g_attrDefault);
6756 else
6757 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758}
6759
6760
6761static WORD g_attrPreStandout = 0;
6762
6763/*
6764 * Make the text standout, by brightening it
6765 */
6766 static void
6767standout(void)
6768{
6769 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006770
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6772}
6773
6774
6775/*
6776 * Turn off standout mode
6777 */
6778 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006779standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780{
6781 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006783
6784 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785}
6786
6787
6788/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006789 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790 */
6791 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006792mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006793{
6794 char_u *p;
6795 int n;
6796
6797 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6798 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006799 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006800# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006801 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006802# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006803 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804 {
6805 p = T_ME + 2;
6806 n = getdigits(&p);
6807 if (*p == 'm' && n > 0)
6808 {
6809 cterm_normal_fg_color = (n & 0xf) + 1;
6810 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6811 }
6812 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006813# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006814 cterm_normal_fg_gui_color = INVALCOLOR;
6815 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006816# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817}
6818
6819
6820/*
6821 * visual bell: flash the screen
6822 */
6823 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006824visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825{
6826 COORD coordOrigin = {0, 0};
6827 WORD attrFlash = ~g_attrCurrent & 0xff;
6828
6829 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006830 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006832# ifdef FEAT_TERMGUICOLORS
6833 if (!(p_tgc || t_colors >= 256))
6834# endif
6835 {
6836 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6837 if (oldattrs == NULL)
6838 return;
6839 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006841 }
6842
Bram Moolenaar071d4272004-06-13 20:20:40 +00006843 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6844 coordOrigin, &dwDummy);
6845
Bram Moolenaar0f873732019-12-05 20:28:46 +01006846 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006847
6848 if (oldattrs != NULL)
6849 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006850 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006852 vim_free(oldattrs);
6853 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854}
6855
6856
6857/*
6858 * Make the cursor visible or invisible
6859 */
6860 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006861cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862{
6863 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006864
Christopher Plewright38804d62022-11-09 23:55:52 +00006865 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006866 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6867
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006868# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006870# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006871}
6872
6873
6874/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006875 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006876 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006878 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006880 char_u *pchBuf,
6881 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006883 COORD coord = g_coord;
6884 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006885 DWORD n, cchwritten;
6886 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006887 static WCHAR *unicodebuf = NULL;
6888 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006889 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006890 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006891 static WCHAR *utf8spbuf = NULL;
6892 static int utf8splength;
6893 static DWORD utf8spcells;
6894 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006896 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006897 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006898 utf8usingbuf = &unicodebuf;
6899 do
6900 {
6901 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6902 unicodebuf, unibuflen);
6903 if (length && length <= unibuflen)
6904 break;
6905 vim_free(unicodebuf);
6906 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6907 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006908 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006909 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006910 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006911 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6912 {
6913 if (utf8usingbuf != &utf8spbuf)
6914 {
6915 if (utf8spbuf == NULL)
6916 {
6917 cells = mb_string2cells((char_u *)" ", 1);
6918 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6919 utf8spbuf = LALLOC_MULT(WCHAR, length);
6920 if (utf8spbuf != NULL)
6921 {
6922 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6923 utf8usingbuf = &utf8spbuf;
6924 utf8splength = length;
6925 utf8spcells = cells;
6926 }
6927 }
6928 else
6929 {
6930 utf8usingbuf = &utf8spbuf;
6931 length = utf8splength;
6932 cells = utf8spcells;
6933 }
6934 }
6935 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006936
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006937 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006938 {
6939 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6940 coord, &written);
6941 // When writing fails or didn't write a single character, pretend one
6942 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006943 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006944 coord, &cchwritten) == 0
6945 || cchwritten == 0 || cchwritten == (DWORD)-1)
6946 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006947 }
6948 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006949 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006950 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006951 NULL) == 0 || cchwritten == 0)
6952 cchwritten = 1;
6953 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006954
K.Takata135e1522022-01-29 15:27:58 +00006955 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006956 {
6957 written = cbToWrite;
6958 g_coord.X += (SHORT)cells;
6959 }
6960 else
6961 {
6962 char_u *p = pchBuf;
6963 for (n = 0; n < cchwritten; n++)
6964 MB_CPTR_ADV(p);
6965 written = p - pchBuf;
6966 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006967 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968
6969 while (g_coord.X > g_srScrollRegion.Right)
6970 {
6971 g_coord.X -= (SHORT) Columns;
6972 if (g_coord.Y < g_srScrollRegion.Bottom)
6973 g_coord.Y++;
6974 }
6975
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006976 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006977 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006978 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979
6980 return written;
6981}
6982
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006983 static char_u *
6984get_seq(
6985 int *args,
6986 int *count,
6987 char_u *head)
6988{
6989 int argc;
6990 char_u *p;
6991
6992 if (head == NULL || *head != '\033')
6993 return NULL;
6994
6995 argc = 0;
6996 p = head;
6997 ++p;
6998 do
6999 {
7000 ++p;
7001 args[argc] = getdigits(&p);
7002 argc += (argc < 15) ? 1 : 0;
7003 } while (*p == ';');
7004 *count = argc;
7005
7006 return p;
7007}
7008
7009 static char_u *
7010get_sgr(
7011 int *args,
7012 int *count,
7013 char_u *head)
7014{
7015 char_u *p = get_seq(args, count, head);
7016
7017 return (p && *p == 'm') ? ++p : NULL;
7018}
7019
7020/*
7021 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
7022 */
7023 static char_u *
7024sgrn2(
7025 char_u *head,
7026 int n)
7027{
7028 int argc;
7029 int args[16];
7030 char_u *p = get_sgr(args, &argc, head);
7031
7032 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
7033}
7034
7035/*
7036 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7037 */
7038 static char_u *
7039sgrnc(
7040 char_u *head,
7041 int n)
7042{
7043 int argc;
7044 int args[16];
7045 char_u *p = get_sgr(args, &argc, head);
7046
7047 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7048 ? p : NULL;
7049}
7050
7051 static char_u *
7052skipblank(char_u *q)
7053{
7054 char_u *p = q;
7055
7056 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7057 ++p;
7058 return p;
7059}
7060
7061/*
7062 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7063 * NULL.
7064 */
7065 static char_u *
7066sgrn2c(
7067 char_u *head,
7068 int n)
7069{
7070 char_u *p = sgrn2(head, n);
7071
7072 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7073}
7074
7075/*
7076 * If there is only a newline between the sequence immediately following it,
7077 * a pointer to the character following the newline is returned.
7078 * Otherwise NULL.
7079 */
7080 static char_u *
7081sgrn2cn(
7082 char_u *head,
7083 int n)
7084{
7085 char_u *p = sgrn2(head, n);
7086
7087 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7088}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089
7090/*
7091 * mch_write(): write the output buffer to the screen, translating ESC
7092 * sequences into calls to console output routines.
7093 */
7094 void
7095mch_write(
7096 char_u *s,
7097 int len)
7098{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007099 char_u *end = s + len;
7100
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007101# ifdef VIMDLL
7102 if (gui.in_use)
7103 return;
7104# endif
7105
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106 if (!term_console)
7107 {
7108 write(1, s, (unsigned)len);
7109 return;
7110 }
7111
Bram Moolenaar0f873732019-12-05 20:28:46 +01007112 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113 while (len--)
7114 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007115 int prefix = -1;
7116 char_u ch;
7117
7118 // While processing a sequence, on rare occasions it seems that another
7119 // sequence may be inserted asynchronously.
7120 if (len < 0)
7121 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007122 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007123 return;
7124 }
7125
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007126 while (s + ++prefix < end)
7127 {
7128 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007129 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7130 && ch != '\a' && ch != '\033'))
7131 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007132 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133
7134 if (p_wd)
7135 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007136 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137 if (prefix != 0)
7138 prefix = 1;
7139 }
7140
7141 if (prefix != 0)
7142 {
7143 DWORD nWritten;
7144
7145 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007146# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147 if (fdDump)
7148 {
7149 fputc('>', fdDump);
7150 fwrite(s, sizeof(char_u), nWritten, fdDump);
7151 fputs("<\n", fdDump);
7152 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007153# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007154 len -= (nWritten - 1);
7155 s += nWritten;
7156 }
7157 else if (s[0] == '\n')
7158 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007159 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007160 if (g_coord.Y == g_srScrollRegion.Bottom)
7161 {
7162 scroll(1);
7163 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7164 }
7165 else
7166 {
7167 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7168 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007169# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170 if (fdDump)
7171 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007172# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007173 s++;
7174 }
7175 else if (s[0] == '\r')
7176 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007177 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007178 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007179# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180 if (fdDump)
7181 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007182# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007183 s++;
7184 }
7185 else if (s[0] == '\b')
7186 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007187 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007188 if (g_coord.X > g_srScrollRegion.Left)
7189 g_coord.X--;
7190 else if (g_coord.Y > g_srScrollRegion.Top)
7191 {
7192 g_coord.X = g_srScrollRegion.Right;
7193 g_coord.Y--;
7194 }
7195 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007196# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197 if (fdDump)
7198 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007199# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 s++;
7201 }
7202 else if (s[0] == '\a')
7203 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007204 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007206# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007207 if (fdDump)
7208 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007209# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007210 s++;
7211 }
7212 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7213 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007214# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007215 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007216# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007217 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007218 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007219 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007220
7221 switch (s[2])
7222 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223 case '0': case '1': case '2': case '3': case '4':
7224 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007225 if (*(p = get_seq(args, &argc, s)) != 'm')
7226 goto notsgr;
7227
7228 p = s;
7229
7230 // Handling frequent optional sequences. Output to the screen
7231 // takes too long, so do not output as much as possible.
7232
7233 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7234 // resetFG,FG,BG are omitted.
7235 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007236 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007237 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7238 len = len + 1 - (int)(p - s);
7239 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007240 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007241 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007243 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7244 // omitted.
7245 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7246 p = sp;
7247
7248 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7249 // omitted.
7250 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7251 p = sp;
7252
7253 // If BG,BG of SGR are connected, the first BG can be omitted.
7254 if (sgrn2((sp = sgrn2(p, 48)), 48))
7255 p = sp;
7256
7257 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007258 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007259 if (sgrn2((sp = sgrnc(p, 39)), 38))
7260 p = sp;
7261
7262 p = get_seq(args, &argc, p);
7263
7264notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007265 arg1 = args[0];
7266 arg2 = args[1];
7267 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007269 if (argc == 1 && args[0] == 0)
7270 normvideo();
7271 else if (argc == 1)
7272 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007273 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007274 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007275 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007276 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007277 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007278 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007279 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007281 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007282 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007283 gotoxy(arg2, arg1);
7284 }
7285 else if (argc == 2 && *p == 'r')
7286 {
7287 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7288 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007289 else if (argc == 2 && *p == 'R')
7290 {
7291 set_scroll_region_tb(arg1, arg2);
7292 }
7293 else if (argc == 2 && *p == 'V')
7294 {
7295 set_scroll_region_lr(arg1, arg2);
7296 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007297 else if (argc == 1 && *p == 'A')
7298 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 gotoxy(g_coord.X + 1,
7300 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7301 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007302 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303 {
7304 textbackground((WORD) arg1);
7305 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007306 else if (argc == 1 && *p == 'C')
7307 {
7308 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7309 g_coord.Y + 1);
7310 }
7311 else if (argc == 1 && *p == 'f')
7312 {
7313 textcolor((WORD) arg1);
7314 }
7315 else if (argc == 1 && *p == 'H')
7316 {
7317 gotoxy(1, arg1);
7318 }
7319 else if (argc == 1 && *p == 'L')
7320 {
7321 insert_lines(arg1);
7322 }
7323 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324 {
7325 delete_lines(arg1);
7326 }
7327
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007328 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329 s = p + 1;
7330 break;
7331
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007333 gotoxy(g_coord.X + 1,
7334 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7335 goto got3;
7336
7337 case 'B':
7338 visual_bell();
7339 goto got3;
7340
7341 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7343 g_coord.Y + 1);
7344 goto got3;
7345
7346 case 'E':
7347 termcap_mode_end();
7348 goto got3;
7349
7350 case 'F':
7351 standout();
7352 goto got3;
7353
7354 case 'f':
7355 standend();
7356 goto got3;
7357
7358 case 'H':
7359 gotoxy(1, 1);
7360 goto got3;
7361
7362 case 'j':
7363 clear_to_end_of_display();
7364 goto got3;
7365
7366 case 'J':
7367 clear_screen();
7368 goto got3;
7369
7370 case 'K':
7371 clear_to_end_of_line();
7372 goto got3;
7373
7374 case 'L':
7375 insert_lines(1);
7376 goto got3;
7377
7378 case 'M':
7379 delete_lines(1);
7380 goto got3;
7381
7382 case 'S':
7383 termcap_mode_start();
7384 goto got3;
7385
7386 case 'V':
7387 cursor_visible(TRUE);
7388 goto got3;
7389
7390 case 'v':
7391 cursor_visible(FALSE);
7392 goto got3;
7393
7394 got3:
7395 s += 3;
7396 len -= 2;
7397 }
7398
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007399# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007400 if (fdDump)
7401 {
7402 fputs("ESC | ", fdDump);
7403 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7404 fputc('\n', fdDump);
7405 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007406# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407 }
K.Takatadf5320c2022-09-01 13:20:16 +01007408 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7409 {
7410 int l = 2;
7411
Keith Thompson184f71c2024-01-04 21:19:04 +01007412 if (SAFE_isdigit(s[l]))
K.Takatadf5320c2022-09-01 13:20:16 +01007413 l++;
7414 if (s[l] == ' ' && s[l + 1] == 'q')
7415 {
7416 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007417 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007418 vtp_printf("%.*s", l + 2, s); // Pass through
7419 s += l + 2;
7420 len -= l + 1;
7421 }
7422 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 else
7424 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007425 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 DWORD nWritten;
7427
7428 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007429# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 if (fdDump)
7431 {
7432 fputc('>', fdDump);
7433 fwrite(s, sizeof(char_u), nWritten, fdDump);
7434 fputs("<\n", fdDump);
7435 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437
7438 len -= (nWritten - 1);
7439 s += nWritten;
7440 }
7441 }
7442
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007443# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 if (fdDump)
7445 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007446# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007447}
7448
Bram Moolenaar0f873732019-12-05 20:28:46 +01007449#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450
7451
7452/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007453 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007454 */
7455 void
7456mch_delay(
7457 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007458 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007460#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007461 Sleep((int)msec); // never wait for input
7462#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007463# ifdef VIMDLL
7464 if (gui.in_use)
7465 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007466 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007467 return;
7468 }
7469# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007470 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007471# ifdef FEAT_MZSCHEME
7472 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7473 {
7474 int towait = p_mzq;
7475
Bram Moolenaar0f873732019-12-05 20:28:46 +01007476 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007477 while (msec > 0)
7478 {
7479 mzvim_check_threads();
7480 if (msec < towait)
7481 towait = msec;
7482 Sleep(towait);
7483 msec -= towait;
7484 }
7485 }
7486 else
7487# endif
7488 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007490 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007491#endif
7492}
7493
7494
7495/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007496 * This version of remove is not scared by a readonly (backup) file.
7497 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007498 * Return 0 for success, -1 for failure.
7499 */
7500 int
7501mch_remove(char_u *name)
7502{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007503 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504 int n;
7505
Bram Moolenaar203258c2016-01-17 22:15:16 +01007506 /*
7507 * On Windows, deleting a directory's symbolic link is done by
7508 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7509 */
7510 if (mch_isdir(name) && mch_is_symbolic_link(name))
7511 return mch_rmdir(name);
7512
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007513 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7514
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007515 wn = enc_to_utf16(name, NULL);
7516 if (wn == NULL)
7517 return -1;
7518
7519 n = DeleteFileW(wn) ? 0 : -1;
7520 vim_free(wn);
7521 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007522}
7523
7524
7525/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007526 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007527 */
7528 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007529mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007531#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7532# ifdef VIMDLL
7533 if (!gui.in_use)
7534# endif
7535 if (g_fCtrlCPressed || g_fCBrkPressed)
7536 {
7537 ctrl_break_was_pressed = g_fCBrkPressed;
7538 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7539 got_int = TRUE;
7540 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007541#endif
7542}
7543
Bram Moolenaar0f873732019-12-05 20:28:46 +01007544// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007545#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007546
7547/*
7548 * How much main memory in KiB that can be used by VIM.
7549 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007550 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007551mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007552{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007553 MEMORYSTATUSEX ms;
7554
Bram Moolenaar0f873732019-12-05 20:28:46 +01007555 // Need to use GlobalMemoryStatusEx() when there is more memory than
7556 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007557 ms.dwLength = sizeof(MEMORYSTATUSEX);
7558 GlobalMemoryStatusEx(&ms);
7559 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007560 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007561 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007562 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007563 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007564 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007565 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007566 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007567 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007568 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007569 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007570 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007571}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007572
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007574 * mch_wrename() works around a bug in rename (aka MoveFile) in
Nir Lichtman563e8ec2024-09-30 19:42:28 +02007575 * Windows, the bug can be demonstrated with the following scenario:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007576 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
Nir Lichtman563e8ec2024-09-30 19:42:28 +02007577 * "abcdef~1.txt" again.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007578 *
7579 * Like rename(), returns 0 upon success, non-zero upon failure.
7580 * Should probably set errno appropriately when errors occur.
7581 */
7582 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007583mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007584{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007585 WCHAR *p;
7586 int i;
7587 WCHAR szTempFile[_MAX_PATH + 1];
7588 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007589 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007590
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007591 // No need to play tricks unless the file name contains a "~" as the
7592 // seventh character.
7593 p = wold;
7594 for (i = 0; wold[i] != NUL; ++i)
7595 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7596 && wold[i + 1] != 0)
7597 p = wold + i + 1;
7598 if ((int)(wold + i - p) < 8 || p[6] != '~')
7599 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007600
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007601 // Get base path of new file name. Undocumented feature: If pszNewFile is
7602 // a directory, no error is returned and pszFilePart will be NULL.
7603 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007604 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007605 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007606
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007607 // Get (and create) a unique temporary file name in directory of new file
7608 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609 return -2;
7610
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007611 // blow the temp file away
7612 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613 return -3;
7614
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007615 // rename old file to the temp file
7616 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007617 return -4;
7618
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007619 // now create an empty file called pszOldFile; this prevents the operating
7620 // system using pszOldFile as an alias (SFN) if we're renaming within the
7621 // same directory. For example, we're editing a file called
7622 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7623 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7624 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7625 // cause all sorts of problems later in buf_write(). So, we create an
7626 // empty file called filena~1.txt and the system will have to find some
7627 // other SFN for filena~1.txt~, such as filena~2.txt
7628 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007629 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7630 return -5;
7631 if (!CloseHandle(hf))
7632 return -6;
7633
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007634 // rename the temp file to the new file
7635 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007636 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007637 // Renaming failed. Rename the file back to its old name, so that it
7638 // looks like nothing happened.
7639 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007640 return -7;
7641 }
7642
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007643 // Seems to be left around on Novell filesystems
7644 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007645
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007646 // finally, remove the empty old file
7647 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007648 return -8;
7649
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007650 return 0;
7651}
7652
7653
7654/*
7655 * Converts the filenames to UTF-16, then call mch_wrename().
7656 * Like rename(), returns 0 upon success, non-zero upon failure.
7657 */
7658 int
7659mch_rename(
7660 const char *pszOldFile,
7661 const char *pszNewFile)
7662{
7663 WCHAR *wold = NULL;
7664 WCHAR *wnew = NULL;
7665 int retval = -1;
7666
7667 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7668 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7669 if (wold != NULL && wnew != NULL)
7670 retval = mch_wrename(wold, wnew);
7671 vim_free(wold);
7672 vim_free(wnew);
7673 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007674}
7675
7676/*
7677 * Get the default shell for the current hardware platform
7678 */
7679 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007680default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007681{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007682 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007683}
7684
7685/*
7686 * mch_access() extends access() to do more detailed check on network drives.
7687 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7688 */
7689 int
7690mch_access(char *n, int p)
7691{
7692 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007693 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007694 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007695
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007696 wn = enc_to_utf16((char_u *)n, NULL);
7697 if (wn == NULL)
7698 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007699
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007700 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007701 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007702 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007703
7704 if (p & R_OK)
7705 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007706 // Read check is performed by seeing if we can do a find file on
7707 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007708 int i;
7709 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007710
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007711 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7712 TempNameW[i] = wn[i];
7713 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7714 TempNameW[i++] = '\\';
7715 TempNameW[i++] = '*';
7716 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007717
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007718 hFile = FindFirstFileW(TempNameW, &d);
7719 if (hFile == INVALID_HANDLE_VALUE)
7720 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007721 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007722 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007723 }
7724
7725 if (p & W_OK)
7726 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007727 // Trying to create a temporary file in the directory should catch
7728 // directories on read-only network shares. However, in
7729 // directories whose ACL allows writes but denies deletes will end
7730 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007731 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7732 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007733 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007734 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007735 }
7736 }
7737 else
7738 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007739 // Don't consider a file read-only if another process has opened it.
7740 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7741
Bram Moolenaar0f873732019-12-05 20:28:46 +01007742 // Trying to open the file for the required access does ACL, read-only
7743 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007744 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7745 | ((p & R_OK) ? GENERIC_READ : 0);
7746
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007747 hFile = CreateFileW(wn, access_mode, share_mode,
7748 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007749 if (hFile == INVALID_HANDLE_VALUE)
7750 goto getout;
7751 CloseHandle(hFile);
7752 }
7753
Bram Moolenaar0f873732019-12-05 20:28:46 +01007754 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007755getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007757 return retval;
7758}
7759
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007761 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007762 */
7763 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007764mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007765{
7766 WCHAR *wn;
7767 int f;
7768
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007769 wn = enc_to_utf16((char_u *)name, NULL);
7770 if (wn == NULL)
7771 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007773 f = _wopen(wn, flags, mode);
7774 vim_free(wn);
7775 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007776}
7777
7778/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007779 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007780 */
7781 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007782mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007783{
7784 WCHAR *wn, *wm;
7785 FILE *f = NULL;
7786
Bram Moolenaara12a1612019-01-24 16:39:02 +01007787#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007788 // Work around an annoying assertion in the Microsoft debug CRT
7789 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007790 char newMode = mode[strlen(mode) - 1];
7791 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007792
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007793 _get_fmode(&oldMode);
7794 if (newMode == 't')
7795 _set_fmode(_O_TEXT);
7796 else if (newMode == 'b')
7797 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007798#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007799 wn = enc_to_utf16((char_u *)name, NULL);
7800 wm = enc_to_utf16((char_u *)mode, NULL);
7801 if (wn != NULL && wm != NULL)
7802 f = _wfopen(wn, wm);
7803 vim_free(wn);
7804 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007805
Bram Moolenaara12a1612019-01-24 16:39:02 +01007806#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007807 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007808#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007809 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007810}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811
Bram Moolenaar071d4272004-06-13 20:20:40 +00007812/*
7813 * SUB STREAM (aka info stream) handling:
7814 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007815 * NTFS can have sub streams for each file. The normal contents of a file is
7816 * stored in the main stream, and extra contents (author information, title and
7817 * so on) can be stored in a sub stream. After Windows 2000, the user can
7818 * access and store this information in sub streams via an explorer's property
7819 * menu item in the right click menu. This information in sub streams was lost
7820 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007821 *
7822 * Incomplete explanation:
7823 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7824 * More useful info and an example:
7825 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7826 */
7827
7828/*
7829 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7830 * and write to stream "substream" of file "to".
7831 * Errors are ignored.
7832 */
7833 static void
7834copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7835{
7836 HANDLE hTo;
7837 WCHAR *to_name;
7838
7839 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7840 wcscpy(to_name, to);
7841 wcscat(to_name, substream);
7842
7843 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7844 FILE_ATTRIBUTE_NORMAL, NULL);
7845 if (hTo != INVALID_HANDLE_VALUE)
7846 {
7847 long done;
7848 DWORD todo;
7849 DWORD readcnt, written;
7850 char buf[4096];
7851
Bram Moolenaar0f873732019-12-05 20:28:46 +01007852 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007853 for (done = 0; done < len; done += written)
7854 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007855 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007856 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7857 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007858 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7859 FALSE, FALSE, context)
7860 || readcnt != todo
7861 || !WriteFile(hTo, buf, todo, &written, NULL)
7862 || written != todo)
7863 break;
7864 }
7865 CloseHandle(hTo);
7866 }
7867
7868 free(to_name);
7869}
7870
7871/*
7872 * Copy info streams from file "from" to file "to".
7873 */
7874 static void
7875copy_infostreams(char_u *from, char_u *to)
7876{
7877 WCHAR *fromw;
7878 WCHAR *tow;
7879 HANDLE sh;
7880 WIN32_STREAM_ID sid;
7881 int headersize;
7882 WCHAR streamname[_MAX_PATH];
7883 DWORD readcount;
7884 void *context = NULL;
7885 DWORD lo, hi;
7886 int len;
7887
Bram Moolenaar0f873732019-12-05 20:28:46 +01007888 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007889 fromw = enc_to_utf16(from, NULL);
7890 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007891 if (fromw != NULL && tow != NULL)
7892 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007893 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007894 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7895 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7896 if (sh != INVALID_HANDLE_VALUE)
7897 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007898 // Use BackupRead() to find the info streams. Repeat until we
7899 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007900 for (;;)
7901 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007902 // Get the header to find the length of the stream name. If
7903 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007904 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007905 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007906 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7907 &readcount, FALSE, FALSE, &context)
7908 || readcount == 0)
7909 break;
7910
Bram Moolenaar0f873732019-12-05 20:28:46 +01007911 // We only deal with streams that have a name. The normal
7912 // file data appears to be without a name, even though docs
7913 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007914 if (sid.dwStreamNameSize > 0)
7915 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007916 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007917 if (!BackupRead(sh, (LPBYTE)streamname,
7918 sid.dwStreamNameSize,
7919 &readcount, FALSE, FALSE, &context))
7920 break;
7921
Bram Moolenaar0f873732019-12-05 20:28:46 +01007922 // Copy an info stream with a name ":anything:$DATA".
7923 // Skip "::$DATA", it has no stream name (examples suggest
7924 // it might be used for the normal file contents).
7925 // Note that BackupRead() counts bytes, but the name is in
7926 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007927 len = readcount / sizeof(WCHAR);
7928 streamname[len] = 0;
7929 if (len > 7 && wcsicmp(streamname + len - 6,
7930 L":$DATA") == 0)
7931 {
7932 streamname[len - 6] = 0;
7933 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007934 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007935 }
7936 }
7937
Bram Moolenaar0f873732019-12-05 20:28:46 +01007938 // Advance to the next stream. We might try seeking too far,
7939 // but BackupSeek() doesn't skip over stream borders, thus
7940 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007941 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007942 &lo, &hi, &context);
7943 }
7944
Bram Moolenaar0f873732019-12-05 20:28:46 +01007945 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007946 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7947
7948 CloseHandle(sh);
7949 }
7950 }
7951 vim_free(fromw);
7952 vim_free(tow);
7953}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007954
7955/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007956 * ntdll.dll definitions
7957 */
7958#define FileEaInformation 7
7959#ifndef STATUS_SUCCESS
7960# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7961#endif
7962
7963typedef struct _FILE_FULL_EA_INFORMATION_ {
7964 ULONG NextEntryOffset;
7965 UCHAR Flags;
7966 UCHAR EaNameLength;
7967 USHORT EaValueLength;
7968 CHAR EaName[1];
7969} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7970
7971typedef struct _FILE_EA_INFORMATION_ {
7972 ULONG EaSize;
7973} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7974
Paul Ollis65745772022-06-05 16:55:54 +01007975#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007976typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7977 PHANDLE FileHandle,
7978 ACCESS_MASK DesiredAccess,
7979 POBJECT_ATTRIBUTES ObjectAttributes,
7980 PIO_STATUS_BLOCK IoStatusBlock,
7981 ULONG ShareAccess,
7982 ULONG OpenOptions);
7983typedef NTSTATUS (NTAPI *PfnNtClose)(
7984 HANDLE Handle);
7985typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007986 HANDLE FileHandle,
7987 PIO_STATUS_BLOCK IoStatusBlock,
7988 PVOID Buffer,
7989 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007990typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7991 HANDLE FileHandle,
7992 PIO_STATUS_BLOCK IoStatusBlock,
7993 PVOID Buffer,
7994 ULONG Length,
7995 BOOLEAN ReturnSingleEntry,
7996 PVOID EaList,
7997 ULONG EaListLength,
7998 PULONG EaIndex,
7999 BOOLEAN RestartScan);
8000typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008001 HANDLE FileHandle,
8002 PIO_STATUS_BLOCK IoStatusBlock,
8003 PVOID FileInformation,
8004 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008005 FILE_INFORMATION_CLASS FileInformationClass);
8006typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
8007 PUNICODE_STRING DestinationString,
8008 PCWSTR SourceString);
8009
8010PfnNtOpenFile pNtOpenFile = NULL;
8011PfnNtClose pNtClose = NULL;
8012PfnNtSetEaFile pNtSetEaFile = NULL;
8013PfnNtQueryEaFile pNtQueryEaFile = NULL;
8014PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
8015PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01008016#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008017
8018/*
8019 * Load ntdll.dll functions.
8020 */
8021 static BOOL
8022load_ntdll(void)
8023{
8024 static int loaded = -1;
8025
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008026 if (loaded != -1)
8027 return (BOOL) loaded;
8028
8029 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8030 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008031 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008032 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8033 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8034 pNtSetEaFile = (PfnNtSetEaFile)
8035 GetProcAddress(hNtdll, "NtSetEaFile");
8036 pNtQueryEaFile = (PfnNtQueryEaFile)
8037 GetProcAddress(hNtdll, "NtQueryEaFile");
8038 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8039 GetProcAddress(hNtdll, "NtQueryInformationFile");
8040 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8041 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008042 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008043 if (pNtOpenFile == NULL
8044 || pNtClose == NULL
8045 || pNtSetEaFile == NULL
8046 || pNtQueryEaFile == NULL
8047 || pNtQueryInformationFile == NULL
8048 || pRtlInitUnicodeString == NULL)
8049 loaded = FALSE;
8050 else
8051 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008052 return (BOOL) loaded;
8053}
8054
8055/*
8056 * Copy extended attributes (EA) from file "from" to file "to".
8057 */
8058 static void
8059copy_extattr(char_u *from, char_u *to)
8060{
8061 char_u *fromf = NULL;
8062 char_u *tof = NULL;
8063 WCHAR *fromw = NULL;
8064 WCHAR *tow = NULL;
8065 UNICODE_STRING u;
8066 HANDLE h;
8067 OBJECT_ATTRIBUTES oa;
8068 IO_STATUS_BLOCK iosb;
8069 FILE_EA_INFORMATION_ eainfo = {0};
8070 void *ea = NULL;
8071
8072 if (!load_ntdll())
8073 return;
8074
8075 // Convert the file names to the fully qualified object names.
8076 fromf = alloc(STRLEN(from) + 5);
8077 tof = alloc(STRLEN(to) + 5);
8078 if (fromf == NULL || tof == NULL)
8079 goto theend;
8080 STRCPY(fromf, "\\??\\");
8081 STRCAT(fromf, from);
8082 STRCPY(tof, "\\??\\");
8083 STRCAT(tof, to);
8084
8085 // Convert the names to wide characters.
8086 fromw = enc_to_utf16(fromf, NULL);
8087 tow = enc_to_utf16(tof, NULL);
8088 if (fromw == NULL || tow == NULL)
8089 goto theend;
8090
8091 // Get the EA.
8092 pRtlInitUnicodeString(&u, fromw);
8093 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8094 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8095 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8096 goto theend;
8097 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8098 FileEaInformation);
8099 if (eainfo.EaSize != 0)
8100 {
8101 ea = alloc(eainfo.EaSize);
8102 if (ea != NULL)
8103 {
8104 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8105 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8106 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008107 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008108 }
8109 }
8110 }
8111 pNtClose(h);
8112
8113 // Set the EA.
8114 if (ea != NULL)
8115 {
8116 pRtlInitUnicodeString(&u, tow);
8117 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8118 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8119 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8120 goto theend;
8121
8122 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8123 pNtClose(h);
8124 }
8125
8126theend:
8127 vim_free(fromf);
8128 vim_free(tof);
8129 vim_free(fromw);
8130 vim_free(tow);
8131 vim_free(ea);
8132}
8133
8134/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008135 * Copy file attributes from file "from" to file "to".
8136 * For Windows NT and later we copy info streams.
8137 * Always returns zero, errors are ignored.
8138 */
8139 int
8140mch_copy_file_attribute(char_u *from, char_u *to)
8141{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008142 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008143 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008144 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008145 return 0;
8146}
8147
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008148
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008149/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008150 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008151 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008152static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008153static LPWSTR *ArglistW = NULL;
8154static int global_argc = 0;
8155static char **global_argv;
8156
Bram Moolenaar0f873732019-12-05 20:28:46 +01008157static int used_file_argc = 0; // last argument in global_argv[] used
8158 // for the argument list.
8159static int *used_file_indexes = NULL; // indexes in global_argv[] for
8160 // command line arguments added to
8161 // the argument list
8162static int used_file_count = 0; // nr of entries in used_file_indexes
8163static int used_file_literal = FALSE; // take file names literally
8164static int used_file_full_path = FALSE; // file name was full path
8165static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008166static int used_alist_count = 0;
8167
8168
8169/*
8170 * Get the command line arguments. Unicode version.
8171 * Returns argc. Zero when something fails.
8172 */
8173 int
8174get_cmd_argsW(char ***argvp)
8175{
8176 char **argv = NULL;
8177 int argc = 0;
8178 int i;
8179
Bram Moolenaar14993322014-09-09 12:25:33 +02008180 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008181 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8182 if (ArglistW != NULL)
8183 {
8184 argv = malloc((nArgsW + 1) * sizeof(char *));
8185 if (argv != NULL)
8186 {
8187 argc = nArgsW;
8188 argv[argc] = NULL;
8189 for (i = 0; i < argc; ++i)
8190 {
8191 int len;
8192
K.Takatadc73b4b2021-06-08 18:32:36 +02008193 // Convert each Unicode argument to UTF-8.
8194 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008195 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008196 (LPSTR *)&argv[i], &len, 0, 0);
8197 if (argv[i] == NULL)
8198 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008199 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008200 while (i > 0)
8201 free(argv[--i]);
8202 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008203 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008204 argc = 0;
8205 }
8206 }
8207 }
8208 }
8209
8210 global_argc = argc;
8211 global_argv = argv;
8212 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008213 {
8214 if (used_file_indexes != NULL)
8215 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008216 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008217 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008218
8219 if (argvp != NULL)
8220 *argvp = argv;
8221 return argc;
8222}
8223
8224 void
8225free_cmd_argsW(void)
8226{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008227 if (ArglistW == NULL)
8228 return;
8229
8230 GlobalFree(ArglistW);
8231 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008232}
8233
8234/*
8235 * Remember "name" is an argument that was added to the argument list.
8236 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8237 * is called.
8238 */
8239 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008240used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008241{
8242 int i;
8243
8244 if (used_file_indexes == NULL)
8245 return;
8246 for (i = used_file_argc + 1; i < global_argc; ++i)
8247 if (STRCMP(global_argv[i], name) == 0)
8248 {
8249 used_file_argc = i;
8250 used_file_indexes[used_file_count++] = i;
8251 break;
8252 }
8253 used_file_literal = literal;
8254 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008255 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008256}
8257
8258/*
8259 * Remember the length of the argument list as it was. If it changes then we
8260 * leave it alone when 'encoding' is set.
8261 */
8262 void
8263set_alist_count(void)
8264{
8265 used_alist_count = GARGCOUNT;
8266}
8267
8268/*
8269 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008270 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008271 * and convert them to 'encoding'.
8272 */
8273 void
8274fix_arg_enc(void)
8275{
8276 int i;
8277 int idx;
8278 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008279 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008280
Bram Moolenaar0f873732019-12-05 20:28:46 +01008281 // Safety checks:
8282 // - if argument count differs between the wide and non-wide argument
8283 // list, something must be wrong.
8284 // - the file name arguments must have been located.
8285 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008286 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008287 || ArglistW == NULL
8288 || used_file_indexes == NULL
8289 || used_file_count == 0
8290 || used_alist_count != GARGCOUNT)
8291 return;
8292
Bram Moolenaar0f873732019-12-05 20:28:46 +01008293 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008294 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008295 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008296 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008297 for (i = 0; i < GARGCOUNT; ++i)
8298 fnum_list[i] = GARGLIST[i].ae_fnum;
8299
Bram Moolenaar0f873732019-12-05 20:28:46 +01008300 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008301 alist_clear(&global_alist);
8302 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008303 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008304
8305 for (i = 0; i < used_file_count; ++i)
8306 {
8307 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008308 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008309 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008310 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008311 int literal = used_file_literal;
8312
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008313#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008314 // When using diff mode may need to concatenate file name to
8315 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008316 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8317 && !mch_isdir(alist_name(&GARGLIST[0])))
8318 {
8319 char_u *r;
8320
8321 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8322 if (r != NULL)
8323 {
8324 vim_free(str);
8325 str = r;
8326 }
8327 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008328#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008329 // Re-use the old buffer by renaming it. When not using literal
8330 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008331 if (used_file_literal)
8332 buf_set_name(fnum_list[i], str);
8333
Bram Moolenaar0f873732019-12-05 20:28:46 +01008334 // Check backtick literal. backtick literal is already expanded in
8335 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008336 if (literal == FALSE)
8337 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008338 size_t len = STRLEN(str);
8339
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008340 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8341 literal = TRUE;
8342 }
8343 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008344 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008345 }
8346
8347 if (!used_file_literal)
8348 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008349 // Now expand wildcards in the arguments.
8350 // Temporarily add '(' and ')' to 'isfname'. These are valid
8351 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008352 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008353 // Also, unset wildignore to not be influenced by this option.
8354 // The arguments specified in command-line should be kept even if
8355 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008356 // Use :legacy so that it also works when in Vim9 script.
8357 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8358 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008359 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008360 do_cmdline_cmd(
8361 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8362 do_cmdline_cmd(
8363 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008364 }
8365
Bram Moolenaar0f873732019-12-05 20:28:46 +01008366 // If wildcard expansion failed, we are editing the first file of the
8367 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008368 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8369 {
8370 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008371 if (GARGCOUNT == 1 && used_file_full_path
8372 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8373 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008374 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008375
8376 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008377}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008378
8379 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008380mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008381{
8382 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008383 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008384
Bram Moolenaar964b3742019-05-24 18:54:09 +02008385 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008386 if (envbuf == NULL)
8387 return -1;
8388
8389 sprintf((char *)envbuf, "%s=%s", var, value);
8390
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008391 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008392
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008393 vim_free(envbuf);
8394 if (p == NULL)
8395 return -1;
8396 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008397#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008398 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008399#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008400 // Unlike Un*x systems, we can free the string for _wputenv().
8401 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008402
8403 return 0;
8404}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008405
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008406/*
8407 * Support for 256 colors and 24-bit colors was added in Windows 10
8408 * version 1703 (Creators update).
8409 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008410#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8411
8412/*
8413 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008414 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008415 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008416#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008417
8418/*
8419 * ConPTY differences between versions, need different logic.
8420 * version 1903 (May 2019 update).
8421 */
8422#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8423
8424/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008425 * version 1909 (November 2019 update).
8426 */
8427#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8428
8429/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008430 * Stay ahead of the next update, and when it's done, fix this.
8431 * version ? (2020 update, temporarily use the build number of insider preview)
8432 */
8433#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8434
8435/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008436 * Confirm until this version. Also the logic changes.
8437 * insider preview.
8438 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008439#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008440
8441/*
8442 * Not stable now.
8443 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008444#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008445// Notes:
8446// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8447// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8448// preview which had a build 19587. And, not sure how stable that was?
8449// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8450// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008451
8452 static void
8453vtp_flag_init(void)
8454{
8455 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008456#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008457 DWORD mode;
8458 HANDLE out;
8459
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008460# ifdef VIMDLL
8461 if (!gui.in_use)
8462# endif
8463 {
8464 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008465
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008466 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8467 GetConsoleMode(out, &mode);
8468 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8469 if (SetConsoleMode(out, mode) == 0)
8470 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008471
8472 // VTP uses alternate screen buffer.
8473 // But, not if running in a nested terminal
8474 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8475 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008476 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008477#endif
8478
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008479 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008480 conpty_working = 1;
8481 if (ver >= CONPTY_STABLE_BUILD)
8482 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008483
Bram Moolenaar57da6982019-09-13 22:30:11 +02008484 if (ver <= CONPTY_INSIDER_BUILD)
8485 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008486 if (ver <= CONPTY_1909_BUILD)
8487 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008488 if (ver <= CONPTY_1903_BUILD)
8489 conpty_type = 2;
8490 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8491 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008492
8493 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8494 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008495}
8496
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008497#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008498
8499 static void
8500vtp_init(void)
8501{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008502# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008503 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8504 csbi.cbSize = sizeof(csbi);
8505 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8506 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8507 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8508 store_console_bg_rgb = save_console_bg_rgb;
8509 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008510
Christopher Plewrightd343c602023-01-22 18:58:30 +00008511 COLORREF bg;
8512 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8513 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8514 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008515
Christopher Plewrightd343c602023-01-22 18:58:30 +00008516 COLORREF fg;
8517 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8518 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8519 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008520# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008521 set_console_color_rgb();
8522}
8523
8524 static void
8525vtp_exit(void)
8526{
Bram Moolenaardf543822020-01-30 11:53:59 +01008527 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008528}
8529
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008530 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008531vtp_printf(
8532 char *format,
8533 ...)
8534{
8535 char_u buf[100];
8536 va_list list;
8537 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008538 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008539
Nir Lichtman6cd2d1d2023-11-11 11:27:41 +01008540 if (silent_mode)
8541 return 0;
8542
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008543 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008544 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008545 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008546 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008547 return (int)result;
8548}
8549
8550 static void
8551vtp_sgr_bulk(
8552 int arg)
8553{
8554 int args[1];
8555
8556 args[0] = arg;
8557 vtp_sgr_bulks(1, args);
8558}
8559
K.Takata6e1d31e2022-02-03 13:05:32 +00008560# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008561 if ((*p-- = "0123456789"[(n = x % 10)]) \
8562 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8563 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8564
K.Takata6e1d31e2022-02-03 13:05:32 +00008565# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008566 case x: \
8567 FAST256(newargs[x - 1]);
8568
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008569 static void
8570vtp_sgr_bulks(
8571 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008572 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008573{
K.Takata6e1d31e2022-02-03 13:05:32 +00008574# define MAXSGR 16
8575# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008576 char_u buf[SGRBUFSIZE];
8577 char_u *p;
8578 int in, out;
8579 int newargs[16];
8580 static int sgrfgr = -1, sgrfgg, sgrfgb;
8581 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008582
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008583 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008584 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008585 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008586 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008587 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008588 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008589
8590 in = out = 0;
8591 while (in < argc)
8592 {
8593 int s = args[in];
8594 int copylen = 1;
8595
8596 if (s == 38)
8597 {
8598 if (argc - in >= 5 && args[in + 1] == 2)
8599 {
8600 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8601 && sgrfgb == args[in + 4])
8602 {
8603 in += 5;
8604 copylen = 0;
8605 }
8606 else
8607 {
8608 sgrfgr = args[in + 2];
8609 sgrfgg = args[in + 3];
8610 sgrfgb = args[in + 4];
8611 copylen = 5;
8612 }
8613 }
8614 else if (argc - in >= 3 && args[in + 1] == 5)
8615 {
8616 sgrfgr = -1;
8617 copylen = 3;
8618 }
8619 }
8620 else if (s == 48)
8621 {
8622 if (argc - in >= 5 && args[in + 1] == 2)
8623 {
8624 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8625 && sgrbgb == args[in + 4])
8626 {
8627 in += 5;
8628 copylen = 0;
8629 }
8630 else
8631 {
8632 sgrbgr = args[in + 2];
8633 sgrbgg = args[in + 3];
8634 sgrbgb = args[in + 4];
8635 copylen = 5;
8636 }
8637 }
8638 else if (argc - in >= 3 && args[in + 1] == 5)
8639 {
8640 sgrbgr = -1;
8641 copylen = 3;
8642 }
8643 }
8644 else if (30 <= s && s <= 39)
8645 sgrfgr = -1;
8646 else if (90 <= s && s <= 97)
8647 sgrfgr = -1;
8648 else if (40 <= s && s <= 49)
8649 sgrbgr = -1;
8650 else if (100 <= s && s <= 107)
8651 sgrbgr = -1;
8652 else if (s == 0)
8653 sgrfgr = sgrbgr = -1;
8654
8655 while (copylen--)
8656 newargs[out++] = args[in++];
8657 }
8658
8659 p = &buf[sizeof(buf) - 1];
8660 *p-- = 'm';
8661
8662 switch (out)
8663 {
8664 int n, m;
8665 DWORD r;
8666
8667 FAST256CASE(16);
8668 *p-- = ';';
8669 FAST256CASE(15);
8670 *p-- = ';';
8671 FAST256CASE(14);
8672 *p-- = ';';
8673 FAST256CASE(13);
8674 *p-- = ';';
8675 FAST256CASE(12);
8676 *p-- = ';';
8677 FAST256CASE(11);
8678 *p-- = ';';
8679 FAST256CASE(10);
8680 *p-- = ';';
8681 FAST256CASE(9);
8682 *p-- = ';';
8683 FAST256CASE(8);
8684 *p-- = ';';
8685 FAST256CASE(7);
8686 *p-- = ';';
8687 FAST256CASE(6);
8688 *p-- = ';';
8689 FAST256CASE(5);
8690 *p-- = ';';
8691 FAST256CASE(4);
8692 *p-- = ';';
8693 FAST256CASE(3);
8694 *p-- = ';';
8695 FAST256CASE(2);
8696 *p-- = ';';
8697 FAST256CASE(1);
8698 *p-- = '[';
8699 *p = '\033';
8700 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8701 default:
8702 break;
8703 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008704}
8705
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008706 static void
8707wt_init(void)
8708{
Christopher Plewright1140b512022-11-12 18:46:05 +00008709 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008710}
8711
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008712# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008713 static int
8714ctermtoxterm(
8715 int cterm)
8716{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008717 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008718
8719 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8720 return (((int)r << 16) | ((int)g << 8) | (int)b);
8721}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008722# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008723
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008724 static void
8725set_console_color_rgb(void)
8726{
8727# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008728 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008729 guicolor_T fg, bg;
8730 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008731
Christopher Plewright38804d62022-11-09 23:55:52 +00008732 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008733 return;
8734
Bram Moolenaara050b942019-12-02 21:35:31 +01008735 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8736
Christopher Plewright38804d62022-11-09 23:55:52 +00008737 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008738 {
8739 term_fg_rgb_color(fg);
8740 term_bg_rgb_color(bg);
8741 return;
8742 }
8743
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008744 if (use_alternate_screen_buffer)
8745 return;
8746
Christopher Plewrightd343c602023-01-22 18:58:30 +00008747 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8748 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008749
Christopher Plewrightd343c602023-01-22 18:58:30 +00008750 csbi.cbSize = sizeof(csbi);
8751 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008752
Christopher Plewrightd343c602023-01-22 18:58:30 +00008753 csbi.cbSize = sizeof(csbi);
8754 csbi.srWindow.Right += 1;
8755 csbi.srWindow.Bottom += 1;
8756 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8757 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8758 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8759 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8760 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008761# endif
8762}
8763
Bram Moolenaara050b942019-12-02 21:35:31 +01008764# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8765 void
8766get_default_console_color(
8767 int *cterm_fg,
8768 int *cterm_bg,
8769 guicolor_T *gui_fg,
8770 guicolor_T *gui_bg)
8771{
8772 int id;
8773 guicolor_T guifg = INVALCOLOR;
8774 guicolor_T guibg = INVALCOLOR;
8775 int ctermfg = 0;
8776 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008777 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008778
8779 id = syn_name2id((char_u *)"Normal");
8780 if (id > 0 && p_tgc)
8781 syn_id2colors(id, &guifg, &guibg);
8782 if (guifg == INVALCOLOR)
8783 {
8784 ctermfg = -1;
8785 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008786 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008787 if (ctermfg != -1)
8788 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008789 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008790 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8791 cterm_normal_fg_gui_color = guifg;
8792 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008793 }
8794 if (guibg == INVALCOLOR)
8795 {
8796 ctermbg = -1;
8797 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008798 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008799 if (ctermbg != -1)
8800 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008801 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008802 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8803 cterm_normal_bg_gui_color = guibg;
8804 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008805 }
8806
8807 *cterm_fg = ctermfg;
8808 *cterm_bg = ctermbg;
8809 *gui_fg = guifg;
8810 *gui_bg = guibg;
8811}
8812# endif
8813
Bram Moolenaardf543822020-01-30 11:53:59 +01008814/*
8815 * Set the console colors to the original colors or the last set colors.
8816 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008817 static void
8818reset_console_color_rgb(void)
8819{
8820# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008821 if (use_alternate_screen_buffer)
8822 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008823
Christopher Plewright38804d62022-11-09 23:55:52 +00008824 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8825
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008826 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008827 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008828
8829 csbi.cbSize = sizeof(csbi);
8830 csbi.srWindow.Right += 1;
8831 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008832 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8833 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008834 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008835# endif
8836}
8837
8838/*
8839 * Set the console colors to the original colors.
8840 */
8841 static void
8842restore_console_color_rgb(void)
8843{
8844# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008845 if (use_alternate_screen_buffer)
8846 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008847
K.Takata27b53be2022-09-18 12:25:49 +01008848 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008849
8850 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008851 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008852
8853 csbi.cbSize = sizeof(csbi);
8854 csbi.srWindow.Right += 1;
8855 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008856 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8857 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008858 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008859# endif
8860}
8861
8862 void
8863control_console_color_rgb(void)
8864{
Christopher Plewright38804d62022-11-09 23:55:52 +00008865 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008866 set_console_color_rgb();
8867 else
8868 reset_console_color_rgb();
8869}
8870
8871 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008872use_vtp(void)
8873{
8874 return USE_VTP;
8875}
8876
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008877 int
8878is_term_win32(void)
8879{
8880 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8881}
8882
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008883 int
8884has_vtp_working(void)
8885{
8886 return vtp_working;
8887}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008888
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008889#endif
8890
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008891 int
8892has_conpty_working(void)
8893{
8894 return conpty_working;
8895}
8896
8897 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008898get_conpty_type(void)
8899{
8900 return conpty_type;
8901}
8902
8903 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008904is_conpty_stable(void)
8905{
8906 return conpty_stable;
8907}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008908
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008909 int
8910get_conpty_fix_type(void)
8911{
8912 return conpty_fix_type;
8913}
8914
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008915#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008916 void
8917resize_console_buf(void)
8918{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008919 if (use_alternate_screen_buffer)
8920 return;
8921
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008922 CONSOLE_SCREEN_BUFFER_INFO csbi;
8923 COORD coord;
8924 SMALL_RECT newsize;
8925
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008926 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8927 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008928
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008929 coord.X = SRWIDTH(csbi.srWindow);
8930 coord.Y = SRHEIGHT(csbi.srWindow);
8931 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008932
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008933 newsize.Left = 0;
8934 newsize.Top = 0;
8935 newsize.Right = coord.X - 1;
8936 newsize.Bottom = coord.Y - 1;
8937 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8938
8939 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008940}
8941#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008942
8943 char *
8944GetWin32Error(void)
8945{
K.Takatad68b2fc2022-02-12 11:18:37 +00008946 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008947 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008948
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008949 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8950 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008951 if (oldmsg != NULL)
8952 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008953 if (msg == NULL)
8954 return NULL;
8955
8956 // remove trailing \r\n
8957 char *pcrlf = strstr(msg, "\r\n");
8958 if (pcrlf != NULL)
8959 *pcrlf = '\0';
8960 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008961 return msg;
8962}
Paul Ollis65745772022-06-05 16:55:54 +01008963
8964#if defined(FEAT_RELTIME) || defined(PROTO)
8965static HANDLE timer_handle;
8966static int timer_active = FALSE;
8967
8968/*
8969 * Calls to start_timeout alternate the return value pointer between the two
8970 * entries in timeout_flags. If the previously active timeout is very close to
8971 * expiring when start_timeout() is called then a race condition means that the
8972 * set_flag() function may still be invoked after the previous timer is
8973 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8974 * timeouts.
8975 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008976static sig_atomic_t timeout_flags[2];
8977static int timeout_flag_idx = 0;
8978static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008979
8980
8981 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008982set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008983{
8984 int *timeout_flag = (int *)param;
8985
8986 *timeout_flag = TRUE;
8987}
8988
8989/*
8990 * Stop any active timeout.
8991 */
8992 void
8993stop_timeout(void)
8994{
8995 if (timer_active)
8996 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008997 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008998 timer_active = FALSE;
8999 if (!ret && GetLastError() != ERROR_IO_PENDING)
9000 {
9001 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
9002 }
9003 }
9004 *timeout_flag = FALSE;
9005}
9006
9007/*
9008 * Start the timeout timer.
9009 *
9010 * The period is defined in milliseconds.
9011 *
9012 * The return value is a pointer to a flag that is initialised to 0. If the
9013 * timeout expires, the flag is set to 1. This will only return pointers to
9014 * static memory; i.e. any pointer returned by this function may always be
9015 * safely dereferenced.
9016 *
9017 * This function is not expected to fail, but if it does it still returns a
9018 * valid flag pointer; the flag will remain stuck at zero.
9019 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009020 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01009021start_timeout(long msec)
9022{
Paul Ollis65745772022-06-05 16:55:54 +01009023 BOOL ret;
9024
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009025 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009026
9027 stop_timeout();
9028 ret = CreateTimerQueueTimer(
9029 &timer_handle, NULL, set_flag, timeout_flag,
9030 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9031 if (!ret)
9032 {
9033 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9034 }
9035 else
9036 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009037 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009038 timer_active = TRUE;
9039 *timeout_flag = FALSE;
9040 }
9041 return timeout_flag;
9042}
9043#endif