blob: bc8b2a91448dd7895cea1173edfa3d226f37f0f7 [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;
John Marriott9cb27a52025-06-08 16:05:53 +0200167static string_T vimrun_path = {(char_u *)"vimrun ", 7};
168static int vimrun_path_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169#endif
170
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200171static int win32_getattrs(char_u *name);
172static int win32_setattrs(char_u *name, int attrs);
173static int win32_set_archive(char_u *name);
174
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100175static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200176static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100177static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200178static int conpty_fix_type = 0;
John Marriott2c7ccaa2025-05-26 20:25:38 +0200179static void vtp_flag_init(void);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100180
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200181#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100182static int vtp_working = 0;
John Marriott2c7ccaa2025-05-26 20:25:38 +0200183static void vtp_init(void);
184static void vtp_exit(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100185static void vtp_sgr_bulk(int arg);
186static void vtp_sgr_bulks(int argc, int *argv);
187
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200188static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000189static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200190
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200191static int g_color_index_bg = 0;
192static int g_color_index_fg = 7;
193
194# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000195static guicolor_T save_console_bg_rgb;
196static guicolor_T save_console_fg_rgb;
197static guicolor_T store_console_bg_rgb;
198static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100199static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200200static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +0000201# define USE_VTP (vtp_working && is_term_win32() \
202 && (p_tgc || t_colors >= 256))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200203# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100204# else
205# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200206# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100207# endif
208
209static void set_console_color_rgb(void);
210static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100211static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000212#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100213
Bram Moolenaar0f873732019-12-05 20:28:46 +0100214// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100215#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
216# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
217#endif
218
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200219#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100220static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000221#endif
222
K.Takatace3189d2023-02-15 19:13:43 +0000223static WCHAR *exe_pathw = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200224
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100225static BOOL win8_or_later = FALSE;
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000226static BOOL win10_22H2_or_later = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000227#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000228static BOOL use_alternate_screen_buffer = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000229#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100230
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100231/*
232 * Get version number including build number
233 */
234typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100235#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100236 (((major) << 24) | ((minor) << 16) | (build))
237
238 static DWORD
239get_build_number(void)
240{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100241 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100242 HMODULE hNtdll;
243 PfnRtlGetVersion pRtlGetVersion;
244 DWORD ver = MAKE_VER(0, 0, 0);
245
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100246 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100247 hNtdll = GetModuleHandle("ntdll.dll");
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000248 if (hNtdll == NULL)
249 return ver;
250
251 pRtlGetVersion =
252 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
253 pRtlGetVersion(&osver);
254 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
255 min(osver.dwMinorVersion, 255),
256 min(osver.dwBuildNumber, 32767));
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100257 return ver;
258}
259
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200260#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200261 static BOOL
262is_ambiwidth_event(
263 INPUT_RECORD *ir)
264{
265 return ir->EventType == KEY_EVENT
266 && ir->Event.KeyEvent.bKeyDown
267 && ir->Event.KeyEvent.wRepeatCount == 1
268 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
269 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000270 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200271 && ir->Event.KeyEvent.dwControlKeyState == 2;
272}
273
274 static void
275make_ambiwidth_event(
276 INPUT_RECORD *down,
277 INPUT_RECORD *up)
278{
279 down->Event.KeyEvent.wVirtualKeyCode = 0;
280 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000281 down->Event.KeyEvent.uChar.UnicodeChar
282 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200283 down->Event.KeyEvent.dwControlKeyState = 0;
284}
285
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100286/*
287 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100288 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100289 */
290 static BOOL
291read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100292 HANDLE hInput,
293 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100294 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100296{
297 enum
298 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100299 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100300 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100301 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302 static DWORD s_dwIndex = 0;
303 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100304 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100305 int head;
306 int tail;
307 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200308 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100309
Christopher Plewright20b795e2022-12-20 20:01:58 +0000310 if (s_dwMax == 0 && input_record_buffer.length > 0)
311 {
312 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
313 s_dwIndex = 0;
314 s_dwMax = dwEvents;
315 }
316
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200317 if (nLength == -2)
318 return (s_dwMax > 0) ? TRUE : FALSE;
319
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100320 if (!win8_or_later)
321 {
322 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200323 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
324 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100325 }
326
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100327 if (s_dwMax == 0)
328 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000329 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200330 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200331 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
332 if (dwEvents == 0 && nLength == -1)
333 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
334 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100335 s_dwIndex = 0;
336 s_dwMax = dwEvents;
337 if (dwEvents == 0)
338 {
339 *lpEvents = 0;
340 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100341 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100342
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200343 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
344 if (is_ambiwidth_event(&s_irCache[i]))
345 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
346
Bram Moolenaardd415a62014-02-05 14:02:27 +0100347 if (s_dwMax > 1)
348 {
349 head = 0;
350 tail = s_dwMax - 1;
351 while (head != tail)
352 {
353 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
354 && s_irCache[head + 1].EventType
355 == WINDOW_BUFFER_SIZE_EVENT)
356 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100357 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100358 for (i = head; i < tail; ++i)
359 s_irCache[i] = s_irCache[i + 1];
360 --tail;
361 continue;
362 }
363 head++;
364 }
365 s_dwMax = tail + 1;
366 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100368
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200369 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
370 {
371 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
372 {
373 s_irPseudo = s_irCache[s_dwIndex];
374 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
375 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
376 *lpBuffer = s_irPseudo;
377 *lpEvents = 1;
378 return TRUE;
379 }
380 }
381
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100382 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200383 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100384 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100385 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100386 return TRUE;
387}
388
389/*
390 * Version of PeekConsoleInput() that works with IME.
391 */
392 static BOOL
393peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100394 HANDLE hInput,
395 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200396 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100397 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100398{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100399 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100400}
401
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100402# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200403 static DWORD
404msg_wait_for_multiple_objects(
405 DWORD nCount,
406 LPHANDLE pHandles,
407 BOOL fWaitAll,
408 DWORD dwMilliseconds,
409 DWORD dwWakeMask)
410{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100411 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200412 return WAIT_OBJECT_0;
413 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
414 dwMilliseconds, dwWakeMask);
415}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100416# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200417
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100418# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200419 static DWORD
420wait_for_single_object(
421 HANDLE hHandle,
422 DWORD dwMilliseconds)
423{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100424 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200425 return WAIT_OBJECT_0;
426 return WaitForSingleObject(hHandle, dwMilliseconds);
427}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100428# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000429#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200430
K.Takatace3189d2023-02-15 19:13:43 +0000431 void
432mch_get_exe_name(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100434 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
K.Takataf741e3e2023-05-15 16:41:40 +0100435 // as the maximum length that works. Add 1 for a NUL byte and 5 for
436 // "PATH=".
437#define MAX_ENV_PATH_LEN (8191 + 1 + 5)
438 WCHAR temp[MAX_ENV_PATH_LEN];
K.Takatace3189d2023-02-15 19:13:43 +0000439 WCHAR buf[MAX_PATH];
440 int updated = FALSE;
441 static int enc_prev = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442
K.Takatace3189d2023-02-15 19:13:43 +0000443 if (exe_name == NULL || exe_pathw == NULL || enc_prev != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100445 // store the name of the executable, may be used for $VIM
K.Takatace3189d2023-02-15 19:13:43 +0000446 GetModuleFileNameW(NULL, buf, MAX_PATH);
447 if (*buf != NUL)
448 {
449 if (enc_codepage == -1)
450 enc_codepage = GetACP();
K.Takataf741e3e2023-05-15 16:41:40 +0100451 vim_free(exe_name);
K.Takatace3189d2023-02-15 19:13:43 +0000452 exe_name = utf16_to_enc(buf, NULL);
453 enc_prev = enc_codepage;
454
455 WCHAR *wp = wcsrchr(buf, '\\');
456 if (wp != NULL)
457 *wp = NUL;
K.Takataf741e3e2023-05-15 16:41:40 +0100458 vim_free(exe_pathw);
K.Takatace3189d2023-02-15 19:13:43 +0000459 exe_pathw = _wcsdup(buf);
460 updated = TRUE;
461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000462 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000463
K.Takatace3189d2023-02-15 19:13:43 +0000464 if (exe_pathw == NULL || !updated)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000465 return;
466
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000467 // Append our starting directory to $PATH, so that when doing
468 // "!xxd" it's found in our starting directory. Needed because
469 // SearchPath() also looks there.
K.Takataf741e3e2023-05-15 16:41:40 +0100470 WCHAR *p = _wgetenv(L"PATH");
471 if (p == NULL || wcslen(p) + wcslen(exe_pathw) + 2 + 5 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000472 {
K.Takataf741e3e2023-05-15 16:41:40 +0100473 wcscpy(temp, L"PATH=");
474
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000475 if (p == NULL || *p == NUL)
K.Takataf741e3e2023-05-15 16:41:40 +0100476 wcscat(temp, exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000477 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 {
K.Takataf741e3e2023-05-15 16:41:40 +0100479 wcscat(temp, p);
480
481 // Check if exe_path is already included in $PATH.
482 if (wcsstr(temp, exe_pathw) == NULL)
483 {
484 // Append ';' if $PATH doesn't end with it.
485 size_t len = wcslen(temp);
486 if (temp[len - 1] != L';')
487 wcscat(temp, L";");
488
489 wcscat(temp, exe_pathw);
490 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000491 }
K.Takataf741e3e2023-05-15 16:41:40 +0100492 _wputenv(temp);
493#ifdef libintl_wputenv
494 libintl_wputenv(temp);
495#endif
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000496 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497}
498
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200499/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100500 * Unescape characters in "p" that appear in "escaped".
501 */
502 static void
503unescape_shellxquote(char_u *p, char_u *escaped)
504{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100505 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100506 int n;
507
508 while (*p != NUL)
509 {
510 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
511 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100512 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100513 p += n;
514 l -= n;
515 }
516}
517
518/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200519 * Load library "name".
520 */
521 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000522vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200523{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200524 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200525
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200526 // No need to load any library when registering OLE.
527 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000528 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200529
Bram Moolenaar0f873732019-12-05 20:28:46 +0100530 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
531 // vimLoadLib() recursively, which causes a stack overflow.
K.Takatace3189d2023-02-15 19:13:43 +0000532 if (exe_pathw == NULL)
K.Takataf741e3e2023-05-15 16:41:40 +0100533 {
K.Takatace3189d2023-02-15 19:13:43 +0000534 mch_get_exe_name();
K.Takataf741e3e2023-05-15 16:41:40 +0100535 if (exe_pathw == NULL)
536 return NULL;
537 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000538
539 WCHAR old_dirw[MAXPATHL];
540
541 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
542 return NULL;
543
544 // Change directory to where the executable is, both to make
545 // sure we find a .dll there and to avoid looking for a .dll
546 // in the current directory.
K.Takatace3189d2023-02-15 19:13:43 +0000547 SetCurrentDirectoryW(exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000548 dll = LoadLibrary(name);
549 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200550 return dll;
551}
552
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200553#if defined(VIMDLL) || defined(PROTO)
554/*
555 * Check if the current executable file is for the GUI subsystem.
556 */
557 int
558mch_is_gui_executable(void)
559{
560 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
561 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
562 PIMAGE_NT_HEADERS pPE;
563
564 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
565 return FALSE;
566 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
567 if (pPE->Signature != IMAGE_NT_SIGNATURE)
568 return FALSE;
569 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
570 return TRUE;
571 return FALSE;
572}
573#endif
574
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000575#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
576 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100577/*
578 * Get related information about 'funcname' which is imported by 'hInst'.
579 * If 'info' is 0, return the function address.
580 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000581 * If 'info' is 2, hook the function with 'ptr', and return the original
582 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100583 */
584 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000585get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
586 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100587{
588 PBYTE pImage = (PBYTE)hInst;
589 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
590 PIMAGE_NT_HEADERS pPE;
591 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100592 PIMAGE_THUNK_DATA pIAT; // Import Address Table
593 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100594 PIMAGE_IMPORT_BY_NAME pImpName;
Ken Takata119fdd92023-10-04 20:05:05 +0200595 DWORD ImpVA;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100596
597 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
598 return NULL;
599 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
600 if (pPE->Signature != IMAGE_NT_SIGNATURE)
601 return NULL;
Ken Takata119fdd92023-10-04 20:05:05 +0200602
603 ImpVA = pPE->OptionalHeader
604 .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
605 if (ImpVA == 0)
606 return NULL; // No Import Table
607 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage + ImpVA);
608
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100609 for (; pImpDesc->FirstThunk; ++pImpDesc)
610 {
611 if (!pImpDesc->OriginalFirstThunk)
612 continue;
613 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
614 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
615 for (; pIAT->u1.Function; ++pIAT, ++pINT)
616 {
617 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
618 continue;
619 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
620 + (UINT_PTR)(pINT->u1.AddressOfData));
621 if (strcmp((char *)pImpName->Name, funcname) == 0)
622 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000623 void *original;
624 DWORD old, new = PAGE_READWRITE;
625
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100626 switch (info)
627 {
628 case 0:
629 return (void *)pIAT->u1.Function;
630 case 1:
631 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000632 case 2:
633 original = (void *)pIAT->u1.Function;
634 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
635 new, &old);
636 pIAT->u1.Function = (UINT_PTR)ptr;
637 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
638 old, &new);
639 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100640 default:
641 return NULL;
642 }
643 }
644 }
645 }
646 return NULL;
647}
648
649/*
650 * Get the module handle which 'funcname' in 'hInst' is imported from.
651 */
652 HINSTANCE
653find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
654{
655 char *modulename;
656
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000657 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100658 if (modulename != NULL)
659 return GetModuleHandleA(modulename);
660 return NULL;
661}
662
663/*
664 * Get the address of 'funcname' which is imported by 'hInst' DLL.
665 */
666 void *
667get_dll_import_func(HINSTANCE hInst, const char *funcname)
668{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000669 return get_imported_func_info(hInst, funcname, 0, NULL);
670}
671
672/*
673 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
674 * and return the original function address.
675 */
676 void *
677hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
678{
679 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100680}
681#endif
682
Ken Takata119fdd92023-10-04 20:05:05 +0200683#if defined(FEAT_PYTHON3) || defined(PROTO)
684/*
685 * Check if the specified DLL is a function forwarder.
686 * If yes, return the instance of the forwarded DLL.
687 * If no, return the specified DLL.
688 * If error, return NULL.
689 * This assumes that the DLL forwards all the function to a single DLL.
690 */
691 HINSTANCE
692get_forwarded_dll(HINSTANCE hInst)
693{
694 PBYTE pImage = (PBYTE)hInst;
695 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
696 PIMAGE_NT_HEADERS pPE;
697 PIMAGE_EXPORT_DIRECTORY pExpDir;
698 DWORD ExpVA;
699 DWORD ExpSize;
700 LPDWORD pFunctionTable;
701
702 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
703 return NULL;
704 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
705 if (pPE->Signature != IMAGE_NT_SIGNATURE)
706 return NULL;
707
708 ExpVA = pPE->OptionalHeader
709 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
710 ExpSize = pPE->OptionalHeader
711 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
712 if (ExpVA == 0)
713 return hInst; // No Export Directory
714 pExpDir = (PIMAGE_EXPORT_DIRECTORY)(pImage + ExpVA);
715 pFunctionTable = (LPDWORD)(pImage + pExpDir->AddressOfFunctions);
716
717 if (pExpDir->NumberOfNames == 0)
718 return hInst; // No export names.
719
720 // Check only the first entry.
721 if ((pFunctionTable[0] < ExpVA) || (pFunctionTable[0] >= ExpVA + ExpSize))
722 // The first entry is not a function forwarder.
723 return hInst;
724
725 // The first entry is a function forwarder.
726 // The name is represented as "DllName.FunctionName".
727 const char *name = (const char *)(pImage + pFunctionTable[0]);
728 const char *p = strchr(name, '.');
729 if (p == NULL)
730 return hInst;
731
732 // Extract DllName.
733 char buf[MAX_PATH];
734 if (p - name + 1 > sizeof(buf))
735 return NULL;
736 strncpy(buf, name, p - name);
737 buf[p - name] = '\0';
738 return GetModuleHandleA(buf);
739}
740#endif
741
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
743# ifndef GETTEXT_DLL
744# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200745# define GETTEXT_DLL_ALT1 "libintl-8.dll"
746# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100748// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000749static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200750static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000751static char *null_libintl_textdomain(const char *);
752static char *null_libintl_bindtextdomain(const char *, const char *);
753static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100754static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200756static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000757char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200758char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
759 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000760char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
761char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000762 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000763char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
764 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100765int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000766
767 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100768dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769{
770 int i;
771 static struct
772 {
773 char *name;
774 FARPROC *ptr;
775 } libintl_entry[] =
776 {
777 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200778 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
780 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
781 {NULL, NULL}
782 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100783 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784
Bram Moolenaar7554c542018-10-06 15:03:15 +0200785 // No need to initialize twice.
786 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000787 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200788 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100789 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100790# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100791 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200792 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100793# endif
794# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200795 if (!hLibintlDLL)
796 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100797# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100798 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200800 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000801 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200802 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000803 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200804 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200806 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000807 }
808 for (i = 0; libintl_entry[i].name != NULL
809 && libintl_entry[i].ptr != NULL; ++i)
810 {
K.Takata54119102022-02-03 13:33:03 +0000811 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000812 libintl_entry[i].name)) == NULL)
813 {
814 dyn_libintl_end();
815 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000816 {
817 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000818 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000819 verbose_leave();
820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821 return 0;
822 }
823 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000824
Bram Moolenaar0f873732019-12-05 20:28:46 +0100825 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100826 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
827 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000828 if (dyn_libintl_bind_textdomain_codeset == NULL)
829 dyn_libintl_bind_textdomain_codeset =
830 null_libintl_bind_textdomain_codeset;
831
Bram Moolenaar0f873732019-12-05 20:28:46 +0100832 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100833 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
834 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100835 dyn_libintl_wputenv = (int (*)(const wchar_t *))
836 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100837 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
838 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100839
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840 return 1;
841}
842
843 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100844dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845{
846 if (hLibintlDLL)
847 FreeLibrary(hLibintlDLL);
848 hLibintlDLL = NULL;
849 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200850 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000851 dyn_libintl_textdomain = null_libintl_textdomain;
852 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000853 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100854 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855}
856
857 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000858null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000859{
860 return (char*)msgid;
861}
862
863 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200864null_libintl_ngettext(
865 const char *msgid,
866 const char *msgid_plural,
867 unsigned long n)
868{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200869 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200870}
871
Bram Moolenaaree695f72016-08-03 22:08:45 +0200872 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100873null_libintl_bindtextdomain(
874 const char *domainname UNUSED,
875 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876{
877 return NULL;
878}
879
880 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100881null_libintl_bind_textdomain_codeset(
882 const char *domainname UNUSED,
883 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000884{
885 return NULL;
886}
887
888 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100889null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890{
891 return NULL;
892}
893
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200894 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100895null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100896{
897 return 0;
898}
899
Bram Moolenaar0f873732019-12-05 20:28:46 +0100900#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901
Bram Moolenaar0f873732019-12-05 20:28:46 +0100902// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903
904#ifndef VER_PLATFORM_WIN32_WINDOWS
905# define VER_PLATFORM_WIN32_WINDOWS 1
906#endif
907
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100909# ifndef PROTO
910# include <aclapi.h>
911# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200912# ifndef PROTECTED_DACL_SECURITY_INFORMATION
913# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
914# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915#endif
916
Bram Moolenaar27515922013-06-29 15:36:26 +0200917#ifdef HAVE_ACL
918/*
919 * Enables or disables the specified privilege.
920 */
921 static BOOL
Nir Lichtmanb5165982024-10-13 19:44:07 +0200922win32_enable_privilege(LPTSTR lpszPrivilege)
Bram Moolenaar27515922013-06-29 15:36:26 +0200923{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100924 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;
Nir Lichtmanb5165982024-10-13 19:44:07 +0200940 tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
Bram Moolenaar27515922013-06-29 15:36:26 +0200941
Nir Lichtmanb5165982024-10-13 19:44:07 +0200942 if (!AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges, 0, NULL, NULL))
943 {
944 CloseHandle(hToken);
945 return FALSE;
946 }
947
948 if (GetLastError() != ERROR_SUCCESS)
949 {
950 CloseHandle(hToken);
951 return FALSE;
952 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200953
954 CloseHandle(hToken);
Nir Lichtmanb5165982024-10-13 19:44:07 +0200955 return TRUE;
Bram Moolenaar27515922013-06-29 15:36:26 +0200956}
957#endif
958
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100959#ifdef _MSC_VER
960// Suppress the deprecation warning for using GetVersionEx().
961// It is needed for implementing "windowsversion()".
962# pragma warning(push)
963# pragma warning(disable: 4996)
964#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200966 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967 */
968 void
969PlatformId(void)
970{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000971 OSVERSIONINFO ovi;
972
973 ovi.dwOSVersionInfoSize = sizeof(ovi);
Nir Lichtmanb5165982024-10-13 19:44:07 +0200974 if (!GetVersionEx(&ovi))
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +0200975 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200977#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000978 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
979 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200980#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000981 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
982 || ovi.dwMajorVersion > 6)
983 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100984
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000985 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
986 || ovi.dwMajorVersion > 10)
987 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000988
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000990 // Enable privilege for getting or setting SACLs.
Nir Lichtmanb5165982024-10-13 19:44:07 +0200991 if (!win32_enable_privilege(SE_SECURITY_NAME))
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +0200992 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000994}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100995#ifdef _MSC_VER
996# pragma warning(pop)
997#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200999#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001001# define SHIFT (SHIFT_PRESSED)
1002# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
1003# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
1004# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001005
1006
Bram Moolenaar0f873732019-12-05 20:28:46 +01001007// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
1008// We map function keys to their ANSI terminal equivalents, as produced
1009// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
1010// ANSI key with a value >= '\300' is nonstandard, but provided anyway
1011// so that the user can have access to all SHIFT-, CTRL-, and ALT-
1012// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013
Bram Moolenaard6f676d2005-06-01 21:51:55 +00001014static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +00001015{
1016 WORD wVirtKey;
1017 BOOL fAnsiKey;
1018 int chAlone;
1019 int chShift;
1020 int chCtrl;
1021 int chAlt;
1022} VirtKeyMap[] =
1023{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001024// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001025 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
1026
1027 { VK_F1, TRUE, ';', 'T', '^', 'h', },
1028 { VK_F2, TRUE, '<', 'U', '_', 'i', },
1029 { VK_F3, TRUE, '=', 'V', '`', 'j', },
1030 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
1031 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
1032 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
1033 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
1034 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
1035 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
1036 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001037 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
1038 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001039
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001040 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
1041 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
1042 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
1043 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
1044 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
1045 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
1046 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
1047 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
1048 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
1049 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001050 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001052 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001054# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001055 // Most people don't have F13-F20, but what the hell...
1056 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
1057 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
1058 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1059 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1060 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1061 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1062 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1063 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001064# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001065 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1066 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1067 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1068 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001070 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1071 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1072 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1073 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1074 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1075 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1076 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1077 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1078 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1079 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001080 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081};
1082
1083
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084/*
1085 * The return code indicates key code size.
1086 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001089 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001090{
1091 UINT uMods = pker->dwControlKeyState;
1092 static int s_iIsDead = 0;
1093 static WORD awAnsiCode[2];
1094 static BYTE abKeystate[256];
1095
1096
1097 if (s_iIsDead == 2)
1098 {
K.Takata972db232022-02-04 10:45:38 +00001099 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100 s_iIsDead = 0;
1101 return 1;
1102 }
1103
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001104 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001105 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 return 1;
1107
Bram Moolenaara80faa82020-04-12 19:37:17 +02001108 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109
Bram Moolenaar0f873732019-12-05 20:28:46 +01001110 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001111 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112
1113 if (uMods & SHIFT_PRESSED)
1114 abKeystate[VK_SHIFT] = 0x80;
1115 if (uMods & CAPSLOCK_ON)
1116 abKeystate[VK_CAPITAL] = 1;
1117
1118 if ((uMods & ALT_GR) == ALT_GR)
1119 {
1120 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1121 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1122 }
1123
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001124 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1125 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126
1127 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001128 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129
1130 return s_iIsDead;
1131}
1132
Bram Moolenaar071d4272004-06-13 20:20:40 +00001133static BOOL g_fJustGotFocus = FALSE;
1134
1135/*
1136 * Decode a KEY_EVENT into one or two keystrokes
1137 */
1138 static BOOL
1139decode_key_event(
1140 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001141 WCHAR *pch,
1142 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001144 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145{
1146 int i;
1147 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1148
1149 *pch = *pch2 = NUL;
1150 g_fJustGotFocus = FALSE;
1151
Bram Moolenaar0f873732019-12-05 20:28:46 +01001152 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001153 if (!pker->bKeyDown)
1154 return FALSE;
1155
Bram Moolenaar0f873732019-12-05 20:28:46 +01001156 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 switch (pker->wVirtualKeyCode)
1158 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001159 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160 case VK_SHIFT:
1161 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001162 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163 return FALSE;
1164
1165 default:
1166 break;
1167 }
1168
Bram Moolenaar0f873732019-12-05 20:28:46 +01001169 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001170 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1171 {
1172 *pch = K_NUL;
1173 *pch2 = '\017';
1174 return TRUE;
1175 }
1176
K.Takataeeec2542021-06-02 13:28:16 +02001177 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 {
1179 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1180 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001181 *pch = VirtKeyMap[i].chAlone;
1182 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183 *pch = VirtKeyMap[i].chShift;
1184 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1185 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001186 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187 *pch = VirtKeyMap[i].chAlt;
1188
1189 if (*pch != 0)
1190 {
1191 if (VirtKeyMap[i].fAnsiKey)
1192 {
1193 *pch2 = *pch;
1194 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001195 if (pmodifiers)
1196 {
1197 if (pker->wVirtualKeyCode >= VK_F1
1198 && pker->wVirtualKeyCode <= VK_F12)
1199 {
1200 if ((nModifs & ALT) != 0)
1201 {
1202 *pmodifiers |= MOD_MASK_ALT;
1203 if ((nModifs & SHIFT) == 0)
1204 *pch2 = VirtKeyMap[i].chAlone;
1205 }
1206 if ((nModifs & CTRL) != 0)
1207 {
1208 *pmodifiers |= MOD_MASK_CTRL;
1209 if ((nModifs & SHIFT) == 0)
1210 *pch2 = VirtKeyMap[i].chAlone;
1211 }
1212 }
1213 else if (pker->wVirtualKeyCode >= VK_END
1214 && pker->wVirtualKeyCode <= VK_DOWN)
1215 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001216 // (0x23 - 0x28): VK_END, VK_HOME,
1217 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1218
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001219 *pmodifiers = 0;
1220 *pch2 = VirtKeyMap[i].chAlone;
1221 if ((nModifs & SHIFT) != 0
1222 && (nModifs & ~SHIFT) == 0)
1223 {
1224 *pch2 = VirtKeyMap[i].chShift;
1225 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001226 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001227 && (nModifs & ~CTRL) == 0)
1228 {
1229 *pch2 = VirtKeyMap[i].chCtrl;
1230 if (pker->wVirtualKeyCode == VK_UP
1231 || pker->wVirtualKeyCode == VK_DOWN)
1232 {
1233 *pmodifiers |= MOD_MASK_CTRL;
1234 *pch2 = VirtKeyMap[i].chAlone;
1235 }
1236 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001237 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001238 && (nModifs & CTRL) != 0)
1239 {
1240 *pmodifiers |= MOD_MASK_CTRL;
1241 *pch2 = VirtKeyMap[i].chShift;
1242 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001243 if ((nModifs & ALT) != 0)
1244 {
1245 *pch2 = VirtKeyMap[i].chAlt;
1246 *pmodifiers |= MOD_MASK_ALT;
1247 if ((nModifs & ~ALT) == 0)
1248 {
1249 *pch2 = VirtKeyMap[i].chAlone;
1250 }
1251 else if ((nModifs & SHIFT) != 0)
1252 {
1253 *pch2 = VirtKeyMap[i].chShift;
1254 }
1255 else if ((nModifs & CTRL) != 0)
1256 {
1257 if (pker->wVirtualKeyCode == VK_UP
1258 || pker->wVirtualKeyCode == VK_DOWN)
1259 {
1260 *pmodifiers |= MOD_MASK_CTRL;
1261 *pch2 = VirtKeyMap[i].chAlone;
1262 }
1263 else
1264 {
1265 *pch2 = VirtKeyMap[i].chCtrl;
1266 }
1267 }
1268 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001269 }
Christopher Plewrightf5f69e82024-08-04 19:57:44 +02001270 else if (pker->wVirtualKeyCode == VK_INSERT
1271 && (nModifs & SHIFT) != 0
1272 && (nModifs & ~SHIFT) == 0)
1273 {
1274 *pmodifiers = 0;
1275 *pch2 = VirtKeyMap[i].chShift;
1276 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001277 else
1278 {
1279 *pch2 = VirtKeyMap[i].chAlone;
1280 if ((nModifs & SHIFT) != 0)
1281 *pmodifiers |= MOD_MASK_SHIFT;
1282 if ((nModifs & CTRL) != 0)
1283 *pmodifiers |= MOD_MASK_CTRL;
1284 if ((nModifs & ALT) != 0)
1285 *pmodifiers |= MOD_MASK_ALT;
1286 }
1287 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001288 }
1289
1290 return TRUE;
1291 }
1292 }
1293 }
1294
1295 i = win32_kbd_patch_key(pker);
1296
1297 if (i < 0)
1298 *pch = NUL;
1299 else
1300 {
K.Takata972db232022-02-04 10:45:38 +00001301 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001302
1303 if (pmodifiers != NULL)
1304 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001305 // Pass on the ALT key as a modifier, but only when not combined
1306 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001307 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1308 *pmodifiers |= MOD_MASK_ALT;
1309
Bram Moolenaar0f873732019-12-05 20:28:46 +01001310 // Pass on SHIFT only for special keys, because we don't know when
1311 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001312 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1313 *pmodifiers |= MOD_MASK_SHIFT;
1314
Bram Moolenaar0f873732019-12-05 20:28:46 +01001315 // Pass on CTRL only for non-special keys, because we don't know
1316 // when it's already included with the character. And not when
1317 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1319 && *pch >= 0x20 && *pch < 0x80)
1320 *pmodifiers |= MOD_MASK_CTRL;
1321 }
1322 }
1323
1324 return (*pch != NUL);
1325}
1326
Christopher Plewright20b795e2022-12-20 20:01:58 +00001327# if defined(FEAT_EVAL)
1328 static int
1329encode_key_event(dict_T *args, INPUT_RECORD *ir)
1330{
1331 static int s_dwMods = 0;
1332
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001333 char_u *action = dict_get_string(args, "event", TRUE);
1334 if (action && (STRICMP(action, "keydown") == 0
1335 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001336 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001337 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001338 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1339 if (vkCode <= 0 || vkCode >= 0xFF)
1340 {
1341 semsg(_(e_invalid_argument_nr), (long)vkCode);
1342 return FALSE;
1343 }
1344
1345 ir->EventType = KEY_EVENT;
1346 KEY_EVENT_RECORD ker;
1347 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001348 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001349 ker.wRepeatCount = 1;
1350 ker.wVirtualScanCode = 0;
1351 ker.dwControlKeyState = 0;
1352 int mods = (int)dict_get_number(args, "modifiers");
1353 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1354 if (mods)
1355 {
1356 // If "modifiers" is explicitly set in the args, then we reset any
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00001357 // remembered modifier key state that may have been set from
1358 // earlier mod-key-down events, even if they are not yet unset by
1359 // earlier mod-key-up events.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001360 s_dwMods = 0;
1361 if (mods & MOD_MASK_SHIFT)
1362 ker.dwControlKeyState |= SHIFT_PRESSED;
1363 if (mods & MOD_MASK_CTRL)
1364 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1365 if (mods & MOD_MASK_ALT)
1366 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1367 }
1368
1369 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1370 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001371 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001372 s_dwMods |= SHIFT_PRESSED;
1373 else
1374 s_dwMods &= ~SHIFT_PRESSED;
1375 }
1376 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1377 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001378 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001379 s_dwMods |= LEFT_CTRL_PRESSED;
1380 else
1381 s_dwMods &= ~LEFT_CTRL_PRESSED;
1382 }
1383 else if (vkCode == VK_RCONTROL)
1384 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001385 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001386 s_dwMods |= RIGHT_CTRL_PRESSED;
1387 else
1388 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1389 }
1390 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1391 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001392 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001393 s_dwMods |= LEFT_ALT_PRESSED;
1394 else
1395 s_dwMods &= ~LEFT_ALT_PRESSED;
1396 }
1397 else if (vkCode == VK_RMENU)
1398 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001399 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001400 s_dwMods |= RIGHT_ALT_PRESSED;
1401 else
1402 s_dwMods &= ~RIGHT_ALT_PRESSED;
1403 }
1404 ker.dwControlKeyState |= s_dwMods;
1405 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001406 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001407 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001408 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001409 }
1410 else
1411 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001412 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001413 {
1414 semsg(_(e_missing_argument_str), "event");
1415 }
1416 else
1417 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001418 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1419 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001420 }
1421 return FALSE;
1422 }
1423 return TRUE;
1424}
1425# endif // FEAT_EVAL
1426#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427
1428
Bram Moolenaar071d4272004-06-13 20:20:40 +00001429/*
1430 * For the GUI the mouse handling is in gui_w32.c.
1431 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001432#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001434mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435{
1436}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001437#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001438static int g_fMouseAvail = FALSE; // mouse present
1439static int g_fMouseActive = FALSE; // mouse enabled
1440static int g_nMouseClick = -1; // mouse status
1441static int g_xMouse; // mouse x coordinate
1442static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001443static DWORD g_cmodein = 0; // Original console input mode
1444static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001445
1446/*
1447 * Enable or disable mouse input
1448 */
1449 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001450mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451{
1452 DWORD cmodein;
1453
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001454# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001455 if (gui.in_use)
1456 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458 if (!g_fMouseAvail)
1459 return;
1460
1461 g_fMouseActive = on;
1462 GetConsoleMode(g_hConIn, &cmodein);
1463
1464 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001465 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001467 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001470 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001472 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1473 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001475 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001476}
1477
Bram Moolenaar157d8132018-03-06 17:09:20 +01001478
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001479# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001480/*
1481 * Called when 'balloonevalterm' changed.
1482 */
1483 void
1484mch_bevalterm_changed(void)
1485{
1486 mch_setmouse(g_fMouseActive);
1487}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001488# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001489
Christopher Plewright2a46f812022-10-16 19:47:45 +01001490/*
1491 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001492 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001493 *
1494 * This encodes the mouse scroll direction and keyboard modifiers into
1495 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1496 *
1497 * The direction of the scroll is decoded from two fields of the win32 console
1498 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001499 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001500 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1501 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001502 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001503 * - If the high word of the dwButtonState member contains a positive
1504 * value, the wheel was rotated to the right.
1505 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001506 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001507 * - If the high word of the dwButtonState member contains a positive value,
1508 * the wheel was rotated forward, away from the user.
1509 * - Otherwise, the wheel was rotated backward, toward the user.
1510 */
1511 static void
1512decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1513{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001514 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1515 int zDelta = pmer->dwButtonState;
1516
1517 g_xMouse = pmer->dwMousePosition.X;
1518 g_yMouse = pmer->dwMousePosition.Y;
1519
K.Takata161b6ac2022-11-14 15:31:07 +00001520# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001521 int lcol = g_xMouse;
1522 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001523 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001524 if (wp != NULL && popup_is_popup(wp))
1525 {
1526 g_nMouseClick = -1;
1527 cmdarg_T cap;
1528 oparg_T oa;
1529 CLEAR_FIELD(cap);
1530 clear_oparg(&oa);
1531 cap.oap = &oa;
1532 if (horizontal)
1533 {
1534 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1535 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1536 }
1537 else
1538 {
1539 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1540 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1541 }
1542
1543 // Mouse hovers over popup window, scroll it if possible.
1544 mouse_row = wp->w_winrow;
1545 mouse_col = wp->w_wincol;
1546 nv_mousescroll(&cap);
1547 update_screen(0);
1548 setcursor();
1549 out_flush();
1550 return;
1551 }
K.Takata161b6ac2022-11-14 15:31:07 +00001552# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001553 mouse_col = g_xMouse;
1554 mouse_row = g_yMouse;
1555
1556 char_u modifiers = 0;
1557 char_u direction = 0;
1558
1559 // Decode the direction into an event that Vim can process
1560 if (horizontal)
1561 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1562 else
1563 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1564
dundargocc57b5bc2022-11-02 13:30:51 +00001565 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001566 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001567 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001568 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001569 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001570 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1571 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1572
1573 // add (bitwise or) the scroll direction and the key modifier chars
1574 // together.
1575 g_nMouseClick = ((direction << 8) | modifiers);
1576
1577 return;
1578}
1579
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580/*
1581 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1582 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1583 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1584 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1585 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1586 * and we return the mouse position in g_xMouse and g_yMouse.
1587 *
1588 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1589 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1590 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1591 *
1592 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1593 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1594 *
1595 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1596 * moves, even if it stays within the same character cell. We ignore
1597 * all MOUSE_MOVED messages if the position hasn't really changed, and
1598 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1599 * we're only interested in MOUSE_DRAG).
1600 *
1601 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1602 * 2-button mouses by pressing the left & right buttons simultaneously.
1603 * In practice, it's almost impossible to click both at the same time,
1604 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1605 * in such cases, if the user is clicking quickly.
1606 */
1607 static BOOL
1608decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001609 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610{
1611 static int s_nOldButton = -1;
1612 static int s_nOldMouseClick = -1;
1613 static int s_xOldMouse = -1;
1614 static int s_yOldMouse = -1;
1615 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001616# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001618# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001619 static int s_cClicks = 1;
1620 static BOOL s_fReleased = TRUE;
1621 static DWORD s_dwLastClickTime = 0;
1622 static BOOL s_fNextIsMiddle = FALSE;
1623
Bram Moolenaar0f873732019-12-05 20:28:46 +01001624 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625
1626 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1627 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1628 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1629 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1630
1631 int nButton;
1632
1633 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1634 cButtons = 2;
1635
1636 if (!g_fMouseAvail || !g_fMouseActive)
1637 {
1638 g_nMouseClick = -1;
1639 return FALSE;
1640 }
1641
Bram Moolenaar0f873732019-12-05 20:28:46 +01001642 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643 if (g_fJustGotFocus)
1644 {
1645 g_fJustGotFocus = FALSE;
1646 return FALSE;
1647 }
1648
Christopher Plewright605d02a2022-10-19 11:54:46 +01001649 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650 if (g_nMouseClick != -1)
1651 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001652
Christopher Plewright2a46f812022-10-16 19:47:45 +01001653 if (pmer->dwEventFlags == MOUSE_WHEELED
1654 || pmer->dwEventFlags == MOUSE_HWHEELED)
1655 {
1656 decode_mouse_wheel(pmer);
1657 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1658 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001659
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660 nButton = -1;
1661 g_xMouse = pmer->dwMousePosition.X;
1662 g_yMouse = pmer->dwMousePosition.Y;
1663
1664 if (pmer->dwEventFlags == MOUSE_MOVED)
1665 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001666 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1667 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1669 return FALSE;
1670 }
1671
Bram Moolenaar0f873732019-12-05 20:28:46 +01001672 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1674 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001675 nButton = MOUSE_RELEASE;
1676
Bram Moolenaar0f873732019-12-05 20:28:46 +01001677 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001679 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001680# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001681 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001682 if (p_bevalterm)
1683 nButton = MOUSE_DRAG;
1684 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001685# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001686 return FALSE;
1687 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 s_fReleased = TRUE;
1690 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001691 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001693 // on a 2-button mouse, hold down left and right buttons
1694 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695
1696 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1697 {
1698 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1699
Bram Moolenaar0f873732019-12-05 20:28:46 +01001700 // if either left or right button only is pressed, see if the
1701 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702 if (dwLR == LEFT || dwLR == RIGHT)
1703 {
1704 for (;;)
1705 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001706 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001707 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1708 != WAIT_OBJECT_0)
1709 break;
1710 else
1711 {
1712 DWORD cRecords = 0;
1713 INPUT_RECORD ir;
1714 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1715
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001716 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717
1718 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1719 || !(pmer2->dwButtonState & LEFT_RIGHT))
1720 break;
1721 else
1722 {
1723 if (pmer2->dwEventFlags != MOUSE_MOVED)
1724 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001725 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726
1727 return decode_mouse_event(pmer2);
1728 }
1729 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1730 s_yOldMouse == pmer2->dwMousePosition.Y)
1731 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001732 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001733 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734
Bram Moolenaar0f873732019-12-05 20:28:46 +01001735 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001736 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001737
1738 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1739 break;
1740 }
1741 else
1742 break;
1743 }
1744 }
1745 }
1746 }
1747 }
1748
1749 if (s_fNextIsMiddle)
1750 {
1751 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1752 ? MOUSE_DRAG : MOUSE_MIDDLE;
1753 s_fNextIsMiddle = FALSE;
1754 }
1755 else if (cButtons == 2 &&
1756 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1757 {
1758 nButton = MOUSE_MIDDLE;
1759
1760 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1761 {
1762 s_fNextIsMiddle = TRUE;
1763 nButton = MOUSE_RELEASE;
1764 }
1765 }
1766 else if ((pmer->dwButtonState & LEFT) == LEFT)
1767 nButton = MOUSE_LEFT;
1768 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1769 nButton = MOUSE_MIDDLE;
1770 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1771 nButton = MOUSE_RIGHT;
1772
1773 if (! s_fReleased && ! s_fNextIsMiddle
1774 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1775 return FALSE;
1776
1777 s_fReleased = s_fNextIsMiddle;
1778 }
1779
1780 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1781 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001782 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783 if (nButton != -1 && nButton != MOUSE_RELEASE)
1784 {
1785 DWORD dwCurrentTime = GetTickCount();
1786
1787 if (s_xOldMouse != g_xMouse
1788 || s_yOldMouse != g_yMouse
1789 || s_nOldButton != nButton
1790 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001791# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001793# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1795 {
1796 s_cClicks = 1;
1797 }
1798 else if (++s_cClicks > 4)
1799 {
1800 s_cClicks = 1;
1801 }
1802
1803 s_dwLastClickTime = dwCurrentTime;
1804 }
1805 }
1806 else if (pmer->dwEventFlags == MOUSE_MOVED)
1807 {
1808 if (nButton != -1 && nButton != MOUSE_RELEASE)
1809 nButton = MOUSE_DRAG;
1810
1811 s_cClicks = 1;
1812 }
1813
1814 if (nButton == -1)
1815 return FALSE;
1816
1817 if (nButton != MOUSE_RELEASE)
1818 s_nOldButton = nButton;
1819
1820 g_nMouseClick = nButton;
1821
1822 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1823 g_nMouseClick |= MOUSE_SHIFT;
1824 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1825 g_nMouseClick |= MOUSE_CTRL;
1826 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1827 g_nMouseClick |= MOUSE_ALT;
1828
1829 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1830 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1831
Bram Moolenaar0f873732019-12-05 20:28:46 +01001832 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 if (s_xOldMouse == g_xMouse
1834 && s_yOldMouse == g_yMouse
1835 && s_nOldMouseClick == g_nMouseClick)
1836 {
1837 g_nMouseClick = -1;
1838 return FALSE;
1839 }
1840
1841 s_xOldMouse = g_xMouse;
1842 s_yOldMouse = g_yMouse;
1843 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001844# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001845 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001846# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 s_nOldMouseClick = g_nMouseClick;
1848
1849 return TRUE;
1850}
1851
Christopher Plewright20b795e2022-12-20 20:01:58 +00001852# ifdef FEAT_EVAL
1853 static int
1854encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1855{
1856 int button;
1857 int row;
1858 int col;
1859 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001860 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001861 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862
Christopher Plewright20b795e2022-12-20 20:01:58 +00001863 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1864 return FALSE;
1865
1866 // Note: "move" is optional, requires fewer arguments
1867 move = (int)dict_get_bool(args, "move", FALSE);
1868 if (!move && (!dict_has_key(args, "button")
1869 || !dict_has_key(args, "multiclick")
1870 || !dict_has_key(args, "modifiers")))
1871 return FALSE;
1872
1873 row = (int)dict_get_number(args, "row") - 1;
1874 col = (int)dict_get_number(args, "col") - 1;
1875
1876 ir->EventType = MOUSE_EVENT;
1877 MOUSE_EVENT_RECORD mer;
1878 ZeroMemory(&mer, sizeof(mer));
1879 mer.dwMousePosition.X = col;
1880 mer.dwMousePosition.Y = row;
1881
1882 if (move)
1883 {
1884 mer.dwButtonState = 0;
1885 mer.dwEventFlags = MOUSE_MOVED;
1886 }
1887 else
1888 {
1889 button = (int)dict_get_number(args, "button");
1890 repeated_click = (int)dict_get_number(args, "multiclick");
1891 mods = (int)dict_get_number(args, "modifiers");
1892 // Reset the scroll values to known values.
1893 // XXX: Remove this when/if the scroll step is made configurable.
1894 mouse_set_hor_scroll_step(6);
1895 mouse_set_vert_scroll_step(3);
1896
1897 switch (button)
1898 {
1899 case MOUSE_LEFT:
1900 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1901 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1902 break;
1903 case MOUSE_MIDDLE:
1904 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1905 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1906 break;
1907 case MOUSE_RIGHT:
1908 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1909 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1910 break;
1911 case MOUSE_RELEASE:
1912 // umm? Assume Left Release?
1913 mer.dwEventFlags = 0;
1914
1915 case MOUSE_MOVE:
1916 mer.dwButtonState = 0;
1917 mer.dwEventFlags = MOUSE_MOVED;
1918 break;
1919 case MOUSE_X1:
1920 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1921 break;
1922 case MOUSE_X2:
1923 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1924 break;
1925 case MOUSE_4: // KE_MOUSEDOWN;
1926 mer.dwButtonState = -1;
1927 mer.dwEventFlags = MOUSE_WHEELED;
1928 break;
1929 case MOUSE_5: // KE_MOUSEUP;
1930 mer.dwButtonState = +1;
1931 mer.dwEventFlags = MOUSE_WHEELED;
1932 break;
1933 case MOUSE_6: // KE_MOUSELEFT;
1934 mer.dwButtonState = -1;
1935 mer.dwEventFlags = MOUSE_HWHEELED;
1936 break;
1937 case MOUSE_7: // KE_MOUSERIGHT;
1938 mer.dwButtonState = +1;
1939 mer.dwEventFlags = MOUSE_HWHEELED;
1940 break;
1941 default:
1942 semsg(_(e_invalid_argument_str), "button");
1943 return FALSE;
1944 }
1945 }
1946
1947 mer.dwControlKeyState = 0;
1948 if (mods != 0)
1949 {
1950 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1951 if (mods & MOUSE_SHIFT)
1952 mer.dwControlKeyState |= SHIFT_PRESSED;
1953 if (mods & MOUSE_CTRL)
1954 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1955 if (mods & MOUSE_ALT)
1956 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1957 }
1958 ir->Event.MouseEvent = mer;
1959 return TRUE;
1960}
1961# endif // FEAT_EVAL
1962
1963 static int
1964write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1965{
John Marriott738df382025-06-05 20:49:39 +02001966 int nCount = 0;
1967 input_record_buffer_node_T *event_node;
1968
Christopher Plewright20b795e2022-12-20 20:01:58 +00001969 while (nCount < nLength)
1970 {
John Marriott738df382025-06-05 20:49:39 +02001971 event_node = alloc(sizeof(input_record_buffer_node_T));
1972 if (event_node == NULL)
1973 return -1;
1974
Christopher Plewright20b795e2022-12-20 20:01:58 +00001975 event_node->ir = irEvents[nCount++];
1976 event_node->next = NULL;
John Marriott738df382025-06-05 20:49:39 +02001977
1978 input_record_buffer.length++;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001979 if (input_record_buffer.tail == NULL)
1980 {
1981 input_record_buffer.head = event_node;
1982 input_record_buffer.tail = event_node;
1983 }
1984 else
1985 {
1986 input_record_buffer.tail->next = event_node;
1987 input_record_buffer.tail = input_record_buffer.tail->next;
1988 }
1989 }
1990 return nCount;
1991}
1992
1993 static int
1994read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1995{
1996 int nCount = 0;
1997 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1998 {
1999 input_record_buffer.length--;
2000 input_record_buffer_node_T *pop_head = input_record_buffer.head;
2001 irEvents[nCount++] = pop_head->ir;
2002 input_record_buffer.head = pop_head->next;
2003 vim_free(pop_head);
2004 if (input_record_buffer.length == 0)
2005 input_record_buffer.tail = NULL;
2006 }
2007 return nCount;
2008}
Christopher Plewright20b795e2022-12-20 20:01:58 +00002009#endif // !FEAT_GUI_MSWIN || VIMDLL
2010
2011#ifdef FEAT_EVAL
2012/*
2013 * The 'test_mswin_event' function is for testing Vim's low-level handling of
2014 * user input events. ie, this manages the encoding of INPUT_RECORD events
2015 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
2016 * consoles.
2017 *
2018 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
2019 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
2020 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
2021 *
2022 * When the Windows console is running, the arguments; 'event' and 'args', are
2023 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
2024 * events are encoded as INPUT_RECORD events.
2025 *
2026 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
2027 * GUI sends MSG structs instead.
2028 */
2029 int
2030test_mswin_event(char_u *event, dict_T *args)
2031{
2032 int lpEventsWritten = 0;
2033
2034# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
2035 if (gui.in_use)
2036 return test_gui_w32_sendevent(event, args);
2037# endif
2038
2039# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
2040
2041// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
2042// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
2043// Maybe also: MENU_EVENT
2044
2045 INPUT_RECORD ir;
2046 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002047 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002048 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002049 {
2050 execute = dict_get_bool(args, "execute", FALSE);
2051 if (dict_has_key(args, "event"))
2052 input_encoded = encode_key_event(args, &ir);
2053 else if (!execute)
2054 {
2055 semsg(_(e_missing_argument_str), "event");
2056 return FALSE;
2057 }
2058 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002059 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002060 {
2061 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002062 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002063 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002064 else
2065 {
2066 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
2067 return FALSE;
2068 }
2069
2070 // Ideally, WriteConsoleInput would be used to inject these low-level
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002071 // events. But, this doesn't work well in the CI test environment. So
Christopher Plewright20b795e2022-12-20 20:01:58 +00002072 // implementing an input_record_buffer instead.
2073 if (input_encoded)
John Marriott738df382025-06-05 20:49:39 +02002074 {
2075 if ((lpEventsWritten = write_input_record_buffer(&ir, 1)) < 0)
2076 {
2077 semsg(_(e_out_of_memory), "event");
2078 return FALSE;
2079 }
2080 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002081
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002082 // Set flags to execute the event, ie. like feedkeys mode X.
2083 if (execute)
2084 {
2085 int save_msg_scroll = msg_scroll;
2086 // Avoid a 1 second delay when the keys start Insert mode.
2087 msg_scroll = FALSE;
2088 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002089 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002090 msg_scroll |= save_msg_scroll;
2091 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002092
2093# endif
2094 return lpEventsWritten;
2095}
2096#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097
2098#ifdef MCH_CURSOR_SHAPE
2099/*
2100 * Set the shape of the cursor.
2101 * 'thickness' can be from 1 (thin) to 99 (block)
2102 */
2103 static void
2104mch_set_cursor_shape(int thickness)
2105{
Christopher Plewright38804d62022-11-09 23:55:52 +00002106 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002107 {
2108 if (*T_CSI == NUL)
2109 {
2110 // If 't_SI' is not set, use the default cursor styles.
2111 if (thickness < 50)
2112 vtp_printf("\033[3 q"); // underline
2113 else
2114 vtp_printf("\033[0 q"); // default
2115 }
2116 }
2117 else
2118 {
2119 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2120 ConsoleCursorInfo.dwSize = thickness;
2121 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002122
K.Takatadf5320c2022-09-01 13:20:16 +01002123 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2124 if (s_cursor_visible)
2125 SetConsoleCursorPosition(g_hConOut, g_coord);
2126 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127}
2128
2129 void
2130mch_update_cursor(void)
2131{
2132 int idx;
2133 int thickness;
2134
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002135# ifdef VIMDLL
2136 if (gui.in_use)
2137 return;
2138# endif
2139
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 /*
2141 * How the cursor is drawn depends on the current mode.
2142 */
2143 idx = get_shape_idx(FALSE);
2144
2145 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002146 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002147 else
2148 thickness = shape_table[idx].percentage;
2149 mch_set_cursor_shape(thickness);
2150}
2151#endif
2152
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002153#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002154/*
2155 * Handle FOCUS_EVENT.
2156 */
2157 static void
2158handle_focus_event(INPUT_RECORD ir)
2159{
2160 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2161 ui_focus_change((int)g_fJustGotFocus);
2162}
2163
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002164static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2165
Bram Moolenaar071d4272004-06-13 20:20:40 +00002166/*
2167 * Wait until console input from keyboard or mouse is available,
2168 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002169 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002170 * Return TRUE if something is available FALSE if not.
2171 */
2172 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002173WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174{
2175 DWORD dwNow = 0, dwEndTime = 0;
2176 INPUT_RECORD ir;
2177 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002178 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002179# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002180 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002181# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002182
2183 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002184 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 dwEndTime = GetTickCount() + msec;
2186 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002187 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002188 dwEndTime = INFINITE;
2189
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002190 // We need to loop until the end of the time period, because
2191 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 for (;;)
2193 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002194 // Only process messages when waiting.
2195 if (msec != 0)
2196 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002197# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002198 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002199# endif
2200# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002201 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002202# endif
2203# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002204 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002205# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002206 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002207
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002208 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002209# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002210 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002211# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212 )
2213 return TRUE;
2214
2215 if (msec > 0)
2216 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002217 // If the specified wait time has passed, return. Beware that
2218 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002220 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002221 break;
2222 }
2223 if (msec != 0)
2224 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002225 DWORD dwWaitTime = dwEndTime - dwNow;
2226
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002227 // Don't wait for more than 11 msec to avoid dropping characters,
2228 // check channel while waiting for input and handle a callback from
2229 // 'balloonexpr'.
2230 if (dwWaitTime > 11)
2231 dwWaitTime = 11;
2232
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002233# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002234 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002235 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002236# endif
2237# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002238 // When waiting very briefly don't trigger timers.
2239 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002240 {
2241 long due_time;
2242
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002243 // Trigger timers and then get the time in msec until the next
2244 // one is due. Wait up to that time.
2245 due_time = check_due_timer();
2246 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002247 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002248 // timer may have used feedkeys().
2249 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002250 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002251 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2252 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002253 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002254# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002255 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002256# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002257 // Wait for either an event on the console input or a
2258 // message in the client-server window.
2259 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2260 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002261# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002262 wait_for_single_object(g_hConIn, dwWaitTime)
2263 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002264# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002265 )
2266 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002267 }
2268
2269 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002270 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002271
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002272# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002273 // May have to redraw if the cursor ends up in the wrong place.
2274 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002275 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 {
2277 CONSOLE_SCREEN_BUFFER_INFO csbi;
2278
2279 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2280 {
2281 if (csbi.dwCursorPosition.Y != msg_row)
2282 {
matveyte08795e2021-05-07 15:00:17 +02002283 // The screen is now messed up, must redraw the command
2284 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002285 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002286 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287 redrawcmd();
2288 }
2289 }
2290 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002291# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292
2293 if (cRecords > 0)
2294 {
2295 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2296 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002297# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002298 // Windows IME sends two '\n's with only one 'ENTER'. First:
2299 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002300 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002301 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2302 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002303 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 continue;
2305 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002306# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002307 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2308 NULL, FALSE))
2309 return TRUE;
2310 }
2311
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002312 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313
2314 if (ir.EventType == FOCUS_EVENT)
2315 handle_focus_event(ir);
2316 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002317 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002318 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2319
Bram Moolenaar36698e32019-12-11 22:57:40 +01002320 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002321 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002322 if (dwSize.X != Columns || dwSize.Y != Rows)
2323 {
2324 CONSOLE_SCREEN_BUFFER_INFO csbi;
2325 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002326 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002327 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002328 if (dwSize.X != Columns || dwSize.Y != Rows)
2329 {
2330 ResizeConBuf(g_hConOut, dwSize);
2331 shell_resized();
2332 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002333 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002334 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 else if (ir.EventType == MOUSE_EVENT
2336 && decode_mouse_event(&ir.Event.MouseEvent))
2337 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338 }
2339 else if (msec == 0)
2340 break;
2341 }
2342
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002343# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002344 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345 if (input_available())
2346 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002347# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002348
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349 return FALSE;
2350}
2351
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352/*
2353 * return non-zero if a character is available
2354 */
2355 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002356mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357{
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, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002364
2365# if defined(FEAT_TERMINAL) || defined(PROTO)
2366/*
2367 * Check for any pending input or messages.
2368 */
2369 int
2370mch_check_messages(void)
2371{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002372# ifdef VIMDLL
2373 if (gui.in_use)
2374 return TRUE;
2375# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002376 return WaitForChar(0L, TRUE);
2377}
2378# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379
2380/*
2381 * Create the console input. Used when reading stdin doesn't work.
2382 */
2383 static void
2384create_conin(void)
2385{
2386 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2387 FILE_SHARE_READ|FILE_SHARE_WRITE,
2388 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002389 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390 did_create_conin = TRUE;
2391}
2392
2393/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002394 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002396 static WCHAR
2397tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002399 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400
2401 for (;;)
2402 {
2403 INPUT_RECORD ir;
2404 DWORD cRecords = 0;
2405
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002406# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002407 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 if (input_available())
2409 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002410 if (g_nMouseClick != -1)
2411 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002412# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002413 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 {
2415 if (did_create_conin)
2416 read_error_exit();
2417 create_conin();
2418 continue;
2419 }
2420
2421 if (ir.EventType == KEY_EVENT)
2422 {
2423 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2424 pmodifiers, TRUE))
2425 return ch;
2426 }
2427 else if (ir.EventType == FOCUS_EVENT)
2428 handle_focus_event(ir);
2429 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2430 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 else if (ir.EventType == MOUSE_EVENT)
2432 {
2433 if (decode_mouse_event(&ir.Event.MouseEvent))
2434 return 0;
2435 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 }
2437}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002438#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439
2440
2441/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002442 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 * Get one or more characters from the keyboard or the mouse.
2444 * If time == 0, do not wait for characters.
2445 * If time == n, wait a short time for characters.
2446 * If time == -1, wait forever for characters.
2447 * Returns the number of characters read into buf.
2448 */
2449 int
2450mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002451 char_u *buf UNUSED,
2452 int maxlen UNUSED,
2453 long time UNUSED,
2454 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002456#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457
2458 int len;
2459 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002460# ifdef VIMDLL
2461// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2462# define TYPEAHEADSPACE 6
2463# else
2464# define TYPEAHEADSPACE 0
2465# endif
2466# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002467 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002468 static int typeaheadlen = 0;
2469
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002470# ifdef VIMDLL
2471 if (gui.in_use)
2472 return 0;
2473# endif
2474
Bram Moolenaar0f873732019-12-05 20:28:46 +01002475 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002476 if (typeaheadlen > 0)
2477 goto theend;
2478
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479 if (time >= 0)
2480 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002481 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002483 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002484 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002486 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487
Bram Moolenaar3918c952005-03-15 22:34:55 +00002488 /*
2489 * If there is no character available within 2 seconds (default)
2490 * write the autoscript file to disk. Or cause the CursorHold event
2491 * to be triggered.
2492 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002493 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002495 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002497 buf[0] = K_SPECIAL;
2498 buf[1] = KS_EXTRA;
2499 buf[2] = (int)KE_CURSORHOLD;
2500 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002502 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 }
2504 }
2505
2506 /*
2507 * Try to read as many characters as there are, until the buffer is full.
2508 */
2509
Bram Moolenaar0f873732019-12-05 20:28:46 +01002510 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 g_fCBrkPressed = FALSE;
2512
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002513# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 if (fdDump)
2515 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002516# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517
Bram Moolenaar0f873732019-12-05 20:28:46 +01002518 // Keep looping until there is something in the typeahead buffer and more
2519 // to get and still room in the buffer (up to two bytes for a char and
2520 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002521 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002522 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 {
2524 if (typebuf_changed(tb_change_cnt))
2525 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002526 // "buf" may be invalid now if a client put something in the
2527 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 typeaheadlen = 0;
2529 break;
2530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 if (g_nMouseClick != -1)
2532 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002533# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 if (fdDump)
2535 fprintf(fdDump, "{%02x @ %d, %d}",
2536 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002537# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002538 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2539 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2540
2541 if (scroll_dir == KE_MOUSEDOWN
2542 || scroll_dir == KE_MOUSEUP
2543 || scroll_dir == KE_MOUSELEFT
2544 || scroll_dir == KE_MOUSERIGHT)
2545 {
2546 if (modifiers > 0)
2547 {
Christopher Plewright03193062022-11-22 12:58:27 +00002548 // use K_SPECIAL instead of CSI to make mappings work
2549 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002550 typeahead[typeaheadlen++] = KS_MODIFIER;
2551 typeahead[typeaheadlen++] = modifiers;
2552 }
2553 typeahead[typeaheadlen++] = CSI;
2554 typeahead[typeaheadlen++] = KS_EXTRA;
2555 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002556 }
2557 else
2558 {
2559 typeahead[typeaheadlen++] = ESC + 128;
2560 typeahead[typeaheadlen++] = 'M';
2561 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002562 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002563
2564 // Pass the pointer coordinates of the mouse event in 2 bytes,
2565 // allowing for > 223 columns. Both for click and scroll events.
2566 // This is the same as what is used for the GUI.
2567 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2568 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2569 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2570 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2571
2572 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573 }
2574 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002576 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 int modifiers = 0;
2578
2579 c = tgetch(&modifiers, &ch2);
2580
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002581 c = simplify_key(c, &modifiers);
2582
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002583 // Some chars need adjustment when the Ctrl modifier is used.
2584 ++no_reduce_keys;
2585 c = may_adjust_key_for_ctrl(modifiers, c);
2586 --no_reduce_keys;
2587
2588 // remove the SHIFT modifier for keys where it's already included,
2589 // e.g., '(' and '*'
2590 modifiers = may_remove_shift_modifier(modifiers, c);
2591
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 if (typebuf_changed(tb_change_cnt))
2593 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002594 // "buf" may be invalid now if a client put something in the
2595 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596 typeaheadlen = 0;
2597 break;
2598 }
2599
2600 if (c == Ctrl_C && ctrl_c_interrupts)
2601 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002602# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002604# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605 got_int = TRUE;
2606 }
2607
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609 {
2610 int n = 1;
2611
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002612 if (ch2 == NUL)
2613 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002614 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002615 char_u *p;
2616 WCHAR ch[2];
2617
2618 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002619 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002620 {
2621 ch[1] = tgetch(&modifiers, &ch2);
2622 n++;
2623 }
2624 p = utf16_to_enc(ch, &n);
2625 if (p != NULL)
2626 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002627 for (i = 0, j = 0; i < n; i++)
2628 {
2629 typeahead[typeaheadlen + j++] = p[i];
2630# ifdef VIMDLL
2631 if (p[i] == CSI)
2632 {
2633 typeahead[typeaheadlen + j++] = KS_EXTRA;
2634 typeahead[typeaheadlen + j++] = KE_CSI;
2635 }
2636# endif
2637 }
2638 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002639 vim_free(p);
2640 }
2641 }
2642 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002643 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002644 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002645# ifdef VIMDLL
2646 if (c == CSI)
2647 {
2648 typeahead[typeaheadlen + 1] = KS_EXTRA;
2649 typeahead[typeaheadlen + 2] = KE_CSI;
2650 n = 3;
2651 }
2652# endif
2653 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002654 if (ch2 != NUL)
2655 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002656 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002657 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002658 switch (ch2)
2659 {
2660 case (WCHAR)'\324': // SHIFT+Insert
2661 case (WCHAR)'\325': // CTRL+Insert
2662 case (WCHAR)'\327': // SHIFT+Delete
2663 case (WCHAR)'\330': // CTRL+Delete
2664 typeahead[typeaheadlen + n] = (char_u)ch2;
2665 n++;
2666 break;
2667
2668 default:
2669 typeahead[typeaheadlen + n] = 3;
2670 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2671 n += 2;
2672 break;
2673 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002674 }
2675 else
2676 {
2677 typeahead[typeaheadlen + n] = 3;
2678 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2679 n += 2;
2680 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002681 }
2682
Bram Moolenaar0f873732019-12-05 20:28:46 +01002683 // Use the ALT key to set the 8th bit of the character
2684 // when it's one byte, the 8th bit isn't set yet and not
2685 // using a double-byte encoding (would become a lead
2686 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687 if ((modifiers & MOD_MASK_ALT)
2688 && n == 1
2689 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002691 )
2692 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002693 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2694 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002695 modifiers &= ~MOD_MASK_ALT;
2696 }
2697
2698 if (modifiers != 0)
2699 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002700 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002701 mch_memmove(typeahead + typeaheadlen + 3,
2702 typeahead + typeaheadlen, n);
2703 typeahead[typeaheadlen++] = K_SPECIAL;
2704 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2705 typeahead[typeaheadlen++] = modifiers;
2706 }
2707
2708 typeaheadlen += n;
2709
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002710# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 if (fdDump)
2712 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 }
2715 }
2716 }
2717
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002718# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 if (fdDump)
2720 {
2721 fputs("]\n", fdDump);
2722 fflush(fdDump);
2723 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725
Bram Moolenaar071d4272004-06-13 20:20:40 +00002726theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002727 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728 len = 0;
2729 while (len < maxlen && typeaheadlen > 0)
2730 {
2731 buf[len++] = typeahead[0];
2732 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2733 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002734# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002735 if (len > 0)
2736 {
2737 buf[len] = NUL;
2738 ch_log(NULL, "raw key input: \"%s\"", buf);
2739 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002740# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741 return len;
2742
Bram Moolenaar0f873732019-12-05 20:28:46 +01002743#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002745#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746}
2747
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002748/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002749 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002750 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2751 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002752 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002753 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002755executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002756{
LemonBoy40fd7e62022-05-05 20:18:16 +01002757 int attrs = win32_getattrs((char_u *)name);
2758
2759 // The file doesn't exist or is a folder.
2760 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2761 return FALSE;
2762 // Check if the file is an AppExecLink, a special alias used by Windows
2763 // Store for its apps.
2764 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002765 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002766 char_u *res = resolve_appexeclink((char_u *)name);
2767 if (res == NULL)
AmberArrf5d0f542023-08-20 20:03:45 +02002768 res = resolve_reparse_point((char_u *)name);
2769 if (res == NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002770 return FALSE;
2771 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002772 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002773 *path = res;
2774 else
2775 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002776 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002777 else if (path != NULL)
2778 *path = FullName_save((char_u *)name, FALSE);
2779 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002780}
2781
2782/*
2783 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2784 * If "use_path" is FALSE: Return TRUE if "name" exists.
2785 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2786 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2787 * the allocated memory.
2788 */
2789 static int
2790executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2791{
2792 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2793 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2794 // UTF-8.
2795 char_u buf[_MAX_PATH * 3];
2796 size_t len = STRLEN(name);
2797 size_t tmplen;
2798 char_u *p, *e, *e2;
2799 char_u *pathbuf = NULL;
2800 char_u *pathext = NULL;
2801 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002802 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002803 int noext = FALSE;
2804 int retval = FALSE;
2805
2806 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002807 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002808
2809 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002810 shname = gettail(p_sh);
2811 if (strstr((char *)shname, "sh") != NULL &&
2812 !(strstr((char *)shname, "powershell") != NULL
2813 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002814 noext = TRUE;
2815
2816 if (use_pathext)
2817 {
2818 pathext = mch_getenv("PATHEXT");
2819 if (pathext == NULL)
2820 pathext = (char_u *)".com;.exe;.bat;.cmd";
2821
2822 if (noext == FALSE)
2823 {
2824 /*
2825 * Loop over all extensions in $PATHEXT.
2826 * Check "name" ends with extension.
2827 */
2828 p = pathext;
2829 while (*p)
2830 {
2831 if (p[0] == ';'
2832 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2833 {
2834 // Skip empty or single ".".
2835 ++p;
2836 continue;
2837 }
2838 e = vim_strchr(p, ';');
2839 if (e == NULL)
2840 e = p + STRLEN(p);
2841 tmplen = e - p;
2842
2843 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2844 {
2845 noext = TRUE;
2846 break;
2847 }
2848
2849 p = e;
2850 }
2851 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002852 }
2853
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002854 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002855 if (pathext == NULL)
2856 pathext = (char_u *)".";
2857 else if (noext == TRUE)
2858 {
2859 if (pathextbuf == NULL)
2860 pathextbuf = alloc(STRLEN(pathext) + 3);
2861 if (pathextbuf == NULL)
2862 {
2863 retval = FALSE;
2864 goto theend;
2865 }
2866 STRCPY(pathextbuf, ".;");
2867 STRCAT(pathextbuf, pathext);
2868 pathext = pathextbuf;
2869 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002870
Bram Moolenaar95da1362020-05-30 18:37:55 +02002871 // Use $PATH when "use_path" is TRUE and "name" is basename.
2872 if (use_path && gettail((char_u *)name) == (char_u *)name)
2873 {
2874 p = mch_getenv("PATH");
2875 if (p != NULL)
2876 {
2877 pathbuf = alloc(STRLEN(p) + 3);
2878 if (pathbuf == NULL)
2879 {
2880 retval = FALSE;
2881 goto theend;
2882 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002883
2884 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2885 STRCPY(pathbuf, ".;");
2886 else
2887 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002888 STRCAT(pathbuf, p);
2889 }
2890 }
2891
2892 /*
2893 * Walk through all entries in $PATH to check if "name" exists there and
2894 * is an executable file.
2895 */
2896 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2897 while (*p)
2898 {
2899 if (*p == ';') // Skip empty entry
2900 {
2901 ++p;
2902 continue;
2903 }
2904 e = vim_strchr(p, ';');
2905 if (e == NULL)
2906 e = p + STRLEN(p);
2907
2908 if (e - p + len + 2 > sizeof(buf))
2909 {
2910 retval = FALSE;
2911 goto theend;
2912 }
2913 // A single "." that means current dir.
2914 if (e - p == 1 && *p == '.')
2915 STRCPY(buf, name);
2916 else
2917 {
2918 vim_strncpy(buf, p, e - p);
2919 add_pathsep(buf);
2920 STRCAT(buf, name);
2921 }
2922 tmplen = STRLEN(buf);
2923
2924 /*
2925 * Loop over all extensions in $PATHEXT.
2926 * Check "name" with extension added.
2927 */
2928 p = pathext;
2929 while (*p)
2930 {
2931 if (*p == ';')
2932 {
2933 // Skip empty entry
2934 ++p;
2935 continue;
2936 }
2937 e2 = vim_strchr(p, (int)';');
2938 if (e2 == NULL)
2939 e2 = p + STRLEN(p);
2940
2941 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2942 {
2943 // Not a single "." that means no extension is added.
2944 if (e2 - p + tmplen + 1 > sizeof(buf))
2945 {
2946 retval = FALSE;
2947 goto theend;
2948 }
2949 vim_strncpy(buf + tmplen, p, e2 - p);
2950 }
2951 if (executable_file((char *)buf, path))
2952 {
2953 retval = TRUE;
2954 goto theend;
2955 }
2956
2957 p = e2;
2958 }
2959
2960 p = e;
2961 }
2962
2963theend:
2964 free(pathextbuf);
2965 free(pathbuf);
2966 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967}
2968
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002969#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2970 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002971/*
2972 * Bad parameter handler.
2973 *
2974 * Certain MS CRT functions will intentionally crash when passed invalid
2975 * parameters to highlight possible security holes. Setting this function as
2976 * the bad parameter handler will prevent the crash.
2977 *
2978 * In debug builds the parameters contain CRT information that might help track
2979 * down the source of a problem, but in non-debug builds the arguments are all
2980 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2981 * worth allowing these to make debugging of issues easier.
2982 */
2983 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002984bad_param_handler(const wchar_t *expression UNUSED,
2985 const wchar_t *function UNUSED,
2986 const wchar_t *file UNUSED,
2987 unsigned int line UNUSED,
2988 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002989{
2990}
2991
2992# define SET_INVALID_PARAM_HANDLER \
2993 ((void)_set_invalid_parameter_handler(bad_param_handler))
2994#else
2995# define SET_INVALID_PARAM_HANDLER
2996#endif
2997
Bram Moolenaar4f974752019-02-17 17:44:42 +01002998#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999
3000/*
3001 * GUI version of mch_init().
3002 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003003 static void
3004mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003006# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003008# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009
Bram Moolenaar0f873732019-12-05 20:28:46 +01003010 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003011 SET_INVALID_PARAM_HANDLER;
3012
Bram Moolenaar0f873732019-12-05 20:28:46 +01003013 // Let critical errors result in a failure, not in a dialog box. Required
3014 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015 SetErrorMode(SEM_FAILCRITICALERRORS);
3016
Bram Moolenaar0f873732019-12-05 20:28:46 +01003017 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018
Bram Moolenaar0f873732019-12-05 20:28:46 +01003019 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 Rows = 25;
3021 Columns = 80;
3022
John Marriott9cb27a52025-06-08 16:05:53 +02003023 // Look for 'vimrun'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024 {
John Marriott9cb27a52025-06-08 16:05:53 +02003025 char_u vimrun_location[_MAX_PATH + 4];
3026 size_t exe_pathlen = (size_t)(gettail(exe_name) - exe_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027
John Marriott9cb27a52025-06-08 16:05:53 +02003028 // Note: 10 is length of 'vimrun.exe'.
3029 if (exe_pathlen + 10 >= sizeof(vimrun_location))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 {
John Marriott9cb27a52025-06-08 16:05:53 +02003031 if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
John Marriott738df382025-06-05 20:49:39 +02003032 s_dont_use_vimrun = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033 }
John Marriott9cb27a52025-06-08 16:05:53 +02003034 else
3035 {
3036 // First try in same directory as gvim.exe.
3037 if (exe_pathlen > 0)
3038 vim_strncpy(vimrun_location, exe_name, exe_pathlen);
3039 STRCPY(vimrun_location + exe_pathlen, "vimrun.exe");
3040
3041 if (mch_getperm(vimrun_location) >= 0)
3042 {
3043 char_u *p;
3044 size_t plen;
3045
3046 if (exe_pathlen > 0 && *skiptowhite(vimrun_location) != NUL)
3047 {
3048 // Enclose path with white space in double quotes.
3049 plen = vim_snprintf_safelen(
3050 (char *)vimrun_location,
3051 sizeof(vimrun_location),
3052 "\"%.*svimrun\" ",
3053 (int)exe_pathlen, exe_name);
3054 }
3055 else
3056 {
3057 // Remove the suffix ('.exe').
3058 vimrun_location[exe_pathlen + 6] = ' ';
3059 vimrun_location[exe_pathlen + 7] = NUL;
3060 plen = exe_pathlen + 7;
3061 }
3062
3063 p = vim_strnsave(vimrun_location, plen);
3064 if (p != NULL)
3065 {
3066 vimrun_path.string = p;
3067 vimrun_path.length = plen;
3068 vimrun_path_allocated = TRUE;
3069 s_dont_use_vimrun = FALSE;
3070 }
3071 }
3072 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
3073 s_dont_use_vimrun = FALSE;
3074 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075
Bram Moolenaar0f873732019-12-05 20:28:46 +01003076 // Don't give the warning for a missing vimrun.exe right now, but only
3077 // when vimrun was supposed to be used. Don't bother people that do
3078 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079 if (s_dont_use_vimrun)
3080 need_vimrun_warning = TRUE;
3081 }
3082
3083 /*
John Marriott9cb27a52025-06-08 16:05:53 +02003084 * If "findstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085 * Otherwise the default "findstr /n" is used.
3086 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02003087 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003088 set_option_value_give_err((char_u *)"grepprg",
3089 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003091# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003092 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003093# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003094
3095 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096}
3097
3098
Bram Moolenaar0f873732019-12-05 20:28:46 +01003099#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003100
3101#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003103# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3104# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105
3106/*
3107 * ClearConsoleBuffer()
3108 * Description:
3109 * Clears the entire contents of the console screen buffer, using the
3110 * specified attribute.
3111 * Returns:
3112 * TRUE on success
3113 */
3114 static BOOL
3115ClearConsoleBuffer(WORD wAttribute)
3116{
3117 CONSOLE_SCREEN_BUFFER_INFO csbi;
3118 COORD coord;
3119 DWORD NumCells, dummy;
3120
3121 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3122 return FALSE;
3123
3124 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3125 coord.X = 0;
3126 coord.Y = 0;
3127 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3128 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3131 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003132 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133
3134 return TRUE;
3135}
3136
3137/*
3138 * FitConsoleWindow()
3139 * Description:
3140 * Checks if the console window will fit within given buffer dimensions.
3141 * Also, if requested, will shrink the window to fit.
3142 * Returns:
3143 * TRUE on success
3144 */
3145 static BOOL
3146FitConsoleWindow(
3147 COORD dwBufferSize,
3148 BOOL WantAdjust)
3149{
3150 CONSOLE_SCREEN_BUFFER_INFO csbi;
3151 COORD dwWindowSize;
3152 BOOL NeedAdjust = FALSE;
3153
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003154 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3155 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003157 /*
3158 * A buffer resize will fail if the current console window does
3159 * not lie completely within that buffer. To avoid this, we might
3160 * have to move and possibly shrink the window.
3161 */
3162 if (csbi.srWindow.Right >= dwBufferSize.X)
3163 {
3164 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3165 if (dwWindowSize.X > dwBufferSize.X)
3166 dwWindowSize.X = dwBufferSize.X;
3167 csbi.srWindow.Right = dwBufferSize.X - 1;
3168 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3169 NeedAdjust = TRUE;
3170 }
3171 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3172 {
3173 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3174 if (dwWindowSize.Y > dwBufferSize.Y)
3175 dwWindowSize.Y = dwBufferSize.Y;
3176 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3177 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3178 NeedAdjust = TRUE;
3179 }
3180 if (NeedAdjust && WantAdjust)
3181 {
3182 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3183 return FALSE;
3184 }
3185 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186}
3187
3188typedef struct ConsoleBufferStruct
3189{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003190 BOOL IsValid;
3191 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003192 PCHAR_INFO Buffer;
3193 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003194 PSMALL_RECT Regions;
3195 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196} ConsoleBuffer;
3197
3198/*
3199 * SaveConsoleBuffer()
3200 * Description:
3201 * Saves important information about the console buffer, including the
3202 * actual buffer contents. The saved information is suitable for later
3203 * restoration by RestoreConsoleBuffer().
3204 * Returns:
3205 * TRUE if all information was saved; FALSE otherwise
3206 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3207 */
3208 static BOOL
3209SaveConsoleBuffer(
3210 ConsoleBuffer *cb)
3211{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003212 DWORD NumCells;
3213 COORD BufferCoord;
3214 SMALL_RECT ReadRegion;
3215 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003216 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003217
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218 if (cb == NULL)
3219 return FALSE;
3220
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003221 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222 {
3223 cb->IsValid = FALSE;
3224 return FALSE;
3225 }
3226 cb->IsValid = TRUE;
3227
Christopher Plewright1140b512022-11-12 18:46:05 +00003228 // VTP uses alternate screen buffer.
3229 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003230 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003231 return TRUE;
3232
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003233 /*
3234 * Allocate a buffer large enough to hold the entire console screen
3235 * buffer. If this ConsoleBuffer structure has already been initialized
3236 * with a buffer of the correct size, then just use that one.
3237 */
3238 if (!cb->IsValid || cb->Buffer == NULL ||
3239 cb->BufferSize.X != cb->Info.dwSize.X ||
3240 cb->BufferSize.Y != cb->Info.dwSize.Y)
3241 {
3242 cb->BufferSize.X = cb->Info.dwSize.X;
3243 cb->BufferSize.Y = cb->Info.dwSize.Y;
3244 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3245 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003246 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003247 if (cb->Buffer == NULL)
3248 return FALSE;
3249 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250
3251 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003252 * We will now copy the console screen buffer into our buffer.
3253 * ReadConsoleOutput() seems to be limited as far as how much you
3254 * can read at a time. Empirically, this number seems to be about
3255 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3256 * in chunks until it is all copied. The chunks will all have the
3257 * same horizontal characteristics, so initialize them now. The
3258 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003260 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003261 ReadRegion.Left = 0;
3262 ReadRegion.Right = cb->Info.dwSize.X - 1;
3263 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003264
3265 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3266 if (cb->Regions == NULL || numregions != cb->NumRegions)
3267 {
3268 cb->NumRegions = numregions;
3269 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003270 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003271 if (cb->Regions == NULL)
3272 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003273 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003274 return FALSE;
3275 }
3276 }
3277
3278 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003280 /*
3281 * Read into position (0, Y) in our buffer.
3282 */
3283 BufferCoord.Y = Y;
3284 /*
3285 * Read the region whose top left corner is (0, Y) and whose bottom
3286 * right corner is (width - 1, Y + Y_incr - 1). This should define
3287 * a region of size width by Y_incr. Don't worry if this region is
3288 * too large for the remaining buffer; it will be cropped.
3289 */
3290 ReadRegion.Top = Y;
3291 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003292 if (!ReadConsoleOutputW(g_hConOut, // output handle
3293 cb->Buffer, // our buffer
3294 cb->BufferSize, // dimensions of our buffer
3295 BufferCoord, // offset in our buffer
3296 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003297 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003298 VIM_CLEAR(cb->Buffer);
3299 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003300 return FALSE;
3301 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003302 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003303 }
3304
3305 return TRUE;
3306}
3307
3308/*
3309 * RestoreConsoleBuffer()
3310 * Description:
3311 * Restores important information about the console buffer, including the
3312 * actual buffer contents, if desired. The information to restore is in
3313 * the same format used by SaveConsoleBuffer().
3314 * Returns:
3315 * TRUE on success
3316 */
3317 static BOOL
3318RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003319 ConsoleBuffer *cb,
3320 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003322 COORD BufferCoord;
3323 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003324 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003325
Christopher Plewright1140b512022-11-12 18:46:05 +00003326
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327 if (cb == NULL || !cb->IsValid)
3328 return FALSE;
3329
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003330 /*
3331 * Before restoring the buffer contents, clear the current buffer, and
3332 * restore the cursor position and window information. Doing this now
3333 * prevents old buffer contents from "flashing" onto the screen.
3334 */
3335 if (RestoreScreen)
3336 ClearConsoleBuffer(cb->Info.wAttributes);
3337
3338 FitConsoleWindow(cb->Info.dwSize, TRUE);
3339 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3340 return FALSE;
3341 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3342 return FALSE;
3343
3344 if (!RestoreScreen)
3345 {
3346 /*
3347 * No need to restore the screen buffer contents, so we're done.
3348 */
3349 return TRUE;
3350 }
3351
3352 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3353 return FALSE;
3354 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3355 return FALSE;
3356
Christopher Plewrightab281f82025-03-16 19:14:31 +01003357 // VTP uses alternate screen buffer.
3358 // No need to restore buffer contents.
3359 if (use_alternate_screen_buffer)
3360 return TRUE;
3361
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003362 /*
3363 * Restore the screen buffer contents.
3364 */
3365 if (cb->Buffer != NULL)
3366 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003367 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003368 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003369 BufferCoord.X = cb->Regions[i].Left;
3370 BufferCoord.Y = cb->Regions[i].Top;
3371 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003372 if (!WriteConsoleOutputW(g_hConOut, // output handle
3373 cb->Buffer, // our buffer
3374 cb->BufferSize, // dimensions of our buffer
3375 BufferCoord, // offset in our buffer
3376 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003377 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003378 }
3379 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380
3381 return TRUE;
3382}
3383
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003384# define FEAT_RESTORE_ORIG_SCREEN
3385# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003386static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003387# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388static ConsoleBuffer g_cbNonTermcap = { 0 };
3389static ConsoleBuffer g_cbTermcap = { 0 };
3390
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003392HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003393static HICON g_hOrigIconSmall = NULL;
3394static HICON g_hOrigIcon = NULL;
3395static HICON g_hVimIcon = NULL;
3396static BOOL g_fCanChangeIcon = FALSE;
3397
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398/*
3399 * GetConsoleIcon()
3400 * Description:
3401 * Attempts to retrieve the small icon and/or the big icon currently in
3402 * use by a given window.
3403 * Returns:
3404 * TRUE on success
3405 */
3406 static BOOL
3407GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003408 HWND hWnd,
3409 HICON *phIconSmall,
3410 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411{
3412 if (hWnd == NULL)
3413 return FALSE;
3414
3415 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003416 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3417 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003419 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3420 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003421 return TRUE;
3422}
3423
3424/*
3425 * SetConsoleIcon()
3426 * Description:
3427 * Attempts to change the small icon and/or the big icon currently in
3428 * use by a given window.
3429 * Returns:
3430 * TRUE on success
3431 */
3432 static BOOL
3433SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003434 HWND hWnd,
3435 HICON hIconSmall,
3436 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 if (hWnd == NULL)
3439 return FALSE;
3440
3441 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003442 SendMessage(hWnd, WM_SETICON,
3443 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003445 SendMessage(hWnd, WM_SETICON,
3446 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447 return TRUE;
3448}
3449
3450/*
3451 * SaveConsoleTitleAndIcon()
3452 * Description:
3453 * Saves the current console window title in g_szOrigTitle, for later
3454 * restoration. Also, attempts to obtain a handle to the console window,
3455 * and use it to save the small and big icons currently in use by the
3456 * console window. This is not always possible on some versions of Windows;
3457 * nor is it possible when running Vim remotely using Telnet (since the
3458 * console window the user sees is owned by a remote process).
3459 */
3460 static void
3461SaveConsoleTitleAndIcon(void)
3462{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003463 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003464 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3465 return;
3466
3467 /*
3468 * Obtain a handle to the console window using GetConsoleWindow() from
3469 * KERNEL32.DLL; we need to handle in order to change the window icon.
3470 * This function only exists on NT-based Windows, starting with Windows
3471 * 2000. On older operating systems, we can't change the window icon
3472 * anyway.
3473 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003474 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475 if (g_hWnd == NULL)
3476 return;
3477
Bram Moolenaar0f873732019-12-05 20:28:46 +01003478 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003479 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3480 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3481 return;
3482
Bram Moolenaar0f873732019-12-05 20:28:46 +01003483 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003484 if (
3485# ifdef FEAT_LIBCALL
3486 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3487# endif
3488 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003489 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490 if (g_hVimIcon != NULL)
3491 g_fCanChangeIcon = TRUE;
3492}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493
3494static int g_fWindInitCalled = FALSE;
3495static int g_fTermcapMode = FALSE;
3496static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497
3498/*
3499 * non-GUI version of mch_init().
3500 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003501 static void
3502mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003504# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003505 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003506# endif
3507# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003509# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510
Bram Moolenaar0f873732019-12-05 20:28:46 +01003511 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003512 SET_INVALID_PARAM_HANDLER;
3513
Bram Moolenaar0f873732019-12-05 20:28:46 +01003514 // Let critical errors result in a failure, not in a dialog box. Required
3515 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516 SetErrorMode(SEM_FAILCRITICALERRORS);
3517
Bram Moolenaar0f873732019-12-05 20:28:46 +01003518 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519 out_flush();
3520
Bram Moolenaar0f873732019-12-05 20:28:46 +01003521 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522 if (read_cmd_fd == 0)
3523 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3524 else
3525 create_conin();
3526 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3527
Christopher Plewright38804d62022-11-09 23:55:52 +00003528 wt_init();
3529 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003530# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003531 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003532 SaveConsoleBuffer(&g_cbOrig);
3533 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003534# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003535 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003536 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3537 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003539 if (cterm_normal_fg_color == 0)
3540 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3541 if (cterm_normal_bg_color == 0)
3542 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3543
Bram Moolenaarbdace832019-03-02 10:13:42 +01003544 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003545 g_color_index_fg = g_attrDefault & 0xf;
3546 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3547
Bram Moolenaar0f873732019-12-05 20:28:46 +01003548 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549 update_tcap(g_attrCurrent);
3550
3551 GetConsoleCursorInfo(g_hConOut, &g_cci);
3552 GetConsoleMode(g_hConIn, &g_cmodein);
3553 GetConsoleMode(g_hConOut, &g_cmodeout);
3554
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555 SaveConsoleTitleAndIcon();
3556 /*
3557 * Set both the small and big icons of the console window to Vim's icon.
3558 * Note that Vim presently only has one size of icon (32x32), but it
3559 * automatically gets scaled down to 16x16 when setting the small icon.
3560 */
3561 if (g_fCanChangeIcon)
3562 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563
3564 ui_get_shellsize();
3565
Christopher Plewrightd343c602023-01-22 18:58:30 +00003566 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003567 // Switch to a new alternate screen buffer.
3568 if (use_alternate_screen_buffer)
3569 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003570
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003571# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 fdDump = fopen("dump", "wt");
3573
3574 if (fdDump)
3575 {
3576 time_t t;
3577
3578 time(&t);
3579 fputs(ctime(&t), fdDump);
3580 fflush(fdDump);
3581 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003582# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583
3584 g_fWindInitCalled = TRUE;
3585
Bram Moolenaar071d4272004-06-13 20:20:40 +00003586 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003587
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003588# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003589 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003590# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003591}
3592
3593/*
3594 * non-GUI version of mch_exit().
3595 * Shut down and exit with status `r'
3596 * Careful: mch_exit() may be called before mch_init()!
3597 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003598 static void
3599mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600{
William Breslerded59132024-10-08 21:30:48 +02003601 // Copy flag since stoptermcap() will clear the flag.
3602 int fTermcapMode = g_fTermcapMode;
3603
Bram Moolenaar955f1982017-02-05 15:10:51 +01003604 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003606 vtp_exit();
3607
Bram Moolenaar955f1982017-02-05 15:10:51 +01003608 stoptermcap();
William Breslerded59132024-10-08 21:30:48 +02003609 // Switch back to main screen buffer if TermcapMode was not active.
3610 if (!fTermcapMode && use_alternate_screen_buffer)
Ken Takata568cbc92024-08-07 21:18:24 +02003611 vtp_printf("\033[?1049l");
3612
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613 if (g_fWindInitCalled)
3614 settmode(TMODE_COOK);
3615
Bram Moolenaar0f873732019-12-05 20:28:46 +01003616 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003617
3618 if (g_fWindInitCalled)
3619 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003620 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621 /*
3622 * Restore both the small and big icons of the console window to
3623 * what they were at startup. Don't do this when the window is
3624 * closed, Vim would hang here.
3625 */
3626 if (g_fCanChangeIcon && !g_fForceExit)
3627 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003629# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 if (fdDump)
3631 {
3632 time_t t;
3633
3634 time(&t);
3635 fputs(ctime(&t), fdDump);
3636 fclose(fdDump);
3637 }
3638 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003639# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003640 }
3641
3642 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003643 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644 SetConsoleMode(g_hConOut, g_cmodeout);
3645
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003646# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003648# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649
3650 exit(r);
3651}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003652#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003653
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003654 void
3655mch_init(void)
3656{
3657#ifdef VIMDLL
3658 if (gui.starting)
3659 mch_init_g();
3660 else
3661 mch_init_c();
3662#elif defined(FEAT_GUI_MSWIN)
3663 mch_init_g();
3664#else
3665 mch_init_c();
3666#endif
3667}
3668
3669 void
3670mch_exit(int r)
3671{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003672#ifdef FEAT_NETBEANS_INTG
3673 netbeans_send_disconnect();
3674#endif
3675
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003676#ifdef VIMDLL
John Marriott9cb27a52025-06-08 16:05:53 +02003677 if (vimrun_path_allocated)
3678 vim_free(vimrun_path.string);
3679
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003680 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003681 mch_exit_g(r);
3682 else
3683 mch_exit_c(r);
3684#elif defined(FEAT_GUI_MSWIN)
John Marriott9cb27a52025-06-08 16:05:53 +02003685 if (vimrun_path_allocated)
3686 vim_free(vimrun_path.string);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003687 mch_exit_g(r);
3688#else
3689 mch_exit_c(r);
3690#endif
3691}
3692
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693/*
3694 * Do we have an interactive window?
3695 */
3696 int
3697mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003698 int argc UNUSED,
3699 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700{
K.Takatace3189d2023-02-15 19:13:43 +00003701 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003702
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003703#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003704 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003706# ifdef VIMDLL
3707 if (gui.in_use)
3708 return OK;
3709# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003710 if (isatty(1))
3711 return OK;
3712 return FAIL;
3713#endif
3714}
3715
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003716/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003717 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718 * When "len" is > 0, also expand short to long filenames.
3719 */
3720 void
3721fname_case(
3722 char_u *name,
3723 int len)
3724{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003725 WCHAR *p;
3726 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727
John Marriott9cb27a52025-06-08 16:05:53 +02003728 if (*name == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 return;
3730
3731 slash_adjust(name);
3732
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003733 p = enc_to_utf16(name, NULL);
3734 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003735 return;
3736
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003737 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003739 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003741 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742 {
John Marriott9cb27a52025-06-08 16:05:53 +02003743 if (len > 0)
3744 vim_strncpy(name, q, len - 1);
3745 else
3746 {
3747 size_t namelen = STRLEN(name);
3748 if (namelen >= STRLEN(q))
3749 vim_strncpy(name, q, namelen);
3750 }
3751
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003752 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 }
3754 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003755 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756}
3757
3758
3759/*
3760 * Insert user name in s[len].
3761 */
3762 int
3763mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003764 char_u *s,
3765 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003767 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003768 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003770 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003771 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003772 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003773
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003774 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003775 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003776 vim_strncpy(s, p, len - 1);
3777 vim_free(p);
3778 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003779 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003780 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 s[0] = NUL;
3782 return FAIL;
3783}
3784
3785
3786/*
3787 * Insert host name in s[len].
3788 */
3789 void
3790mch_get_host_name(
3791 char_u *s,
3792 int len)
3793{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003794 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003795 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003796
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003797 if (!GetComputerNameW(wszHostName, &wcch))
3798 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003799
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003800 char_u *p = utf16_to_enc(wszHostName, NULL);
3801 if (p == NULL)
3802 return;
3803
3804 vim_strncpy(s, p, len - 1);
3805 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806}
3807
3808
3809/*
3810 * return process ID
3811 */
3812 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003813mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814{
3815 return (long)GetCurrentProcessId();
3816}
3817
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003818/*
3819 * return TRUE if process "pid" is still running
3820 */
3821 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003822mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003823{
3824 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3825 DWORD status = 0;
3826 int ret = FALSE;
3827
3828 if (hProcess == NULL)
3829 return FALSE; // might not have access
3830 if (GetExitCodeProcess(hProcess, &status) )
3831 ret = status == STILL_ACTIVE;
3832 CloseHandle(hProcess);
3833 return ret;
3834}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835
3836/*
3837 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3838 * Return OK for success, FAIL for failure.
3839 */
3840 int
3841mch_dirname(
3842 char_u *buf,
3843 int len)
3844{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003845 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003846
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847 /*
3848 * Originally this was:
3849 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3850 * But the Win32s known bug list says that getcwd() doesn't work
3851 * so use the Win32 system call instead. <Negri>
3852 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003853 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3854 return FAIL;
3855
3856 WCHAR wcbuf[_MAX_PATH + 1];
3857 char_u *p = NULL;
3858
3859 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003861 p = utf16_to_enc(wcbuf, NULL);
John Marriott031f2272025-04-23 20:56:08 +02003862 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863 {
John Marriott031f2272025-04-23 20:56:08 +02003864 if (STRLEN(p) >= (size_t)len)
3865 {
3866 // long path name is too long, fall back to short one
3867 VIM_CLEAR(p);
3868 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003869 }
3870 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003871 if (p == NULL)
3872 p = utf16_to_enc(wbuf, NULL);
3873
3874 if (p == NULL)
3875 return FAIL;
3876
3877 vim_strncpy(buf, p, len - 1);
3878 vim_free(p);
3879 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003880}
3881
3882/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003883 * Get file permissions for "name".
3884 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885 */
3886 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003887mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003888{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003889 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003890 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003891
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003892 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003893 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003894}
3895
3896
3897/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003898 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003899 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003900 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901 */
3902 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003903mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003904{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003905 long n;
3906 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003907
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003908 p = enc_to_utf16(name, NULL);
3909 if (p == NULL)
3910 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003912 n = _wchmod(p, perm);
3913 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003914 if (n == -1)
3915 return FAIL;
3916
3917 win32_set_archive(name);
3918
3919 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003920}
3921
3922/*
3923 * Set hidden flag for "name".
3924 */
3925 void
3926mch_hide(char_u *name)
3927{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003928 int attrs = win32_getattrs(name);
3929 if (attrs == -1)
3930 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003931
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003932 attrs |= FILE_ATTRIBUTE_HIDDEN;
3933 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934}
3935
3936/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003937 * Return TRUE if file "name" exists and is hidden.
3938 */
3939 int
3940mch_ishidden(char_u *name)
3941{
3942 int f = win32_getattrs(name);
3943
3944 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003945 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003946
3947 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3948}
3949
3950/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 * return TRUE if "name" is a directory
3952 * return FALSE if "name" is not a directory or upon error
3953 */
3954 int
3955mch_isdir(char_u *name)
3956{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003957 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003958
3959 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003960 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961
3962 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3963}
3964
3965/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003966 * return TRUE if "name" is a directory, NOT a symlink to a directory
3967 * return FALSE if "name" is not a directory
3968 * return FALSE for error
3969 */
3970 int
3971mch_isrealdir(char_u *name)
3972{
3973 return mch_isdir(name) && !mch_is_symbolic_link(name);
3974}
3975
3976/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003977 * Create directory "name".
3978 * Return 0 on success, -1 on error.
3979 */
3980 int
3981mch_mkdir(char_u *name)
3982{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003983 WCHAR *p;
3984 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003985
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003986 p = enc_to_utf16(name, NULL);
3987 if (p == NULL)
3988 return -1;
3989 retval = _wmkdir(p);
3990 vim_free(p);
3991 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003992}
3993
3994/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003995 * Delete directory "name".
3996 * Return 0 on success, -1 on error.
3997 */
3998 int
3999mch_rmdir(char_u *name)
4000{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004001 WCHAR *p;
4002 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01004003
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004004 p = enc_to_utf16(name, NULL);
4005 if (p == NULL)
4006 return -1;
4007 retval = _wrmdir(p);
4008 vim_free(p);
4009 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01004010}
4011
4012/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00004013 * Return TRUE if file "fname" has more than one link.
4014 */
4015 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004016mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00004017{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004018 BY_HANDLE_FILE_INFORMATION info;
4019
4020 return win32_fileinfo(fname, &info) == FILEINFO_OK
4021 && info.nNumberOfLinks > 1;
4022}
4023
4024/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01004025 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004026 */
4027 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01004028mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004029{
4030 HANDLE hFind;
4031 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004032 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004033 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004034 WIN32_FIND_DATAW findDataW;
4035
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004036 wn = enc_to_utf16(name, NULL);
4037 if (wn == NULL)
4038 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004039
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004040 hFind = FindFirstFileW(wn, &findDataW);
4041 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004042 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004043 {
4044 fileFlags = findDataW.dwFileAttributes;
4045 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004046 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004047 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004048
4049 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01004050 && (reparseTag == IO_REPARSE_TAG_SYMLINK
4051 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004052 res = TRUE;
4053
4054 return res;
4055}
4056
4057/*
4058 * Return TRUE if file "fname" has more than one link or if it is a symbolic
4059 * link.
4060 */
4061 int
4062mch_is_linked(char_u *fname)
4063{
4064 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
4065 return TRUE;
4066 return FALSE;
4067}
4068
4069/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004070 * Get the by-handle-file-information for "fname".
4071 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004072 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004073 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
4074 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
4075 */
4076 int
4077win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
4078{
Bram Moolenaar03f48552006-02-28 23:52:23 +00004079 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004080 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004081 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00004082
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004083 wn = enc_to_utf16(fname, NULL);
4084 if (wn == NULL)
4085 return FILEINFO_ENC_FAIL;
4086
4087 hFile = CreateFileW(wn, // file name
4088 GENERIC_READ, // access mode
4089 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
4090 NULL, // security descriptor
4091 OPEN_EXISTING, // creation disposition
4092 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
4093 NULL); // handle to template file
4094 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004095
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004096 if (hFile == INVALID_HANDLE_VALUE)
4097 return FILEINFO_READ_FAIL;
4098
4099 if (GetFileInformationByHandle(hFile, info) != 0)
4100 res = FILEINFO_OK;
4101 else
4102 res = FILEINFO_INFO_FAIL;
4103 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004104
Bram Moolenaar03f48552006-02-28 23:52:23 +00004105 return res;
4106}
4107
4108/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004109 * get file attributes for `name'
4110 * -1 : error
4111 * else FILE_ATTRIBUTE_* defined in winnt.h
4112 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004113 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004114win32_getattrs(char_u *name)
4115{
4116 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004117 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004118
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004119 p = enc_to_utf16(name, NULL);
4120 if (p == NULL)
4121 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004122
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004123 attr = GetFileAttributesW(p);
4124 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004125
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004126 return attr;
4127}
4128
4129/*
4130 * set file attributes for `name' to `attrs'
4131 *
4132 * return -1 for failure, 0 otherwise
4133 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004134 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004135win32_setattrs(char_u *name, int attrs)
4136{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004137 int res;
4138 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004139
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004140 p = enc_to_utf16(name, NULL);
4141 if (p == NULL)
4142 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004143
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004144 res = SetFileAttributesW(p, attrs);
4145 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004146
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004147 return res ? 0 : -1;
4148}
4149
4150/*
4151 * Set archive flag for "name".
4152 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004153 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004154win32_set_archive(char_u *name)
4155{
4156 int attrs = win32_getattrs(name);
4157 if (attrs == -1)
4158 return -1;
4159
4160 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4161 return win32_setattrs(name, attrs);
4162}
4163
4164/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165 * Return TRUE if file or directory "name" is writable (not readonly).
4166 * Strange semantics of Win32: a readonly directory is writable, but you can't
4167 * delete a file. Let's say this means it is writable.
4168 */
4169 int
4170mch_writable(char_u *name)
4171{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004172 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004174 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4175 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176}
4177
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004179 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004180 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004181 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4182 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 */
4184 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004185mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004187 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004188}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189
4190/*
4191 * Check what "name" is:
4192 * NODE_NORMAL: file or directory (or doesn't exist)
4193 * NODE_WRITABLE: writable device, socket, fifo, etc.
4194 * NODE_OTHER: non-writable things
4195 */
4196 int
4197mch_nodetype(char_u *name)
4198{
4199 HANDLE hFile;
4200 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004201 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202
Bram Moolenaar0f873732019-12-05 20:28:46 +01004203 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4204 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4205 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004206 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4207 return NODE_WRITABLE;
4208
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004209 wn = enc_to_utf16(name, NULL);
4210 if (wn == NULL)
4211 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004212
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004213 hFile = CreateFileW(wn, // file name
4214 GENERIC_WRITE, // access mode
4215 0, // share mode
4216 NULL, // security descriptor
4217 OPEN_EXISTING, // creation disposition
4218 0, // file attributes
4219 NULL); // handle to template file
4220 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221 if (hFile == INVALID_HANDLE_VALUE)
4222 return NODE_NORMAL;
4223
4224 type = GetFileType(hFile);
4225 CloseHandle(hFile);
4226 if (type == FILE_TYPE_CHAR)
4227 return NODE_WRITABLE;
4228 if (type == FILE_TYPE_DISK)
4229 return NODE_NORMAL;
4230 return NODE_OTHER;
4231}
4232
4233#ifdef HAVE_ACL
4234struct my_acl
4235{
4236 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4237 PSID pSidOwner;
4238 PSID pSidGroup;
4239 PACL pDacl;
4240 PACL pSacl;
4241};
4242#endif
4243
4244/*
4245 * Return a pointer to the ACL of file "fname" in allocated memory.
4246 * Return NULL if the ACL is not available for whatever reason.
4247 */
4248 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004249mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004250{
4251#ifndef HAVE_ACL
4252 return (vim_acl_T)NULL;
4253#else
4254 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004255 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004256
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004257 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004258 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004260 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004261
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004262 wn = enc_to_utf16(fname, NULL);
4263 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004264 {
4265 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004266 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004267 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004268
4269 // Try to retrieve the entire security descriptor.
4270 err = GetNamedSecurityInfoW(
4271 wn, // Abstract filename
4272 SE_FILE_OBJECT, // File Object
4273 OWNER_SECURITY_INFORMATION |
4274 GROUP_SECURITY_INFORMATION |
4275 DACL_SECURITY_INFORMATION |
4276 SACL_SECURITY_INFORMATION,
4277 &p->pSidOwner, // Ownership information.
4278 &p->pSidGroup, // Group membership.
4279 &p->pDacl, // Discretionary information.
4280 &p->pSacl, // For auditing purposes.
4281 &p->pSecurityDescriptor);
4282 if (err == ERROR_ACCESS_DENIED ||
4283 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004284 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004285 // Retrieve only DACL.
4286 (void)GetNamedSecurityInfoW(
4287 wn,
4288 SE_FILE_OBJECT,
4289 DACL_SECURITY_INFORMATION,
4290 NULL,
4291 NULL,
4292 &p->pDacl,
4293 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004294 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004295 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004296 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004297 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004298 mch_free_acl((vim_acl_T)p);
4299 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004301 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302 }
4303
4304 return (vim_acl_T)p;
4305#endif
4306}
4307
Bram Moolenaar27515922013-06-29 15:36:26 +02004308#ifdef HAVE_ACL
4309/*
4310 * Check if "acl" contains inherited ACE.
4311 */
4312 static BOOL
4313is_acl_inherited(PACL acl)
4314{
4315 DWORD i;
4316 ACL_SIZE_INFORMATION acl_info;
4317 PACCESS_ALLOWED_ACE ace;
4318
4319 acl_info.AceCount = 0;
4320 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4321 for (i = 0; i < acl_info.AceCount; i++)
4322 {
4323 GetAce(acl, i, (LPVOID *)&ace);
4324 if (ace->Header.AceFlags & INHERITED_ACE)
4325 return TRUE;
4326 }
4327 return FALSE;
4328}
4329#endif
4330
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331/*
4332 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4333 * Errors are ignored.
4334 * This must only be called with "acl" equal to what mch_get_acl() returned.
4335 */
4336 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004337mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004338{
4339#ifdef HAVE_ACL
4340 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004341 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004342 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004344 if (p == NULL)
4345 return;
4346
4347 wn = enc_to_utf16(fname, NULL);
4348 if (wn == NULL)
4349 return;
4350
4351 // Set security flags
4352 if (p->pSidOwner)
4353 sec_info |= OWNER_SECURITY_INFORMATION;
4354 if (p->pSidGroup)
4355 sec_info |= GROUP_SECURITY_INFORMATION;
4356 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004357 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004358 sec_info |= DACL_SECURITY_INFORMATION;
4359 // Do not inherit its parent's DACL.
4360 // If the DACL is inherited, Cygwin permissions would be changed.
4361 if (!is_acl_inherited(p->pDacl))
4362 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004363 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004364 if (p->pSacl)
4365 sec_info |= SACL_SECURITY_INFORMATION;
4366
4367 (void)SetNamedSecurityInfoW(
4368 wn, // Abstract filename
4369 SE_FILE_OBJECT, // File Object
4370 sec_info,
4371 p->pSidOwner, // Ownership information.
4372 p->pSidGroup, // Group membership.
4373 p->pDacl, // Discretionary information.
4374 p->pSacl // For auditing purposes.
4375 );
4376 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004377#endif
4378}
4379
4380 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004381mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004382{
4383#ifdef HAVE_ACL
4384 struct my_acl *p = (struct my_acl *)acl;
4385
4386 if (p != NULL)
4387 {
4388 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4389 vim_free(p);
4390 }
4391#endif
4392}
4393
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004394#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004395
4396/*
4397 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4398 */
4399 static BOOL WINAPI
4400handler_routine(
4401 DWORD dwCtrlType)
4402{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004403 INPUT_RECORD ir;
4404 DWORD out;
4405
Bram Moolenaar071d4272004-06-13 20:20:40 +00004406 switch (dwCtrlType)
4407 {
4408 case CTRL_C_EVENT:
4409 if (ctrl_c_interrupts)
4410 g_fCtrlCPressed = TRUE;
4411 return TRUE;
4412
4413 case CTRL_BREAK_EVENT:
4414 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004415 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004416 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004417 ir.EventType = KEY_EVENT;
4418 ir.Event.KeyEvent.bKeyDown = TRUE;
4419 ir.Event.KeyEvent.wRepeatCount = 1;
4420 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4421 ir.Event.KeyEvent.wVirtualScanCode = 0;
4422 ir.Event.KeyEvent.dwControlKeyState = 0;
4423 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4424 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004425 return TRUE;
4426
Bram Moolenaar0f873732019-12-05 20:28:46 +01004427 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004428 case CTRL_CLOSE_EVENT:
4429 case CTRL_LOGOFF_EVENT:
4430 case CTRL_SHUTDOWN_EVENT:
4431 windgoto((int)Rows - 1, 0);
4432 g_fForceExit = TRUE;
4433
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004434 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435 (dwCtrlType == CTRL_CLOSE_EVENT
4436 ? _("close")
4437 : dwCtrlType == CTRL_LOGOFF_EVENT
4438 ? _("logoff")
4439 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004440# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004441 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004442# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443
Bram Moolenaar0f873732019-12-05 20:28:46 +01004444 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445
Bram Moolenaar0f873732019-12-05 20:28:46 +01004446 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004447
4448 default:
4449 return FALSE;
4450 }
4451}
4452
4453
4454/*
4455 * set the tty in (raw) ? "raw" : "cooked" mode
4456 */
4457 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004458mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004459{
4460 DWORD cmodein;
4461 DWORD cmodeout;
4462 BOOL bEnableHandler;
4463
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004464# ifdef VIMDLL
4465 if (gui.in_use)
4466 return;
4467# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004468 GetConsoleMode(g_hConIn, &cmodein);
4469 GetConsoleMode(g_hConOut, &cmodeout);
4470 if (tmode == TMODE_RAW)
4471 {
4472 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4473 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004475 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004477 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4478 }
4479 else
4480 {
4481 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4482 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004483 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004484# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004485 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4486 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004487 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004488# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004489 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004490# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004491 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492 bEnableHandler = TRUE;
4493 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004494 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495 {
4496 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4497 ENABLE_ECHO_INPUT);
4498 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4499 bEnableHandler = FALSE;
4500 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004501 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 SetConsoleMode(g_hConOut, cmodeout);
4503 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4504
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004505# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506 if (fdDump)
4507 {
4508 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4509 tmode == TMODE_RAW ? "raw" :
4510 tmode == TMODE_COOK ? "cooked" : "normal",
4511 cmodein, cmodeout);
4512 fflush(fdDump);
4513 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004515}
4516
4517
4518/*
4519 * Get the size of the current window in `Rows' and `Columns'
4520 * Return OK when size could be determined, FAIL otherwise.
4521 */
4522 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004523mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524{
4525 CONSOLE_SCREEN_BUFFER_INFO csbi;
4526
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004527# ifdef VIMDLL
4528 if (gui.in_use)
4529 return OK;
4530# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4532 {
4533 /*
4534 * For some reason, we are trying to get the screen dimensions
4535 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4536 * variables are really intended to mean the size of Vim screen
4537 * while in termcap mode.
4538 */
4539 Rows = g_cbTermcap.Info.dwSize.Y;
4540 Columns = g_cbTermcap.Info.dwSize.X;
4541 }
4542 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4543 {
4544 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4545 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4546 }
4547 else
4548 {
4549 Rows = 25;
4550 Columns = 80;
4551 }
4552 return OK;
4553}
4554
4555/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004556 * Resize console buffer to 'COORD'
4557 */
4558 static void
4559ResizeConBuf(
4560 HANDLE hConsole,
4561 COORD coordScreen)
4562{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004563 if (use_alternate_screen_buffer)
4564 return;
4565
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004566 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4567 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004568# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004569 if (fdDump)
4570 {
4571 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4572 GetLastError());
4573 fflush(fdDump);
4574 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004575# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004576 }
4577}
4578
4579/*
4580 * Resize console window size to 'srWindowRect'
4581 */
4582 static void
4583ResizeWindow(
4584 HANDLE hConsole,
4585 SMALL_RECT srWindowRect)
4586{
4587 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4588 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004589# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004590 if (fdDump)
4591 {
4592 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4593 GetLastError());
4594 fflush(fdDump);
4595 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004596# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004597 }
4598}
4599
4600/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004601 * Set a console window to `xSize' * `ySize'
4602 */
4603 static void
4604ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004605 HANDLE hConsole,
4606 int xSize,
4607 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004608{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004609 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4610 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004612 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004613 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004614
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004615# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616 if (fdDump)
4617 {
4618 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4619 fflush(fdDump);
4620 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004621# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004622
Bram Moolenaar0f873732019-12-05 20:28:46 +01004623 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004624 coordScreen = GetLargestConsoleWindowSize(hConsole);
4625
Bram Moolenaar0f873732019-12-05 20:28:46 +01004626 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004627 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4628 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4629 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4630
4631 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4632 {
4633 int sx, sy;
4634
4635 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4636 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4637 if (sy < ySize || sx < xSize)
4638 {
4639 /*
4640 * Increasing number of lines/columns, do buffer first.
4641 * Use the maximal size in x and y direction.
4642 */
4643 if (sy < ySize)
4644 coordScreen.Y = ySize;
4645 else
4646 coordScreen.Y = sy;
4647 if (sx < xSize)
4648 coordScreen.X = xSize;
4649 else
4650 coordScreen.X = sx;
4651 SetConsoleScreenBufferSize(hConsole, coordScreen);
4652 }
4653 }
4654
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004655 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 coordScreen.X = xSize;
4657 coordScreen.Y = ySize;
4658
Bram Moolenaar2551c032018-08-23 22:38:31 +02004659 // In the new console call API, only the first time in reverse order
4660 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004661 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004662 ResizeWindow(hConsole, srWindowRect);
4663 ResizeConBuf(hConsole, coordScreen);
4664 }
4665 else
4666 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004667 // Workaround for a Windows 10 bug
4668 cursor.X = srWindowRect.Left;
4669 cursor.Y = srWindowRect.Top;
4670 SetConsoleCursorPosition(hConsole, cursor);
4671
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004672 ResizeConBuf(hConsole, coordScreen);
4673 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004674 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675 }
4676}
4677
4678
4679/*
4680 * Set the console window to `Rows' * `Columns'
4681 */
4682 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004683mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004684{
4685 COORD coordScreen;
4686
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004687# ifdef VIMDLL
4688 if (gui.in_use)
4689 return;
4690# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004691 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692 if (suppress_winsize != 0)
4693 {
4694 suppress_winsize = 2;
4695 return;
4696 }
4697
4698 if (term_console)
4699 {
4700 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4701
Bram Moolenaar0f873732019-12-05 20:28:46 +01004702 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004703 if (Rows > coordScreen.Y)
4704 Rows = coordScreen.Y;
4705 if (Columns > coordScreen.X)
4706 Columns = coordScreen.X;
4707
4708 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4709 }
4710}
4711
4712/*
4713 * Rows and/or Columns has changed.
4714 */
4715 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004716mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004717{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004718# ifdef VIMDLL
4719 if (gui.in_use)
4720 return;
4721# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4723}
4724
4725
4726/*
4727 * Called when started up, to set the winsize that was delayed.
4728 */
4729 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004730mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004731{
4732 if (suppress_winsize == 2)
4733 {
4734 suppress_winsize = 0;
4735 mch_set_shellsize();
4736 shell_resized();
4737 }
4738 suppress_winsize = 0;
4739}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004740#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004742 static BOOL
4743vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004744 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004745 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004746 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004747 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004748 PROCESS_INFORMATION *pi,
4749 LPVOID *env,
4750 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004751{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004752 BOOL ret = FALSE;
4753 WCHAR *wcmd, *wcwd = NULL;
4754
4755 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4756 if (wcmd == NULL)
4757 return FALSE;
4758 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004759 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004760 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4761 if (wcwd == NULL)
4762 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004763 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004764
4765 ret = CreateProcessW(
4766 NULL, // Executable name
4767 wcmd, // Command to execute
4768 NULL, // Process security attributes
4769 NULL, // Thread security attributes
4770 inherit_handles, // Inherit handles
4771 flags, // Creation flags
4772 env, // Environment
4773 wcwd, // Current directory
4774 (LPSTARTUPINFOW)si, // Startup information
4775 pi); // Process information
4776theend:
4777 vim_free(wcmd);
4778 vim_free(wcwd);
4779 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004780}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781
4782
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004783 static HINSTANCE
4784vim_shell_execute(
4785 char *cmd,
4786 INT n_show_cmd)
4787{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004788 HINSTANCE ret;
4789 WCHAR *wcmd;
4790
4791 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4792 if (wcmd == NULL)
4793 return (HINSTANCE) 0;
4794
4795 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4796 vim_free(wcmd);
4797 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004798}
4799
4800
Bram Moolenaar4f974752019-02-17 17:44:42 +01004801#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802
4803/*
4804 * Specialised version of system() for Win32 GUI mode.
4805 * This version proceeds as follows:
4806 * 1. Create a console window for use by the subprocess
4807 * 2. Run the subprocess (it gets the allocated console by default)
4808 * 3. Wait for the subprocess to terminate and get its exit code
4809 * 4. Prompt the user to press a key to close the console window
4810 */
4811 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004812mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813{
4814 STARTUPINFO si;
4815 PROCESS_INFORMATION pi;
4816 DWORD ret = 0;
4817 HWND hwnd = GetFocus();
4818
4819 si.cb = sizeof(si);
4820 si.lpReserved = NULL;
4821 si.lpDesktop = NULL;
4822 si.lpTitle = NULL;
4823 si.dwFlags = STARTF_USESHOWWINDOW;
4824 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004825 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004826 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004828 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004829 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830 else
4831 si.wShowWindow = SW_SHOWNORMAL;
4832 si.cbReserved2 = 0;
4833 si.lpReserved2 = NULL;
4834
Bram Moolenaar0f873732019-12-05 20:28:46 +01004835 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004836 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004837 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4838 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004839
Bram Moolenaar0f873732019-12-05 20:28:46 +01004840 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004842# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843 int delay = 1;
4844
Bram Moolenaar0f873732019-12-05 20:28:46 +01004845 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846 for (;;)
4847 {
4848 MSG msg;
4849
K.Takatab7057bd2022-01-21 11:37:07 +00004850 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851 {
4852 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004853 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004854 delay = 1;
4855 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004856 }
4857 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4858 break;
4859
Bram Moolenaar0f873732019-12-05 20:28:46 +01004860 // We start waiting for a very short time and then increase it, so
4861 // that we respond quickly when the process is quick, and don't
4862 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004863 if (delay < 50)
4864 delay += 10;
4865 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004866# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004868# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004869
Bram Moolenaar0f873732019-12-05 20:28:46 +01004870 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871 GetExitCodeProcess(pi.hProcess, &ret);
4872 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873
Bram Moolenaar0f873732019-12-05 20:28:46 +01004874 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875 CloseHandle(pi.hThread);
4876 CloseHandle(pi.hProcess);
4877
Bram Moolenaar0f873732019-12-05 20:28:46 +01004878 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4880
4881 return ret;
4882}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004883
4884/*
4885 * Thread launched by the gui to send the current buffer data to the
4886 * process. This way avoid to hang up vim totally if the children
4887 * process take a long time to process the lines.
4888 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004889 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004890sub_process_writer(LPVOID param)
4891{
4892 HANDLE g_hChildStd_IN_Wr = param;
4893 linenr_T lnum = curbuf->b_op_start.lnum;
4894 DWORD len = 0;
4895 DWORD l;
4896 char_u *lp = ml_get(lnum);
4897 char_u *s;
4898 int written = 0;
4899
4900 for (;;)
4901 {
4902 l = (DWORD)STRLEN(lp + written);
4903 if (l == 0)
4904 len = 0;
4905 else if (lp[written] == NL)
4906 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004907 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004908 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4909 }
4910 else
4911 {
4912 s = vim_strchr(lp + written, NL);
4913 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4914 s == NULL ? l : (DWORD)(s - (lp + written)),
4915 &len, NULL);
4916 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004917 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004918 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004919 // Finished a line, add a NL, unless this line should not have
4920 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004921 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004922 || (!curbuf->b_p_bin
4923 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004924 || (lnum != curbuf->b_no_eol_lnum
4925 && (lnum != curbuf->b_ml.ml_line_count
4926 || curbuf->b_p_eol)))
4927 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004928 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4929 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004930 }
4931
4932 ++lnum;
4933 if (lnum > curbuf->b_op_end.lnum)
4934 break;
4935
4936 lp = ml_get(lnum);
4937 written = 0;
4938 }
4939 else if (len > 0)
4940 written += len;
4941 }
4942
Bram Moolenaar0f873732019-12-05 20:28:46 +01004943 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004944 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004945 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004946}
4947
4948
Bram Moolenaar0f873732019-12-05 20:28:46 +01004949# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004950
4951/*
4952 * This function read from the children's stdout and write the
4953 * data on screen or in the buffer accordingly.
4954 */
4955 static void
4956dump_pipe(int options,
4957 HANDLE g_hChildStd_OUT_Rd,
4958 garray_T *ga,
4959 char_u buffer[],
4960 DWORD *buffer_off)
4961{
4962 DWORD availableBytes = 0;
4963 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004964 int ret;
4965 DWORD len;
4966 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004967
Bram Moolenaar0f873732019-12-05 20:28:46 +01004968 // we query the pipe to see if there is any data to read
4969 // to avoid to perform a blocking read
4970 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4971 NULL, // optional buffer
4972 0, // buffer size
4973 NULL, // number of read bytes
4974 &availableBytes, // available bytes total
4975 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004976
Bram Moolenaar0f873732019-12-05 20:28:46 +01004977 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004978 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004979 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004980 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004981 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004982 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004983
Bram Moolenaar0f873732019-12-05 20:28:46 +01004984 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004985 if (len == 0)
4986 break;
4987
4988 availableBytes -= len;
4989
4990 if (options & SHELL_READ)
4991 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004992 // Do NUL -> NL translation, append NL separated
4993 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004994 for (i = 0; i < len; ++i)
4995 {
4996 if (buffer[i] == NL)
4997 append_ga_line(ga);
4998 else if (buffer[i] == NUL)
4999 ga_append(ga, NL);
5000 else
5001 ga_append(ga, buffer[i]);
5002 }
5003 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005004 else if (has_mbyte)
5005 {
5006 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005007 int c;
5008 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005009
5010 len += *buffer_off;
5011 buffer[len] = NUL;
5012
Bram Moolenaar0f873732019-12-05 20:28:46 +01005013 // Check if the last character in buffer[] is
5014 // incomplete, keep these bytes for the next
5015 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005016 for (p = buffer; p < buffer + len; p += l)
5017 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02005018 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005019 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005020 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005021 else if (MB_BYTE2LEN(*p) != l)
5022 break;
5023 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005024 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005025 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005026 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005027 if (len >= 12)
5028 ++p;
5029 else
5030 {
5031 *buffer_off = len;
5032 return;
5033 }
5034 }
5035 c = *p;
5036 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005037 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005038 if (p < buffer + len)
5039 {
5040 *p = c;
5041 *buffer_off = (DWORD)((buffer + len) - p);
5042 mch_memmove(buffer, p, *buffer_off);
5043 return;
5044 }
5045 *buffer_off = 0;
5046 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005047 else
5048 {
5049 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005050 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005051 }
5052
5053 windgoto(msg_row, msg_col);
5054 cursor_on();
5055 out_flush();
5056 }
5057}
5058
5059/*
5060 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
5061 * for communication and doesn't open any new window.
5062 */
5063 static int
5064mch_system_piped(char *cmd, int options)
5065{
5066 STARTUPINFO si;
5067 PROCESS_INFORMATION pi;
5068 DWORD ret = 0;
5069
5070 HANDLE g_hChildStd_IN_Rd = NULL;
5071 HANDLE g_hChildStd_IN_Wr = NULL;
5072 HANDLE g_hChildStd_OUT_Rd = NULL;
5073 HANDLE g_hChildStd_OUT_Wr = NULL;
5074
Bram Moolenaar0f873732019-12-05 20:28:46 +01005075 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005076 DWORD len;
5077
Bram Moolenaar0f873732019-12-05 20:28:46 +01005078 // buffer used to receive keys
5079 char_u ta_buf[BUFLEN + 1]; // TypeAHead
5080 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005081
5082 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005083 int noread_cnt = 0;
5084 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005085 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005086 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005087 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005088
5089 SECURITY_ATTRIBUTES saAttr;
5090
Bram Moolenaar0f873732019-12-05 20:28:46 +01005091 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005092 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5093 saAttr.bInheritHandle = TRUE;
5094 saAttr.lpSecurityDescriptor = NULL;
5095
5096 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005097 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005098 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005099 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005100 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005101 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005102 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005103 {
5104 CloseHandle(g_hChildStd_IN_Rd);
5105 CloseHandle(g_hChildStd_IN_Wr);
5106 CloseHandle(g_hChildStd_OUT_Rd);
5107 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005108 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005109 }
5110
5111 si.cb = sizeof(si);
5112 si.lpReserved = NULL;
5113 si.lpDesktop = NULL;
5114 si.lpTitle = NULL;
5115 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5116
Bram Moolenaar0f873732019-12-05 20:28:46 +01005117 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005118 si.hStdError = g_hChildStd_OUT_Wr;
5119 si.hStdOutput = g_hChildStd_OUT_Wr;
5120 si.hStdInput = g_hChildStd_IN_Rd;
5121 si.wShowWindow = SW_HIDE;
5122 si.cbReserved2 = 0;
5123 si.lpReserved2 = NULL;
5124
5125 if (options & SHELL_READ)
5126 ga_init2(&ga, 1, BUFLEN);
5127
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005128 if (cmd != NULL)
5129 {
5130 p = (char *)vim_strsave((char_u *)cmd);
5131 if (p != NULL)
5132 unescape_shellxquote((char_u *)p, p_sxe);
5133 else
5134 p = cmd;
5135 }
5136
Bram Moolenaar0f873732019-12-05 20:28:46 +01005137 // Now, run the command.
5138 // About "Inherit handles" being TRUE: this command can be litigious,
5139 // handle inheritance was deactivated for pending temp file, but, if we
5140 // deactivate it, the pipes don't work for some reason.
Yegappan Lakshmanane89aef32025-05-14 20:31:55 +02005141 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5142 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005143
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005144 if (p != cmd)
5145 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005146
Bram Moolenaar0f873732019-12-05 20:28:46 +01005147 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005148 CloseHandle(g_hChildStd_IN_Rd);
5149 CloseHandle(g_hChildStd_OUT_Wr);
5150
5151 if (options & SHELL_WRITE)
5152 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005153 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005154 _beginthreadex(NULL, // security attributes
5155 0, // default stack size
5156 sub_process_writer, // function to be executed
5157 g_hChildStd_IN_Wr, // parameter
5158 0, // creation flag, start immediately
5159 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005160 CloseHandle(thread);
5161 g_hChildStd_IN_Wr = NULL;
5162 }
5163
Bram Moolenaar0f873732019-12-05 20:28:46 +01005164 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005165 for (;;)
5166 {
5167 MSG msg;
5168
K.Takatab7057bd2022-01-21 11:37:07 +00005169 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005170 {
5171 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005172 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005173 }
5174
Bram Moolenaar0f873732019-12-05 20:28:46 +01005175 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005176 if ((options & (SHELL_READ|SHELL_WRITE))
5177# ifdef FEAT_GUI
5178 || gui.in_use
5179# endif
5180 )
5181 {
5182 len = 0;
GuyBrush52ecc762024-02-21 20:16:38 +01005183 if (((options &
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005184 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5185 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5186# ifdef FEAT_GUI
5187 || gui.in_use
5188# endif
5189 )
5190 && (ta_len > 0 || noread_cnt > 4))
5191 {
5192 if (ta_len == 0)
5193 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005194 // Get extra characters when we don't have any. Reset the
5195 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005196 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005197 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5198 }
5199 if (ta_len > 0 || len > 0)
5200 {
5201 /*
5202 * For pipes: Check for CTRL-C: send interrupt signal to
GuyBrush1f13fcc2024-01-14 20:08:40 +01005203 * child.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005204 */
5205 if (len == 1 && cmd != NULL)
5206 {
5207 if (ta_buf[ta_len] == Ctrl_C)
5208 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005209 // Learn what exit code is expected, for
5210 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005211 TerminateProcess(pi.hProcess, 9);
5212 }
GuyBrush1f13fcc2024-01-14 20:08:40 +01005213 }
5214
5215 /*
5216 * Check for CTRL-D: EOF, close pipe to child.
5217 * Ctrl_D may be decorated by _OnChar()
5218 */
5219 if ((len == 1 || len == 4 ) && cmd != NULL)
5220 {
5221 if (ta_buf[0] == Ctrl_D
5222 || (ta_buf[0] == CSI
5223 && ta_buf[1] == KS_MODIFIER
5224 && ta_buf[3] == Ctrl_D))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005225 {
5226 CloseHandle(g_hChildStd_IN_Wr);
5227 g_hChildStd_IN_Wr = NULL;
GuyBrush1f13fcc2024-01-14 20:08:40 +01005228 len = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005229 }
5230 }
5231
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005232 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005233
5234 /*
5235 * For pipes: echo the typed characters. For a pty this
5236 * does not seem to work.
5237 */
5238 for (i = ta_len; i < ta_len + len; ++i)
5239 {
5240 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5241 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005242 else if (has_mbyte)
5243 {
5244 int l = (*mb_ptr2len)(ta_buf + i);
5245
5246 msg_outtrans_len(ta_buf + i, l);
5247 i += l - 1;
5248 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005249 else
5250 msg_outtrans_len(ta_buf + i, 1);
5251 }
5252 windgoto(msg_row, msg_col);
5253 out_flush();
5254
5255 ta_len += len;
5256
5257 /*
5258 * Write the characters to the child, unless EOF has been
5259 * typed for pipes. Write one character at a time, to
5260 * avoid losing too much typeahead. When writing buffer
5261 * lines, drop the typed characters (only check for
5262 * CTRL-C).
5263 */
5264 if (options & SHELL_WRITE)
5265 ta_len = 0;
5266 else if (g_hChildStd_IN_Wr != NULL)
5267 {
5268 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5269 1, &len, NULL);
5270 // if we are typing in, we want to keep things reactive
5271 delay = 1;
5272 if (len > 0)
5273 {
5274 ta_len -= len;
5275 mch_memmove(ta_buf, ta_buf + len, ta_len);
5276 }
5277 }
5278 }
5279 }
5280 }
5281
5282 if (ta_len)
5283 ui_inchar_undo(ta_buf, ta_len);
5284
5285 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5286 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005287 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005288 break;
5289 }
5290
5291 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005292 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005293
Bram Moolenaar0f873732019-12-05 20:28:46 +01005294 // We start waiting for a very short time and then increase it, so
5295 // that we respond quickly when the process is quick, and don't
5296 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005297 if (delay < 50)
5298 delay += 10;
5299 }
5300
Bram Moolenaar0f873732019-12-05 20:28:46 +01005301 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005302 CloseHandle(g_hChildStd_OUT_Rd);
5303 if (g_hChildStd_IN_Wr != NULL)
5304 CloseHandle(g_hChildStd_IN_Wr);
5305
5306 WaitForSingleObject(pi.hProcess, INFINITE);
5307
Bram Moolenaar0f873732019-12-05 20:28:46 +01005308 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005309 GetExitCodeProcess(pi.hProcess, &ret);
5310
5311 if (options & SHELL_READ)
5312 {
5313 if (ga.ga_len > 0)
5314 {
5315 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005316 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005317 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5318 }
5319 else
5320 curbuf->b_no_eol_lnum = 0;
5321 ga_clear(&ga);
5322 }
5323
Bram Moolenaar0f873732019-12-05 20:28:46 +01005324 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005325 CloseHandle(pi.hThread);
5326 CloseHandle(pi.hProcess);
5327
5328 return ret;
5329}
5330
5331 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005332mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005333{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005334 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005335 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005336 return mch_system_piped(cmd, options);
5337 else
5338 return mch_system_classic(cmd, options);
5339}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005340#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005341
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005342#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005343 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005344mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005345{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005346 int ret;
5347 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005348 char_u *buf;
5349 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005350
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005351 // If the command starts and ends with double quotes, enclose the command
5352 // in parentheses.
5353 len = STRLEN(cmd);
5354 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5355 {
5356 len += 3;
5357 buf = alloc(len);
5358 if (buf == NULL)
5359 return -1;
5360 vim_snprintf((char *)buf, len, "(%s)", cmd);
5361 wcmd = enc_to_utf16(buf, NULL);
5362 free(buf);
5363 }
5364 else
5365 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5366
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005367 if (wcmd == NULL)
5368 return -1;
5369
5370 ret = _wsystem(wcmd);
5371 vim_free(wcmd);
5372 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005373}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005374
5375#endif
5376
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005377 static int
5378mch_system(char *cmd, int options)
5379{
5380#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005381 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005382 return mch_system_g(cmd, options);
5383 else
5384 return mch_system_c(cmd, options);
5385#elif defined(FEAT_GUI_MSWIN)
5386 return mch_system_g(cmd, options);
5387#else
5388 return mch_system_c(cmd, options);
5389#endif
5390}
5391
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005392#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5393/*
5394 * Use a terminal window to run a shell command in.
5395 */
5396 static int
5397mch_call_shell_terminal(
5398 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005399 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005400{
5401 jobopt_T opt;
5402 char_u *newcmd = NULL;
5403 typval_T argvar[2];
5404 long_u cmdlen;
5405 int retval = -1;
5406 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005407 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005408 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005409 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005410
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005411 if (cmd == NULL)
5412 cmdlen = STRLEN(p_sh) + 1;
5413 else
5414 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005415 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005416 if (newcmd == NULL)
5417 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005418 if (cmd == NULL)
5419 {
5420 STRCPY(newcmd, p_sh);
5421 ch_log(NULL, "starting terminal to run a shell");
5422 }
5423 else
5424 {
5425 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5426 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5427 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005428
5429 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005430
5431 argvar[0].v_type = VAR_STRING;
5432 argvar[0].vval.v_string = newcmd;
5433 argvar[1].v_type = VAR_UNKNOWN;
5434 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005435 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005436 {
5437 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005438 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005439 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005440
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005441 job = term_getjob(buf->b_term);
5442 ++job->jv_refcount;
5443
Bram Moolenaar0f873732019-12-05 20:28:46 +01005444 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005445 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005446 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005447 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005448 // Only do this when a window was found for "buf".
5449 clear_oparg(&oa);
5450 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005451 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005452 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5453 {
5454 // If terminal_loop() returns OK we got a key that is handled
5455 // in Normal model. We don't do redrawing anyway.
5456 if (terminal_loop(TRUE) == OK)
5457 normal_cmd(&oa, TRUE);
5458 }
5459 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005460 normal_cmd(&oa, TRUE);
5461 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005462 retval = job->jv_exitval;
5463 ch_log(NULL, "system command finished");
5464
5465 job_unref(job);
5466
5467 // restore curwin/curbuf and a few other things
5468 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005469 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005470
5471 wait_return(TRUE);
5472 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5473
5474 vim_free(newcmd);
5475 return retval;
5476}
5477#endif
5478
Bram Moolenaar071d4272004-06-13 20:20:40 +00005479/*
5480 * Either execute a command by calling the shell or start a new shell
5481 */
5482 int
5483mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005484 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005485 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005486{
5487 int x = 0;
5488 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005489 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005490
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005491#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005492 ch_log(NULL, "executing shell command: %s", cmd);
5493#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005494 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005495 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005496 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005497 if (cmd == NULL)
5498 wcscat(szShellTitle, L" :sh");
5499 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005500 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005501 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005502
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005503 if (wn != NULL)
5504 {
5505 wcscat(szShellTitle, L" - !");
5506 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005507 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005508 wcscat(szShellTitle, wn);
5509 SetConsoleTitleW(szShellTitle);
5510 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005511 }
5512 }
5513 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005514
5515 out_flush();
5516
5517#ifdef MCH_WRITE_DUMP
5518 if (fdDump)
5519 {
5520 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5521 fflush(fdDump);
5522 }
5523#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005524#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005525 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005526 if (
5527# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005528 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005529# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005530 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005531 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5532 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005533 char_u *cmdbase = cmd;
5534
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005535 if (cmdbase != NULL)
5536 // Skip a leading quote and (.
5537 while (*cmdbase == '"' || *cmdbase == '(')
5538 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005539
5540 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005541 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5542 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005543 {
5544 // Use a terminal window to run the command in.
5545 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005546 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005547 return x;
5548 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005549 }
5550#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005551
5552 /*
5553 * Catch all deadly signals while running the external command, because a
5554 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5555 */
ichizok378447f2023-05-11 22:25:42 +01005556 mch_signal(SIGINT, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005557 mch_signal(SIGBREAK, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005558 mch_signal(SIGILL, SIG_IGN);
5559 mch_signal(SIGFPE, SIG_IGN);
5560 mch_signal(SIGSEGV, SIG_IGN);
5561 mch_signal(SIGTERM, SIG_IGN);
5562 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563
5564 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005565 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566
5567 if (cmd == NULL)
5568 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005569 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005570 }
5571 else
5572 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005573 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005574 char_u *newcmd = NULL;
5575 char_u *cmdbase = cmd;
5576 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005577
Bram Moolenaar0f873732019-12-05 20:28:46 +01005578 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005579 if (*cmdbase == '"' )
5580 ++cmdbase;
5581 if (*cmdbase == '(')
5582 ++cmdbase;
5583
Bram Moolenaar1c465442017-03-12 20:10:05 +01005584 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005585 {
5586 STARTUPINFO si;
5587 PROCESS_INFORMATION pi;
5588 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005589 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005590 char_u *p;
5591
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005592 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005593 si.cb = sizeof(si);
5594 si.lpReserved = NULL;
5595 si.lpDesktop = NULL;
5596 si.lpTitle = NULL;
5597 si.dwFlags = 0;
5598 si.cbReserved2 = 0;
5599 si.lpReserved2 = NULL;
5600
5601 cmdbase = skipwhite(cmdbase + 5);
5602 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005603 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005604 {
5605 cmdbase = skipwhite(cmdbase + 4);
5606 si.dwFlags = STARTF_USESHOWWINDOW;
5607 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005608 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005609 }
5610 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005611 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005612 {
5613 cmdbase = skipwhite(cmdbase + 2);
5614 flags = CREATE_NO_WINDOW;
5615 si.dwFlags = STARTF_USESTDHANDLES;
5616 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005617 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005618 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005619 NULL, // Security att.
5620 OPEN_EXISTING, // Open flags
5621 FILE_ATTRIBUTE_NORMAL, // File att.
5622 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005623 si.hStdOutput = si.hStdInput;
5624 si.hStdError = si.hStdInput;
5625 }
5626
Bram Moolenaar0f873732019-12-05 20:28:46 +01005627 // Remove a trailing ", ) and )" if they have a match
5628 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005629 if (cmdbase > cmd)
5630 {
5631 p = cmdbase + STRLEN(cmdbase);
5632 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5633 *--p = NUL;
5634 if (p > cmdbase && p[-1] == ')'
5635 && (*cmd =='(' || cmd[1] == '('))
5636 *--p = NUL;
5637 }
5638
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005639 newcmd = cmdbase;
5640 unescape_shellxquote(cmdbase, p_sxe);
5641
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005642 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005643 * If creating new console, arguments are passed to the
5644 * 'cmd.exe' as-is. If it's not, arguments are not treated
5645 * correctly for current 'cmd.exe'. So unescape characters in
5646 * shellxescape except '|' for avoiding to be treated as
5647 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005648 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005649 if (flags != CREATE_NEW_CONSOLE)
5650 {
5651 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005652 char_u *cmd_shell = mch_getenv("COMSPEC");
5653
5654 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005655 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005656
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005657 subcmd = vim_strsave_escaped_ext(cmdbase,
5658 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005659 if (subcmd != NULL)
5660 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005661 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005662 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005663 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005664 if (newcmd != NULL)
5665 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005666 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005667 else
5668 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005669 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005670 }
5671 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005672
5673 /*
5674 * Now, start the command as a process, so that it doesn't
5675 * inherit our handles which causes unpleasant dangling swap
5676 * files if we exit before the spawned process
5677 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005678 if (vim_create_process((char *)newcmd, FALSE, flags,
5679 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005680 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005681 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5682 > (HINSTANCE)32)
5683 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005684 else
5685 {
5686 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005687#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005688# ifdef VIMDLL
5689 if (gui.in_use)
5690# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005691 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005692#endif
5693 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005694
5695 if (newcmd != cmdbase)
5696 vim_free(newcmd);
5697
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005698 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005699 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005700 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005701 CloseHandle(si.hStdInput);
5702 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005703 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005704 CloseHandle(pi.hThread);
5705 CloseHandle(pi.hProcess);
5706 }
5707 else
5708 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005709 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005710#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005711 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005712 (!s_dont_use_vimrun && p_stmp ?
John Marriott9cb27a52025-06-08 16:05:53 +02005713 vimrun_path.length : STRLEN(p_sh) + STRLEN(p_shcf))
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005714 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005716 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005717
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005718 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005719 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005721#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005722 if (
5723# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005724 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005725# endif
5726 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005727 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005728 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5729 "External commands will not pause after completion.\n"
5730 "See :help win32-vimrun for more information.");
5731 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005732 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5733 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005734
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005735 if (wmsg != NULL && wtitle != NULL)
5736 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5737 vim_free(wmsg);
5738 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005739 need_vimrun_warning = FALSE;
5740 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005741 if (
5742# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005743 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005744# endif
5745 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005746 // Use vimrun to execute the command. It opens a console
5747 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005748 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
John Marriott9cb27a52025-06-08 16:05:53 +02005749 vimrun_path.string,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750 (msg_silent != 0 || (options & SHELL_DOOUT))
5751 ? "-s " : "",
5752 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005753 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005754# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005755 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005756# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005757 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005758 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005759 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5760 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005761 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005762#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005763 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005764 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005765 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005766 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 }
5769 }
5770
5771 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005772 {
5773 // The shell may have messed with the mode, always set it.
5774 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005775 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005776 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777
Bram Moolenaar0f873732019-12-05 20:28:46 +01005778 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005780#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005781 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005782 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005783#endif
5784 )
5785 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005786 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787 msg_putchar('\n');
5788 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790
ichizok378447f2023-05-11 22:25:42 +01005791 mch_signal(SIGINT, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005792 mch_signal(SIGBREAK, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005793 mch_signal(SIGILL, SIG_DFL);
5794 mch_signal(SIGFPE, SIG_DFL);
5795 mch_signal(SIGSEGV, SIG_DFL);
5796 mch_signal(SIGTERM, SIG_DFL);
5797 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798
5799 return x;
5800}
5801
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005802#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005803 static HANDLE
5804job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005805 char_u *fname,
5806 DWORD dwDesiredAccess,
5807 DWORD dwShareMode,
5808 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5809 DWORD dwCreationDisposition,
5810 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005811{
5812 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005813 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005814
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005815 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005816 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005817 return INVALID_HANDLE_VALUE;
5818
5819 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5820 lpSecurityAttributes, dwCreationDisposition,
5821 dwFlagsAndAttributes, NULL);
5822 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005823 return h;
5824}
5825
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005826/*
5827 * Turn the dictionary "env" into a NUL separated list that can be used as the
5828 * environment argument of vim_create_process().
5829 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005830 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005831win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005832{
5833 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005834 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005835 LPVOID base = GetEnvironmentStringsW();
5836
Bram Moolenaar0f873732019-12-05 20:28:46 +01005837 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005838 if (ga_grow(gap, 1) == FAIL)
5839 return;
5840
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005841 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005842 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005843 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005844 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005845 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005846 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005847 typval_T *item = &dict_lookup(hi)->di_tv;
5848 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005849 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005850 --todo;
5851 if (wkey != NULL && wval != NULL)
5852 {
5853 size_t n;
5854 size_t lkey = wcslen(wkey);
5855 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005856
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005857 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005858 continue;
5859 for (n = 0; n < lkey; n++)
5860 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5861 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5862 for (n = 0; n < lval; n++)
5863 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5864 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5865 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005866 vim_free(wkey);
5867 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005868 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005869 }
5870 }
5871
Bram Moolenaar355757a2020-02-10 22:06:32 +01005872 if (base)
5873 {
5874 WCHAR *p = (WCHAR*) base;
5875
5876 // for last \0
5877 if (ga_grow(gap, 1) == FAIL)
5878 return;
5879
5880 while (*p != 0 || *(p + 1) != 0)
5881 {
5882 if (ga_grow(gap, 1) == OK)
5883 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5884 p++;
5885 }
Ken Takataad29f6a2023-09-16 13:56:02 +02005886 FreeEnvironmentStringsW(base);
Bram Moolenaar355757a2020-02-10 22:06:32 +01005887 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5888 }
5889
Bram Moolenaar493359e2018-06-12 20:25:52 +02005890# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005891 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005892# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005893 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005894 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005895# endif
5896# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005897 char_u *version = get_vim_var_str(VV_VERSION);
5898 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005899# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005900 // size of "VIM_SERVERNAME=" and value,
5901 // plus "VIM_TERMINAL=" and value,
5902 // plus two terminating NULs
5903 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005904# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005905 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005906# endif
5907# ifdef FEAT_TERMINAL
5908 + 13 + version_len + 2
5909# endif
5910 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005911
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005912 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005913 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005914# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005915 for (n = 0; n < 15; n++)
5916 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5917 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005918 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005919 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5920 (WCHAR)servername[n];
5921 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005922# endif
5923# ifdef FEAT_TERMINAL
5924 if (is_terminal)
5925 {
5926 for (n = 0; n < 13; n++)
5927 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5928 (WCHAR)"VIM_TERMINAL="[n];
5929 for (n = 0; n < version_len; n++)
5930 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5931 (WCHAR)version[n];
5932 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5933 }
5934# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005935 }
5936 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005937# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005938}
5939
Bram Moolenaarb091f302019-01-19 14:37:00 +01005940/*
5941 * Create a pair of pipes.
5942 * Return TRUE for success, FALSE for failure.
5943 */
5944 static BOOL
5945create_pipe_pair(HANDLE handles[2])
5946{
5947 static LONG s;
5948 char name[64];
5949 SECURITY_ATTRIBUTES sa;
5950
5951 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5952 GetCurrentProcessId(),
5953 InterlockedIncrement(&s));
5954
5955 // Create named pipe. Max size of named pipe is 65535.
5956 handles[1] = CreateNamedPipe(
5957 name,
5958 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5959 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005960 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005961
5962 if (handles[1] == INVALID_HANDLE_VALUE)
5963 return FALSE;
5964
5965 sa.nLength = sizeof(sa);
5966 sa.bInheritHandle = TRUE;
5967 sa.lpSecurityDescriptor = NULL;
5968
5969 handles[0] = CreateFile(name,
5970 FILE_GENERIC_READ,
5971 FILE_SHARE_READ, &sa,
5972 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5973
5974 if (handles[0] == INVALID_HANDLE_VALUE)
5975 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005976 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005977 return FALSE;
5978 }
5979
5980 return TRUE;
5981}
5982
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005983 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005984mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005985{
5986 STARTUPINFO si;
5987 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005988 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005989 SECURITY_ATTRIBUTES saAttr;
5990 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005991 HANDLE ifd[2];
5992 HANDLE ofd[2];
5993 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005994 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005995
5996 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5997 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5998 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5999 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
6000 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
6001 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
6002 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
6003
6004 if (use_out_for_err && use_null_for_out)
6005 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01006006
6007 ifd[0] = INVALID_HANDLE_VALUE;
6008 ifd[1] = INVALID_HANDLE_VALUE;
6009 ofd[0] = INVALID_HANDLE_VALUE;
6010 ofd[1] = INVALID_HANDLE_VALUE;
6011 efd[0] = INVALID_HANDLE_VALUE;
6012 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00006013 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006014
Bram Moolenaar14207f42016-10-27 21:13:10 +02006015 jo = CreateJobObject(NULL, NULL);
6016 if (jo == NULL)
6017 {
6018 job->jv_status = JOB_FAILED;
6019 goto failed;
6020 }
6021
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006022 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006023 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006024
Bram Moolenaar76467df2016-02-12 19:30:26 +01006025 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006026 ZeroMemory(&si, sizeof(si));
6027 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01006028 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006029 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006030
Bram Moolenaard8070362016-02-15 21:56:54 +01006031 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
6032 saAttr.bInheritHandle = TRUE;
6033 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006034
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006035 if (use_file_for_in)
6036 {
6037 char_u *fname = options->jo_io_name[PART_IN];
6038
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006039 ifd[0] = job_io_file_open(fname, GENERIC_READ,
6040 FILE_SHARE_READ | FILE_SHARE_WRITE,
6041 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
6042 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01006043 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006044 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01006045 goto failed;
6046 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006047 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01006048 else if (!use_null_for_in
6049 && (!create_pipe_pair(ifd)
6050 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006051 goto failed;
6052
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006053 if (use_file_for_out)
6054 {
6055 char_u *fname = options->jo_io_name[PART_OUT];
6056
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006057 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
6058 FILE_SHARE_READ | FILE_SHARE_WRITE,
6059 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6060 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006061 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006062 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006063 goto failed;
6064 }
6065 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006066 else if (!use_null_for_out &&
6067 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006068 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006069 goto failed;
6070
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006071 if (use_file_for_err)
6072 {
6073 char_u *fname = options->jo_io_name[PART_ERR];
6074
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006075 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
6076 FILE_SHARE_READ | FILE_SHARE_WRITE,
6077 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6078 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006079 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006080 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006081 goto failed;
6082 }
6083 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006084 else if (!use_out_for_err && !use_null_for_err &&
6085 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006086 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01006087 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006088
Bram Moolenaard8070362016-02-15 21:56:54 +01006089 si.dwFlags |= STARTF_USESTDHANDLES;
6090 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006091 si.hStdOutput = ofd[1];
6092 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
6093
6094 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
6095 {
Bram Moolenaarde279892016-03-11 22:19:44 +01006096 if (options->jo_set & JO_CHANNEL)
6097 {
6098 channel = options->jo_channel;
6099 if (channel != NULL)
6100 ++channel->ch_refcount;
6101 }
6102 else
6103 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006104 if (channel == NULL)
6105 goto failed;
6106 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006107
6108 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006109 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006110 CREATE_DEFAULT_ERROR_MODE |
6111 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006112 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006113 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006114 &si, &pi,
6115 ga.ga_data,
6116 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006117 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006118 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006119 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006120 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006121 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006122
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006123 ga_clear(&ga);
6124
Bram Moolenaar14207f42016-10-27 21:13:10 +02006125 if (!AssignProcessToJobObject(jo, pi.hProcess))
6126 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006127 // if failing, switch the way to terminate
6128 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006129 CloseHandle(jo);
6130 jo = NULL;
6131 }
6132 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006133 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006134 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006135 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006136 job->jv_status = JOB_STARTED;
6137
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006138 CloseHandle(ifd[0]);
6139 CloseHandle(ofd[1]);
6140 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006141 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006142
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006143 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006144 if (channel != NULL)
6145 {
6146 channel_set_pipes(channel,
6147 use_file_for_in || use_null_for_in
6148 ? INVALID_FD : (sock_T)ifd[1],
6149 use_file_for_out || use_null_for_out
6150 ? INVALID_FD : (sock_T)ofd[0],
6151 use_out_for_err || use_file_for_err || use_null_for_err
6152 ? INVALID_FD : (sock_T)efd[0]);
6153 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006154 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006155 return;
6156
6157failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006158 CloseHandle(ifd[0]);
6159 CloseHandle(ofd[0]);
6160 CloseHandle(efd[0]);
6161 CloseHandle(ifd[1]);
6162 CloseHandle(ofd[1]);
6163 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006164 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006165 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006166}
6167
6168 char *
6169mch_job_status(job_T *job)
6170{
6171 DWORD dwExitCode = 0;
6172
Bram Moolenaar76467df2016-02-12 19:30:26 +01006173 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6174 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006175 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006176 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006177 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006178 {
6179 ch_log(job->jv_channel, "Job ended");
6180 job->jv_status = JOB_ENDED;
6181 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006182 return "dead";
6183 }
6184 return "run";
6185}
6186
Bram Moolenaar97792de2016-10-15 18:36:49 +02006187 job_T *
6188mch_detect_ended_job(job_T *job_list)
6189{
6190 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6191 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6192 job_T *job = job_list;
6193
6194 while (job != NULL)
6195 {
6196 DWORD n;
6197 DWORD result;
6198
6199 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6200 && job != NULL; job = job->jv_next)
6201 {
6202 if (job->jv_status == JOB_STARTED)
6203 {
6204 jobHandles[n] = job->jv_proc_info.hProcess;
6205 jobArray[n] = job;
6206 ++n;
6207 }
6208 }
6209 if (n == 0)
6210 continue;
6211 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6212 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6213 {
6214 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6215
6216 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6217 return wait_job;
6218 }
6219 }
6220 return NULL;
6221}
6222
Bram Moolenaarfb630902016-10-29 14:55:00 +02006223 static BOOL
6224terminate_all(HANDLE process, int code)
6225{
6226 PROCESSENTRY32 pe;
6227 HANDLE h = INVALID_HANDLE_VALUE;
6228 DWORD pid = GetProcessId(process);
6229
6230 if (pid != 0)
6231 {
6232 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6233 if (h != INVALID_HANDLE_VALUE)
6234 {
6235 pe.dwSize = sizeof(PROCESSENTRY32);
6236 if (!Process32First(h, &pe))
6237 goto theend;
6238
6239 do
6240 {
6241 if (pe.th32ParentProcessID == pid)
6242 {
6243 HANDLE ph = OpenProcess(
6244 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6245 if (ph != NULL)
6246 {
6247 terminate_all(ph, code);
6248 CloseHandle(ph);
6249 }
6250 }
6251 } while (Process32Next(h, &pe));
6252
6253 CloseHandle(h);
6254 }
6255 }
6256
6257theend:
6258 return TerminateProcess(process, code);
6259}
6260
6261/*
6262 * Send a (deadly) signal to "job".
6263 * Return FAIL if it didn't work.
6264 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006265 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006266mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006267{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006268 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006269
Bram Moolenaar923d9262016-02-25 20:56:01 +01006270 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006271 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006272 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006273 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006274 {
6275 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6276 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006277 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006278 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006279 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006280 }
6281
6282 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6283 return FAIL;
6284 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006285 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6286 job->jv_proc_info.dwProcessId)
6287 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006288 FreeConsole();
6289 return ret;
6290}
6291
6292/*
6293 * Clear the data related to "job".
6294 */
6295 void
6296mch_clear_job(job_T *job)
6297{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006298 if (job->jv_status == JOB_FAILED)
6299 return;
6300
6301 if (job->jv_job_object != NULL)
6302 CloseHandle(job->jv_job_object);
6303 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006304}
6305#endif
6306
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006308#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309
6310/*
6311 * Start termcap mode
6312 */
6313 static void
6314termcap_mode_start(void)
6315{
6316 DWORD cmodein;
6317
6318 if (g_fTermcapMode)
6319 return;
6320
6321 SaveConsoleBuffer(&g_cbNonTermcap);
6322
6323 if (g_cbTermcap.IsValid)
6324 {
6325 /*
6326 * We've been in termcap mode before. Restore certain screen
6327 * characteristics, including the buffer size and the window
6328 * size. Since we will be redrawing the screen, we don't need
6329 * to restore the actual contents of the buffer.
6330 */
6331 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006332 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6334 Rows = g_cbTermcap.Info.dwSize.Y;
6335 Columns = g_cbTermcap.Info.dwSize.X;
6336 }
6337 else
6338 {
6339 /*
6340 * This is our first time entering termcap mode. Clear the console
6341 * screen buffer, and resize the buffer to match the current window
6342 * size. We will use this as the size of our editing environment.
6343 */
6344 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006345 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6347 }
6348
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350
6351 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006353 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006355 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6356 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006357 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006358 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006360 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6361 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006363 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364
6365 redraw_later_clear();
6366 g_fTermcapMode = TRUE;
6367}
6368
6369
6370/*
6371 * End termcap mode
6372 */
6373 static void
6374termcap_mode_end(void)
6375{
6376 DWORD cmodein;
6377 ConsoleBuffer *cb;
6378 COORD coord;
6379 DWORD dwDummy;
6380
6381 if (!g_fTermcapMode)
6382 return;
6383
6384 SaveConsoleBuffer(&g_cbTermcap);
6385
6386 GetConsoleMode(g_hConIn, &cmodein);
6387 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006388 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6389 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006391# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006392 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006393# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006394 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006395# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006396 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006397 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006398
William Breslerded59132024-10-08 21:30:48 +02006399 // Switch back to main screen buffer.
6400 if (exiting && use_alternate_screen_buffer)
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +02006401 vtp_printf("\033[?1049l");
William Breslerded59132024-10-08 21:30:48 +02006402
Christopher Plewright1140b512022-11-12 18:46:05 +00006403 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404 {
6405 /*
6406 * Clear anything that happens to be on the current line.
6407 */
6408 coord.X = 0;
6409 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006410 FillConsoleOutputCharacter(g_hConOut, ' ',
6411 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006412 /*
6413 * The following is just for aesthetics. If we are exiting without
6414 * restoring the screen, then we want to have a prompt string
6415 * appear at the bottom line. However, the command interpreter
6416 * seems to always advance the cursor one line before displaying
6417 * the prompt string, which causes the screen to scroll. To
6418 * counter this, move the cursor up one line before exiting.
6419 */
6420 if (exiting && !p_rs)
6421 coord.Y--;
6422 /*
6423 * Position the cursor at the leftmost column of the desired row.
6424 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006425 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006426 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006427 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428 g_fTermcapMode = FALSE;
6429}
Christopher Plewright38804d62022-11-09 23:55:52 +00006430#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006431
6432
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006433#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006434 void
6435mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006436 char_u *s UNUSED,
6437 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006438{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006439 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006440}
6441
6442#else
6443
6444/*
6445 * clear `n' chars, starting from `coord'
6446 */
6447 static void
6448clear_chars(
6449 COORD coord,
6450 DWORD n)
6451{
Christopher Plewright38804d62022-11-09 23:55:52 +00006452 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006453 {
6454 DWORD dwDummy;
6455
6456 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6457 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6458 &dwDummy);
6459 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006460 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006461 {
6462 set_console_color_rgb();
6463 gotoxy(coord.X + 1, coord.Y + 1);
6464 vtp_printf("\033[%dX", n);
6465 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466}
6467
6468
6469/*
6470 * Clear the screen
6471 */
6472 static void
6473clear_screen(void)
6474{
6475 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006476
Christopher Plewright38804d62022-11-09 23:55:52 +00006477 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006478 clear_chars(g_coord, Rows * Columns);
6479 else
6480 {
6481 set_console_color_rgb();
6482 gotoxy(1, 1);
6483 vtp_printf("\033[2J");
6484 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485}
6486
6487
6488/*
6489 * Clear to end of display
6490 */
6491 static void
6492clear_to_end_of_display(void)
6493{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006494 COORD save = g_coord;
6495
Christopher Plewright38804d62022-11-09 23:55:52 +00006496 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006497 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006499 else
6500 {
6501 set_console_color_rgb();
6502 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6503 vtp_printf("\033[0J");
6504
6505 gotoxy(save.X + 1, save.Y + 1);
6506 g_coord = save;
6507 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508}
6509
6510
6511/*
6512 * Clear to end of line
6513 */
6514 static void
6515clear_to_end_of_line(void)
6516{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006517 COORD save = g_coord;
6518
Christopher Plewright38804d62022-11-09 23:55:52 +00006519 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006520 clear_chars(g_coord, Columns - g_coord.X);
6521 else
6522 {
6523 set_console_color_rgb();
6524 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6525 vtp_printf("\033[0K");
6526
6527 gotoxy(save.X + 1, save.Y + 1);
6528 g_coord = save;
6529 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530}
6531
6532
6533/*
6534 * Scroll the scroll region up by `cLines' lines
6535 */
6536 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006537scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538{
6539 COORD oldcoord = g_coord;
6540
6541 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6542 delete_lines(cLines);
6543
6544 g_coord = oldcoord;
6545}
6546
6547
6548/*
6549 * Set the scroll region
6550 */
6551 static void
6552set_scroll_region(
6553 unsigned left,
6554 unsigned top,
6555 unsigned right,
6556 unsigned bottom)
6557{
6558 if (left >= right
6559 || top >= bottom
6560 || right > (unsigned) Columns - 1
6561 || bottom > (unsigned) Rows - 1)
6562 return;
6563
6564 g_srScrollRegion.Left = left;
6565 g_srScrollRegion.Top = top;
6566 g_srScrollRegion.Right = right;
6567 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006568}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006569
Bram Moolenaar6982f422019-02-16 16:48:01 +01006570 static void
6571set_scroll_region_tb(
6572 unsigned top,
6573 unsigned bottom)
6574{
6575 if (top >= bottom || bottom > (unsigned)Rows - 1)
6576 return;
6577
6578 g_srScrollRegion.Top = top;
6579 g_srScrollRegion.Bottom = bottom;
6580}
6581
6582 static void
6583set_scroll_region_lr(
6584 unsigned left,
6585 unsigned right)
6586{
6587 if (left >= right || right > (unsigned)Columns - 1)
6588 return;
6589
6590 g_srScrollRegion.Left = left;
6591 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592}
6593
6594
6595/*
6596 * Insert `cLines' lines at the current cursor position
6597 */
6598 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006599insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006601 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 COORD dest;
6603 CHAR_INFO fill;
6604
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006605 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6606
Bram Moolenaar6982f422019-02-16 16:48:01 +01006607 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608 dest.Y = g_coord.Y + cLines;
6609
Bram Moolenaar6982f422019-02-16 16:48:01 +01006610 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006611 source.Top = g_coord.Y;
6612 source.Right = g_srScrollRegion.Right;
6613 source.Bottom = g_srScrollRegion.Bottom - cLines;
6614
Bram Moolenaar6982f422019-02-16 16:48:01 +01006615 clip.Left = g_srScrollRegion.Left;
6616 clip.Top = g_coord.Y;
6617 clip.Right = g_srScrollRegion.Right;
6618 clip.Bottom = g_srScrollRegion.Bottom;
6619
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006620 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006621 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006622 fill.Attributes = g_attrCurrent;
6623 else
6624 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006626 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006627
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006628 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6629
Bram Moolenaar6982f422019-02-16 16:48:01 +01006630 // Here we have to deal with a win32 console flake: If the scroll
6631 // region looks like abc and we scroll c to a and fill with d we get
6632 // cbd... if we scroll block c one line at a time to a, we get cdd...
6633 // vim expects cdd consistently... So we have to deal with that
6634 // here... (this also occurs scrolling the same way in the other
6635 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636
6637 if (source.Bottom < dest.Y)
6638 {
6639 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006640 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641
Bram Moolenaar6982f422019-02-16 16:48:01 +01006642 coord.X = source.Left;
6643 for (i = clip.Top; i < dest.Y; ++i)
6644 {
6645 coord.Y = i;
6646 clear_chars(coord, source.Right - source.Left + 1);
6647 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006649
Christopher Plewright38804d62022-11-09 23:55:52 +00006650 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006651 {
6652 COORD coord;
6653 int i;
6654
6655 coord.X = source.Left;
6656 for (i = source.Top; i < dest.Y; ++i)
6657 {
6658 coord.Y = i;
6659 clear_chars(coord, source.Right - source.Left + 1);
6660 }
6661 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662}
6663
6664
6665/*
6666 * Delete `cLines' lines at the current cursor position
6667 */
6668 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006669delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006671 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 COORD dest;
6673 CHAR_INFO fill;
6674 int nb;
6675
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006676 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6677
Bram Moolenaar6982f422019-02-16 16:48:01 +01006678 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 dest.Y = g_coord.Y;
6680
Bram Moolenaar6982f422019-02-16 16:48:01 +01006681 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 source.Top = g_coord.Y + cLines;
6683 source.Right = g_srScrollRegion.Right;
6684 source.Bottom = g_srScrollRegion.Bottom;
6685
Bram Moolenaar6982f422019-02-16 16:48:01 +01006686 clip.Left = g_srScrollRegion.Left;
6687 clip.Top = g_coord.Y;
6688 clip.Right = g_srScrollRegion.Right;
6689 clip.Bottom = g_srScrollRegion.Bottom;
6690
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006691 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006692 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006693 fill.Attributes = g_attrCurrent;
6694 else
6695 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006697 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006698
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006699 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6700
Bram Moolenaar6982f422019-02-16 16:48:01 +01006701 // Here we have to deal with a win32 console flake; See insert_lines()
6702 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703
6704 nb = dest.Y + (source.Bottom - source.Top) + 1;
6705
6706 if (nb < source.Top)
6707 {
6708 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006709 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710
Bram Moolenaar6982f422019-02-16 16:48:01 +01006711 coord.X = source.Left;
6712 for (i = nb; i < clip.Bottom; ++i)
6713 {
6714 coord.Y = i;
6715 clear_chars(coord, source.Right - source.Left + 1);
6716 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006717 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006718
Christopher Plewright38804d62022-11-09 23:55:52 +00006719 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006720 {
6721 COORD coord;
6722 int i;
6723
6724 coord.X = source.Left;
6725 for (i = nb; i <= source.Bottom; ++i)
6726 {
6727 coord.Y = i;
6728 clear_chars(coord, source.Right - source.Left + 1);
6729 }
6730 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731}
6732
6733
6734/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006735 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736 */
6737 static void
6738gotoxy(
6739 unsigned x,
6740 unsigned y)
6741{
6742 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6743 return;
6744
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006745 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006746 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006747 // There are reports of double-width characters not displayed
6748 // correctly. This workaround should fix it, similar to how it's done
6749 // for VTP.
6750 g_coord.X = 0;
6751 SetConsoleCursorPosition(g_hConOut, g_coord);
6752
Bram Moolenaar2313b612019-09-27 14:14:32 +02006753 // external cursor coords are 1-based; internal are 0-based
6754 g_coord.X = x - 1;
6755 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006756 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006757 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006758 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006759 {
6760 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006761 // destruction. Insider build bug. Always enabled because it's cheap
6762 // and avoids mistakes with recognizing the build.
6763 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006764
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006765 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006766
6767 g_coord.X = x - 1;
6768 g_coord.Y = y - 1;
6769 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770}
6771
6772
6773/*
6774 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006775 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776 */
6777 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006778textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006780 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006781
6782 SetConsoleTextAttribute(g_hConOut, wAttr);
6783}
6784
6785
6786 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006787textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006789 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790
Christopher Plewright38804d62022-11-09 23:55:52 +00006791 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006792 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6793 else
6794 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006795}
6796
6797
6798 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006799textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006801 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802
Christopher Plewright38804d62022-11-09 23:55:52 +00006803 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006804 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6805 else
6806 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807}
6808
6809
6810/*
6811 * restore the default text attribute (whatever we started with)
6812 */
6813 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006814normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815{
Christopher Plewright38804d62022-11-09 23:55:52 +00006816 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006817 textattr(g_attrDefault);
6818 else
6819 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820}
6821
6822
6823static WORD g_attrPreStandout = 0;
6824
6825/*
6826 * Make the text standout, by brightening it
6827 */
6828 static void
6829standout(void)
6830{
6831 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006832
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6834}
6835
6836
6837/*
6838 * Turn off standout mode
6839 */
6840 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006841standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842{
6843 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006845
6846 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847}
6848
6849
6850/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006851 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852 */
6853 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006854mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855{
6856 char_u *p;
6857 int n;
6858
6859 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6860 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006861 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006862# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006863 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006864# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006865 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006866 {
6867 p = T_ME + 2;
6868 n = getdigits(&p);
6869 if (*p == 'm' && n > 0)
6870 {
6871 cterm_normal_fg_color = (n & 0xf) + 1;
6872 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6873 }
6874 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006875# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006876 cterm_normal_fg_gui_color = INVALCOLOR;
6877 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006878# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879}
6880
6881
6882/*
6883 * visual bell: flash the screen
6884 */
6885 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006886visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006887{
6888 COORD coordOrigin = {0, 0};
6889 WORD attrFlash = ~g_attrCurrent & 0xff;
6890
6891 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006892 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006894# ifdef FEAT_TERMGUICOLORS
6895 if (!(p_tgc || t_colors >= 256))
6896# endif
6897 {
6898 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6899 if (oldattrs == NULL)
6900 return;
6901 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006903 }
6904
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6906 coordOrigin, &dwDummy);
6907
Bram Moolenaar0f873732019-12-05 20:28:46 +01006908 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006909
6910 if (oldattrs != NULL)
6911 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006912 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006914 vim_free(oldattrs);
6915 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916}
6917
6918
6919/*
6920 * Make the cursor visible or invisible
6921 */
6922 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006923cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924{
6925 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006926
Christopher Plewright38804d62022-11-09 23:55:52 +00006927 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006928 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6929
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006930# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006932# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933}
6934
6935
6936/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006937 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006938 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006940 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006942 char_u *pchBuf,
6943 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006945 COORD coord = g_coord;
6946 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006947 DWORD n, cchwritten;
6948 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006949 static WCHAR *unicodebuf = NULL;
6950 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006951 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006952 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006953 static WCHAR *utf8spbuf = NULL;
6954 static int utf8splength;
6955 static DWORD utf8spcells;
6956 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006958 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006959 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006960 utf8usingbuf = &unicodebuf;
6961 do
6962 {
6963 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6964 unicodebuf, unibuflen);
6965 if (length && length <= unibuflen)
6966 break;
6967 vim_free(unicodebuf);
6968 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6969 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006970 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006971 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006972 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006973 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6974 {
6975 if (utf8usingbuf != &utf8spbuf)
6976 {
6977 if (utf8spbuf == NULL)
6978 {
6979 cells = mb_string2cells((char_u *)" ", 1);
6980 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6981 utf8spbuf = LALLOC_MULT(WCHAR, length);
6982 if (utf8spbuf != NULL)
6983 {
6984 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6985 utf8usingbuf = &utf8spbuf;
6986 utf8splength = length;
6987 utf8spcells = cells;
6988 }
6989 }
6990 else
6991 {
6992 utf8usingbuf = &utf8spbuf;
6993 length = utf8splength;
6994 cells = utf8spcells;
6995 }
6996 }
6997 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006998
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006999 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007000 {
7001 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
7002 coord, &written);
7003 // When writing fails or didn't write a single character, pretend one
7004 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007005 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007006 coord, &cchwritten) == 0
7007 || cchwritten == 0 || cchwritten == (DWORD)-1)
7008 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007009 }
7010 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007011 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007012 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007013 NULL) == 0 || cchwritten == 0)
7014 cchwritten = 1;
7015 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007016
K.Takata135e1522022-01-29 15:27:58 +00007017 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007018 {
7019 written = cbToWrite;
7020 g_coord.X += (SHORT)cells;
7021 }
7022 else
7023 {
7024 char_u *p = pchBuf;
7025 for (n = 0; n < cchwritten; n++)
7026 MB_CPTR_ADV(p);
7027 written = p - pchBuf;
7028 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007029 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007030
7031 while (g_coord.X > g_srScrollRegion.Right)
7032 {
7033 g_coord.X -= (SHORT) Columns;
7034 if (g_coord.Y < g_srScrollRegion.Bottom)
7035 g_coord.Y++;
7036 }
7037
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007038 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007039 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007040 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041
7042 return written;
7043}
7044
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007045 static char_u *
7046get_seq(
7047 int *args,
7048 int *count,
7049 char_u *head)
7050{
7051 int argc;
7052 char_u *p;
7053
7054 if (head == NULL || *head != '\033')
7055 return NULL;
7056
7057 argc = 0;
7058 p = head;
7059 ++p;
7060 do
7061 {
7062 ++p;
7063 args[argc] = getdigits(&p);
7064 argc += (argc < 15) ? 1 : 0;
7065 } while (*p == ';');
7066 *count = argc;
7067
7068 return p;
7069}
7070
7071 static char_u *
7072get_sgr(
7073 int *args,
7074 int *count,
7075 char_u *head)
7076{
7077 char_u *p = get_seq(args, count, head);
7078
7079 return (p && *p == 'm') ? ++p : NULL;
7080}
7081
7082/*
7083 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
7084 */
7085 static char_u *
7086sgrn2(
7087 char_u *head,
7088 int n)
7089{
7090 int argc;
7091 int args[16];
7092 char_u *p = get_sgr(args, &argc, head);
7093
7094 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
7095}
7096
7097/*
7098 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7099 */
7100 static char_u *
7101sgrnc(
7102 char_u *head,
7103 int n)
7104{
7105 int argc;
7106 int args[16];
7107 char_u *p = get_sgr(args, &argc, head);
7108
7109 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7110 ? p : NULL;
7111}
7112
7113 static char_u *
7114skipblank(char_u *q)
7115{
7116 char_u *p = q;
7117
7118 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7119 ++p;
7120 return p;
7121}
7122
7123/*
7124 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7125 * NULL.
7126 */
7127 static char_u *
7128sgrn2c(
7129 char_u *head,
7130 int n)
7131{
7132 char_u *p = sgrn2(head, n);
7133
7134 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7135}
7136
7137/*
7138 * If there is only a newline between the sequence immediately following it,
7139 * a pointer to the character following the newline is returned.
7140 * Otherwise NULL.
7141 */
7142 static char_u *
7143sgrn2cn(
7144 char_u *head,
7145 int n)
7146{
7147 char_u *p = sgrn2(head, n);
7148
7149 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7150}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151
7152/*
7153 * mch_write(): write the output buffer to the screen, translating ESC
7154 * sequences into calls to console output routines.
7155 */
7156 void
7157mch_write(
7158 char_u *s,
7159 int len)
7160{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007161 char_u *end = s + len;
7162
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007163# ifdef VIMDLL
7164 if (gui.in_use)
7165 return;
7166# endif
7167
Bram Moolenaar071d4272004-06-13 20:20:40 +00007168 if (!term_console)
7169 {
7170 write(1, s, (unsigned)len);
7171 return;
7172 }
7173
Bram Moolenaar0f873732019-12-05 20:28:46 +01007174 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007175 while (len--)
7176 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007177 int prefix = -1;
7178 char_u ch;
7179
7180 // While processing a sequence, on rare occasions it seems that another
7181 // sequence may be inserted asynchronously.
7182 if (len < 0)
7183 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007184 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007185 return;
7186 }
7187
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007188 while (s + ++prefix < end)
7189 {
7190 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007191 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7192 && ch != '\a' && ch != '\033'))
7193 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007194 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007195
7196 if (p_wd)
7197 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007198 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007199 if (prefix != 0)
7200 prefix = 1;
7201 }
7202
7203 if (prefix != 0)
7204 {
7205 DWORD nWritten;
7206
7207 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007208# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007209 if (fdDump)
7210 {
7211 fputc('>', fdDump);
7212 fwrite(s, sizeof(char_u), nWritten, fdDump);
7213 fputs("<\n", fdDump);
7214 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007215# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007216 len -= (nWritten - 1);
7217 s += nWritten;
7218 }
7219 else if (s[0] == '\n')
7220 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007221 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007222 if (g_coord.Y == g_srScrollRegion.Bottom)
7223 {
7224 scroll(1);
7225 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7226 }
7227 else
7228 {
7229 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7230 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007231# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007232 if (fdDump)
7233 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007234# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007235 s++;
7236 }
7237 else if (s[0] == '\r')
7238 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007239 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007240 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007241# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242 if (fdDump)
7243 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007244# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 s++;
7246 }
7247 else if (s[0] == '\b')
7248 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007249 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007250 if (g_coord.X > g_srScrollRegion.Left)
7251 g_coord.X--;
7252 else if (g_coord.Y > g_srScrollRegion.Top)
7253 {
7254 g_coord.X = g_srScrollRegion.Right;
7255 g_coord.Y--;
7256 }
7257 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007258# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007259 if (fdDump)
7260 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007261# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007262 s++;
7263 }
7264 else if (s[0] == '\a')
7265 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007266 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007267 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007268# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007269 if (fdDump)
7270 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007271# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 s++;
7273 }
7274 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7275 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007276# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007277 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007278# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007279 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007280 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007281 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007282
7283 switch (s[2])
7284 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007285 case '0': case '1': case '2': case '3': case '4':
7286 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007287 if (*(p = get_seq(args, &argc, s)) != 'm')
7288 goto notsgr;
7289
7290 p = s;
7291
7292 // Handling frequent optional sequences. Output to the screen
7293 // takes too long, so do not output as much as possible.
7294
7295 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7296 // resetFG,FG,BG are omitted.
7297 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007298 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007299 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7300 len = len + 1 - (int)(p - s);
7301 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007303 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007304
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007305 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7306 // omitted.
7307 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7308 p = sp;
7309
7310 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7311 // omitted.
7312 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7313 p = sp;
7314
7315 // If BG,BG of SGR are connected, the first BG can be omitted.
7316 if (sgrn2((sp = sgrn2(p, 48)), 48))
7317 p = sp;
7318
7319 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007320 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007321 if (sgrn2((sp = sgrnc(p, 39)), 38))
7322 p = sp;
7323
7324 p = get_seq(args, &argc, p);
7325
7326notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007327 arg1 = args[0];
7328 arg2 = args[1];
7329 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007330 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007331 if (argc == 1 && args[0] == 0)
7332 normvideo();
7333 else if (argc == 1)
7334 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007335 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007336 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007337 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007338 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007339 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007340 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007341 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007343 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007345 gotoxy(arg2, arg1);
7346 }
7347 else if (argc == 2 && *p == 'r')
7348 {
7349 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7350 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007351 else if (argc == 2 && *p == 'R')
7352 {
7353 set_scroll_region_tb(arg1, arg2);
7354 }
7355 else if (argc == 2 && *p == 'V')
7356 {
7357 set_scroll_region_lr(arg1, arg2);
7358 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007359 else if (argc == 1 && *p == 'A')
7360 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007361 gotoxy(g_coord.X + 1,
7362 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7363 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007364 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007365 {
7366 textbackground((WORD) arg1);
7367 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007368 else if (argc == 1 && *p == 'C')
7369 {
7370 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7371 g_coord.Y + 1);
7372 }
7373 else if (argc == 1 && *p == 'f')
7374 {
7375 textcolor((WORD) arg1);
7376 }
7377 else if (argc == 1 && *p == 'H')
7378 {
7379 gotoxy(1, arg1);
7380 }
7381 else if (argc == 1 && *p == 'L')
7382 {
7383 insert_lines(arg1);
7384 }
7385 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 {
7387 delete_lines(arg1);
7388 }
7389
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007390 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007391 s = p + 1;
7392 break;
7393
Bram Moolenaar071d4272004-06-13 20:20:40 +00007394 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 gotoxy(g_coord.X + 1,
7396 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7397 goto got3;
7398
7399 case 'B':
7400 visual_bell();
7401 goto got3;
7402
7403 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7405 g_coord.Y + 1);
7406 goto got3;
7407
7408 case 'E':
7409 termcap_mode_end();
7410 goto got3;
7411
7412 case 'F':
7413 standout();
7414 goto got3;
7415
7416 case 'f':
7417 standend();
7418 goto got3;
7419
7420 case 'H':
7421 gotoxy(1, 1);
7422 goto got3;
7423
7424 case 'j':
7425 clear_to_end_of_display();
7426 goto got3;
7427
7428 case 'J':
7429 clear_screen();
7430 goto got3;
7431
7432 case 'K':
7433 clear_to_end_of_line();
7434 goto got3;
7435
7436 case 'L':
7437 insert_lines(1);
7438 goto got3;
7439
7440 case 'M':
7441 delete_lines(1);
7442 goto got3;
7443
7444 case 'S':
7445 termcap_mode_start();
7446 goto got3;
7447
7448 case 'V':
7449 cursor_visible(TRUE);
7450 goto got3;
7451
7452 case 'v':
7453 cursor_visible(FALSE);
7454 goto got3;
7455
7456 got3:
7457 s += 3;
7458 len -= 2;
7459 }
7460
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007461# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462 if (fdDump)
7463 {
7464 fputs("ESC | ", fdDump);
7465 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7466 fputc('\n', fdDump);
7467 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007468# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007469 }
K.Takatadf5320c2022-09-01 13:20:16 +01007470 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7471 {
7472 int l = 2;
7473
Keith Thompson184f71c2024-01-04 21:19:04 +01007474 if (SAFE_isdigit(s[l]))
K.Takatadf5320c2022-09-01 13:20:16 +01007475 l++;
7476 if (s[l] == ' ' && s[l + 1] == 'q')
7477 {
7478 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007479 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007480 vtp_printf("%.*s", l + 2, s); // Pass through
7481 s += l + 2;
7482 len -= l + 1;
7483 }
7484 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485 else
7486 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007487 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488 DWORD nWritten;
7489
7490 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007491# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492 if (fdDump)
7493 {
7494 fputc('>', fdDump);
7495 fwrite(s, sizeof(char_u), nWritten, fdDump);
7496 fputs("<\n", fdDump);
7497 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007498# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499
7500 len -= (nWritten - 1);
7501 s += nWritten;
7502 }
7503 }
7504
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007505# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 if (fdDump)
7507 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007508# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007509}
7510
Bram Moolenaar0f873732019-12-05 20:28:46 +01007511#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007512
7513
7514/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007515 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007516 */
7517 void
7518mch_delay(
7519 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007520 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007521{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007522#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007523 Sleep((int)msec); // never wait for input
7524#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007525# ifdef VIMDLL
7526 if (gui.in_use)
7527 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007528 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007529 return;
7530 }
7531# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007532 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007533# ifdef FEAT_MZSCHEME
7534 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7535 {
7536 int towait = p_mzq;
7537
Bram Moolenaar0f873732019-12-05 20:28:46 +01007538 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007539 while (msec > 0)
7540 {
7541 mzvim_check_threads();
7542 if (msec < towait)
7543 towait = msec;
7544 Sleep(towait);
7545 msec -= towait;
7546 }
7547 }
7548 else
7549# endif
7550 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007551 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007552 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553#endif
7554}
7555
7556
7557/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007558 * This version of remove is not scared by a readonly (backup) file.
7559 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560 * Return 0 for success, -1 for failure.
7561 */
7562 int
7563mch_remove(char_u *name)
7564{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007565 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007566 int n;
7567
Bram Moolenaar203258c2016-01-17 22:15:16 +01007568 /*
7569 * On Windows, deleting a directory's symbolic link is done by
7570 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7571 */
7572 if (mch_isdir(name) && mch_is_symbolic_link(name))
7573 return mch_rmdir(name);
7574
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007575 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7576
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007577 wn = enc_to_utf16(name, NULL);
7578 if (wn == NULL)
7579 return -1;
7580
7581 n = DeleteFileW(wn) ? 0 : -1;
7582 vim_free(wn);
7583 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007584}
7585
7586
7587/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007588 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007589 */
7590 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007591mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007592{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007593#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7594# ifdef VIMDLL
7595 if (!gui.in_use)
7596# endif
7597 if (g_fCtrlCPressed || g_fCBrkPressed)
7598 {
7599 ctrl_break_was_pressed = g_fCBrkPressed;
7600 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7601 got_int = TRUE;
7602 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007603#endif
7604}
7605
Bram Moolenaar0f873732019-12-05 20:28:46 +01007606// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007607#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007608
7609/*
7610 * How much main memory in KiB that can be used by VIM.
7611 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007612 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007613mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007614{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007615 MEMORYSTATUSEX ms;
7616
Bram Moolenaar0f873732019-12-05 20:28:46 +01007617 // Need to use GlobalMemoryStatusEx() when there is more memory than
7618 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007619 ms.dwLength = sizeof(MEMORYSTATUSEX);
7620 GlobalMemoryStatusEx(&ms);
7621 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007622 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007623 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007624 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007625 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007626 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007627 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007628 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007629 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007630 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007631 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007632 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007633}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007634
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007636 * mch_wrename() works around a bug in rename (aka MoveFile) in
Nir Lichtman563e8ec2024-09-30 19:42:28 +02007637 * Windows, the bug can be demonstrated with the following scenario:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007638 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
Nir Lichtman563e8ec2024-09-30 19:42:28 +02007639 * "abcdef~1.txt" again.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007640 *
7641 * Like rename(), returns 0 upon success, non-zero upon failure.
7642 * Should probably set errno appropriately when errors occur.
7643 */
7644 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007645mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007646{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007647 WCHAR *p;
7648 int i;
7649 WCHAR szTempFile[_MAX_PATH + 1];
7650 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007651 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007652
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007653 // No need to play tricks unless the file name contains a "~" as the
7654 // seventh character.
7655 p = wold;
7656 for (i = 0; wold[i] != NUL; ++i)
7657 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7658 && wold[i + 1] != 0)
7659 p = wold + i + 1;
7660 if ((int)(wold + i - p) < 8 || p[6] != '~')
7661 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007663 // Get base path of new file name. Undocumented feature: If pszNewFile is
7664 // a directory, no error is returned and pszFilePart will be NULL.
7665 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007666 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007667 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007669 // Get (and create) a unique temporary file name in directory of new file
7670 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007671 return -2;
7672
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007673 // blow the temp file away
7674 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007675 return -3;
7676
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007677 // rename old file to the temp file
7678 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007679 return -4;
7680
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007681 // now create an empty file called pszOldFile; this prevents the operating
7682 // system using pszOldFile as an alias (SFN) if we're renaming within the
7683 // same directory. For example, we're editing a file called
7684 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7685 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7686 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7687 // cause all sorts of problems later in buf_write(). So, we create an
7688 // empty file called filena~1.txt and the system will have to find some
7689 // other SFN for filena~1.txt~, such as filena~2.txt
7690 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007691 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7692 return -5;
7693 if (!CloseHandle(hf))
7694 return -6;
7695
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007696 // rename the temp file to the new file
7697 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007698 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007699 // Renaming failed. Rename the file back to its old name, so that it
7700 // looks like nothing happened.
7701 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007702 return -7;
7703 }
7704
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007705 // Seems to be left around on Novell filesystems
7706 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007708 // finally, remove the empty old file
7709 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007710 return -8;
7711
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007712 return 0;
7713}
7714
7715
7716/*
7717 * Converts the filenames to UTF-16, then call mch_wrename().
7718 * Like rename(), returns 0 upon success, non-zero upon failure.
7719 */
7720 int
7721mch_rename(
7722 const char *pszOldFile,
7723 const char *pszNewFile)
7724{
7725 WCHAR *wold = NULL;
7726 WCHAR *wnew = NULL;
7727 int retval = -1;
7728
7729 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7730 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7731 if (wold != NULL && wnew != NULL)
7732 retval = mch_wrename(wold, wnew);
7733 vim_free(wold);
7734 vim_free(wnew);
7735 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007736}
7737
7738/*
7739 * Get the default shell for the current hardware platform
7740 */
7741 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007742default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007743{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007744 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007745}
7746
7747/*
7748 * mch_access() extends access() to do more detailed check on network drives.
7749 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7750 */
7751 int
7752mch_access(char *n, int p)
7753{
7754 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007755 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007756 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007757
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007758 wn = enc_to_utf16((char_u *)n, NULL);
7759 if (wn == NULL)
7760 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007761
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007762 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007765
7766 if (p & R_OK)
7767 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007768 // Read check is performed by seeing if we can do a find file on
7769 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007770 int i;
7771 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007773 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7774 TempNameW[i] = wn[i];
7775 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7776 TempNameW[i++] = '\\';
7777 TempNameW[i++] = '*';
7778 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007780 hFile = FindFirstFileW(TempNameW, &d);
7781 if (hFile == INVALID_HANDLE_VALUE)
7782 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007783 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007784 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007785 }
7786
7787 if (p & W_OK)
7788 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007789 // Trying to create a temporary file in the directory should catch
7790 // directories on read-only network shares. However, in
7791 // directories whose ACL allows writes but denies deletes will end
7792 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007793 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7794 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007795 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007796 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007797 }
7798 }
7799 else
7800 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007801 // Don't consider a file read-only if another process has opened it.
7802 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7803
Bram Moolenaar0f873732019-12-05 20:28:46 +01007804 // Trying to open the file for the required access does ACL, read-only
7805 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007806 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7807 | ((p & R_OK) ? GENERIC_READ : 0);
7808
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007809 hFile = CreateFileW(wn, access_mode, share_mode,
7810 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811 if (hFile == INVALID_HANDLE_VALUE)
7812 goto getout;
7813 CloseHandle(hFile);
7814 }
7815
Bram Moolenaar0f873732019-12-05 20:28:46 +01007816 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007818 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007819 return retval;
7820}
7821
Bram Moolenaar071d4272004-06-13 20:20:40 +00007822/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007823 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007824 */
7825 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007826mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007827{
7828 WCHAR *wn;
7829 int f;
7830
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007831 wn = enc_to_utf16((char_u *)name, NULL);
7832 if (wn == NULL)
7833 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007834
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007835 f = _wopen(wn, flags, mode);
7836 vim_free(wn);
7837 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007838}
7839
7840/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007841 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007842 */
7843 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007844mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007845{
7846 WCHAR *wn, *wm;
7847 FILE *f = NULL;
7848
Bram Moolenaara12a1612019-01-24 16:39:02 +01007849#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007850 // Work around an annoying assertion in the Microsoft debug CRT
7851 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007852 char newMode = mode[strlen(mode) - 1];
7853 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007854
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007855 _get_fmode(&oldMode);
7856 if (newMode == 't')
7857 _set_fmode(_O_TEXT);
7858 else if (newMode == 'b')
7859 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007860#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007861 wn = enc_to_utf16((char_u *)name, NULL);
7862 wm = enc_to_utf16((char_u *)mode, NULL);
7863 if (wn != NULL && wm != NULL)
7864 f = _wfopen(wn, wm);
7865 vim_free(wn);
7866 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007867
Bram Moolenaara12a1612019-01-24 16:39:02 +01007868#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007869 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007870#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007871 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007872}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007873
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874/*
7875 * SUB STREAM (aka info stream) handling:
7876 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007877 * NTFS can have sub streams for each file. The normal contents of a file is
7878 * stored in the main stream, and extra contents (author information, title and
7879 * so on) can be stored in a sub stream. After Windows 2000, the user can
7880 * access and store this information in sub streams via an explorer's property
7881 * menu item in the right click menu. This information in sub streams was lost
7882 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007883 *
7884 * Incomplete explanation:
7885 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7886 * More useful info and an example:
7887 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7888 */
7889
7890/*
7891 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7892 * and write to stream "substream" of file "to".
7893 * Errors are ignored.
7894 */
7895 static void
7896copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7897{
7898 HANDLE hTo;
7899 WCHAR *to_name;
7900
John Marriott738df382025-06-05 20:49:39 +02007901 to_name = alloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7902 if (to_name == NULL)
7903 return;
7904
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905 wcscpy(to_name, to);
7906 wcscat(to_name, substream);
7907
7908 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7909 FILE_ATTRIBUTE_NORMAL, NULL);
7910 if (hTo != INVALID_HANDLE_VALUE)
7911 {
7912 long done;
7913 DWORD todo;
7914 DWORD readcnt, written;
7915 char buf[4096];
7916
Bram Moolenaar0f873732019-12-05 20:28:46 +01007917 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007918 for (done = 0; done < len; done += written)
7919 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007920 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007921 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7922 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007923 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7924 FALSE, FALSE, context)
7925 || readcnt != todo
7926 || !WriteFile(hTo, buf, todo, &written, NULL)
7927 || written != todo)
7928 break;
7929 }
7930 CloseHandle(hTo);
7931 }
7932
7933 free(to_name);
7934}
7935
7936/*
7937 * Copy info streams from file "from" to file "to".
7938 */
7939 static void
7940copy_infostreams(char_u *from, char_u *to)
7941{
7942 WCHAR *fromw;
7943 WCHAR *tow;
7944 HANDLE sh;
7945 WIN32_STREAM_ID sid;
7946 int headersize;
7947 WCHAR streamname[_MAX_PATH];
7948 DWORD readcount;
7949 void *context = NULL;
7950 DWORD lo, hi;
7951 int len;
7952
Bram Moolenaar0f873732019-12-05 20:28:46 +01007953 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007954 fromw = enc_to_utf16(from, NULL);
7955 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007956 if (fromw != NULL && tow != NULL)
7957 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007958 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007959 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7960 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7961 if (sh != INVALID_HANDLE_VALUE)
7962 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007963 // Use BackupRead() to find the info streams. Repeat until we
7964 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007965 for (;;)
7966 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007967 // Get the header to find the length of the stream name. If
7968 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007969 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007970 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007971 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7972 &readcount, FALSE, FALSE, &context)
7973 || readcount == 0)
7974 break;
7975
Bram Moolenaar0f873732019-12-05 20:28:46 +01007976 // We only deal with streams that have a name. The normal
7977 // file data appears to be without a name, even though docs
7978 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007979 if (sid.dwStreamNameSize > 0)
7980 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007981 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007982 if (!BackupRead(sh, (LPBYTE)streamname,
7983 sid.dwStreamNameSize,
7984 &readcount, FALSE, FALSE, &context))
7985 break;
7986
Bram Moolenaar0f873732019-12-05 20:28:46 +01007987 // Copy an info stream with a name ":anything:$DATA".
7988 // Skip "::$DATA", it has no stream name (examples suggest
7989 // it might be used for the normal file contents).
7990 // Note that BackupRead() counts bytes, but the name is in
7991 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007992 len = readcount / sizeof(WCHAR);
7993 streamname[len] = 0;
7994 if (len > 7 && wcsicmp(streamname + len - 6,
7995 L":$DATA") == 0)
7996 {
7997 streamname[len - 6] = 0;
7998 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007999 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008000 }
8001 }
8002
Bram Moolenaar0f873732019-12-05 20:28:46 +01008003 // Advance to the next stream. We might try seeking too far,
8004 // but BackupSeek() doesn't skip over stream borders, thus
8005 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00008006 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00008007 &lo, &hi, &context);
8008 }
8009
Bram Moolenaar0f873732019-12-05 20:28:46 +01008010 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008011 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
8012
8013 CloseHandle(sh);
8014 }
8015 }
8016 vim_free(fromw);
8017 vim_free(tow);
8018}
Bram Moolenaar071d4272004-06-13 20:20:40 +00008019
8020/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008021 * ntdll.dll definitions
8022 */
8023#define FileEaInformation 7
8024#ifndef STATUS_SUCCESS
8025# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
8026#endif
8027
8028typedef struct _FILE_FULL_EA_INFORMATION_ {
8029 ULONG NextEntryOffset;
8030 UCHAR Flags;
8031 UCHAR EaNameLength;
8032 USHORT EaValueLength;
8033 CHAR EaName[1];
8034} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
8035
8036typedef struct _FILE_EA_INFORMATION_ {
8037 ULONG EaSize;
8038} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
8039
Paul Ollis65745772022-06-05 16:55:54 +01008040#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008041typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
8042 PHANDLE FileHandle,
8043 ACCESS_MASK DesiredAccess,
8044 POBJECT_ATTRIBUTES ObjectAttributes,
8045 PIO_STATUS_BLOCK IoStatusBlock,
8046 ULONG ShareAccess,
8047 ULONG OpenOptions);
8048typedef NTSTATUS (NTAPI *PfnNtClose)(
8049 HANDLE Handle);
8050typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008051 HANDLE FileHandle,
8052 PIO_STATUS_BLOCK IoStatusBlock,
8053 PVOID Buffer,
8054 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008055typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
8056 HANDLE FileHandle,
8057 PIO_STATUS_BLOCK IoStatusBlock,
8058 PVOID Buffer,
8059 ULONG Length,
8060 BOOLEAN ReturnSingleEntry,
8061 PVOID EaList,
8062 ULONG EaListLength,
8063 PULONG EaIndex,
8064 BOOLEAN RestartScan);
8065typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008066 HANDLE FileHandle,
8067 PIO_STATUS_BLOCK IoStatusBlock,
8068 PVOID FileInformation,
8069 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008070 FILE_INFORMATION_CLASS FileInformationClass);
8071typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
8072 PUNICODE_STRING DestinationString,
8073 PCWSTR SourceString);
8074
8075PfnNtOpenFile pNtOpenFile = NULL;
8076PfnNtClose pNtClose = NULL;
8077PfnNtSetEaFile pNtSetEaFile = NULL;
8078PfnNtQueryEaFile pNtQueryEaFile = NULL;
8079PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
8080PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01008081#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008082
8083/*
8084 * Load ntdll.dll functions.
8085 */
8086 static BOOL
8087load_ntdll(void)
8088{
8089 static int loaded = -1;
8090
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008091 if (loaded != -1)
8092 return (BOOL) loaded;
8093
8094 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8095 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008096 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008097 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8098 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8099 pNtSetEaFile = (PfnNtSetEaFile)
8100 GetProcAddress(hNtdll, "NtSetEaFile");
8101 pNtQueryEaFile = (PfnNtQueryEaFile)
8102 GetProcAddress(hNtdll, "NtQueryEaFile");
8103 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8104 GetProcAddress(hNtdll, "NtQueryInformationFile");
8105 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8106 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008107 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008108 if (pNtOpenFile == NULL
8109 || pNtClose == NULL
8110 || pNtSetEaFile == NULL
8111 || pNtQueryEaFile == NULL
8112 || pNtQueryInformationFile == NULL
8113 || pRtlInitUnicodeString == NULL)
8114 loaded = FALSE;
8115 else
8116 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008117 return (BOOL) loaded;
8118}
8119
8120/*
8121 * Copy extended attributes (EA) from file "from" to file "to".
8122 */
8123 static void
8124copy_extattr(char_u *from, char_u *to)
8125{
8126 char_u *fromf = NULL;
8127 char_u *tof = NULL;
8128 WCHAR *fromw = NULL;
8129 WCHAR *tow = NULL;
8130 UNICODE_STRING u;
8131 HANDLE h;
8132 OBJECT_ATTRIBUTES oa;
8133 IO_STATUS_BLOCK iosb;
8134 FILE_EA_INFORMATION_ eainfo = {0};
8135 void *ea = NULL;
8136
8137 if (!load_ntdll())
8138 return;
8139
8140 // Convert the file names to the fully qualified object names.
8141 fromf = alloc(STRLEN(from) + 5);
8142 tof = alloc(STRLEN(to) + 5);
8143 if (fromf == NULL || tof == NULL)
8144 goto theend;
8145 STRCPY(fromf, "\\??\\");
John Marriott9cb27a52025-06-08 16:05:53 +02008146 STRCPY(fromf + STRLEN_LITERAL("\\??\\"), from);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008147 STRCPY(tof, "\\??\\");
John Marriott9cb27a52025-06-08 16:05:53 +02008148 STRCPY(tof + STRLEN_LITERAL("\\??\\"), to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008149
8150 // Convert the names to wide characters.
8151 fromw = enc_to_utf16(fromf, NULL);
8152 tow = enc_to_utf16(tof, NULL);
8153 if (fromw == NULL || tow == NULL)
8154 goto theend;
8155
8156 // Get the EA.
8157 pRtlInitUnicodeString(&u, fromw);
8158 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8159 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8160 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8161 goto theend;
8162 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8163 FileEaInformation);
8164 if (eainfo.EaSize != 0)
8165 {
8166 ea = alloc(eainfo.EaSize);
8167 if (ea != NULL)
8168 {
8169 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8170 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8171 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008172 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008173 }
8174 }
8175 }
8176 pNtClose(h);
8177
8178 // Set the EA.
8179 if (ea != NULL)
8180 {
8181 pRtlInitUnicodeString(&u, tow);
8182 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8183 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8184 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8185 goto theend;
8186
8187 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8188 pNtClose(h);
8189 }
8190
8191theend:
8192 vim_free(fromf);
8193 vim_free(tof);
8194 vim_free(fromw);
8195 vim_free(tow);
8196 vim_free(ea);
8197}
8198
8199/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008200 * Copy file attributes from file "from" to file "to".
8201 * For Windows NT and later we copy info streams.
8202 * Always returns zero, errors are ignored.
8203 */
8204 int
8205mch_copy_file_attribute(char_u *from, char_u *to)
8206{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008207 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008208 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008209 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008210 return 0;
8211}
8212
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008213
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008214/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008215 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008216 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008217static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008218static LPWSTR *ArglistW = NULL;
8219static int global_argc = 0;
8220static char **global_argv;
8221
Bram Moolenaar0f873732019-12-05 20:28:46 +01008222static int used_file_argc = 0; // last argument in global_argv[] used
8223 // for the argument list.
8224static int *used_file_indexes = NULL; // indexes in global_argv[] for
8225 // command line arguments added to
8226 // the argument list
8227static int used_file_count = 0; // nr of entries in used_file_indexes
8228static int used_file_literal = FALSE; // take file names literally
8229static int used_file_full_path = FALSE; // file name was full path
8230static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008231static int used_alist_count = 0;
8232
8233
8234/*
8235 * Get the command line arguments. Unicode version.
8236 * Returns argc. Zero when something fails.
8237 */
8238 int
8239get_cmd_argsW(char ***argvp)
8240{
8241 char **argv = NULL;
8242 int argc = 0;
8243 int i;
8244
Bram Moolenaar14993322014-09-09 12:25:33 +02008245 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008246 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8247 if (ArglistW != NULL)
8248 {
John Marriott738df382025-06-05 20:49:39 +02008249 argv = alloc((nArgsW + 1) * sizeof(char *));
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008250 if (argv != NULL)
8251 {
8252 argc = nArgsW;
8253 argv[argc] = NULL;
8254 for (i = 0; i < argc; ++i)
8255 {
8256 int len;
8257
K.Takatadc73b4b2021-06-08 18:32:36 +02008258 // Convert each Unicode argument to UTF-8.
8259 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008260 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008261 (LPSTR *)&argv[i], &len, 0, 0);
8262 if (argv[i] == NULL)
8263 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008264 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008265 while (i > 0)
8266 free(argv[--i]);
8267 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008268 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008269 argc = 0;
8270 }
8271 }
8272 }
8273 }
8274
8275 global_argc = argc;
8276 global_argv = argv;
8277 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008278 {
8279 if (used_file_indexes != NULL)
8280 free(used_file_indexes);
John Marriott738df382025-06-05 20:49:39 +02008281 used_file_indexes = alloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008282 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008283
8284 if (argvp != NULL)
8285 *argvp = argv;
8286 return argc;
8287}
8288
8289 void
8290free_cmd_argsW(void)
8291{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008292 if (ArglistW == NULL)
8293 return;
8294
8295 GlobalFree(ArglistW);
8296 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008297}
8298
8299/*
8300 * Remember "name" is an argument that was added to the argument list.
8301 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8302 * is called.
8303 */
8304 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008305used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008306{
8307 int i;
8308
8309 if (used_file_indexes == NULL)
8310 return;
8311 for (i = used_file_argc + 1; i < global_argc; ++i)
8312 if (STRCMP(global_argv[i], name) == 0)
8313 {
8314 used_file_argc = i;
8315 used_file_indexes[used_file_count++] = i;
8316 break;
8317 }
8318 used_file_literal = literal;
8319 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008320 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008321}
8322
8323/*
8324 * Remember the length of the argument list as it was. If it changes then we
8325 * leave it alone when 'encoding' is set.
8326 */
8327 void
8328set_alist_count(void)
8329{
8330 used_alist_count = GARGCOUNT;
8331}
8332
8333/*
8334 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008335 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008336 * and convert them to 'encoding'.
8337 */
8338 void
8339fix_arg_enc(void)
8340{
8341 int i;
8342 int idx;
8343 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008344 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008345
Bram Moolenaar0f873732019-12-05 20:28:46 +01008346 // Safety checks:
8347 // - if argument count differs between the wide and non-wide argument
8348 // list, something must be wrong.
8349 // - the file name arguments must have been located.
8350 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008351 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008352 || ArglistW == NULL
8353 || used_file_indexes == NULL
8354 || used_file_count == 0
8355 || used_alist_count != GARGCOUNT)
8356 return;
8357
Bram Moolenaar0f873732019-12-05 20:28:46 +01008358 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008359 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008360 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008361 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008362 for (i = 0; i < GARGCOUNT; ++i)
8363 fnum_list[i] = GARGLIST[i].ae_fnum;
8364
Bram Moolenaar0f873732019-12-05 20:28:46 +01008365 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008366 alist_clear(&global_alist);
8367 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008368 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008369
8370 for (i = 0; i < used_file_count; ++i)
8371 {
8372 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008373 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008374 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008375 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008376 int literal = used_file_literal;
8377
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008378#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008379 // When using diff mode may need to concatenate file name to
8380 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008381 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8382 && !mch_isdir(alist_name(&GARGLIST[0])))
8383 {
8384 char_u *r;
8385
8386 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8387 if (r != NULL)
8388 {
8389 vim_free(str);
8390 str = r;
8391 }
8392 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008393#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008394 // Re-use the old buffer by renaming it. When not using literal
8395 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008396 if (used_file_literal)
8397 buf_set_name(fnum_list[i], str);
8398
Bram Moolenaar0f873732019-12-05 20:28:46 +01008399 // Check backtick literal. backtick literal is already expanded in
8400 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008401 if (literal == FALSE)
8402 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008403 size_t len = STRLEN(str);
8404
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008405 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8406 literal = TRUE;
8407 }
8408 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008409 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008410 }
8411
8412 if (!used_file_literal)
8413 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008414 // Now expand wildcards in the arguments.
8415 // Temporarily add '(' and ')' to 'isfname'. These are valid
8416 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008417 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008418 // Also, unset wildignore to not be influenced by this option.
8419 // The arguments specified in command-line should be kept even if
8420 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008421 // Use :legacy so that it also works when in Vim9 script.
8422 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8423 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008424 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008425 do_cmdline_cmd(
8426 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8427 do_cmdline_cmd(
8428 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008429 }
8430
Bram Moolenaar0f873732019-12-05 20:28:46 +01008431 // If wildcard expansion failed, we are editing the first file of the
8432 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008433 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8434 {
8435 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008436 if (GARGCOUNT == 1 && used_file_full_path
8437 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8438 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008439 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008440
8441 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008442}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008443
8444 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008445mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008446{
8447 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008448 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008449
Bram Moolenaar964b3742019-05-24 18:54:09 +02008450 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008451 if (envbuf == NULL)
8452 return -1;
8453
8454 sprintf((char *)envbuf, "%s=%s", var, value);
8455
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008456 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008457
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008458 vim_free(envbuf);
8459 if (p == NULL)
8460 return -1;
8461 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008462#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008463 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008464#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008465 // Unlike Un*x systems, we can free the string for _wputenv().
8466 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008467
8468 return 0;
8469}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008470
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008471/*
8472 * Support for 256 colors and 24-bit colors was added in Windows 10
8473 * version 1703 (Creators update).
8474 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008475#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8476
8477/*
8478 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008479 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008480 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008481#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008482
8483/*
8484 * ConPTY differences between versions, need different logic.
8485 * version 1903 (May 2019 update).
8486 */
8487#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8488
8489/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008490 * version 1909 (November 2019 update).
8491 */
8492#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8493
8494/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008495 * Stay ahead of the next update, and when it's done, fix this.
8496 * version ? (2020 update, temporarily use the build number of insider preview)
8497 */
8498#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8499
8500/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008501 * Confirm until this version. Also the logic changes.
8502 * insider preview.
8503 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008504#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008505
8506/*
8507 * Not stable now.
8508 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008509#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008510// Notes:
8511// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8512// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8513// preview which had a build 19587. And, not sure how stable that was?
8514// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8515// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008516
8517 static void
8518vtp_flag_init(void)
8519{
8520 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008521#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008522 DWORD mode;
8523 HANDLE out;
8524
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008525# ifdef VIMDLL
8526 if (!gui.in_use)
8527# endif
8528 {
8529 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008530
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008531 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8532 GetConsoleMode(out, &mode);
8533 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8534 if (SetConsoleMode(out, mode) == 0)
8535 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008536
8537 // VTP uses alternate screen buffer.
8538 // But, not if running in a nested terminal
8539 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8540 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008541 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008542#endif
8543
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008544 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008545 conpty_working = 1;
8546 if (ver >= CONPTY_STABLE_BUILD)
8547 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008548
Bram Moolenaar57da6982019-09-13 22:30:11 +02008549 if (ver <= CONPTY_INSIDER_BUILD)
8550 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008551 if (ver <= CONPTY_1909_BUILD)
8552 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008553 if (ver <= CONPTY_1903_BUILD)
8554 conpty_type = 2;
8555 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8556 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008557
8558 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8559 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008560}
8561
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008562#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008563
8564 static void
8565vtp_init(void)
8566{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008567# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008568 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8569 csbi.cbSize = sizeof(csbi);
8570 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8571 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8572 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8573 store_console_bg_rgb = save_console_bg_rgb;
8574 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008575
Christopher Plewrightd343c602023-01-22 18:58:30 +00008576 COLORREF bg;
8577 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8578 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8579 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008580
Christopher Plewrightd343c602023-01-22 18:58:30 +00008581 COLORREF fg;
8582 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8583 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8584 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008585# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008586 set_console_color_rgb();
8587}
8588
8589 static void
8590vtp_exit(void)
8591{
Bram Moolenaardf543822020-01-30 11:53:59 +01008592 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008593}
8594
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008595 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008596vtp_printf(
8597 char *format,
8598 ...)
8599{
8600 char_u buf[100];
8601 va_list list;
8602 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008603 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008604
Nir Lichtman6cd2d1d2023-11-11 11:27:41 +01008605 if (silent_mode)
8606 return 0;
8607
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008608 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008609 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008610 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008611 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008612 return (int)result;
8613}
8614
8615 static void
8616vtp_sgr_bulk(
8617 int arg)
8618{
8619 int args[1];
8620
8621 args[0] = arg;
8622 vtp_sgr_bulks(1, args);
8623}
8624
K.Takata6e1d31e2022-02-03 13:05:32 +00008625# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008626 if ((*p-- = "0123456789"[(n = x % 10)]) \
8627 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8628 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8629
K.Takata6e1d31e2022-02-03 13:05:32 +00008630# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008631 case x: \
8632 FAST256(newargs[x - 1]);
8633
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008634 static void
8635vtp_sgr_bulks(
8636 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008637 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008638{
K.Takata6e1d31e2022-02-03 13:05:32 +00008639# define MAXSGR 16
8640# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008641 char_u buf[SGRBUFSIZE];
8642 char_u *p;
8643 int in, out;
8644 int newargs[16];
8645 static int sgrfgr = -1, sgrfgg, sgrfgb;
8646 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008647
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008648 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008649 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008650 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008651 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008652 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008653 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008654
8655 in = out = 0;
8656 while (in < argc)
8657 {
8658 int s = args[in];
8659 int copylen = 1;
8660
8661 if (s == 38)
8662 {
8663 if (argc - in >= 5 && args[in + 1] == 2)
8664 {
8665 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8666 && sgrfgb == args[in + 4])
8667 {
8668 in += 5;
8669 copylen = 0;
8670 }
8671 else
8672 {
8673 sgrfgr = args[in + 2];
8674 sgrfgg = args[in + 3];
8675 sgrfgb = args[in + 4];
8676 copylen = 5;
8677 }
8678 }
8679 else if (argc - in >= 3 && args[in + 1] == 5)
8680 {
8681 sgrfgr = -1;
8682 copylen = 3;
8683 }
8684 }
8685 else if (s == 48)
8686 {
8687 if (argc - in >= 5 && args[in + 1] == 2)
8688 {
8689 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8690 && sgrbgb == args[in + 4])
8691 {
8692 in += 5;
8693 copylen = 0;
8694 }
8695 else
8696 {
8697 sgrbgr = args[in + 2];
8698 sgrbgg = args[in + 3];
8699 sgrbgb = args[in + 4];
8700 copylen = 5;
8701 }
8702 }
8703 else if (argc - in >= 3 && args[in + 1] == 5)
8704 {
8705 sgrbgr = -1;
8706 copylen = 3;
8707 }
8708 }
8709 else if (30 <= s && s <= 39)
8710 sgrfgr = -1;
8711 else if (90 <= s && s <= 97)
8712 sgrfgr = -1;
8713 else if (40 <= s && s <= 49)
8714 sgrbgr = -1;
8715 else if (100 <= s && s <= 107)
8716 sgrbgr = -1;
8717 else if (s == 0)
8718 sgrfgr = sgrbgr = -1;
8719
8720 while (copylen--)
8721 newargs[out++] = args[in++];
8722 }
8723
8724 p = &buf[sizeof(buf) - 1];
8725 *p-- = 'm';
8726
8727 switch (out)
8728 {
8729 int n, m;
8730 DWORD r;
8731
8732 FAST256CASE(16);
8733 *p-- = ';';
8734 FAST256CASE(15);
8735 *p-- = ';';
8736 FAST256CASE(14);
8737 *p-- = ';';
8738 FAST256CASE(13);
8739 *p-- = ';';
8740 FAST256CASE(12);
8741 *p-- = ';';
8742 FAST256CASE(11);
8743 *p-- = ';';
8744 FAST256CASE(10);
8745 *p-- = ';';
8746 FAST256CASE(9);
8747 *p-- = ';';
8748 FAST256CASE(8);
8749 *p-- = ';';
8750 FAST256CASE(7);
8751 *p-- = ';';
8752 FAST256CASE(6);
8753 *p-- = ';';
8754 FAST256CASE(5);
8755 *p-- = ';';
8756 FAST256CASE(4);
8757 *p-- = ';';
8758 FAST256CASE(3);
8759 *p-- = ';';
8760 FAST256CASE(2);
8761 *p-- = ';';
8762 FAST256CASE(1);
8763 *p-- = '[';
8764 *p = '\033';
8765 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8766 default:
8767 break;
8768 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008769}
8770
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008771 static void
8772wt_init(void)
8773{
Christopher Plewright1140b512022-11-12 18:46:05 +00008774 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008775}
8776
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008777# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008778 static int
8779ctermtoxterm(
8780 int cterm)
8781{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008782 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008783
8784 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8785 return (((int)r << 16) | ((int)g << 8) | (int)b);
8786}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008787# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008788
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008789 static void
8790set_console_color_rgb(void)
8791{
8792# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008793 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008794 guicolor_T fg, bg;
8795 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008796
Christopher Plewright38804d62022-11-09 23:55:52 +00008797 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008798 return;
8799
Bram Moolenaara050b942019-12-02 21:35:31 +01008800 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8801
Christopher Plewright38804d62022-11-09 23:55:52 +00008802 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008803 {
8804 term_fg_rgb_color(fg);
8805 term_bg_rgb_color(bg);
8806 return;
8807 }
8808
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008809 if (use_alternate_screen_buffer)
8810 return;
8811
Christopher Plewrightd343c602023-01-22 18:58:30 +00008812 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8813 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008814
Christopher Plewrightd343c602023-01-22 18:58:30 +00008815 csbi.cbSize = sizeof(csbi);
8816 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008817
Christopher Plewrightd343c602023-01-22 18:58:30 +00008818 csbi.cbSize = sizeof(csbi);
8819 csbi.srWindow.Right += 1;
8820 csbi.srWindow.Bottom += 1;
8821 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8822 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8823 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8824 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8825 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008826# endif
8827}
8828
Bram Moolenaara050b942019-12-02 21:35:31 +01008829# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8830 void
8831get_default_console_color(
8832 int *cterm_fg,
8833 int *cterm_bg,
8834 guicolor_T *gui_fg,
8835 guicolor_T *gui_bg)
8836{
8837 int id;
8838 guicolor_T guifg = INVALCOLOR;
8839 guicolor_T guibg = INVALCOLOR;
8840 int ctermfg = 0;
8841 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008842 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008843
8844 id = syn_name2id((char_u *)"Normal");
8845 if (id > 0 && p_tgc)
8846 syn_id2colors(id, &guifg, &guibg);
8847 if (guifg == INVALCOLOR)
8848 {
8849 ctermfg = -1;
8850 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008851 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008852 if (ctermfg != -1)
8853 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008854 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008855 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8856 cterm_normal_fg_gui_color = guifg;
8857 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008858 }
8859 if (guibg == INVALCOLOR)
8860 {
8861 ctermbg = -1;
8862 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008863 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008864 if (ctermbg != -1)
8865 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008866 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008867 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8868 cterm_normal_bg_gui_color = guibg;
8869 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008870 }
8871
8872 *cterm_fg = ctermfg;
8873 *cterm_bg = ctermbg;
8874 *gui_fg = guifg;
8875 *gui_bg = guibg;
8876}
8877# endif
8878
Bram Moolenaardf543822020-01-30 11:53:59 +01008879/*
8880 * Set the console colors to the original colors or the last set colors.
8881 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008882 static void
8883reset_console_color_rgb(void)
8884{
8885# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008886 if (use_alternate_screen_buffer)
8887 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008888
Christopher Plewright38804d62022-11-09 23:55:52 +00008889 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8890
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008891 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008892 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008893
8894 csbi.cbSize = sizeof(csbi);
8895 csbi.srWindow.Right += 1;
8896 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008897 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8898 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008899 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008900# endif
8901}
8902
8903/*
8904 * Set the console colors to the original colors.
8905 */
8906 static void
8907restore_console_color_rgb(void)
8908{
8909# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008910 if (use_alternate_screen_buffer)
8911 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008912
K.Takata27b53be2022-09-18 12:25:49 +01008913 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008914
8915 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008916 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008917
8918 csbi.cbSize = sizeof(csbi);
8919 csbi.srWindow.Right += 1;
8920 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008921 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8922 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008923 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008924# endif
8925}
8926
8927 void
8928control_console_color_rgb(void)
8929{
Christopher Plewright38804d62022-11-09 23:55:52 +00008930 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008931 set_console_color_rgb();
8932 else
8933 reset_console_color_rgb();
8934}
8935
8936 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008937use_vtp(void)
8938{
8939 return USE_VTP;
8940}
8941
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008942 int
8943is_term_win32(void)
8944{
8945 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8946}
8947
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008948 int
8949has_vtp_working(void)
8950{
8951 return vtp_working;
8952}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008953
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008954#endif
8955
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008956 int
8957has_conpty_working(void)
8958{
8959 return conpty_working;
8960}
8961
8962 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008963get_conpty_type(void)
8964{
8965 return conpty_type;
8966}
8967
8968 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008969is_conpty_stable(void)
8970{
8971 return conpty_stable;
8972}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008973
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008974 int
8975get_conpty_fix_type(void)
8976{
8977 return conpty_fix_type;
8978}
8979
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008980#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008981 void
8982resize_console_buf(void)
8983{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008984 if (use_alternate_screen_buffer)
8985 return;
8986
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008987 CONSOLE_SCREEN_BUFFER_INFO csbi;
8988 COORD coord;
8989 SMALL_RECT newsize;
8990
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008991 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8992 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008993
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008994 coord.X = SRWIDTH(csbi.srWindow);
8995 coord.Y = SRHEIGHT(csbi.srWindow);
8996 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008997
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008998 newsize.Left = 0;
8999 newsize.Top = 0;
9000 newsize.Right = coord.X - 1;
9001 newsize.Bottom = coord.Y - 1;
9002 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
9003
9004 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01009005}
9006#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009007
9008 char *
9009GetWin32Error(void)
9010{
K.Takatad68b2fc2022-02-12 11:18:37 +00009011 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009012 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00009013
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009014 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
9015 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00009016 if (oldmsg != NULL)
9017 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00009018 if (msg == NULL)
9019 return NULL;
9020
9021 // remove trailing \r\n
9022 char *pcrlf = strstr(msg, "\r\n");
9023 if (pcrlf != NULL)
9024 *pcrlf = '\0';
9025 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009026 return msg;
9027}
Paul Ollis65745772022-06-05 16:55:54 +01009028
9029#if defined(FEAT_RELTIME) || defined(PROTO)
9030static HANDLE timer_handle;
9031static int timer_active = FALSE;
9032
9033/*
9034 * Calls to start_timeout alternate the return value pointer between the two
9035 * entries in timeout_flags. If the previously active timeout is very close to
9036 * expiring when start_timeout() is called then a race condition means that the
9037 * set_flag() function may still be invoked after the previous timer is
9038 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
9039 * timeouts.
9040 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009041static sig_atomic_t timeout_flags[2];
9042static int timeout_flag_idx = 0;
9043static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01009044
9045
9046 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01009047set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01009048{
John Marriott2c7ccaa2025-05-26 20:25:38 +02009049 *(sig_atomic_t *)param = TRUE;
Paul Ollis65745772022-06-05 16:55:54 +01009050}
9051
9052/*
9053 * Stop any active timeout.
9054 */
9055 void
9056stop_timeout(void)
9057{
9058 if (timer_active)
9059 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01009060 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01009061 timer_active = FALSE;
9062 if (!ret && GetLastError() != ERROR_IO_PENDING)
9063 {
9064 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
9065 }
9066 }
9067 *timeout_flag = FALSE;
9068}
9069
9070/*
9071 * Start the timeout timer.
9072 *
9073 * The period is defined in milliseconds.
9074 *
9075 * The return value is a pointer to a flag that is initialised to 0. If the
9076 * timeout expires, the flag is set to 1. This will only return pointers to
9077 * static memory; i.e. any pointer returned by this function may always be
9078 * safely dereferenced.
9079 *
9080 * This function is not expected to fail, but if it does it still returns a
9081 * valid flag pointer; the flag will remain stuck at zero.
9082 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009083 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01009084start_timeout(long msec)
9085{
Paul Ollis65745772022-06-05 16:55:54 +01009086 BOOL ret;
9087
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009088 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009089
9090 stop_timeout();
9091 ret = CreateTimerQueueTimer(
9092 &timer_handle, NULL, set_flag, timeout_flag,
9093 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9094 if (!ret)
9095 {
9096 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9097 }
9098 else
9099 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009100 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009101 timer_active = TRUE;
9102 *timeout_flag = FALSE;
9103 }
9104 return timeout_flag;
9105}
9106#endif