blob: 0f71a3cd99a073b0de32ca6e52e48ee4d3ff935b [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{
K.Takatace3189d2023-02-15 19:13:43 +0000434 int updated = FALSE;
435 static int enc_prev = -1;
John Marriotte5297e32025-06-15 16:50:38 +0200436 WCHAR *path;
437 size_t pathlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000438
K.Takatace3189d2023-02-15 19:13:43 +0000439 if (exe_name == NULL || exe_pathw == NULL || enc_prev != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440 {
John Marriotte5297e32025-06-15 16:50:38 +0200441 WCHAR buf[MAX_PATH];
442 WCHAR *p;
443
Bram Moolenaar0f873732019-12-05 20:28:46 +0100444 // store the name of the executable, may be used for $VIM
John Marriotte5297e32025-06-15 16:50:38 +0200445 p = buf + GetModuleFileNameW(NULL, buf, MAX_PATH);
446 if (p > buf)
K.Takatace3189d2023-02-15 19:13:43 +0000447 {
448 if (enc_codepage == -1)
449 enc_codepage = GetACP();
K.Takataf741e3e2023-05-15 16:41:40 +0100450 vim_free(exe_name);
K.Takatace3189d2023-02-15 19:13:43 +0000451 exe_name = utf16_to_enc(buf, NULL);
452 enc_prev = enc_codepage;
453
John Marriotte5297e32025-06-15 16:50:38 +0200454 // truncate the buffer at the last path separator
455 // to isolate the path.
456 do
457 {
458 --p;
459 if (*p == L'\\')
460 {
461 *p = L'\0';
462 break;
463 }
464 } while (p > buf);
465
K.Takataf741e3e2023-05-15 16:41:40 +0100466 vim_free(exe_pathw);
K.Takatace3189d2023-02-15 19:13:43 +0000467 exe_pathw = _wcsdup(buf);
468 updated = TRUE;
469 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000471
K.Takatace3189d2023-02-15 19:13:43 +0000472 if (exe_pathw == NULL || !updated)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000473 return;
474
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000475 // Append our starting directory to $PATH, so that when doing
476 // "!xxd" it's found in our starting directory. Needed because
477 // SearchPath() also looks there.
John Marriotte5297e32025-06-15 16:50:38 +0200478 path = _wgetenv(L"PATH");
479 pathlen = (path == NULL) ? 0 : wcslen(path);
K.Takataf741e3e2023-05-15 16:41:40 +0100480
John Marriotte5297e32025-06-15 16:50:38 +0200481 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
482 // as the maximum length that works. Add an extra 7 characters (5 for
483 // "PATH=", 1 for a potential ";" and 1 for the NUL byte).
484#define EXTRA_LEN 7
485#define MAX_ENV_STRING_LEN 8191
486
487 if (pathlen + wcslen(exe_pathw) < MAX_ENV_STRING_LEN)
488 {
489 WCHAR temp[MAX_ENV_STRING_LEN + EXTRA_LEN] = L"PATH=";
490 size_t templen = 5;
491
492 if (pathlen == 0)
493 wcscpy(temp + templen, exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000494 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000495 {
John Marriotte5297e32025-06-15 16:50:38 +0200496 wcscpy(temp + templen, path);
K.Takataf741e3e2023-05-15 16:41:40 +0100497
498 // Check if exe_path is already included in $PATH.
499 if (wcsstr(temp, exe_pathw) == NULL)
500 {
John Marriotte5297e32025-06-15 16:50:38 +0200501 templen += pathlen;
K.Takataf741e3e2023-05-15 16:41:40 +0100502
John Marriotte5297e32025-06-15 16:50:38 +0200503 // Append ';' if $PATH doesn't end with it.
504 if (temp[templen - 1] != L';')
505 {
506 wcscpy(temp + templen, L";");
507 ++templen;
508 }
509
510 wcscpy(temp + templen, exe_pathw);
K.Takataf741e3e2023-05-15 16:41:40 +0100511 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000512 }
John Marriotte5297e32025-06-15 16:50:38 +0200513
K.Takataf741e3e2023-05-15 16:41:40 +0100514 _wputenv(temp);
515#ifdef libintl_wputenv
516 libintl_wputenv(temp);
517#endif
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000518 }
John Marriotte5297e32025-06-15 16:50:38 +0200519#undef EXTRA_LEN
520#undef MAX_ENV_PATH_LEN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521}
522
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200523/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100524 * Unescape characters in "p" that appear in "escaped".
525 */
526 static void
527unescape_shellxquote(char_u *p, char_u *escaped)
528{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100529 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100530 int n;
531
532 while (*p != NUL)
533 {
534 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
535 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100536 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100537 p += n;
538 l -= n;
539 }
540}
541
542/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200543 * Load library "name".
544 */
545 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000546vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200547{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200548 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200549
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200550 // No need to load any library when registering OLE.
551 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000552 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200553
Bram Moolenaar0f873732019-12-05 20:28:46 +0100554 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
555 // vimLoadLib() recursively, which causes a stack overflow.
K.Takatace3189d2023-02-15 19:13:43 +0000556 if (exe_pathw == NULL)
K.Takataf741e3e2023-05-15 16:41:40 +0100557 {
K.Takatace3189d2023-02-15 19:13:43 +0000558 mch_get_exe_name();
K.Takataf741e3e2023-05-15 16:41:40 +0100559 if (exe_pathw == NULL)
560 return NULL;
561 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000562
563 WCHAR old_dirw[MAXPATHL];
564
565 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
566 return NULL;
567
568 // Change directory to where the executable is, both to make
569 // sure we find a .dll there and to avoid looking for a .dll
570 // in the current directory.
K.Takatace3189d2023-02-15 19:13:43 +0000571 SetCurrentDirectoryW(exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000572 dll = LoadLibrary(name);
573 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200574 return dll;
575}
576
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200577#if defined(VIMDLL) || defined(PROTO)
578/*
579 * Check if the current executable file is for the GUI subsystem.
580 */
581 int
582mch_is_gui_executable(void)
583{
584 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
585 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
586 PIMAGE_NT_HEADERS pPE;
587
588 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
589 return FALSE;
590 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
591 if (pPE->Signature != IMAGE_NT_SIGNATURE)
592 return FALSE;
593 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
594 return TRUE;
595 return FALSE;
596}
597#endif
598
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000599#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
600 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100601/*
602 * Get related information about 'funcname' which is imported by 'hInst'.
603 * If 'info' is 0, return the function address.
604 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000605 * If 'info' is 2, hook the function with 'ptr', and return the original
606 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100607 */
608 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000609get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
610 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100611{
612 PBYTE pImage = (PBYTE)hInst;
613 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
614 PIMAGE_NT_HEADERS pPE;
615 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100616 PIMAGE_THUNK_DATA pIAT; // Import Address Table
617 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100618 PIMAGE_IMPORT_BY_NAME pImpName;
Ken Takata119fdd92023-10-04 20:05:05 +0200619 DWORD ImpVA;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100620
621 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
622 return NULL;
623 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
624 if (pPE->Signature != IMAGE_NT_SIGNATURE)
625 return NULL;
Ken Takata119fdd92023-10-04 20:05:05 +0200626
627 ImpVA = pPE->OptionalHeader
628 .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
629 if (ImpVA == 0)
630 return NULL; // No Import Table
631 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage + ImpVA);
632
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100633 for (; pImpDesc->FirstThunk; ++pImpDesc)
634 {
635 if (!pImpDesc->OriginalFirstThunk)
636 continue;
637 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
638 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
639 for (; pIAT->u1.Function; ++pIAT, ++pINT)
640 {
641 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
642 continue;
643 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
644 + (UINT_PTR)(pINT->u1.AddressOfData));
645 if (strcmp((char *)pImpName->Name, funcname) == 0)
646 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000647 void *original;
648 DWORD old, new = PAGE_READWRITE;
649
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100650 switch (info)
651 {
652 case 0:
653 return (void *)pIAT->u1.Function;
654 case 1:
655 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000656 case 2:
657 original = (void *)pIAT->u1.Function;
658 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
659 new, &old);
660 pIAT->u1.Function = (UINT_PTR)ptr;
661 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
662 old, &new);
663 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100664 default:
665 return NULL;
666 }
667 }
668 }
669 }
670 return NULL;
671}
672
673/*
674 * Get the module handle which 'funcname' in 'hInst' is imported from.
675 */
676 HINSTANCE
677find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
678{
679 char *modulename;
680
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000681 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100682 if (modulename != NULL)
683 return GetModuleHandleA(modulename);
684 return NULL;
685}
686
687/*
688 * Get the address of 'funcname' which is imported by 'hInst' DLL.
689 */
690 void *
691get_dll_import_func(HINSTANCE hInst, const char *funcname)
692{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000693 return get_imported_func_info(hInst, funcname, 0, NULL);
694}
695
696/*
697 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
698 * and return the original function address.
699 */
700 void *
701hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
702{
703 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100704}
705#endif
706
Ken Takata119fdd92023-10-04 20:05:05 +0200707#if defined(FEAT_PYTHON3) || defined(PROTO)
708/*
709 * Check if the specified DLL is a function forwarder.
710 * If yes, return the instance of the forwarded DLL.
711 * If no, return the specified DLL.
712 * If error, return NULL.
713 * This assumes that the DLL forwards all the function to a single DLL.
714 */
715 HINSTANCE
716get_forwarded_dll(HINSTANCE hInst)
717{
718 PBYTE pImage = (PBYTE)hInst;
719 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
720 PIMAGE_NT_HEADERS pPE;
721 PIMAGE_EXPORT_DIRECTORY pExpDir;
722 DWORD ExpVA;
723 DWORD ExpSize;
724 LPDWORD pFunctionTable;
725
726 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
727 return NULL;
728 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
729 if (pPE->Signature != IMAGE_NT_SIGNATURE)
730 return NULL;
731
732 ExpVA = pPE->OptionalHeader
733 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
734 ExpSize = pPE->OptionalHeader
735 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
736 if (ExpVA == 0)
737 return hInst; // No Export Directory
738 pExpDir = (PIMAGE_EXPORT_DIRECTORY)(pImage + ExpVA);
739 pFunctionTable = (LPDWORD)(pImage + pExpDir->AddressOfFunctions);
740
741 if (pExpDir->NumberOfNames == 0)
742 return hInst; // No export names.
743
744 // Check only the first entry.
745 if ((pFunctionTable[0] < ExpVA) || (pFunctionTable[0] >= ExpVA + ExpSize))
746 // The first entry is not a function forwarder.
747 return hInst;
748
749 // The first entry is a function forwarder.
750 // The name is represented as "DllName.FunctionName".
751 const char *name = (const char *)(pImage + pFunctionTable[0]);
752 const char *p = strchr(name, '.');
753 if (p == NULL)
754 return hInst;
755
756 // Extract DllName.
757 char buf[MAX_PATH];
758 if (p - name + 1 > sizeof(buf))
759 return NULL;
760 strncpy(buf, name, p - name);
John Marriotte5297e32025-06-15 16:50:38 +0200761 buf[p - name] = NUL;
Ken Takata119fdd92023-10-04 20:05:05 +0200762 return GetModuleHandleA(buf);
763}
764#endif
765
Bram Moolenaar071d4272004-06-13 20:20:40 +0000766#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
767# ifndef GETTEXT_DLL
768# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200769# define GETTEXT_DLL_ALT1 "libintl-8.dll"
770# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100772// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000773static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200774static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000775static char *null_libintl_textdomain(const char *);
776static char *null_libintl_bindtextdomain(const char *, const char *);
777static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100778static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200780static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000781char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200782char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
783 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000784char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
785char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000787char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
788 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100789int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790
791 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100792dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000793{
794 int i;
795 static struct
796 {
797 char *name;
798 FARPROC *ptr;
799 } libintl_entry[] =
800 {
801 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200802 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
804 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
805 {NULL, NULL}
806 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100807 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808
Bram Moolenaar7554c542018-10-06 15:03:15 +0200809 // No need to initialize twice.
810 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200812 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100813 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100814# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100815 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200816 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100817# endif
818# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200819 if (!hLibintlDLL)
820 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100821# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100822 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000823 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200824 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200826 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000827 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200828 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200830 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000831 }
832 for (i = 0; libintl_entry[i].name != NULL
833 && libintl_entry[i].ptr != NULL; ++i)
834 {
K.Takata54119102022-02-03 13:33:03 +0000835 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836 libintl_entry[i].name)) == NULL)
837 {
838 dyn_libintl_end();
839 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000840 {
841 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000842 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000843 verbose_leave();
844 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845 return 0;
846 }
847 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000848
Bram Moolenaar0f873732019-12-05 20:28:46 +0100849 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100850 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
851 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000852 if (dyn_libintl_bind_textdomain_codeset == NULL)
853 dyn_libintl_bind_textdomain_codeset =
854 null_libintl_bind_textdomain_codeset;
855
Bram Moolenaar0f873732019-12-05 20:28:46 +0100856 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100857 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
858 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100859 dyn_libintl_wputenv = (int (*)(const wchar_t *))
860 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100861 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
862 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100863
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864 return 1;
865}
866
867 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100868dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869{
870 if (hLibintlDLL)
871 FreeLibrary(hLibintlDLL);
872 hLibintlDLL = NULL;
873 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200874 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875 dyn_libintl_textdomain = null_libintl_textdomain;
876 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000877 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100878 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879}
880
881 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000882null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883{
884 return (char*)msgid;
885}
886
887 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200888null_libintl_ngettext(
889 const char *msgid,
890 const char *msgid_plural,
891 unsigned long n)
892{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200893 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200894}
895
Bram Moolenaaree695f72016-08-03 22:08:45 +0200896 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100897null_libintl_bindtextdomain(
898 const char *domainname UNUSED,
899 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900{
901 return NULL;
902}
903
904 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100905null_libintl_bind_textdomain_codeset(
906 const char *domainname UNUSED,
907 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000908{
909 return NULL;
910}
911
912 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100913null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914{
915 return NULL;
916}
917
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200918 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100919null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100920{
921 return 0;
922}
923
Bram Moolenaar0f873732019-12-05 20:28:46 +0100924#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925
Bram Moolenaar0f873732019-12-05 20:28:46 +0100926// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927
928#ifndef VER_PLATFORM_WIN32_WINDOWS
929# define VER_PLATFORM_WIN32_WINDOWS 1
930#endif
931
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100933# ifndef PROTO
934# include <aclapi.h>
935# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200936# ifndef PROTECTED_DACL_SECURITY_INFORMATION
937# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
938# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939#endif
940
Bram Moolenaar27515922013-06-29 15:36:26 +0200941#ifdef HAVE_ACL
942/*
943 * Enables or disables the specified privilege.
944 */
945 static BOOL
Nir Lichtmanb5165982024-10-13 19:44:07 +0200946win32_enable_privilege(LPTSTR lpszPrivilege)
Bram Moolenaar27515922013-06-29 15:36:26 +0200947{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100948 LUID luid;
949 HANDLE hToken;
950 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200951
952 if (!OpenProcessToken(GetCurrentProcess(),
953 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
954 return FALSE;
955
956 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
957 {
958 CloseHandle(hToken);
959 return FALSE;
960 }
961
Bram Moolenaar45500912014-07-09 20:51:07 +0200962 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200963 tokenPrivileges.Privileges[0].Luid = luid;
Nir Lichtmanb5165982024-10-13 19:44:07 +0200964 tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
Bram Moolenaar27515922013-06-29 15:36:26 +0200965
Nir Lichtmanb5165982024-10-13 19:44:07 +0200966 if (!AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges, 0, NULL, NULL))
967 {
968 CloseHandle(hToken);
969 return FALSE;
970 }
971
972 if (GetLastError() != ERROR_SUCCESS)
973 {
974 CloseHandle(hToken);
975 return FALSE;
976 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200977
978 CloseHandle(hToken);
Nir Lichtmanb5165982024-10-13 19:44:07 +0200979 return TRUE;
Bram Moolenaar27515922013-06-29 15:36:26 +0200980}
981#endif
982
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100983#ifdef _MSC_VER
984// Suppress the deprecation warning for using GetVersionEx().
985// It is needed for implementing "windowsversion()".
986# pragma warning(push)
987# pragma warning(disable: 4996)
988#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200990 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991 */
992 void
993PlatformId(void)
994{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000995 OSVERSIONINFO ovi;
996
997 ovi.dwOSVersionInfoSize = sizeof(ovi);
Nir Lichtmanb5165982024-10-13 19:44:07 +0200998 if (!GetVersionEx(&ovi))
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +0200999 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +02001001#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001002 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
1003 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +02001004#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001005 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
1006 || ovi.dwMajorVersion > 6)
1007 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +01001008
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001009 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
1010 || ovi.dwMajorVersion > 10)
1011 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +00001012
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001014 // Enable privilege for getting or setting SACLs.
Nir Lichtmanb5165982024-10-13 19:44:07 +02001015 if (!win32_enable_privilege(SE_SECURITY_NAME))
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +02001016 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001018}
Bram Moolenaar29d2f452020-12-04 19:42:52 +01001019#ifdef _MSC_VER
1020# pragma warning(pop)
1021#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001023#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001025# define SHIFT (SHIFT_PRESSED)
1026# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
1027# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
1028# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029
1030
Bram Moolenaar0f873732019-12-05 20:28:46 +01001031// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
1032// We map function keys to their ANSI terminal equivalents, as produced
1033// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
1034// ANSI key with a value >= '\300' is nonstandard, but provided anyway
1035// so that the user can have access to all SHIFT-, CTRL-, and ALT-
1036// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
Bram Moolenaard6f676d2005-06-01 21:51:55 +00001038static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +00001039{
1040 WORD wVirtKey;
1041 BOOL fAnsiKey;
1042 int chAlone;
1043 int chShift;
1044 int chCtrl;
1045 int chAlt;
1046} VirtKeyMap[] =
1047{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001048// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
1050
1051 { VK_F1, TRUE, ';', 'T', '^', 'h', },
1052 { VK_F2, TRUE, '<', 'U', '_', 'i', },
1053 { VK_F3, TRUE, '=', 'V', '`', 'j', },
1054 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
1055 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
1056 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
1057 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
1058 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
1059 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
1060 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001061 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
1062 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001064 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
1065 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
1066 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
1067 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
1068 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
1069 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
1070 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
1071 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
1072 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
1073 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001074 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001076 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001078# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001079 // Most people don't have F13-F20, but what the hell...
1080 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
1081 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
1082 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1083 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1084 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1085 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1086 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1087 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001088# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001089 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1090 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1091 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1092 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001094 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1095 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1096 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1097 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1098 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1099 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1100 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1101 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1102 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1103 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001104 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105};
1106
1107
Bram Moolenaar0f873732019-12-05 20:28:46 +01001108/*
1109 * The return code indicates key code size.
1110 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001113 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114{
1115 UINT uMods = pker->dwControlKeyState;
1116 static int s_iIsDead = 0;
1117 static WORD awAnsiCode[2];
1118 static BYTE abKeystate[256];
1119
Bram Moolenaar071d4272004-06-13 20:20:40 +00001120 if (s_iIsDead == 2)
1121 {
K.Takata972db232022-02-04 10:45:38 +00001122 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123 s_iIsDead = 0;
1124 return 1;
1125 }
1126
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001127 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001128 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129 return 1;
1130
Bram Moolenaara80faa82020-04-12 19:37:17 +02001131 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001132
Bram Moolenaar0f873732019-12-05 20:28:46 +01001133 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001134 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001135
1136 if (uMods & SHIFT_PRESSED)
1137 abKeystate[VK_SHIFT] = 0x80;
1138 if (uMods & CAPSLOCK_ON)
1139 abKeystate[VK_CAPITAL] = 1;
1140
1141 if ((uMods & ALT_GR) == ALT_GR)
1142 {
1143 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1144 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1145 }
1146
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001147 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1148 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001149
1150 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001151 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001152
1153 return s_iIsDead;
1154}
1155
Bram Moolenaar071d4272004-06-13 20:20:40 +00001156static BOOL g_fJustGotFocus = FALSE;
1157
1158/*
1159 * Decode a KEY_EVENT into one or two keystrokes
1160 */
1161 static BOOL
1162decode_key_event(
1163 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001164 WCHAR *pch,
1165 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001167 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168{
1169 int i;
1170 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1171
1172 *pch = *pch2 = NUL;
1173 g_fJustGotFocus = FALSE;
1174
Bram Moolenaar0f873732019-12-05 20:28:46 +01001175 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001176 if (!pker->bKeyDown)
1177 return FALSE;
1178
Bram Moolenaar0f873732019-12-05 20:28:46 +01001179 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180 switch (pker->wVirtualKeyCode)
1181 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001182 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183 case VK_SHIFT:
1184 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001185 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001186 return FALSE;
1187
1188 default:
1189 break;
1190 }
1191
Bram Moolenaar0f873732019-12-05 20:28:46 +01001192 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001193 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1194 {
1195 *pch = K_NUL;
1196 *pch2 = '\017';
1197 return TRUE;
1198 }
1199
John Marriotte5297e32025-06-15 16:50:38 +02001200 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001201 {
1202 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1203 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001204 *pch = VirtKeyMap[i].chAlone;
1205 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001206 *pch = VirtKeyMap[i].chShift;
1207 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1208 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001209 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210 *pch = VirtKeyMap[i].chAlt;
1211
1212 if (*pch != 0)
1213 {
1214 if (VirtKeyMap[i].fAnsiKey)
1215 {
1216 *pch2 = *pch;
1217 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001218 if (pmodifiers)
1219 {
1220 if (pker->wVirtualKeyCode >= VK_F1
1221 && pker->wVirtualKeyCode <= VK_F12)
1222 {
1223 if ((nModifs & ALT) != 0)
1224 {
1225 *pmodifiers |= MOD_MASK_ALT;
1226 if ((nModifs & SHIFT) == 0)
1227 *pch2 = VirtKeyMap[i].chAlone;
1228 }
1229 if ((nModifs & CTRL) != 0)
1230 {
1231 *pmodifiers |= MOD_MASK_CTRL;
1232 if ((nModifs & SHIFT) == 0)
1233 *pch2 = VirtKeyMap[i].chAlone;
1234 }
1235 }
1236 else if (pker->wVirtualKeyCode >= VK_END
1237 && pker->wVirtualKeyCode <= VK_DOWN)
1238 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001239 // (0x23 - 0x28): VK_END, VK_HOME,
1240 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1241
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001242 *pmodifiers = 0;
1243 *pch2 = VirtKeyMap[i].chAlone;
1244 if ((nModifs & SHIFT) != 0
1245 && (nModifs & ~SHIFT) == 0)
1246 {
1247 *pch2 = VirtKeyMap[i].chShift;
1248 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001249 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001250 && (nModifs & ~CTRL) == 0)
1251 {
1252 *pch2 = VirtKeyMap[i].chCtrl;
1253 if (pker->wVirtualKeyCode == VK_UP
1254 || pker->wVirtualKeyCode == VK_DOWN)
1255 {
1256 *pmodifiers |= MOD_MASK_CTRL;
1257 *pch2 = VirtKeyMap[i].chAlone;
1258 }
1259 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001260 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001261 && (nModifs & CTRL) != 0)
1262 {
1263 *pmodifiers |= MOD_MASK_CTRL;
1264 *pch2 = VirtKeyMap[i].chShift;
1265 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001266 if ((nModifs & ALT) != 0)
1267 {
1268 *pch2 = VirtKeyMap[i].chAlt;
1269 *pmodifiers |= MOD_MASK_ALT;
1270 if ((nModifs & ~ALT) == 0)
1271 {
1272 *pch2 = VirtKeyMap[i].chAlone;
1273 }
1274 else if ((nModifs & SHIFT) != 0)
1275 {
1276 *pch2 = VirtKeyMap[i].chShift;
1277 }
1278 else if ((nModifs & CTRL) != 0)
1279 {
1280 if (pker->wVirtualKeyCode == VK_UP
1281 || pker->wVirtualKeyCode == VK_DOWN)
1282 {
1283 *pmodifiers |= MOD_MASK_CTRL;
1284 *pch2 = VirtKeyMap[i].chAlone;
1285 }
1286 else
1287 {
1288 *pch2 = VirtKeyMap[i].chCtrl;
1289 }
1290 }
1291 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001292 }
Christopher Plewrightf5f69e82024-08-04 19:57:44 +02001293 else if (pker->wVirtualKeyCode == VK_INSERT
1294 && (nModifs & SHIFT) != 0
1295 && (nModifs & ~SHIFT) == 0)
1296 {
1297 *pmodifiers = 0;
1298 *pch2 = VirtKeyMap[i].chShift;
1299 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001300 else
1301 {
1302 *pch2 = VirtKeyMap[i].chAlone;
1303 if ((nModifs & SHIFT) != 0)
1304 *pmodifiers |= MOD_MASK_SHIFT;
1305 if ((nModifs & CTRL) != 0)
1306 *pmodifiers |= MOD_MASK_CTRL;
1307 if ((nModifs & ALT) != 0)
1308 *pmodifiers |= MOD_MASK_ALT;
1309 }
1310 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001311 }
1312
1313 return TRUE;
1314 }
1315 }
1316 }
1317
1318 i = win32_kbd_patch_key(pker);
1319
1320 if (i < 0)
1321 *pch = NUL;
1322 else
1323 {
K.Takata972db232022-02-04 10:45:38 +00001324 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325
1326 if (pmodifiers != NULL)
1327 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001328 // Pass on the ALT key as a modifier, but only when not combined
1329 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001330 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1331 *pmodifiers |= MOD_MASK_ALT;
1332
Bram Moolenaar0f873732019-12-05 20:28:46 +01001333 // Pass on SHIFT only for special keys, because we don't know when
1334 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1336 *pmodifiers |= MOD_MASK_SHIFT;
1337
Bram Moolenaar0f873732019-12-05 20:28:46 +01001338 // Pass on CTRL only for non-special keys, because we don't know
1339 // when it's already included with the character. And not when
1340 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1342 && *pch >= 0x20 && *pch < 0x80)
1343 *pmodifiers |= MOD_MASK_CTRL;
1344 }
1345 }
1346
1347 return (*pch != NUL);
1348}
1349
Christopher Plewright20b795e2022-12-20 20:01:58 +00001350# if defined(FEAT_EVAL)
1351 static int
1352encode_key_event(dict_T *args, INPUT_RECORD *ir)
1353{
1354 static int s_dwMods = 0;
1355
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001356 char_u *action = dict_get_string(args, "event", TRUE);
1357 if (action && (STRICMP(action, "keydown") == 0
1358 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001359 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001360 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001361 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1362 if (vkCode <= 0 || vkCode >= 0xFF)
1363 {
1364 semsg(_(e_invalid_argument_nr), (long)vkCode);
1365 return FALSE;
1366 }
1367
1368 ir->EventType = KEY_EVENT;
1369 KEY_EVENT_RECORD ker;
1370 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001371 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001372 ker.wRepeatCount = 1;
1373 ker.wVirtualScanCode = 0;
1374 ker.dwControlKeyState = 0;
1375 int mods = (int)dict_get_number(args, "modifiers");
1376 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1377 if (mods)
1378 {
1379 // If "modifiers" is explicitly set in the args, then we reset any
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00001380 // remembered modifier key state that may have been set from
1381 // earlier mod-key-down events, even if they are not yet unset by
1382 // earlier mod-key-up events.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001383 s_dwMods = 0;
1384 if (mods & MOD_MASK_SHIFT)
1385 ker.dwControlKeyState |= SHIFT_PRESSED;
1386 if (mods & MOD_MASK_CTRL)
1387 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1388 if (mods & MOD_MASK_ALT)
1389 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1390 }
1391
1392 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1393 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001394 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001395 s_dwMods |= SHIFT_PRESSED;
1396 else
1397 s_dwMods &= ~SHIFT_PRESSED;
1398 }
1399 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1400 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001401 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001402 s_dwMods |= LEFT_CTRL_PRESSED;
1403 else
1404 s_dwMods &= ~LEFT_CTRL_PRESSED;
1405 }
1406 else if (vkCode == VK_RCONTROL)
1407 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001408 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001409 s_dwMods |= RIGHT_CTRL_PRESSED;
1410 else
1411 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1412 }
1413 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1414 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001415 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001416 s_dwMods |= LEFT_ALT_PRESSED;
1417 else
1418 s_dwMods &= ~LEFT_ALT_PRESSED;
1419 }
1420 else if (vkCode == VK_RMENU)
1421 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001422 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001423 s_dwMods |= RIGHT_ALT_PRESSED;
1424 else
1425 s_dwMods &= ~RIGHT_ALT_PRESSED;
1426 }
1427 ker.dwControlKeyState |= s_dwMods;
1428 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001429 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001430 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001431 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001432 }
1433 else
1434 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001435 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001436 {
1437 semsg(_(e_missing_argument_str), "event");
1438 }
1439 else
1440 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001441 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1442 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001443 }
1444 return FALSE;
1445 }
1446 return TRUE;
1447}
1448# endif // FEAT_EVAL
1449#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450
1451
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452/*
1453 * For the GUI the mouse handling is in gui_w32.c.
1454 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001455#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001457mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458{
1459}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001460#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001461static int g_fMouseAvail = FALSE; // mouse present
1462static int g_fMouseActive = FALSE; // mouse enabled
1463static int g_nMouseClick = -1; // mouse status
1464static int g_xMouse; // mouse x coordinate
1465static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001466static DWORD g_cmodein = 0; // Original console input mode
1467static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468
1469/*
1470 * Enable or disable mouse input
1471 */
1472 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001473mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474{
1475 DWORD cmodein;
1476
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001477# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001478 if (gui.in_use)
1479 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001480# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001481 if (!g_fMouseAvail)
1482 return;
1483
1484 g_fMouseActive = on;
1485 GetConsoleMode(g_hConIn, &cmodein);
1486
1487 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001488 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001490 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001493 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001495 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1496 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001498 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499}
1500
Bram Moolenaar157d8132018-03-06 17:09:20 +01001501
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001502# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001503/*
1504 * Called when 'balloonevalterm' changed.
1505 */
1506 void
1507mch_bevalterm_changed(void)
1508{
1509 mch_setmouse(g_fMouseActive);
1510}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001511# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001512
Christopher Plewright2a46f812022-10-16 19:47:45 +01001513/*
1514 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001515 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001516 *
1517 * This encodes the mouse scroll direction and keyboard modifiers into
1518 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1519 *
1520 * The direction of the scroll is decoded from two fields of the win32 console
1521 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001522 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001523 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1524 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001525 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001526 * - If the high word of the dwButtonState member contains a positive
1527 * value, the wheel was rotated to the right.
1528 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001529 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001530 * - If the high word of the dwButtonState member contains a positive value,
1531 * the wheel was rotated forward, away from the user.
1532 * - Otherwise, the wheel was rotated backward, toward the user.
1533 */
1534 static void
1535decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1536{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001537 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1538 int zDelta = pmer->dwButtonState;
1539
1540 g_xMouse = pmer->dwMousePosition.X;
1541 g_yMouse = pmer->dwMousePosition.Y;
1542
K.Takata161b6ac2022-11-14 15:31:07 +00001543# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001544 int lcol = g_xMouse;
1545 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001546 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001547 if (wp != NULL && popup_is_popup(wp))
1548 {
1549 g_nMouseClick = -1;
1550 cmdarg_T cap;
1551 oparg_T oa;
1552 CLEAR_FIELD(cap);
1553 clear_oparg(&oa);
1554 cap.oap = &oa;
1555 if (horizontal)
1556 {
1557 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1558 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1559 }
1560 else
1561 {
1562 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1563 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1564 }
1565
1566 // Mouse hovers over popup window, scroll it if possible.
1567 mouse_row = wp->w_winrow;
1568 mouse_col = wp->w_wincol;
1569 nv_mousescroll(&cap);
1570 update_screen(0);
1571 setcursor();
1572 out_flush();
1573 return;
1574 }
K.Takata161b6ac2022-11-14 15:31:07 +00001575# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001576 mouse_col = g_xMouse;
1577 mouse_row = g_yMouse;
1578
1579 char_u modifiers = 0;
1580 char_u direction = 0;
1581
1582 // Decode the direction into an event that Vim can process
1583 if (horizontal)
1584 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1585 else
1586 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1587
dundargocc57b5bc2022-11-02 13:30:51 +00001588 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001589 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001590 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001591 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001592 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001593 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1594 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1595
1596 // add (bitwise or) the scroll direction and the key modifier chars
1597 // together.
1598 g_nMouseClick = ((direction << 8) | modifiers);
1599
1600 return;
1601}
1602
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603/*
1604 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1605 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1606 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1607 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1608 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1609 * and we return the mouse position in g_xMouse and g_yMouse.
1610 *
1611 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1612 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1613 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1614 *
1615 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1616 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1617 *
1618 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1619 * moves, even if it stays within the same character cell. We ignore
1620 * all MOUSE_MOVED messages if the position hasn't really changed, and
1621 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1622 * we're only interested in MOUSE_DRAG).
1623 *
1624 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1625 * 2-button mouses by pressing the left & right buttons simultaneously.
1626 * In practice, it's almost impossible to click both at the same time,
1627 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1628 * in such cases, if the user is clicking quickly.
1629 */
1630 static BOOL
1631decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001632 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633{
1634 static int s_nOldButton = -1;
1635 static int s_nOldMouseClick = -1;
1636 static int s_xOldMouse = -1;
1637 static int s_yOldMouse = -1;
1638 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001639# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001641# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 static int s_cClicks = 1;
1643 static BOOL s_fReleased = TRUE;
1644 static DWORD s_dwLastClickTime = 0;
1645 static BOOL s_fNextIsMiddle = FALSE;
1646
Bram Moolenaar0f873732019-12-05 20:28:46 +01001647 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648
1649 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1650 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1651 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1652 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1653
1654 int nButton;
1655
1656 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1657 cButtons = 2;
1658
1659 if (!g_fMouseAvail || !g_fMouseActive)
1660 {
1661 g_nMouseClick = -1;
1662 return FALSE;
1663 }
1664
Bram Moolenaar0f873732019-12-05 20:28:46 +01001665 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666 if (g_fJustGotFocus)
1667 {
1668 g_fJustGotFocus = FALSE;
1669 return FALSE;
1670 }
1671
Christopher Plewright605d02a2022-10-19 11:54:46 +01001672 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673 if (g_nMouseClick != -1)
1674 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001675
Christopher Plewright2a46f812022-10-16 19:47:45 +01001676 if (pmer->dwEventFlags == MOUSE_WHEELED
1677 || pmer->dwEventFlags == MOUSE_HWHEELED)
1678 {
1679 decode_mouse_wheel(pmer);
1680 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1681 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001682
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 nButton = -1;
1684 g_xMouse = pmer->dwMousePosition.X;
1685 g_yMouse = pmer->dwMousePosition.Y;
1686
1687 if (pmer->dwEventFlags == MOUSE_MOVED)
1688 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001689 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1690 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1692 return FALSE;
1693 }
1694
Bram Moolenaar0f873732019-12-05 20:28:46 +01001695 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1697 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001698 nButton = MOUSE_RELEASE;
1699
Bram Moolenaar0f873732019-12-05 20:28:46 +01001700 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001702 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001703# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001704 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001705 if (p_bevalterm)
1706 nButton = MOUSE_DRAG;
1707 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001708# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001709 return FALSE;
1710 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 s_fReleased = TRUE;
1713 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001714 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001716 // on a 2-button mouse, hold down left and right buttons
1717 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718
1719 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1720 {
1721 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1722
Bram Moolenaar0f873732019-12-05 20:28:46 +01001723 // if either left or right button only is pressed, see if the
1724 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 if (dwLR == LEFT || dwLR == RIGHT)
1726 {
1727 for (;;)
1728 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001729 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1731 != WAIT_OBJECT_0)
1732 break;
1733 else
1734 {
1735 DWORD cRecords = 0;
1736 INPUT_RECORD ir;
1737 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1738
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001739 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001740
1741 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1742 || !(pmer2->dwButtonState & LEFT_RIGHT))
1743 break;
1744 else
1745 {
1746 if (pmer2->dwEventFlags != MOUSE_MOVED)
1747 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001748 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749
1750 return decode_mouse_event(pmer2);
1751 }
1752 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1753 s_yOldMouse == pmer2->dwMousePosition.Y)
1754 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001755 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001756 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001757
Bram Moolenaar0f873732019-12-05 20:28:46 +01001758 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001759 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760
1761 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1762 break;
1763 }
1764 else
1765 break;
1766 }
1767 }
1768 }
1769 }
1770 }
1771
1772 if (s_fNextIsMiddle)
1773 {
1774 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1775 ? MOUSE_DRAG : MOUSE_MIDDLE;
1776 s_fNextIsMiddle = FALSE;
1777 }
1778 else if (cButtons == 2 &&
1779 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1780 {
1781 nButton = MOUSE_MIDDLE;
1782
1783 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1784 {
1785 s_fNextIsMiddle = TRUE;
1786 nButton = MOUSE_RELEASE;
1787 }
1788 }
1789 else if ((pmer->dwButtonState & LEFT) == LEFT)
1790 nButton = MOUSE_LEFT;
1791 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1792 nButton = MOUSE_MIDDLE;
1793 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1794 nButton = MOUSE_RIGHT;
1795
1796 if (! s_fReleased && ! s_fNextIsMiddle
1797 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1798 return FALSE;
1799
1800 s_fReleased = s_fNextIsMiddle;
1801 }
1802
1803 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1804 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001805 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 if (nButton != -1 && nButton != MOUSE_RELEASE)
1807 {
1808 DWORD dwCurrentTime = GetTickCount();
1809
1810 if (s_xOldMouse != g_xMouse
1811 || s_yOldMouse != g_yMouse
1812 || s_nOldButton != nButton
1813 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001814# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001816# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1818 {
1819 s_cClicks = 1;
1820 }
1821 else if (++s_cClicks > 4)
1822 {
1823 s_cClicks = 1;
1824 }
1825
1826 s_dwLastClickTime = dwCurrentTime;
1827 }
1828 }
1829 else if (pmer->dwEventFlags == MOUSE_MOVED)
1830 {
1831 if (nButton != -1 && nButton != MOUSE_RELEASE)
1832 nButton = MOUSE_DRAG;
1833
1834 s_cClicks = 1;
1835 }
1836
1837 if (nButton == -1)
1838 return FALSE;
1839
1840 if (nButton != MOUSE_RELEASE)
1841 s_nOldButton = nButton;
1842
1843 g_nMouseClick = nButton;
1844
1845 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1846 g_nMouseClick |= MOUSE_SHIFT;
1847 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1848 g_nMouseClick |= MOUSE_CTRL;
1849 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1850 g_nMouseClick |= MOUSE_ALT;
1851
1852 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1853 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1854
Bram Moolenaar0f873732019-12-05 20:28:46 +01001855 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001856 if (s_xOldMouse == g_xMouse
1857 && s_yOldMouse == g_yMouse
1858 && s_nOldMouseClick == g_nMouseClick)
1859 {
1860 g_nMouseClick = -1;
1861 return FALSE;
1862 }
1863
1864 s_xOldMouse = g_xMouse;
1865 s_yOldMouse = g_yMouse;
1866 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001867# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001869# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870 s_nOldMouseClick = g_nMouseClick;
1871
1872 return TRUE;
1873}
1874
Christopher Plewright20b795e2022-12-20 20:01:58 +00001875# ifdef FEAT_EVAL
1876 static int
1877encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1878{
1879 int button;
1880 int row;
1881 int col;
1882 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001883 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001884 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885
Christopher Plewright20b795e2022-12-20 20:01:58 +00001886 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1887 return FALSE;
1888
1889 // Note: "move" is optional, requires fewer arguments
1890 move = (int)dict_get_bool(args, "move", FALSE);
1891 if (!move && (!dict_has_key(args, "button")
1892 || !dict_has_key(args, "multiclick")
1893 || !dict_has_key(args, "modifiers")))
1894 return FALSE;
1895
1896 row = (int)dict_get_number(args, "row") - 1;
1897 col = (int)dict_get_number(args, "col") - 1;
1898
1899 ir->EventType = MOUSE_EVENT;
1900 MOUSE_EVENT_RECORD mer;
1901 ZeroMemory(&mer, sizeof(mer));
1902 mer.dwMousePosition.X = col;
1903 mer.dwMousePosition.Y = row;
1904
1905 if (move)
1906 {
1907 mer.dwButtonState = 0;
1908 mer.dwEventFlags = MOUSE_MOVED;
1909 }
1910 else
1911 {
1912 button = (int)dict_get_number(args, "button");
1913 repeated_click = (int)dict_get_number(args, "multiclick");
1914 mods = (int)dict_get_number(args, "modifiers");
1915 // Reset the scroll values to known values.
1916 // XXX: Remove this when/if the scroll step is made configurable.
1917 mouse_set_hor_scroll_step(6);
1918 mouse_set_vert_scroll_step(3);
1919
1920 switch (button)
1921 {
1922 case MOUSE_LEFT:
1923 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1924 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1925 break;
1926 case MOUSE_MIDDLE:
1927 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1928 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1929 break;
1930 case MOUSE_RIGHT:
1931 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1932 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1933 break;
1934 case MOUSE_RELEASE:
1935 // umm? Assume Left Release?
1936 mer.dwEventFlags = 0;
1937
1938 case MOUSE_MOVE:
1939 mer.dwButtonState = 0;
1940 mer.dwEventFlags = MOUSE_MOVED;
1941 break;
1942 case MOUSE_X1:
1943 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1944 break;
1945 case MOUSE_X2:
1946 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1947 break;
1948 case MOUSE_4: // KE_MOUSEDOWN;
1949 mer.dwButtonState = -1;
1950 mer.dwEventFlags = MOUSE_WHEELED;
1951 break;
1952 case MOUSE_5: // KE_MOUSEUP;
1953 mer.dwButtonState = +1;
1954 mer.dwEventFlags = MOUSE_WHEELED;
1955 break;
1956 case MOUSE_6: // KE_MOUSELEFT;
1957 mer.dwButtonState = -1;
1958 mer.dwEventFlags = MOUSE_HWHEELED;
1959 break;
1960 case MOUSE_7: // KE_MOUSERIGHT;
1961 mer.dwButtonState = +1;
1962 mer.dwEventFlags = MOUSE_HWHEELED;
1963 break;
1964 default:
1965 semsg(_(e_invalid_argument_str), "button");
1966 return FALSE;
1967 }
1968 }
1969
1970 mer.dwControlKeyState = 0;
1971 if (mods != 0)
1972 {
1973 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1974 if (mods & MOUSE_SHIFT)
1975 mer.dwControlKeyState |= SHIFT_PRESSED;
1976 if (mods & MOUSE_CTRL)
1977 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1978 if (mods & MOUSE_ALT)
1979 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1980 }
1981 ir->Event.MouseEvent = mer;
1982 return TRUE;
1983}
1984# endif // FEAT_EVAL
1985
1986 static int
1987write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1988{
John Marriott738df382025-06-05 20:49:39 +02001989 int nCount = 0;
1990 input_record_buffer_node_T *event_node;
1991
Christopher Plewright20b795e2022-12-20 20:01:58 +00001992 while (nCount < nLength)
1993 {
John Marriott738df382025-06-05 20:49:39 +02001994 event_node = alloc(sizeof(input_record_buffer_node_T));
1995 if (event_node == NULL)
1996 return -1;
1997
Christopher Plewright20b795e2022-12-20 20:01:58 +00001998 event_node->ir = irEvents[nCount++];
1999 event_node->next = NULL;
John Marriott738df382025-06-05 20:49:39 +02002000
2001 input_record_buffer.length++;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002002 if (input_record_buffer.tail == NULL)
2003 {
2004 input_record_buffer.head = event_node;
2005 input_record_buffer.tail = event_node;
2006 }
2007 else
2008 {
2009 input_record_buffer.tail->next = event_node;
2010 input_record_buffer.tail = input_record_buffer.tail->next;
2011 }
2012 }
2013 return nCount;
2014}
2015
2016 static int
2017read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
2018{
2019 int nCount = 0;
2020 while (nCount < nMaxLength && input_record_buffer.head != NULL)
2021 {
2022 input_record_buffer.length--;
2023 input_record_buffer_node_T *pop_head = input_record_buffer.head;
2024 irEvents[nCount++] = pop_head->ir;
2025 input_record_buffer.head = pop_head->next;
2026 vim_free(pop_head);
2027 if (input_record_buffer.length == 0)
2028 input_record_buffer.tail = NULL;
2029 }
2030 return nCount;
2031}
Christopher Plewright20b795e2022-12-20 20:01:58 +00002032#endif // !FEAT_GUI_MSWIN || VIMDLL
2033
2034#ifdef FEAT_EVAL
2035/*
2036 * The 'test_mswin_event' function is for testing Vim's low-level handling of
2037 * user input events. ie, this manages the encoding of INPUT_RECORD events
2038 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
2039 * consoles.
2040 *
2041 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
2042 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
2043 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
2044 *
2045 * When the Windows console is running, the arguments; 'event' and 'args', are
2046 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
2047 * events are encoded as INPUT_RECORD events.
2048 *
2049 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
2050 * GUI sends MSG structs instead.
2051 */
2052 int
2053test_mswin_event(char_u *event, dict_T *args)
2054{
2055 int lpEventsWritten = 0;
2056
2057# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
2058 if (gui.in_use)
2059 return test_gui_w32_sendevent(event, args);
2060# endif
2061
2062# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
2063
2064// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
2065// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
2066// Maybe also: MENU_EVENT
2067
2068 INPUT_RECORD ir;
2069 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002070 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002071 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002072 {
2073 execute = dict_get_bool(args, "execute", FALSE);
2074 if (dict_has_key(args, "event"))
2075 input_encoded = encode_key_event(args, &ir);
2076 else if (!execute)
2077 {
2078 semsg(_(e_missing_argument_str), "event");
2079 return FALSE;
2080 }
2081 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002082 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002083 {
2084 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002085 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002086 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002087 else
2088 {
2089 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
2090 return FALSE;
2091 }
2092
2093 // Ideally, WriteConsoleInput would be used to inject these low-level
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002094 // events. But, this doesn't work well in the CI test environment. So
Christopher Plewright20b795e2022-12-20 20:01:58 +00002095 // implementing an input_record_buffer instead.
2096 if (input_encoded)
John Marriott738df382025-06-05 20:49:39 +02002097 {
2098 if ((lpEventsWritten = write_input_record_buffer(&ir, 1)) < 0)
2099 {
2100 semsg(_(e_out_of_memory), "event");
2101 return FALSE;
2102 }
2103 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002104
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002105 // Set flags to execute the event, ie. like feedkeys mode X.
2106 if (execute)
2107 {
2108 int save_msg_scroll = msg_scroll;
2109 // Avoid a 1 second delay when the keys start Insert mode.
2110 msg_scroll = FALSE;
2111 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002112 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002113 msg_scroll |= save_msg_scroll;
2114 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002115
2116# endif
2117 return lpEventsWritten;
2118}
2119#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120
2121#ifdef MCH_CURSOR_SHAPE
2122/*
2123 * Set the shape of the cursor.
2124 * 'thickness' can be from 1 (thin) to 99 (block)
2125 */
2126 static void
2127mch_set_cursor_shape(int thickness)
2128{
Christopher Plewright38804d62022-11-09 23:55:52 +00002129 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002130 {
2131 if (*T_CSI == NUL)
2132 {
2133 // If 't_SI' is not set, use the default cursor styles.
2134 if (thickness < 50)
2135 vtp_printf("\033[3 q"); // underline
2136 else
2137 vtp_printf("\033[0 q"); // default
2138 }
2139 }
2140 else
2141 {
2142 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2143 ConsoleCursorInfo.dwSize = thickness;
2144 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145
K.Takatadf5320c2022-09-01 13:20:16 +01002146 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2147 if (s_cursor_visible)
2148 SetConsoleCursorPosition(g_hConOut, g_coord);
2149 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002150}
2151
2152 void
2153mch_update_cursor(void)
2154{
2155 int idx;
2156 int thickness;
2157
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002158# ifdef VIMDLL
2159 if (gui.in_use)
2160 return;
2161# endif
2162
Bram Moolenaar071d4272004-06-13 20:20:40 +00002163 /*
2164 * How the cursor is drawn depends on the current mode.
2165 */
2166 idx = get_shape_idx(FALSE);
2167
2168 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002169 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002170 else
2171 thickness = shape_table[idx].percentage;
2172 mch_set_cursor_shape(thickness);
2173}
2174#endif
2175
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002176#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177/*
2178 * Handle FOCUS_EVENT.
2179 */
2180 static void
2181handle_focus_event(INPUT_RECORD ir)
2182{
2183 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2184 ui_focus_change((int)g_fJustGotFocus);
2185}
2186
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002187static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2188
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189/*
2190 * Wait until console input from keyboard or mouse is available,
2191 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002192 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193 * Return TRUE if something is available FALSE if not.
2194 */
2195 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002196WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197{
2198 DWORD dwNow = 0, dwEndTime = 0;
2199 INPUT_RECORD ir;
2200 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002201 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002202# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002203 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002204# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205
2206 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002207 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208 dwEndTime = GetTickCount() + msec;
2209 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002210 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211 dwEndTime = INFINITE;
2212
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002213 // We need to loop until the end of the time period, because
2214 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002215 for (;;)
2216 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002217 // Only process messages when waiting.
2218 if (msec != 0)
2219 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002220# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002221 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002222# endif
2223# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002224 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002225# endif
2226# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002227 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002228# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002229 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002230
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002231 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002232# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002233 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002234# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 )
2236 return TRUE;
2237
2238 if (msec > 0)
2239 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002240 // If the specified wait time has passed, return. Beware that
2241 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002242 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002243 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 break;
2245 }
2246 if (msec != 0)
2247 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002248 DWORD dwWaitTime = dwEndTime - dwNow;
2249
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002250 // Don't wait for more than 11 msec to avoid dropping characters,
2251 // check channel while waiting for input and handle a callback from
2252 // 'balloonexpr'.
2253 if (dwWaitTime > 11)
2254 dwWaitTime = 11;
2255
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002256# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002257 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002258 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002259# endif
2260# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002261 // When waiting very briefly don't trigger timers.
2262 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002263 {
2264 long due_time;
2265
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002266 // Trigger timers and then get the time in msec until the next
2267 // one is due. Wait up to that time.
2268 due_time = check_due_timer();
2269 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002270 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002271 // timer may have used feedkeys().
2272 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002273 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002274 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2275 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002276 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002277# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002278 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002279# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002280 // Wait for either an event on the console input or a
2281 // message in the client-server window.
2282 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2283 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002284# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002285 wait_for_single_object(g_hConIn, dwWaitTime)
2286 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002287# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002288 )
2289 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290 }
2291
2292 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002293 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002294
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002295# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002296 // May have to redraw if the cursor ends up in the wrong place.
2297 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002298 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 {
2300 CONSOLE_SCREEN_BUFFER_INFO csbi;
2301
2302 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2303 {
2304 if (csbi.dwCursorPosition.Y != msg_row)
2305 {
matveyte08795e2021-05-07 15:00:17 +02002306 // The screen is now messed up, must redraw the command
2307 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002308 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002309 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002310 redrawcmd();
2311 }
2312 }
2313 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002314# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315
2316 if (cRecords > 0)
2317 {
2318 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2319 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002320# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002321 // Windows IME sends two '\n's with only one 'ENTER'. First:
2322 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002323 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2325 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002326 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327 continue;
2328 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002329# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2331 NULL, FALSE))
2332 return TRUE;
2333 }
2334
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002335 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336
2337 if (ir.EventType == FOCUS_EVENT)
2338 handle_focus_event(ir);
2339 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002340 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002341 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2342
Bram Moolenaar36698e32019-12-11 22:57:40 +01002343 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002344 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002345 if (dwSize.X != Columns || dwSize.Y != Rows)
2346 {
2347 CONSOLE_SCREEN_BUFFER_INFO csbi;
2348 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002349 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002350 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002351 if (dwSize.X != Columns || dwSize.Y != Rows)
2352 {
2353 ResizeConBuf(g_hConOut, dwSize);
2354 shell_resized();
2355 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002356 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002357 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358 else if (ir.EventType == MOUSE_EVENT
2359 && decode_mouse_event(&ir.Event.MouseEvent))
2360 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002361 }
2362 else if (msec == 0)
2363 break;
2364 }
2365
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002366# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002367 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 if (input_available())
2369 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002370# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002371
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372 return FALSE;
2373}
2374
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375/*
2376 * return non-zero if a character is available
2377 */
2378 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002379mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002381# ifdef VIMDLL
2382 if (gui.in_use)
2383 return TRUE;
2384# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002385 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002387
2388# if defined(FEAT_TERMINAL) || defined(PROTO)
2389/*
2390 * Check for any pending input or messages.
2391 */
2392 int
2393mch_check_messages(void)
2394{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002395# ifdef VIMDLL
2396 if (gui.in_use)
2397 return TRUE;
2398# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002399 return WaitForChar(0L, TRUE);
2400}
2401# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402
2403/*
2404 * Create the console input. Used when reading stdin doesn't work.
2405 */
2406 static void
2407create_conin(void)
2408{
2409 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2410 FILE_SHARE_READ|FILE_SHARE_WRITE,
2411 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002412 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413 did_create_conin = TRUE;
2414}
2415
2416/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002417 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002419 static WCHAR
2420tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002422 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423
2424 for (;;)
2425 {
2426 INPUT_RECORD ir;
2427 DWORD cRecords = 0;
2428
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002429# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002430 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 if (input_available())
2432 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 if (g_nMouseClick != -1)
2434 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002435# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002436 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 {
2438 if (did_create_conin)
2439 read_error_exit();
2440 create_conin();
2441 continue;
2442 }
2443
2444 if (ir.EventType == KEY_EVENT)
2445 {
2446 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2447 pmodifiers, TRUE))
2448 return ch;
2449 }
2450 else if (ir.EventType == FOCUS_EVENT)
2451 handle_focus_event(ir);
2452 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2453 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 else if (ir.EventType == MOUSE_EVENT)
2455 {
2456 if (decode_mouse_event(&ir.Event.MouseEvent))
2457 return 0;
2458 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002459 }
2460}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002461#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462
2463
2464/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002465 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466 * Get one or more characters from the keyboard or the mouse.
2467 * If time == 0, do not wait for characters.
2468 * If time == n, wait a short time for characters.
2469 * If time == -1, wait forever for characters.
2470 * Returns the number of characters read into buf.
2471 */
2472 int
2473mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002474 char_u *buf UNUSED,
2475 int maxlen UNUSED,
2476 long time UNUSED,
2477 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002479#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480
2481 int len;
2482 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002483# ifdef VIMDLL
2484// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2485# define TYPEAHEADSPACE 6
2486# else
2487# define TYPEAHEADSPACE 0
2488# endif
2489# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002490 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 static int typeaheadlen = 0;
2492
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002493# ifdef VIMDLL
2494 if (gui.in_use)
2495 return 0;
2496# endif
2497
Bram Moolenaar0f873732019-12-05 20:28:46 +01002498 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 if (typeaheadlen > 0)
2500 goto theend;
2501
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 if (time >= 0)
2503 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002504 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002505 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002507 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002509 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510
Bram Moolenaar3918c952005-03-15 22:34:55 +00002511 /*
2512 * If there is no character available within 2 seconds (default)
2513 * write the autoscript file to disk. Or cause the CursorHold event
2514 * to be triggered.
2515 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002516 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002518 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002520 buf[0] = K_SPECIAL;
2521 buf[1] = KS_EXTRA;
2522 buf[2] = (int)KE_CURSORHOLD;
2523 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002525 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 }
2527 }
2528
2529 /*
2530 * Try to read as many characters as there are, until the buffer is full.
2531 */
2532
Bram Moolenaar0f873732019-12-05 20:28:46 +01002533 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 g_fCBrkPressed = FALSE;
2535
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002536# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537 if (fdDump)
2538 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002539# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540
Bram Moolenaar0f873732019-12-05 20:28:46 +01002541 // Keep looping until there is something in the typeahead buffer and more
2542 // to get and still room in the buffer (up to two bytes for a char and
2543 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002544 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002545 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 {
2547 if (typebuf_changed(tb_change_cnt))
2548 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002549 // "buf" may be invalid now if a client put something in the
2550 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 typeaheadlen = 0;
2552 break;
2553 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554 if (g_nMouseClick != -1)
2555 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002556# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557 if (fdDump)
2558 fprintf(fdDump, "{%02x @ %d, %d}",
2559 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002560# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002561 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2562 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2563
2564 if (scroll_dir == KE_MOUSEDOWN
2565 || scroll_dir == KE_MOUSEUP
2566 || scroll_dir == KE_MOUSELEFT
2567 || scroll_dir == KE_MOUSERIGHT)
2568 {
2569 if (modifiers > 0)
2570 {
Christopher Plewright03193062022-11-22 12:58:27 +00002571 // use K_SPECIAL instead of CSI to make mappings work
2572 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002573 typeahead[typeaheadlen++] = KS_MODIFIER;
2574 typeahead[typeaheadlen++] = modifiers;
2575 }
2576 typeahead[typeaheadlen++] = CSI;
2577 typeahead[typeaheadlen++] = KS_EXTRA;
2578 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002579 }
2580 else
2581 {
2582 typeahead[typeaheadlen++] = ESC + 128;
2583 typeahead[typeaheadlen++] = 'M';
2584 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002585 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002586
2587 // Pass the pointer coordinates of the mouse event in 2 bytes,
2588 // allowing for > 223 columns. Both for click and scroll events.
2589 // This is the same as what is used for the GUI.
2590 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2591 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2592 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2593 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2594
2595 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596 }
2597 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002599 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600 int modifiers = 0;
2601
2602 c = tgetch(&modifiers, &ch2);
2603
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002604 c = simplify_key(c, &modifiers);
2605
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002606 // Some chars need adjustment when the Ctrl modifier is used.
2607 ++no_reduce_keys;
2608 c = may_adjust_key_for_ctrl(modifiers, c);
2609 --no_reduce_keys;
2610
2611 // remove the SHIFT modifier for keys where it's already included,
2612 // e.g., '(' and '*'
2613 modifiers = may_remove_shift_modifier(modifiers, c);
2614
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615 if (typebuf_changed(tb_change_cnt))
2616 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002617 // "buf" may be invalid now if a client put something in the
2618 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002619 typeaheadlen = 0;
2620 break;
2621 }
2622
2623 if (c == Ctrl_C && ctrl_c_interrupts)
2624 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002625# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002627# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002628 got_int = TRUE;
2629 }
2630
Bram Moolenaar071d4272004-06-13 20:20:40 +00002631 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632 {
2633 int n = 1;
2634
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002635 if (ch2 == NUL)
2636 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002637 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002638 char_u *p;
2639 WCHAR ch[2];
2640
2641 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002642 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002643 {
2644 ch[1] = tgetch(&modifiers, &ch2);
2645 n++;
2646 }
2647 p = utf16_to_enc(ch, &n);
2648 if (p != NULL)
2649 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002650 for (i = 0, j = 0; i < n; i++)
2651 {
2652 typeahead[typeaheadlen + j++] = p[i];
2653# ifdef VIMDLL
2654 if (p[i] == CSI)
2655 {
2656 typeahead[typeaheadlen + j++] = KS_EXTRA;
2657 typeahead[typeaheadlen + j++] = KE_CSI;
2658 }
2659# endif
2660 }
2661 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002662 vim_free(p);
2663 }
2664 }
2665 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002666 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002667 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002668# ifdef VIMDLL
2669 if (c == CSI)
2670 {
2671 typeahead[typeaheadlen + 1] = KS_EXTRA;
2672 typeahead[typeaheadlen + 2] = KE_CSI;
2673 n = 3;
2674 }
2675# endif
2676 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002677 if (ch2 != NUL)
2678 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002679 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002680 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002681 switch (ch2)
2682 {
2683 case (WCHAR)'\324': // SHIFT+Insert
2684 case (WCHAR)'\325': // CTRL+Insert
2685 case (WCHAR)'\327': // SHIFT+Delete
2686 case (WCHAR)'\330': // CTRL+Delete
2687 typeahead[typeaheadlen + n] = (char_u)ch2;
2688 n++;
2689 break;
2690
2691 default:
2692 typeahead[typeaheadlen + n] = 3;
2693 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2694 n += 2;
2695 break;
2696 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002697 }
2698 else
2699 {
2700 typeahead[typeaheadlen + n] = 3;
2701 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2702 n += 2;
2703 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002704 }
2705
Bram Moolenaar0f873732019-12-05 20:28:46 +01002706 // Use the ALT key to set the 8th bit of the character
2707 // when it's one byte, the 8th bit isn't set yet and not
2708 // using a double-byte encoding (would become a lead
2709 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710 if ((modifiers & MOD_MASK_ALT)
2711 && n == 1
2712 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 )
2715 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002716 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2717 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718 modifiers &= ~MOD_MASK_ALT;
2719 }
2720
2721 if (modifiers != 0)
2722 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002723 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724 mch_memmove(typeahead + typeaheadlen + 3,
2725 typeahead + typeaheadlen, n);
2726 typeahead[typeaheadlen++] = K_SPECIAL;
2727 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2728 typeahead[typeaheadlen++] = modifiers;
2729 }
2730
2731 typeaheadlen += n;
2732
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002733# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734 if (fdDump)
2735 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002736# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737 }
2738 }
2739 }
2740
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002741# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742 if (fdDump)
2743 {
2744 fputs("]\n", fdDump);
2745 fflush(fdDump);
2746 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002747# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002748
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002750 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002751 len = 0;
2752 while (len < maxlen && typeaheadlen > 0)
2753 {
2754 buf[len++] = typeahead[0];
2755 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2756 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002757# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002758 if (len > 0)
2759 {
2760 buf[len] = NUL;
2761 ch_log(NULL, "raw key input: \"%s\"", buf);
2762 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002763# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764 return len;
2765
Bram Moolenaar0f873732019-12-05 20:28:46 +01002766#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002768#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002769}
2770
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002771/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002772 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002773 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2774 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002775 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002776 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002778executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779{
LemonBoy40fd7e62022-05-05 20:18:16 +01002780 int attrs = win32_getattrs((char_u *)name);
2781
2782 // The file doesn't exist or is a folder.
2783 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2784 return FALSE;
2785 // Check if the file is an AppExecLink, a special alias used by Windows
2786 // Store for its apps.
2787 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002788 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002789 char_u *res = resolve_appexeclink((char_u *)name);
2790 if (res == NULL)
AmberArrf5d0f542023-08-20 20:03:45 +02002791 res = resolve_reparse_point((char_u *)name);
2792 if (res == NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002793 return FALSE;
2794 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002795 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002796 *path = res;
2797 else
2798 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002799 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002800 else if (path != NULL)
2801 *path = FullName_save((char_u *)name, FALSE);
2802 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002803}
2804
2805/*
2806 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2807 * If "use_path" is FALSE: Return TRUE if "name" exists.
2808 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2809 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2810 * the allocated memory.
2811 */
2812 static int
John Marriotte5297e32025-06-15 16:50:38 +02002813executable_exists(char *name, size_t namelen, char_u **path, int use_path, int use_pathext)
Bram Moolenaar95da1362020-05-30 18:37:55 +02002814{
2815 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2816 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2817 // UTF-8.
2818 char_u buf[_MAX_PATH * 3];
John Marriotte5297e32025-06-15 16:50:38 +02002819 char_u *p;
2820 string_T pathbuf = {NULL, 0};
2821 int pathbuf_allocated = FALSE;
2822 string_T pathext = {NULL, 0};
2823 int pathext_allocated = FALSE;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002824 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002825 int noext = FALSE;
2826 int retval = FALSE;
2827
John Marriotte5297e32025-06-15 16:50:38 +02002828 if (namelen >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002829 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002830
2831 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002832 shname = gettail(p_sh);
2833 if (strstr((char *)shname, "sh") != NULL &&
2834 !(strstr((char *)shname, "powershell") != NULL
2835 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002836 noext = TRUE;
2837
2838 if (use_pathext)
2839 {
John Marriotte5297e32025-06-15 16:50:38 +02002840 pathext.string = mch_getenv("PATHEXT");
2841 if (pathext.string == NULL)
2842 {
2843 pathext.string = (char_u *)".com;.exe;.bat;.cmd";
2844 pathext.length = 19;
2845 }
2846 else
2847 pathext.length = STRLEN(pathext.string);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002848
2849 if (noext == FALSE)
2850 {
John Marriotte5297e32025-06-15 16:50:38 +02002851 char_u *e;
2852 size_t plen;
2853
Bram Moolenaar95da1362020-05-30 18:37:55 +02002854 /*
2855 * Loop over all extensions in $PATHEXT.
2856 * Check "name" ends with extension.
2857 */
John Marriotte5297e32025-06-15 16:50:38 +02002858 p = pathext.string;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002859 while (*p)
2860 {
2861 if (p[0] == ';'
2862 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2863 {
2864 // Skip empty or single ".".
2865 ++p;
2866 continue;
2867 }
2868 e = vim_strchr(p, ';');
2869 if (e == NULL)
John Marriotte5297e32025-06-15 16:50:38 +02002870 e = pathext.string + pathext.length;
2871 plen = (size_t)(e - p);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002872
John Marriotte5297e32025-06-15 16:50:38 +02002873 if (_strnicoll(name + namelen - plen, (char *)p, plen) == 0)
Bram Moolenaar95da1362020-05-30 18:37:55 +02002874 {
2875 noext = TRUE;
2876 break;
2877 }
2878
2879 p = e;
2880 }
2881 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002882 }
2883
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002884 // Prepend single "." to pathext, it means no extension added.
John Marriotte5297e32025-06-15 16:50:38 +02002885 if (pathext.string == NULL)
2886 {
2887 pathext.string = (char_u *)".";
2888 pathext.length = 1;
2889 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002890 else if (noext == TRUE)
2891 {
John Marriotte5297e32025-06-15 16:50:38 +02002892 char_u *tmp;
2893
2894 tmp = alloc(pathext.length + 3);
2895 if (tmp == NULL)
Bram Moolenaar95da1362020-05-30 18:37:55 +02002896 {
2897 retval = FALSE;
2898 goto theend;
2899 }
John Marriotte5297e32025-06-15 16:50:38 +02002900
2901 STRCPY(tmp, ".;");
2902 STRCPY(tmp + 2, pathext.string);
2903 pathext.string = tmp;
2904 pathext.length += 2;
2905 pathext_allocated = TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002906 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002907
Bram Moolenaar95da1362020-05-30 18:37:55 +02002908 // Use $PATH when "use_path" is TRUE and "name" is basename.
2909 if (use_path && gettail((char_u *)name) == (char_u *)name)
2910 {
2911 p = mch_getenv("PATH");
2912 if (p != NULL)
2913 {
John Marriotte5297e32025-06-15 16:50:38 +02002914 size_t plen = STRLEN(p);
2915
2916 pathbuf.string = alloc(plen + 3);
2917 if (pathbuf.string == NULL)
Bram Moolenaar95da1362020-05-30 18:37:55 +02002918 {
2919 retval = FALSE;
2920 goto theend;
2921 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002922
2923 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
John Marriotte5297e32025-06-15 16:50:38 +02002924 {
2925 STRCPY(pathbuf.string, ".;");
2926 pathbuf.length = 2;
2927 }
2928 STRCPY(pathbuf.string + pathbuf.length, p);
2929 pathbuf.length += plen;
2930 pathbuf_allocated = TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002931 }
2932 }
2933
2934 /*
2935 * Walk through all entries in $PATH to check if "name" exists there and
2936 * is an executable file.
2937 */
John Marriotte5297e32025-06-15 16:50:38 +02002938 if (pathbuf.string == NULL)
2939 {
2940 pathbuf.string = (char_u *)".";
2941 pathbuf.length = 1;
2942 }
2943 p = pathbuf.string;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002944 while (*p)
2945 {
John Marriotte5297e32025-06-15 16:50:38 +02002946 char_u *e;
2947 size_t buflen;
2948
Bram Moolenaar95da1362020-05-30 18:37:55 +02002949 if (*p == ';') // Skip empty entry
2950 {
2951 ++p;
2952 continue;
2953 }
2954 e = vim_strchr(p, ';');
2955 if (e == NULL)
John Marriotte5297e32025-06-15 16:50:38 +02002956 e = pathbuf.string + pathbuf.length;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002957
John Marriotte5297e32025-06-15 16:50:38 +02002958 if (e - p + namelen + 2 > sizeof(buf))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002959 {
2960 retval = FALSE;
2961 goto theend;
2962 }
2963 // A single "." that means current dir.
2964 if (e - p == 1 && *p == '.')
John Marriotte5297e32025-06-15 16:50:38 +02002965 {
Bram Moolenaar95da1362020-05-30 18:37:55 +02002966 STRCPY(buf, name);
John Marriotte5297e32025-06-15 16:50:38 +02002967 buflen = namelen;
2968 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002969 else
2970 {
John Marriotte5297e32025-06-15 16:50:38 +02002971 buflen = vim_snprintf_safelen(
2972 (char *)buf,
2973 sizeof(buf),
2974 "%.*s%s%s", (int)(e - p), p,
2975 !after_pathsep(p, e - 1) ? PATHSEPSTR : "",
2976 name);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002977 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002978
2979 /*
2980 * Loop over all extensions in $PATHEXT.
2981 * Check "name" with extension added.
2982 */
John Marriotte5297e32025-06-15 16:50:38 +02002983 p = pathext.string;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002984 while (*p)
2985 {
John Marriotte5297e32025-06-15 16:50:38 +02002986 char_u *e2;
2987
Bram Moolenaar95da1362020-05-30 18:37:55 +02002988 if (*p == ';')
2989 {
2990 // Skip empty entry
2991 ++p;
2992 continue;
2993 }
John Marriotte5297e32025-06-15 16:50:38 +02002994 e2 = vim_strchr(p, ';');
Bram Moolenaar95da1362020-05-30 18:37:55 +02002995 if (e2 == NULL)
John Marriotte5297e32025-06-15 16:50:38 +02002996 e2 = pathext.string + pathext.length;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002997
2998 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2999 {
3000 // Not a single "." that means no extension is added.
John Marriotte5297e32025-06-15 16:50:38 +02003001 if (e2 - p + buflen + 1 > sizeof(buf))
Bram Moolenaar95da1362020-05-30 18:37:55 +02003002 {
3003 retval = FALSE;
3004 goto theend;
3005 }
John Marriotte5297e32025-06-15 16:50:38 +02003006 vim_strncpy(buf + buflen, p, e2 - p);
Bram Moolenaar95da1362020-05-30 18:37:55 +02003007 }
3008 if (executable_file((char *)buf, path))
3009 {
3010 retval = TRUE;
3011 goto theend;
3012 }
3013
3014 p = e2;
3015 }
3016
3017 p = e;
3018 }
3019
3020theend:
John Marriotte5297e32025-06-15 16:50:38 +02003021 if (pathbuf_allocated)
3022 free(pathbuf.string);
3023 if (pathext_allocated)
3024 free(pathext.string);
Bram Moolenaar95da1362020-05-30 18:37:55 +02003025 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026}
3027
Bram Moolenaar1eed5322019-02-26 17:03:54 +01003028#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
3029 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003030/*
3031 * Bad parameter handler.
3032 *
3033 * Certain MS CRT functions will intentionally crash when passed invalid
3034 * parameters to highlight possible security holes. Setting this function as
3035 * the bad parameter handler will prevent the crash.
3036 *
3037 * In debug builds the parameters contain CRT information that might help track
3038 * down the source of a problem, but in non-debug builds the arguments are all
3039 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
3040 * worth allowing these to make debugging of issues easier.
3041 */
3042 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01003043bad_param_handler(const wchar_t *expression UNUSED,
3044 const wchar_t *function UNUSED,
3045 const wchar_t *file UNUSED,
3046 unsigned int line UNUSED,
3047 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003048{
3049}
3050
3051# define SET_INVALID_PARAM_HANDLER \
3052 ((void)_set_invalid_parameter_handler(bad_param_handler))
3053#else
3054# define SET_INVALID_PARAM_HANDLER
3055#endif
3056
Bram Moolenaar4f974752019-02-17 17:44:42 +01003057#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058
3059/*
3060 * GUI version of mch_init().
3061 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003062 static void
3063mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003065# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003067# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068
Bram Moolenaar0f873732019-12-05 20:28:46 +01003069 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003070 SET_INVALID_PARAM_HANDLER;
3071
Bram Moolenaar0f873732019-12-05 20:28:46 +01003072 // Let critical errors result in a failure, not in a dialog box. Required
3073 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074 SetErrorMode(SEM_FAILCRITICALERRORS);
3075
Bram Moolenaar0f873732019-12-05 20:28:46 +01003076 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077
Bram Moolenaar0f873732019-12-05 20:28:46 +01003078 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079 Rows = 25;
3080 Columns = 80;
3081
John Marriott9cb27a52025-06-08 16:05:53 +02003082 // Look for 'vimrun'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083 {
John Marriott9cb27a52025-06-08 16:05:53 +02003084 char_u vimrun_location[_MAX_PATH + 4];
3085 size_t exe_pathlen = (size_t)(gettail(exe_name) - exe_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086
John Marriott9cb27a52025-06-08 16:05:53 +02003087 // Note: 10 is length of 'vimrun.exe'.
3088 if (exe_pathlen + 10 >= sizeof(vimrun_location))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 {
John Marriotte5297e32025-06-15 16:50:38 +02003090 if (executable_exists("vimrun.exe", STRLEN_LITERAL("vimrun.exe"),
3091 NULL, TRUE, FALSE))
John Marriott738df382025-06-05 20:49:39 +02003092 s_dont_use_vimrun = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093 }
John Marriott9cb27a52025-06-08 16:05:53 +02003094 else
3095 {
3096 // First try in same directory as gvim.exe.
3097 if (exe_pathlen > 0)
3098 vim_strncpy(vimrun_location, exe_name, exe_pathlen);
3099 STRCPY(vimrun_location + exe_pathlen, "vimrun.exe");
3100
3101 if (mch_getperm(vimrun_location) >= 0)
3102 {
3103 char_u *p;
3104 size_t plen;
3105
3106 if (exe_pathlen > 0 && *skiptowhite(vimrun_location) != NUL)
3107 {
3108 // Enclose path with white space in double quotes.
3109 plen = vim_snprintf_safelen(
3110 (char *)vimrun_location,
3111 sizeof(vimrun_location),
3112 "\"%.*svimrun\" ",
3113 (int)exe_pathlen, exe_name);
3114 }
3115 else
3116 {
3117 // Remove the suffix ('.exe').
3118 vimrun_location[exe_pathlen + 6] = ' ';
3119 vimrun_location[exe_pathlen + 7] = NUL;
3120 plen = exe_pathlen + 7;
3121 }
3122
3123 p = vim_strnsave(vimrun_location, plen);
3124 if (p != NULL)
3125 {
3126 vimrun_path.string = p;
3127 vimrun_path.length = plen;
3128 vimrun_path_allocated = TRUE;
3129 s_dont_use_vimrun = FALSE;
3130 }
3131 }
John Marriotte5297e32025-06-15 16:50:38 +02003132 else if (executable_exists("vimrun.exe", STRLEN_LITERAL("vimrun.exe"),
3133 NULL, TRUE, FALSE))
John Marriott9cb27a52025-06-08 16:05:53 +02003134 s_dont_use_vimrun = FALSE;
3135 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136
Bram Moolenaar0f873732019-12-05 20:28:46 +01003137 // Don't give the warning for a missing vimrun.exe right now, but only
3138 // when vimrun was supposed to be used. Don't bother people that do
3139 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 if (s_dont_use_vimrun)
3141 need_vimrun_warning = TRUE;
3142 }
3143
3144 /*
John Marriott9cb27a52025-06-08 16:05:53 +02003145 * If "findstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146 * Otherwise the default "findstr /n" is used.
3147 */
John Marriotte5297e32025-06-15 16:50:38 +02003148 if (!executable_exists("findstr.exe", STRLEN_LITERAL("findstr.exe"),
3149 NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003150 set_option_value_give_err((char_u *)"grepprg",
3151 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003153# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003154 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003155# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003156
3157 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158}
3159
3160
Bram Moolenaar0f873732019-12-05 20:28:46 +01003161#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003162
3163#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003164
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003165# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3166# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167
3168/*
3169 * ClearConsoleBuffer()
3170 * Description:
3171 * Clears the entire contents of the console screen buffer, using the
3172 * specified attribute.
3173 * Returns:
3174 * TRUE on success
3175 */
3176 static BOOL
3177ClearConsoleBuffer(WORD wAttribute)
3178{
3179 CONSOLE_SCREEN_BUFFER_INFO csbi;
3180 COORD coord;
3181 DWORD NumCells, dummy;
3182
3183 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3184 return FALSE;
3185
3186 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3187 coord.X = 0;
3188 coord.Y = 0;
3189 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3190 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3193 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195
3196 return TRUE;
3197}
3198
3199/*
3200 * FitConsoleWindow()
3201 * Description:
3202 * Checks if the console window will fit within given buffer dimensions.
3203 * Also, if requested, will shrink the window to fit.
3204 * Returns:
3205 * TRUE on success
3206 */
3207 static BOOL
3208FitConsoleWindow(
3209 COORD dwBufferSize,
3210 BOOL WantAdjust)
3211{
3212 CONSOLE_SCREEN_BUFFER_INFO csbi;
3213 COORD dwWindowSize;
3214 BOOL NeedAdjust = FALSE;
3215
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003216 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3217 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003219 /*
3220 * A buffer resize will fail if the current console window does
3221 * not lie completely within that buffer. To avoid this, we might
3222 * have to move and possibly shrink the window.
3223 */
3224 if (csbi.srWindow.Right >= dwBufferSize.X)
3225 {
3226 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3227 if (dwWindowSize.X > dwBufferSize.X)
3228 dwWindowSize.X = dwBufferSize.X;
3229 csbi.srWindow.Right = dwBufferSize.X - 1;
3230 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3231 NeedAdjust = TRUE;
3232 }
3233 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3234 {
3235 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3236 if (dwWindowSize.Y > dwBufferSize.Y)
3237 dwWindowSize.Y = dwBufferSize.Y;
3238 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3239 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3240 NeedAdjust = TRUE;
3241 }
3242 if (NeedAdjust && WantAdjust)
3243 {
3244 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3245 return FALSE;
3246 }
3247 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248}
3249
3250typedef struct ConsoleBufferStruct
3251{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003252 BOOL IsValid;
3253 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003254 PCHAR_INFO Buffer;
3255 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003256 PSMALL_RECT Regions;
3257 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258} ConsoleBuffer;
3259
3260/*
3261 * SaveConsoleBuffer()
3262 * Description:
3263 * Saves important information about the console buffer, including the
3264 * actual buffer contents. The saved information is suitable for later
3265 * restoration by RestoreConsoleBuffer().
3266 * Returns:
3267 * TRUE if all information was saved; FALSE otherwise
3268 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3269 */
3270 static BOOL
3271SaveConsoleBuffer(
3272 ConsoleBuffer *cb)
3273{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003274 DWORD NumCells;
3275 COORD BufferCoord;
3276 SMALL_RECT ReadRegion;
3277 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003278 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003279
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280 if (cb == NULL)
3281 return FALSE;
3282
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003283 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003284 {
3285 cb->IsValid = FALSE;
3286 return FALSE;
3287 }
3288 cb->IsValid = TRUE;
3289
Christopher Plewright1140b512022-11-12 18:46:05 +00003290 // VTP uses alternate screen buffer.
3291 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003292 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003293 return TRUE;
3294
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003295 /*
3296 * Allocate a buffer large enough to hold the entire console screen
3297 * buffer. If this ConsoleBuffer structure has already been initialized
3298 * with a buffer of the correct size, then just use that one.
3299 */
3300 if (!cb->IsValid || cb->Buffer == NULL ||
3301 cb->BufferSize.X != cb->Info.dwSize.X ||
3302 cb->BufferSize.Y != cb->Info.dwSize.Y)
3303 {
3304 cb->BufferSize.X = cb->Info.dwSize.X;
3305 cb->BufferSize.Y = cb->Info.dwSize.Y;
3306 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3307 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003308 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003309 if (cb->Buffer == NULL)
3310 return FALSE;
3311 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312
3313 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003314 * We will now copy the console screen buffer into our buffer.
3315 * ReadConsoleOutput() seems to be limited as far as how much you
3316 * can read at a time. Empirically, this number seems to be about
3317 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3318 * in chunks until it is all copied. The chunks will all have the
3319 * same horizontal characteristics, so initialize them now. The
3320 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003322 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003323 ReadRegion.Left = 0;
3324 ReadRegion.Right = cb->Info.dwSize.X - 1;
3325 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003326
3327 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3328 if (cb->Regions == NULL || numregions != cb->NumRegions)
3329 {
3330 cb->NumRegions = numregions;
3331 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003332 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003333 if (cb->Regions == NULL)
3334 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003335 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003336 return FALSE;
3337 }
3338 }
3339
3340 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003342 /*
3343 * Read into position (0, Y) in our buffer.
3344 */
3345 BufferCoord.Y = Y;
3346 /*
3347 * Read the region whose top left corner is (0, Y) and whose bottom
3348 * right corner is (width - 1, Y + Y_incr - 1). This should define
3349 * a region of size width by Y_incr. Don't worry if this region is
3350 * too large for the remaining buffer; it will be cropped.
3351 */
3352 ReadRegion.Top = Y;
3353 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003354 if (!ReadConsoleOutputW(g_hConOut, // output handle
3355 cb->Buffer, // our buffer
3356 cb->BufferSize, // dimensions of our buffer
3357 BufferCoord, // offset in our buffer
3358 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003359 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003360 VIM_CLEAR(cb->Buffer);
3361 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003362 return FALSE;
3363 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003364 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365 }
3366
3367 return TRUE;
3368}
3369
3370/*
3371 * RestoreConsoleBuffer()
3372 * Description:
3373 * Restores important information about the console buffer, including the
3374 * actual buffer contents, if desired. The information to restore is in
3375 * the same format used by SaveConsoleBuffer().
3376 * Returns:
3377 * TRUE on success
3378 */
3379 static BOOL
3380RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003381 ConsoleBuffer *cb,
3382 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003384 COORD BufferCoord;
3385 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003386 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003387
3388 if (cb == NULL || !cb->IsValid)
3389 return FALSE;
3390
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003391 /*
3392 * Before restoring the buffer contents, clear the current buffer, and
3393 * restore the cursor position and window information. Doing this now
3394 * prevents old buffer contents from "flashing" onto the screen.
3395 */
3396 if (RestoreScreen)
3397 ClearConsoleBuffer(cb->Info.wAttributes);
3398
3399 FitConsoleWindow(cb->Info.dwSize, TRUE);
3400 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3401 return FALSE;
3402 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3403 return FALSE;
3404
3405 if (!RestoreScreen)
3406 {
3407 /*
3408 * No need to restore the screen buffer contents, so we're done.
3409 */
3410 return TRUE;
3411 }
3412
3413 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3414 return FALSE;
3415 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3416 return FALSE;
3417
Christopher Plewrightab281f82025-03-16 19:14:31 +01003418 // VTP uses alternate screen buffer.
3419 // No need to restore buffer contents.
3420 if (use_alternate_screen_buffer)
3421 return TRUE;
3422
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003423 /*
3424 * Restore the screen buffer contents.
3425 */
3426 if (cb->Buffer != NULL)
3427 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003428 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003429 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003430 BufferCoord.X = cb->Regions[i].Left;
3431 BufferCoord.Y = cb->Regions[i].Top;
3432 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003433 if (!WriteConsoleOutputW(g_hConOut, // output handle
3434 cb->Buffer, // our buffer
3435 cb->BufferSize, // dimensions of our buffer
3436 BufferCoord, // offset in our buffer
3437 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003438 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003439 }
3440 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441
3442 return TRUE;
3443}
3444
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003445# define FEAT_RESTORE_ORIG_SCREEN
3446# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003447static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003448# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449static ConsoleBuffer g_cbNonTermcap = { 0 };
3450static ConsoleBuffer g_cbTermcap = { 0 };
3451
Bram Moolenaar071d4272004-06-13 20:20:40 +00003452char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003453HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454static HICON g_hOrigIconSmall = NULL;
3455static HICON g_hOrigIcon = NULL;
3456static HICON g_hVimIcon = NULL;
3457static BOOL g_fCanChangeIcon = FALSE;
3458
Bram Moolenaar071d4272004-06-13 20:20:40 +00003459/*
3460 * GetConsoleIcon()
3461 * Description:
3462 * Attempts to retrieve the small icon and/or the big icon currently in
3463 * use by a given window.
3464 * Returns:
3465 * TRUE on success
3466 */
3467 static BOOL
3468GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003469 HWND hWnd,
3470 HICON *phIconSmall,
3471 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472{
3473 if (hWnd == NULL)
3474 return FALSE;
3475
3476 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003477 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3478 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003479 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003480 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3481 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482 return TRUE;
3483}
3484
3485/*
3486 * SetConsoleIcon()
3487 * Description:
3488 * Attempts to change the small icon and/or the big icon currently in
3489 * use by a given window.
3490 * Returns:
3491 * TRUE on success
3492 */
3493 static BOOL
3494SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003495 HWND hWnd,
3496 HICON hIconSmall,
3497 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003498{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499 if (hWnd == NULL)
3500 return FALSE;
3501
3502 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003503 SendMessage(hWnd, WM_SETICON,
3504 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003506 SendMessage(hWnd, WM_SETICON,
3507 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508 return TRUE;
3509}
3510
3511/*
3512 * SaveConsoleTitleAndIcon()
3513 * Description:
3514 * Saves the current console window title in g_szOrigTitle, for later
3515 * restoration. Also, attempts to obtain a handle to the console window,
3516 * and use it to save the small and big icons currently in use by the
3517 * console window. This is not always possible on some versions of Windows;
3518 * nor is it possible when running Vim remotely using Telnet (since the
3519 * console window the user sees is owned by a remote process).
3520 */
3521 static void
3522SaveConsoleTitleAndIcon(void)
3523{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003524 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3526 return;
3527
3528 /*
3529 * Obtain a handle to the console window using GetConsoleWindow() from
3530 * KERNEL32.DLL; we need to handle in order to change the window icon.
3531 * This function only exists on NT-based Windows, starting with Windows
3532 * 2000. On older operating systems, we can't change the window icon
3533 * anyway.
3534 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003535 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536 if (g_hWnd == NULL)
3537 return;
3538
Bram Moolenaar0f873732019-12-05 20:28:46 +01003539 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3541 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3542 return;
3543
Bram Moolenaar0f873732019-12-05 20:28:46 +01003544 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003545 if (
3546# ifdef FEAT_LIBCALL
3547 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3548# endif
3549 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003550 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551 if (g_hVimIcon != NULL)
3552 g_fCanChangeIcon = TRUE;
3553}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554
3555static int g_fWindInitCalled = FALSE;
3556static int g_fTermcapMode = FALSE;
3557static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003558
3559/*
3560 * non-GUI version of mch_init().
3561 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003562 static void
3563mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003564{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003565# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003566 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003567# endif
3568# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003569 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003570# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003571
Bram Moolenaar0f873732019-12-05 20:28:46 +01003572 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003573 SET_INVALID_PARAM_HANDLER;
3574
Bram Moolenaar0f873732019-12-05 20:28:46 +01003575 // Let critical errors result in a failure, not in a dialog box. Required
3576 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003577 SetErrorMode(SEM_FAILCRITICALERRORS);
3578
Bram Moolenaar0f873732019-12-05 20:28:46 +01003579 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580 out_flush();
3581
Bram Moolenaar0f873732019-12-05 20:28:46 +01003582 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583 if (read_cmd_fd == 0)
3584 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3585 else
3586 create_conin();
3587 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3588
Christopher Plewright38804d62022-11-09 23:55:52 +00003589 wt_init();
3590 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003591# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003592 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003593 SaveConsoleBuffer(&g_cbOrig);
3594 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003595# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003596 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003597 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3598 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003599# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600 if (cterm_normal_fg_color == 0)
3601 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3602 if (cterm_normal_bg_color == 0)
3603 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3604
Bram Moolenaarbdace832019-03-02 10:13:42 +01003605 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003606 g_color_index_fg = g_attrDefault & 0xf;
3607 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3608
Bram Moolenaar0f873732019-12-05 20:28:46 +01003609 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610 update_tcap(g_attrCurrent);
3611
3612 GetConsoleCursorInfo(g_hConOut, &g_cci);
3613 GetConsoleMode(g_hConIn, &g_cmodein);
3614 GetConsoleMode(g_hConOut, &g_cmodeout);
3615
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616 SaveConsoleTitleAndIcon();
3617 /*
3618 * Set both the small and big icons of the console window to Vim's icon.
3619 * Note that Vim presently only has one size of icon (32x32), but it
3620 * automatically gets scaled down to 16x16 when setting the small icon.
3621 */
3622 if (g_fCanChangeIcon)
3623 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003624
3625 ui_get_shellsize();
3626
Christopher Plewrightd343c602023-01-22 18:58:30 +00003627 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003628 // Switch to a new alternate screen buffer.
3629 if (use_alternate_screen_buffer)
3630 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003631
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003632# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003633 fdDump = fopen("dump", "wt");
3634
3635 if (fdDump)
3636 {
3637 time_t t;
3638
3639 time(&t);
3640 fputs(ctime(&t), fdDump);
3641 fflush(fdDump);
3642 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003643# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644
3645 g_fWindInitCalled = TRUE;
3646
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003648
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003649# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003650 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003651# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652}
3653
3654/*
3655 * non-GUI version of mch_exit().
3656 * Shut down and exit with status `r'
3657 * Careful: mch_exit() may be called before mch_init()!
3658 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003659 static void
3660mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003661{
William Breslerded59132024-10-08 21:30:48 +02003662 // Copy flag since stoptermcap() will clear the flag.
3663 int fTermcapMode = g_fTermcapMode;
3664
Bram Moolenaar955f1982017-02-05 15:10:51 +01003665 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003666
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003667 vtp_exit();
3668
Bram Moolenaar955f1982017-02-05 15:10:51 +01003669 stoptermcap();
William Breslerded59132024-10-08 21:30:48 +02003670 // Switch back to main screen buffer if TermcapMode was not active.
3671 if (!fTermcapMode && use_alternate_screen_buffer)
Ken Takata568cbc92024-08-07 21:18:24 +02003672 vtp_printf("\033[?1049l");
3673
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 if (g_fWindInitCalled)
3675 settmode(TMODE_COOK);
3676
Bram Moolenaar0f873732019-12-05 20:28:46 +01003677 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003678
3679 if (g_fWindInitCalled)
3680 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003681 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003682 /*
3683 * Restore both the small and big icons of the console window to
3684 * what they were at startup. Don't do this when the window is
3685 * closed, Vim would hang here.
3686 */
3687 if (g_fCanChangeIcon && !g_fForceExit)
3688 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003690# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003691 if (fdDump)
3692 {
3693 time_t t;
3694
3695 time(&t);
3696 fputs(ctime(&t), fdDump);
3697 fclose(fdDump);
3698 }
3699 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003700# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 }
3702
3703 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003704 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705 SetConsoleMode(g_hConOut, g_cmodeout);
3706
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003707# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003709# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003710
3711 exit(r);
3712}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003713#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003715 void
3716mch_init(void)
3717{
3718#ifdef VIMDLL
3719 if (gui.starting)
3720 mch_init_g();
3721 else
3722 mch_init_c();
3723#elif defined(FEAT_GUI_MSWIN)
3724 mch_init_g();
3725#else
3726 mch_init_c();
3727#endif
3728}
3729
3730 void
3731mch_exit(int r)
3732{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003733#ifdef FEAT_NETBEANS_INTG
3734 netbeans_send_disconnect();
3735#endif
3736
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003737#ifdef VIMDLL
John Marriott9cb27a52025-06-08 16:05:53 +02003738 if (vimrun_path_allocated)
3739 vim_free(vimrun_path.string);
3740
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003741 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003742 mch_exit_g(r);
3743 else
3744 mch_exit_c(r);
3745#elif defined(FEAT_GUI_MSWIN)
John Marriott9cb27a52025-06-08 16:05:53 +02003746 if (vimrun_path_allocated)
3747 vim_free(vimrun_path.string);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003748 mch_exit_g(r);
3749#else
3750 mch_exit_c(r);
3751#endif
3752}
3753
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754/*
3755 * Do we have an interactive window?
3756 */
3757 int
3758mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003759 int argc UNUSED,
3760 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761{
K.Takatace3189d2023-02-15 19:13:43 +00003762 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003763
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003764#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003765 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003767# ifdef VIMDLL
3768 if (gui.in_use)
3769 return OK;
3770# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 if (isatty(1))
3772 return OK;
3773 return FAIL;
3774#endif
3775}
3776
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003777/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003778 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779 * When "len" is > 0, also expand short to long filenames.
3780 */
3781 void
3782fname_case(
3783 char_u *name,
3784 int len)
3785{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003786 WCHAR *p;
3787 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788
John Marriott9cb27a52025-06-08 16:05:53 +02003789 if (*name == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 return;
3791
3792 slash_adjust(name);
3793
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003794 p = enc_to_utf16(name, NULL);
3795 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003796 return;
3797
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003798 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003800 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003802 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803 {
John Marriott9cb27a52025-06-08 16:05:53 +02003804 if (len > 0)
3805 vim_strncpy(name, q, len - 1);
3806 else
3807 {
3808 size_t namelen = STRLEN(name);
John Marriotte5297e32025-06-15 16:50:38 +02003809
John Marriott9cb27a52025-06-08 16:05:53 +02003810 if (namelen >= STRLEN(q))
3811 vim_strncpy(name, q, namelen);
3812 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003813 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 }
3815 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003816 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817}
3818
3819
3820/*
3821 * Insert user name in s[len].
3822 */
3823 int
3824mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003825 char_u *s,
3826 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003828 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003829 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003831 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003832 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003833 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003834
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003835 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003836 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003837 vim_strncpy(s, p, len - 1);
3838 vim_free(p);
3839 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003840 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003841 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842 s[0] = NUL;
3843 return FAIL;
3844}
3845
3846
3847/*
3848 * Insert host name in s[len].
3849 */
3850 void
3851mch_get_host_name(
3852 char_u *s,
3853 int len)
3854{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003855 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003856 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003858 if (!GetComputerNameW(wszHostName, &wcch))
3859 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003860
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003861 char_u *p = utf16_to_enc(wszHostName, NULL);
3862 if (p == NULL)
3863 return;
3864
3865 vim_strncpy(s, p, len - 1);
3866 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867}
3868
3869
3870/*
3871 * return process ID
3872 */
3873 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003874mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003875{
3876 return (long)GetCurrentProcessId();
3877}
3878
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003879/*
3880 * return TRUE if process "pid" is still running
3881 */
3882 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003883mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003884{
3885 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3886 DWORD status = 0;
3887 int ret = FALSE;
3888
3889 if (hProcess == NULL)
3890 return FALSE; // might not have access
John Marriotte5297e32025-06-15 16:50:38 +02003891 if (GetExitCodeProcess(hProcess, &status))
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003892 ret = status == STILL_ACTIVE;
3893 CloseHandle(hProcess);
3894 return ret;
3895}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003896
3897/*
3898 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3899 * Return OK for success, FAIL for failure.
3900 */
3901 int
3902mch_dirname(
3903 char_u *buf,
3904 int len)
3905{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003906 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003907
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908 /*
3909 * Originally this was:
3910 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3911 * But the Win32s known bug list says that getcwd() doesn't work
3912 * so use the Win32 system call instead. <Negri>
3913 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003914 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3915 return FAIL;
3916
3917 WCHAR wcbuf[_MAX_PATH + 1];
3918 char_u *p = NULL;
3919
3920 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003922 p = utf16_to_enc(wcbuf, NULL);
John Marriott031f2272025-04-23 20:56:08 +02003923 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 {
John Marriott031f2272025-04-23 20:56:08 +02003925 if (STRLEN(p) >= (size_t)len)
3926 {
3927 // long path name is too long, fall back to short one
3928 VIM_CLEAR(p);
3929 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003930 }
3931 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003932 if (p == NULL)
3933 p = utf16_to_enc(wbuf, NULL);
3934
3935 if (p == NULL)
3936 return FAIL;
3937
3938 vim_strncpy(buf, p, len - 1);
3939 vim_free(p);
3940 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003941}
3942
3943/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003944 * Get file permissions for "name".
3945 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946 */
3947 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003948mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003949{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003950 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951
John Marriotte5297e32025-06-15 16:50:38 +02003952 return (mch_stat((char *)name, &st) == 0)
3953 ? (long)(unsigned short)st.st_mode
3954 : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955}
3956
3957
3958/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003959 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003960 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003961 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962 */
3963 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003964mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003966 long n;
3967 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003968
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003969 p = enc_to_utf16(name, NULL);
3970 if (p == NULL)
3971 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003972
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003973 n = _wchmod(p, perm);
3974 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003975 if (n == -1)
3976 return FAIL;
3977
3978 win32_set_archive(name);
3979
3980 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003981}
3982
3983/*
3984 * Set hidden flag for "name".
3985 */
3986 void
3987mch_hide(char_u *name)
3988{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003989 int attrs = win32_getattrs(name);
3990 if (attrs == -1)
3991 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003992
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003993 attrs |= FILE_ATTRIBUTE_HIDDEN;
3994 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003995}
3996
3997/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003998 * Return TRUE if file "name" exists and is hidden.
3999 */
4000 int
4001mch_ishidden(char_u *name)
4002{
4003 int f = win32_getattrs(name);
4004
4005 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004006 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01004007
4008 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
4009}
4010
4011/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012 * return TRUE if "name" is a directory
4013 * return FALSE if "name" is not a directory or upon error
4014 */
4015 int
4016mch_isdir(char_u *name)
4017{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004018 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004019
4020 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004021 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00004022
4023 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
4024}
4025
4026/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01004027 * return TRUE if "name" is a directory, NOT a symlink to a directory
4028 * return FALSE if "name" is not a directory
4029 * return FALSE for error
4030 */
4031 int
4032mch_isrealdir(char_u *name)
4033{
4034 return mch_isdir(name) && !mch_is_symbolic_link(name);
4035}
4036
4037/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02004038 * Create directory "name".
4039 * Return 0 on success, -1 on error.
4040 */
4041 int
4042mch_mkdir(char_u *name)
4043{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004044 WCHAR *p;
4045 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02004046
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004047 p = enc_to_utf16(name, NULL);
4048 if (p == NULL)
4049 return -1;
4050 retval = _wmkdir(p);
4051 vim_free(p);
4052 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02004053}
4054
4055/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01004056 * Delete directory "name".
4057 * Return 0 on success, -1 on error.
4058 */
4059 int
4060mch_rmdir(char_u *name)
4061{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004062 WCHAR *p;
4063 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01004064
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004065 p = enc_to_utf16(name, NULL);
4066 if (p == NULL)
4067 return -1;
4068 retval = _wrmdir(p);
4069 vim_free(p);
4070 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01004071}
4072
4073/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00004074 * Return TRUE if file "fname" has more than one link.
4075 */
4076 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004077mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00004078{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004079 BY_HANDLE_FILE_INFORMATION info;
4080
4081 return win32_fileinfo(fname, &info) == FILEINFO_OK
4082 && info.nNumberOfLinks > 1;
4083}
4084
4085/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01004086 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004087 */
4088 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01004089mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004090{
4091 HANDLE hFind;
4092 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004093 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004094 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004095 WIN32_FIND_DATAW findDataW;
4096
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004097 wn = enc_to_utf16(name, NULL);
4098 if (wn == NULL)
4099 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004100
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004101 hFind = FindFirstFileW(wn, &findDataW);
4102 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004103 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004104 {
4105 fileFlags = findDataW.dwFileAttributes;
4106 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004107 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004108 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004109
4110 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01004111 && (reparseTag == IO_REPARSE_TAG_SYMLINK
4112 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004113 res = TRUE;
4114
4115 return res;
4116}
4117
4118/*
4119 * Return TRUE if file "fname" has more than one link or if it is a symbolic
4120 * link.
4121 */
4122 int
4123mch_is_linked(char_u *fname)
4124{
4125 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
4126 return TRUE;
4127 return FALSE;
4128}
4129
4130/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004131 * Get the by-handle-file-information for "fname".
4132 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004133 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004134 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
4135 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
4136 */
4137 int
4138win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
4139{
Bram Moolenaar03f48552006-02-28 23:52:23 +00004140 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004141 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004142 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00004143
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004144 wn = enc_to_utf16(fname, NULL);
4145 if (wn == NULL)
4146 return FILEINFO_ENC_FAIL;
4147
4148 hFile = CreateFileW(wn, // file name
4149 GENERIC_READ, // access mode
4150 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
4151 NULL, // security descriptor
4152 OPEN_EXISTING, // creation disposition
4153 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
4154 NULL); // handle to template file
4155 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004156
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004157 if (hFile == INVALID_HANDLE_VALUE)
4158 return FILEINFO_READ_FAIL;
4159
4160 if (GetFileInformationByHandle(hFile, info) != 0)
4161 res = FILEINFO_OK;
4162 else
4163 res = FILEINFO_INFO_FAIL;
4164 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004165
Bram Moolenaar03f48552006-02-28 23:52:23 +00004166 return res;
4167}
4168
4169/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004170 * get file attributes for `name'
4171 * -1 : error
4172 * else FILE_ATTRIBUTE_* defined in winnt.h
4173 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004174 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004175win32_getattrs(char_u *name)
4176{
4177 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004178 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004179
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004180 p = enc_to_utf16(name, NULL);
4181 if (p == NULL)
4182 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004183
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004184 attr = GetFileAttributesW(p);
4185 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004186
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004187 return attr;
4188}
4189
4190/*
4191 * set file attributes for `name' to `attrs'
4192 *
4193 * return -1 for failure, 0 otherwise
4194 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004195 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004196win32_setattrs(char_u *name, int attrs)
4197{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004198 int res;
4199 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004200
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004201 p = enc_to_utf16(name, NULL);
4202 if (p == NULL)
4203 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004204
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004205 res = SetFileAttributesW(p, attrs);
4206 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004207
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004208 return res ? 0 : -1;
4209}
4210
4211/*
4212 * Set archive flag for "name".
4213 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004214 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004215win32_set_archive(char_u *name)
4216{
4217 int attrs = win32_getattrs(name);
4218 if (attrs == -1)
4219 return -1;
4220
4221 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4222 return win32_setattrs(name, attrs);
4223}
4224
4225/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004226 * Return TRUE if file or directory "name" is writable (not readonly).
4227 * Strange semantics of Win32: a readonly directory is writable, but you can't
4228 * delete a file. Let's say this means it is writable.
4229 */
4230 int
4231mch_writable(char_u *name)
4232{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004233 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004234
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004235 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4236 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237}
4238
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004240 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004241 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004242 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4243 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004244 */
4245 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004246mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247{
John Marriotte5297e32025-06-15 16:50:38 +02004248 return executable_exists((char *)name, STRLEN(name), path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004249}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004250
4251/*
4252 * Check what "name" is:
4253 * NODE_NORMAL: file or directory (or doesn't exist)
4254 * NODE_WRITABLE: writable device, socket, fifo, etc.
4255 * NODE_OTHER: non-writable things
4256 */
4257 int
4258mch_nodetype(char_u *name)
4259{
4260 HANDLE hFile;
4261 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004262 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263
Bram Moolenaar0f873732019-12-05 20:28:46 +01004264 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4265 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4266 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004267 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4268 return NODE_WRITABLE;
4269
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004270 wn = enc_to_utf16(name, NULL);
4271 if (wn == NULL)
4272 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004273
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004274 hFile = CreateFileW(wn, // file name
4275 GENERIC_WRITE, // access mode
4276 0, // share mode
4277 NULL, // security descriptor
4278 OPEN_EXISTING, // creation disposition
4279 0, // file attributes
4280 NULL); // handle to template file
4281 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004282 if (hFile == INVALID_HANDLE_VALUE)
4283 return NODE_NORMAL;
4284
4285 type = GetFileType(hFile);
4286 CloseHandle(hFile);
4287 if (type == FILE_TYPE_CHAR)
4288 return NODE_WRITABLE;
4289 if (type == FILE_TYPE_DISK)
4290 return NODE_NORMAL;
4291 return NODE_OTHER;
4292}
4293
4294#ifdef HAVE_ACL
4295struct my_acl
4296{
4297 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4298 PSID pSidOwner;
4299 PSID pSidGroup;
4300 PACL pDacl;
4301 PACL pSacl;
4302};
4303#endif
4304
4305/*
4306 * Return a pointer to the ACL of file "fname" in allocated memory.
4307 * Return NULL if the ACL is not available for whatever reason.
4308 */
4309 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004310mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004311{
4312#ifndef HAVE_ACL
4313 return (vim_acl_T)NULL;
4314#else
4315 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004316 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004317
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004318 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004319 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004320 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004321 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004322
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004323 wn = enc_to_utf16(fname, NULL);
4324 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004325 {
4326 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004327 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004328 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004329
4330 // Try to retrieve the entire security descriptor.
4331 err = GetNamedSecurityInfoW(
4332 wn, // Abstract filename
4333 SE_FILE_OBJECT, // File Object
4334 OWNER_SECURITY_INFORMATION |
4335 GROUP_SECURITY_INFORMATION |
4336 DACL_SECURITY_INFORMATION |
4337 SACL_SECURITY_INFORMATION,
4338 &p->pSidOwner, // Ownership information.
4339 &p->pSidGroup, // Group membership.
4340 &p->pDacl, // Discretionary information.
4341 &p->pSacl, // For auditing purposes.
4342 &p->pSecurityDescriptor);
4343 if (err == ERROR_ACCESS_DENIED ||
4344 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004345 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004346 // Retrieve only DACL.
4347 (void)GetNamedSecurityInfoW(
4348 wn,
4349 SE_FILE_OBJECT,
4350 DACL_SECURITY_INFORMATION,
4351 NULL,
4352 NULL,
4353 &p->pDacl,
4354 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004355 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004356 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004357 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004358 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004359 mch_free_acl((vim_acl_T)p);
4360 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004361 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004362 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004363 }
4364
4365 return (vim_acl_T)p;
4366#endif
4367}
4368
Bram Moolenaar27515922013-06-29 15:36:26 +02004369#ifdef HAVE_ACL
4370/*
4371 * Check if "acl" contains inherited ACE.
4372 */
4373 static BOOL
4374is_acl_inherited(PACL acl)
4375{
4376 DWORD i;
4377 ACL_SIZE_INFORMATION acl_info;
4378 PACCESS_ALLOWED_ACE ace;
4379
4380 acl_info.AceCount = 0;
4381 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4382 for (i = 0; i < acl_info.AceCount; i++)
4383 {
4384 GetAce(acl, i, (LPVOID *)&ace);
4385 if (ace->Header.AceFlags & INHERITED_ACE)
4386 return TRUE;
4387 }
4388 return FALSE;
4389}
4390#endif
4391
Bram Moolenaar071d4272004-06-13 20:20:40 +00004392/*
4393 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4394 * Errors are ignored.
4395 * This must only be called with "acl" equal to what mch_get_acl() returned.
4396 */
4397 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004398mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004399{
4400#ifdef HAVE_ACL
4401 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004402 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004403 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004404
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004405 if (p == NULL)
4406 return;
4407
4408 wn = enc_to_utf16(fname, NULL);
4409 if (wn == NULL)
4410 return;
4411
4412 // Set security flags
4413 if (p->pSidOwner)
4414 sec_info |= OWNER_SECURITY_INFORMATION;
4415 if (p->pSidGroup)
4416 sec_info |= GROUP_SECURITY_INFORMATION;
4417 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004418 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004419 sec_info |= DACL_SECURITY_INFORMATION;
4420 // Do not inherit its parent's DACL.
4421 // If the DACL is inherited, Cygwin permissions would be changed.
4422 if (!is_acl_inherited(p->pDacl))
4423 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004424 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004425 if (p->pSacl)
4426 sec_info |= SACL_SECURITY_INFORMATION;
4427
4428 (void)SetNamedSecurityInfoW(
4429 wn, // Abstract filename
4430 SE_FILE_OBJECT, // File Object
4431 sec_info,
4432 p->pSidOwner, // Ownership information.
4433 p->pSidGroup, // Group membership.
4434 p->pDacl, // Discretionary information.
4435 p->pSacl // For auditing purposes.
4436 );
4437 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004438#endif
4439}
4440
4441 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004442mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443{
4444#ifdef HAVE_ACL
4445 struct my_acl *p = (struct my_acl *)acl;
4446
4447 if (p != NULL)
4448 {
4449 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4450 vim_free(p);
4451 }
4452#endif
4453}
4454
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004455#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004456
4457/*
4458 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4459 */
4460 static BOOL WINAPI
4461handler_routine(
4462 DWORD dwCtrlType)
4463{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004464 INPUT_RECORD ir;
4465 DWORD out;
4466
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 switch (dwCtrlType)
4468 {
4469 case CTRL_C_EVENT:
4470 if (ctrl_c_interrupts)
4471 g_fCtrlCPressed = TRUE;
4472 return TRUE;
4473
4474 case CTRL_BREAK_EVENT:
4475 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004476 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004477 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004478 ir.EventType = KEY_EVENT;
4479 ir.Event.KeyEvent.bKeyDown = TRUE;
4480 ir.Event.KeyEvent.wRepeatCount = 1;
4481 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4482 ir.Event.KeyEvent.wVirtualScanCode = 0;
4483 ir.Event.KeyEvent.dwControlKeyState = 0;
4484 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4485 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486 return TRUE;
4487
Bram Moolenaar0f873732019-12-05 20:28:46 +01004488 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489 case CTRL_CLOSE_EVENT:
4490 case CTRL_LOGOFF_EVENT:
4491 case CTRL_SHUTDOWN_EVENT:
4492 windgoto((int)Rows - 1, 0);
4493 g_fForceExit = TRUE;
4494
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004495 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496 (dwCtrlType == CTRL_CLOSE_EVENT
4497 ? _("close")
4498 : dwCtrlType == CTRL_LOGOFF_EVENT
4499 ? _("logoff")
4500 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004501# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004503# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004504
Bram Moolenaar0f873732019-12-05 20:28:46 +01004505 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506
Bram Moolenaar0f873732019-12-05 20:28:46 +01004507 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004508
4509 default:
4510 return FALSE;
4511 }
4512}
4513
4514
4515/*
4516 * set the tty in (raw) ? "raw" : "cooked" mode
4517 */
4518 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004519mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520{
4521 DWORD cmodein;
4522 DWORD cmodeout;
4523 BOOL bEnableHandler;
4524
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004525# ifdef VIMDLL
4526 if (gui.in_use)
4527 return;
4528# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529 GetConsoleMode(g_hConIn, &cmodein);
4530 GetConsoleMode(g_hConOut, &cmodeout);
4531 if (tmode == TMODE_RAW)
4532 {
4533 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4534 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004536 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004537 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004538 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4539 }
4540 else
4541 {
4542 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4543 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004544 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004545# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004546 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4547 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004548 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004549# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004550 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004551# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004552 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004553 bEnableHandler = TRUE;
4554 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004555 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556 {
4557 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4558 ENABLE_ECHO_INPUT);
4559 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4560 bEnableHandler = FALSE;
4561 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004562 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 SetConsoleMode(g_hConOut, cmodeout);
4564 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4565
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004566# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567 if (fdDump)
4568 {
4569 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4570 tmode == TMODE_RAW ? "raw" :
4571 tmode == TMODE_COOK ? "cooked" : "normal",
4572 cmodein, cmodeout);
4573 fflush(fdDump);
4574 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004575# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004576}
4577
4578
4579/*
4580 * Get the size of the current window in `Rows' and `Columns'
4581 * Return OK when size could be determined, FAIL otherwise.
4582 */
4583 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004584mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004585{
4586 CONSOLE_SCREEN_BUFFER_INFO csbi;
4587
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004588# ifdef VIMDLL
4589 if (gui.in_use)
4590 return OK;
4591# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004592 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4593 {
4594 /*
4595 * For some reason, we are trying to get the screen dimensions
4596 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4597 * variables are really intended to mean the size of Vim screen
4598 * while in termcap mode.
4599 */
4600 Rows = g_cbTermcap.Info.dwSize.Y;
4601 Columns = g_cbTermcap.Info.dwSize.X;
4602 }
4603 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4604 {
4605 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4606 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4607 }
4608 else
4609 {
4610 Rows = 25;
4611 Columns = 80;
4612 }
4613 return OK;
4614}
4615
4616/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004617 * Resize console buffer to 'COORD'
4618 */
4619 static void
4620ResizeConBuf(
4621 HANDLE hConsole,
4622 COORD coordScreen)
4623{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004624 if (use_alternate_screen_buffer)
4625 return;
4626
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004627 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4628 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004629# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004630 if (fdDump)
4631 {
4632 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4633 GetLastError());
4634 fflush(fdDump);
4635 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004636# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004637 }
4638}
4639
4640/*
4641 * Resize console window size to 'srWindowRect'
4642 */
4643 static void
4644ResizeWindow(
4645 HANDLE hConsole,
4646 SMALL_RECT srWindowRect)
4647{
4648 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4649 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004650# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004651 if (fdDump)
4652 {
4653 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4654 GetLastError());
4655 fflush(fdDump);
4656 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004657# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004658 }
4659}
4660
4661/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004662 * Set a console window to `xSize' * `ySize'
4663 */
4664 static void
4665ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004666 HANDLE hConsole,
4667 int xSize,
4668 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004669{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004670 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4671 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004673 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004674 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004676# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004677 if (fdDump)
4678 {
4679 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4680 fflush(fdDump);
4681 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004682# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683
Bram Moolenaar0f873732019-12-05 20:28:46 +01004684 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685 coordScreen = GetLargestConsoleWindowSize(hConsole);
4686
Bram Moolenaar0f873732019-12-05 20:28:46 +01004687 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004688 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4689 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4690 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4691
4692 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4693 {
4694 int sx, sy;
4695
4696 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4697 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4698 if (sy < ySize || sx < xSize)
4699 {
4700 /*
4701 * Increasing number of lines/columns, do buffer first.
4702 * Use the maximal size in x and y direction.
4703 */
4704 if (sy < ySize)
4705 coordScreen.Y = ySize;
4706 else
4707 coordScreen.Y = sy;
4708 if (sx < xSize)
4709 coordScreen.X = xSize;
4710 else
4711 coordScreen.X = sx;
4712 SetConsoleScreenBufferSize(hConsole, coordScreen);
4713 }
4714 }
4715
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004716 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004717 coordScreen.X = xSize;
4718 coordScreen.Y = ySize;
4719
Bram Moolenaar2551c032018-08-23 22:38:31 +02004720 // In the new console call API, only the first time in reverse order
4721 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004723 ResizeWindow(hConsole, srWindowRect);
4724 ResizeConBuf(hConsole, coordScreen);
4725 }
4726 else
4727 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004728 // Workaround for a Windows 10 bug
4729 cursor.X = srWindowRect.Left;
4730 cursor.Y = srWindowRect.Top;
4731 SetConsoleCursorPosition(hConsole, cursor);
4732
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004733 ResizeConBuf(hConsole, coordScreen);
4734 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004735 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004736 }
4737}
4738
4739
4740/*
4741 * Set the console window to `Rows' * `Columns'
4742 */
4743 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004744mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745{
4746 COORD coordScreen;
4747
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004748# ifdef VIMDLL
4749 if (gui.in_use)
4750 return;
4751# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004752 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753 if (suppress_winsize != 0)
4754 {
4755 suppress_winsize = 2;
4756 return;
4757 }
4758
4759 if (term_console)
4760 {
4761 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4762
Bram Moolenaar0f873732019-12-05 20:28:46 +01004763 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004764 if (Rows > coordScreen.Y)
4765 Rows = coordScreen.Y;
4766 if (Columns > coordScreen.X)
4767 Columns = coordScreen.X;
4768
4769 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4770 }
4771}
4772
4773/*
4774 * Rows and/or Columns has changed.
4775 */
4776 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004777mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004779# ifdef VIMDLL
4780 if (gui.in_use)
4781 return;
4782# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4784}
4785
4786
4787/*
4788 * Called when started up, to set the winsize that was delayed.
4789 */
4790 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004791mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792{
4793 if (suppress_winsize == 2)
4794 {
4795 suppress_winsize = 0;
4796 mch_set_shellsize();
4797 shell_resized();
4798 }
4799 suppress_winsize = 0;
4800}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004801#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004803 static BOOL
4804vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004805 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004806 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004807 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004808 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004809 PROCESS_INFORMATION *pi,
4810 LPVOID *env,
4811 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004812{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004813 BOOL ret = FALSE;
4814 WCHAR *wcmd, *wcwd = NULL;
4815
4816 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4817 if (wcmd == NULL)
4818 return FALSE;
4819 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004820 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004821 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4822 if (wcwd == NULL)
4823 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004824 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004825
4826 ret = CreateProcessW(
4827 NULL, // Executable name
4828 wcmd, // Command to execute
4829 NULL, // Process security attributes
4830 NULL, // Thread security attributes
4831 inherit_handles, // Inherit handles
4832 flags, // Creation flags
4833 env, // Environment
4834 wcwd, // Current directory
4835 (LPSTARTUPINFOW)si, // Startup information
4836 pi); // Process information
4837theend:
4838 vim_free(wcmd);
4839 vim_free(wcwd);
4840 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004841}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842
4843
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004844 static HINSTANCE
4845vim_shell_execute(
4846 char *cmd,
4847 INT n_show_cmd)
4848{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004849 HINSTANCE ret;
4850 WCHAR *wcmd;
4851
4852 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4853 if (wcmd == NULL)
4854 return (HINSTANCE) 0;
4855
4856 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4857 vim_free(wcmd);
4858 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004859}
4860
4861
Bram Moolenaar4f974752019-02-17 17:44:42 +01004862#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004863
4864/*
4865 * Specialised version of system() for Win32 GUI mode.
4866 * This version proceeds as follows:
4867 * 1. Create a console window for use by the subprocess
4868 * 2. Run the subprocess (it gets the allocated console by default)
4869 * 3. Wait for the subprocess to terminate and get its exit code
4870 * 4. Prompt the user to press a key to close the console window
4871 */
4872 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004873mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004874{
4875 STARTUPINFO si;
4876 PROCESS_INFORMATION pi;
4877 DWORD ret = 0;
4878 HWND hwnd = GetFocus();
4879
4880 si.cb = sizeof(si);
4881 si.lpReserved = NULL;
4882 si.lpDesktop = NULL;
4883 si.lpTitle = NULL;
4884 si.dwFlags = STARTF_USESHOWWINDOW;
4885 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004886 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004887 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004889 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004890 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004891 else
4892 si.wShowWindow = SW_SHOWNORMAL;
4893 si.cbReserved2 = 0;
4894 si.lpReserved2 = NULL;
4895
Bram Moolenaar0f873732019-12-05 20:28:46 +01004896 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004897 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004898 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4899 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900
Bram Moolenaar0f873732019-12-05 20:28:46 +01004901 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004902 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004903# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904 int delay = 1;
4905
Bram Moolenaar0f873732019-12-05 20:28:46 +01004906 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907 for (;;)
4908 {
4909 MSG msg;
4910
K.Takatab7057bd2022-01-21 11:37:07 +00004911 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004912 {
4913 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004914 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004915 delay = 1;
4916 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004917 }
4918 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4919 break;
4920
Bram Moolenaar0f873732019-12-05 20:28:46 +01004921 // We start waiting for a very short time and then increase it, so
4922 // that we respond quickly when the process is quick, and don't
4923 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004924 if (delay < 50)
4925 delay += 10;
4926 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004927# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004929# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930
Bram Moolenaar0f873732019-12-05 20:28:46 +01004931 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932 GetExitCodeProcess(pi.hProcess, &ret);
4933 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004934
Bram Moolenaar0f873732019-12-05 20:28:46 +01004935 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 CloseHandle(pi.hThread);
4937 CloseHandle(pi.hProcess);
4938
Bram Moolenaar0f873732019-12-05 20:28:46 +01004939 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4941
4942 return ret;
4943}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004944
4945/*
4946 * Thread launched by the gui to send the current buffer data to the
4947 * process. This way avoid to hang up vim totally if the children
4948 * process take a long time to process the lines.
4949 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004950 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004951sub_process_writer(LPVOID param)
4952{
4953 HANDLE g_hChildStd_IN_Wr = param;
4954 linenr_T lnum = curbuf->b_op_start.lnum;
4955 DWORD len = 0;
4956 DWORD l;
4957 char_u *lp = ml_get(lnum);
4958 char_u *s;
4959 int written = 0;
4960
4961 for (;;)
4962 {
4963 l = (DWORD)STRLEN(lp + written);
4964 if (l == 0)
4965 len = 0;
4966 else if (lp[written] == NL)
4967 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004968 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004969 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4970 }
4971 else
4972 {
4973 s = vim_strchr(lp + written, NL);
4974 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4975 s == NULL ? l : (DWORD)(s - (lp + written)),
4976 &len, NULL);
4977 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004978 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004979 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004980 // Finished a line, add a NL, unless this line should not have
4981 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004982 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004983 || (!curbuf->b_p_bin
4984 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004985 || (lnum != curbuf->b_no_eol_lnum
4986 && (lnum != curbuf->b_ml.ml_line_count
4987 || curbuf->b_p_eol)))
4988 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004989 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4990 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004991 }
4992
4993 ++lnum;
4994 if (lnum > curbuf->b_op_end.lnum)
4995 break;
4996
4997 lp = ml_get(lnum);
4998 written = 0;
4999 }
5000 else if (len > 0)
5001 written += len;
5002 }
5003
Bram Moolenaar0f873732019-12-05 20:28:46 +01005004 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005005 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005006 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005007}
5008
5009
Bram Moolenaar0f873732019-12-05 20:28:46 +01005010# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005011
5012/*
5013 * This function read from the children's stdout and write the
5014 * data on screen or in the buffer accordingly.
5015 */
5016 static void
5017dump_pipe(int options,
5018 HANDLE g_hChildStd_OUT_Rd,
5019 garray_T *ga,
5020 char_u buffer[],
5021 DWORD *buffer_off)
5022{
5023 DWORD availableBytes = 0;
5024 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005025 int ret;
5026 DWORD len;
5027 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005028
Bram Moolenaar0f873732019-12-05 20:28:46 +01005029 // we query the pipe to see if there is any data to read
5030 // to avoid to perform a blocking read
5031 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
5032 NULL, // optional buffer
5033 0, // buffer size
5034 NULL, // number of read bytes
5035 &availableBytes, // available bytes total
5036 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005037
Bram Moolenaar0f873732019-12-05 20:28:46 +01005038 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02005039 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005040 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01005041 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005042 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005043 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005044
Bram Moolenaar0f873732019-12-05 20:28:46 +01005045 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005046 if (len == 0)
5047 break;
5048
5049 availableBytes -= len;
5050
5051 if (options & SHELL_READ)
5052 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005053 // Do NUL -> NL translation, append NL separated
5054 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005055 for (i = 0; i < len; ++i)
5056 {
5057 if (buffer[i] == NL)
5058 append_ga_line(ga);
5059 else if (buffer[i] == NUL)
5060 ga_append(ga, NL);
5061 else
5062 ga_append(ga, buffer[i]);
5063 }
5064 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005065 else if (has_mbyte)
5066 {
5067 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005068 int c;
5069 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005070
5071 len += *buffer_off;
5072 buffer[len] = NUL;
5073
Bram Moolenaar0f873732019-12-05 20:28:46 +01005074 // Check if the last character in buffer[] is
5075 // incomplete, keep these bytes for the next
5076 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005077 for (p = buffer; p < buffer + len; p += l)
5078 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02005079 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005080 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005081 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005082 else if (MB_BYTE2LEN(*p) != l)
5083 break;
5084 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005085 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005086 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005087 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005088 if (len >= 12)
5089 ++p;
5090 else
5091 {
5092 *buffer_off = len;
5093 return;
5094 }
5095 }
5096 c = *p;
5097 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005098 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005099 if (p < buffer + len)
5100 {
5101 *p = c;
5102 *buffer_off = (DWORD)((buffer + len) - p);
5103 mch_memmove(buffer, p, *buffer_off);
5104 return;
5105 }
5106 *buffer_off = 0;
5107 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005108 else
5109 {
5110 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005111 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005112 }
5113
5114 windgoto(msg_row, msg_col);
5115 cursor_on();
5116 out_flush();
5117 }
5118}
5119
5120/*
5121 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
5122 * for communication and doesn't open any new window.
5123 */
5124 static int
5125mch_system_piped(char *cmd, int options)
5126{
5127 STARTUPINFO si;
5128 PROCESS_INFORMATION pi;
5129 DWORD ret = 0;
5130
5131 HANDLE g_hChildStd_IN_Rd = NULL;
5132 HANDLE g_hChildStd_IN_Wr = NULL;
5133 HANDLE g_hChildStd_OUT_Rd = NULL;
5134 HANDLE g_hChildStd_OUT_Wr = NULL;
5135
Bram Moolenaar0f873732019-12-05 20:28:46 +01005136 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005137 DWORD len;
5138
Bram Moolenaar0f873732019-12-05 20:28:46 +01005139 // buffer used to receive keys
5140 char_u ta_buf[BUFLEN + 1]; // TypeAHead
5141 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005142
5143 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005144 int noread_cnt = 0;
5145 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005146 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005147 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005148 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005149
5150 SECURITY_ATTRIBUTES saAttr;
5151
Bram Moolenaar0f873732019-12-05 20:28:46 +01005152 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005153 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5154 saAttr.bInheritHandle = TRUE;
5155 saAttr.lpSecurityDescriptor = NULL;
5156
5157 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005158 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005159 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005160 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005161 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005162 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005163 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005164 {
5165 CloseHandle(g_hChildStd_IN_Rd);
5166 CloseHandle(g_hChildStd_IN_Wr);
5167 CloseHandle(g_hChildStd_OUT_Rd);
5168 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005169 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005170 }
5171
5172 si.cb = sizeof(si);
5173 si.lpReserved = NULL;
5174 si.lpDesktop = NULL;
5175 si.lpTitle = NULL;
5176 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5177
Bram Moolenaar0f873732019-12-05 20:28:46 +01005178 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005179 si.hStdError = g_hChildStd_OUT_Wr;
5180 si.hStdOutput = g_hChildStd_OUT_Wr;
5181 si.hStdInput = g_hChildStd_IN_Rd;
5182 si.wShowWindow = SW_HIDE;
5183 si.cbReserved2 = 0;
5184 si.lpReserved2 = NULL;
5185
5186 if (options & SHELL_READ)
5187 ga_init2(&ga, 1, BUFLEN);
5188
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005189 if (cmd != NULL)
5190 {
5191 p = (char *)vim_strsave((char_u *)cmd);
5192 if (p != NULL)
5193 unescape_shellxquote((char_u *)p, p_sxe);
5194 else
5195 p = cmd;
5196 }
5197
Bram Moolenaar0f873732019-12-05 20:28:46 +01005198 // Now, run the command.
5199 // About "Inherit handles" being TRUE: this command can be litigious,
5200 // handle inheritance was deactivated for pending temp file, but, if we
5201 // deactivate it, the pipes don't work for some reason.
Yegappan Lakshmanane89aef32025-05-14 20:31:55 +02005202 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5203 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005204
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005205 if (p != cmd)
5206 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005207
Bram Moolenaar0f873732019-12-05 20:28:46 +01005208 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005209 CloseHandle(g_hChildStd_IN_Rd);
5210 CloseHandle(g_hChildStd_OUT_Wr);
5211
5212 if (options & SHELL_WRITE)
5213 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005214 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005215 _beginthreadex(NULL, // security attributes
5216 0, // default stack size
5217 sub_process_writer, // function to be executed
5218 g_hChildStd_IN_Wr, // parameter
5219 0, // creation flag, start immediately
5220 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005221 CloseHandle(thread);
5222 g_hChildStd_IN_Wr = NULL;
5223 }
5224
Bram Moolenaar0f873732019-12-05 20:28:46 +01005225 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005226 for (;;)
5227 {
5228 MSG msg;
5229
K.Takatab7057bd2022-01-21 11:37:07 +00005230 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005231 {
5232 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005233 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005234 }
5235
Bram Moolenaar0f873732019-12-05 20:28:46 +01005236 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005237 if ((options & (SHELL_READ|SHELL_WRITE))
5238# ifdef FEAT_GUI
5239 || gui.in_use
5240# endif
5241 )
5242 {
5243 len = 0;
GuyBrush52ecc762024-02-21 20:16:38 +01005244 if (((options &
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005245 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5246 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5247# ifdef FEAT_GUI
5248 || gui.in_use
5249# endif
5250 )
5251 && (ta_len > 0 || noread_cnt > 4))
5252 {
5253 if (ta_len == 0)
5254 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005255 // Get extra characters when we don't have any. Reset the
5256 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005257 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005258 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5259 }
5260 if (ta_len > 0 || len > 0)
5261 {
5262 /*
5263 * For pipes: Check for CTRL-C: send interrupt signal to
GuyBrush1f13fcc2024-01-14 20:08:40 +01005264 * child.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005265 */
5266 if (len == 1 && cmd != NULL)
5267 {
5268 if (ta_buf[ta_len] == Ctrl_C)
5269 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005270 // Learn what exit code is expected, for
5271 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005272 TerminateProcess(pi.hProcess, 9);
5273 }
GuyBrush1f13fcc2024-01-14 20:08:40 +01005274 }
5275
5276 /*
5277 * Check for CTRL-D: EOF, close pipe to child.
5278 * Ctrl_D may be decorated by _OnChar()
5279 */
5280 if ((len == 1 || len == 4 ) && cmd != NULL)
5281 {
5282 if (ta_buf[0] == Ctrl_D
5283 || (ta_buf[0] == CSI
5284 && ta_buf[1] == KS_MODIFIER
5285 && ta_buf[3] == Ctrl_D))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005286 {
5287 CloseHandle(g_hChildStd_IN_Wr);
5288 g_hChildStd_IN_Wr = NULL;
GuyBrush1f13fcc2024-01-14 20:08:40 +01005289 len = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005290 }
5291 }
5292
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005293 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005294
5295 /*
5296 * For pipes: echo the typed characters. For a pty this
5297 * does not seem to work.
5298 */
5299 for (i = ta_len; i < ta_len + len; ++i)
5300 {
5301 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5302 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005303 else if (has_mbyte)
5304 {
5305 int l = (*mb_ptr2len)(ta_buf + i);
5306
5307 msg_outtrans_len(ta_buf + i, l);
5308 i += l - 1;
5309 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005310 else
5311 msg_outtrans_len(ta_buf + i, 1);
5312 }
5313 windgoto(msg_row, msg_col);
5314 out_flush();
5315
5316 ta_len += len;
5317
5318 /*
5319 * Write the characters to the child, unless EOF has been
5320 * typed for pipes. Write one character at a time, to
5321 * avoid losing too much typeahead. When writing buffer
5322 * lines, drop the typed characters (only check for
5323 * CTRL-C).
5324 */
5325 if (options & SHELL_WRITE)
5326 ta_len = 0;
5327 else if (g_hChildStd_IN_Wr != NULL)
5328 {
5329 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5330 1, &len, NULL);
5331 // if we are typing in, we want to keep things reactive
5332 delay = 1;
5333 if (len > 0)
5334 {
5335 ta_len -= len;
5336 mch_memmove(ta_buf, ta_buf + len, ta_len);
5337 }
5338 }
5339 }
5340 }
5341 }
5342
5343 if (ta_len)
5344 ui_inchar_undo(ta_buf, ta_len);
5345
5346 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5347 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005348 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005349 break;
5350 }
5351
5352 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005353 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005354
Bram Moolenaar0f873732019-12-05 20:28:46 +01005355 // We start waiting for a very short time and then increase it, so
5356 // that we respond quickly when the process is quick, and don't
5357 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005358 if (delay < 50)
5359 delay += 10;
5360 }
5361
Bram Moolenaar0f873732019-12-05 20:28:46 +01005362 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005363 CloseHandle(g_hChildStd_OUT_Rd);
5364 if (g_hChildStd_IN_Wr != NULL)
5365 CloseHandle(g_hChildStd_IN_Wr);
5366
5367 WaitForSingleObject(pi.hProcess, INFINITE);
5368
Bram Moolenaar0f873732019-12-05 20:28:46 +01005369 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005370 GetExitCodeProcess(pi.hProcess, &ret);
5371
5372 if (options & SHELL_READ)
5373 {
5374 if (ga.ga_len > 0)
5375 {
5376 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005377 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005378 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5379 }
5380 else
5381 curbuf->b_no_eol_lnum = 0;
5382 ga_clear(&ga);
5383 }
5384
Bram Moolenaar0f873732019-12-05 20:28:46 +01005385 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005386 CloseHandle(pi.hThread);
5387 CloseHandle(pi.hProcess);
5388
5389 return ret;
5390}
5391
5392 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005393mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005394{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005395 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005396 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005397 return mch_system_piped(cmd, options);
5398 else
5399 return mch_system_classic(cmd, options);
5400}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005401#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005403#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005404 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005405mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005406{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005407 int ret;
5408 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005409 char_u *buf;
5410 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005411
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005412 // If the command starts and ends with double quotes, enclose the command
5413 // in parentheses.
5414 len = STRLEN(cmd);
5415 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5416 {
5417 len += 3;
5418 buf = alloc(len);
5419 if (buf == NULL)
5420 return -1;
5421 vim_snprintf((char *)buf, len, "(%s)", cmd);
5422 wcmd = enc_to_utf16(buf, NULL);
5423 free(buf);
5424 }
5425 else
5426 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5427
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005428 if (wcmd == NULL)
5429 return -1;
5430
5431 ret = _wsystem(wcmd);
5432 vim_free(wcmd);
5433 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005434}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435
5436#endif
5437
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005438 static int
5439mch_system(char *cmd, int options)
5440{
5441#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005442 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005443 return mch_system_g(cmd, options);
5444 else
5445 return mch_system_c(cmd, options);
5446#elif defined(FEAT_GUI_MSWIN)
5447 return mch_system_g(cmd, options);
5448#else
5449 return mch_system_c(cmd, options);
5450#endif
5451}
5452
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005453#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5454/*
5455 * Use a terminal window to run a shell command in.
5456 */
5457 static int
5458mch_call_shell_terminal(
5459 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005460 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005461{
5462 jobopt_T opt;
5463 char_u *newcmd = NULL;
5464 typval_T argvar[2];
5465 long_u cmdlen;
5466 int retval = -1;
5467 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005468 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005469 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005470 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005471
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005472 if (cmd == NULL)
5473 cmdlen = STRLEN(p_sh) + 1;
5474 else
5475 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005476 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005477 if (newcmd == NULL)
5478 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005479 if (cmd == NULL)
5480 {
5481 STRCPY(newcmd, p_sh);
5482 ch_log(NULL, "starting terminal to run a shell");
5483 }
5484 else
5485 {
5486 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5487 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5488 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005489
5490 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005491
5492 argvar[0].v_type = VAR_STRING;
5493 argvar[0].vval.v_string = newcmd;
5494 argvar[1].v_type = VAR_UNKNOWN;
5495 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005496 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005497 {
5498 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005499 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005500 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005501
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005502 job = term_getjob(buf->b_term);
5503 ++job->jv_refcount;
5504
Bram Moolenaar0f873732019-12-05 20:28:46 +01005505 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005506 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005507 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005508 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005509 // Only do this when a window was found for "buf".
5510 clear_oparg(&oa);
5511 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005512 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005513 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5514 {
5515 // If terminal_loop() returns OK we got a key that is handled
5516 // in Normal model. We don't do redrawing anyway.
5517 if (terminal_loop(TRUE) == OK)
5518 normal_cmd(&oa, TRUE);
5519 }
5520 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005521 normal_cmd(&oa, TRUE);
5522 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005523 retval = job->jv_exitval;
5524 ch_log(NULL, "system command finished");
5525
5526 job_unref(job);
5527
5528 // restore curwin/curbuf and a few other things
5529 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005530 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005531
5532 wait_return(TRUE);
5533 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5534
5535 vim_free(newcmd);
5536 return retval;
5537}
5538#endif
5539
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540/*
5541 * Either execute a command by calling the shell or start a new shell
5542 */
5543 int
5544mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005545 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005546 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547{
5548 int x = 0;
5549 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005550 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005551
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005552#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005553 ch_log(NULL, "executing shell command: %s", cmd);
5554#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005555 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005556 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005557 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005558 if (cmd == NULL)
5559 wcscat(szShellTitle, L" :sh");
5560 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005561 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005562 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005563
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005564 if (wn != NULL)
5565 {
5566 wcscat(szShellTitle, L" - !");
5567 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005568 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005569 wcscat(szShellTitle, wn);
5570 SetConsoleTitleW(szShellTitle);
5571 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005572 }
5573 }
5574 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575
5576 out_flush();
5577
5578#ifdef MCH_WRITE_DUMP
5579 if (fdDump)
5580 {
5581 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5582 fflush(fdDump);
5583 }
5584#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005585#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005586 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005587 if (
5588# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005589 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005590# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005591 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005592 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5593 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005594 char_u *cmdbase = cmd;
5595
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005596 if (cmdbase != NULL)
5597 // Skip a leading quote and (.
5598 while (*cmdbase == '"' || *cmdbase == '(')
5599 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005600
5601 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005602 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5603 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005604 {
5605 // Use a terminal window to run the command in.
5606 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005607 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005608 return x;
5609 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005610 }
5611#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612
5613 /*
5614 * Catch all deadly signals while running the external command, because a
5615 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5616 */
ichizok378447f2023-05-11 22:25:42 +01005617 mch_signal(SIGINT, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005618 mch_signal(SIGBREAK, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005619 mch_signal(SIGILL, SIG_IGN);
5620 mch_signal(SIGFPE, SIG_IGN);
5621 mch_signal(SIGSEGV, SIG_IGN);
5622 mch_signal(SIGTERM, SIG_IGN);
5623 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624
5625 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005626 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627
5628 if (cmd == NULL)
5629 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005630 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 }
5632 else
5633 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005634 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005635 char_u *newcmd = NULL;
5636 char_u *cmdbase = cmd;
5637 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005638
Bram Moolenaar0f873732019-12-05 20:28:46 +01005639 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005640 if (*cmdbase == '"' )
5641 ++cmdbase;
5642 if (*cmdbase == '(')
5643 ++cmdbase;
5644
Bram Moolenaar1c465442017-03-12 20:10:05 +01005645 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005646 {
5647 STARTUPINFO si;
5648 PROCESS_INFORMATION pi;
5649 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005650 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005651 char_u *p;
5652
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005653 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005654 si.cb = sizeof(si);
5655 si.lpReserved = NULL;
5656 si.lpDesktop = NULL;
5657 si.lpTitle = NULL;
5658 si.dwFlags = 0;
5659 si.cbReserved2 = 0;
5660 si.lpReserved2 = NULL;
5661
5662 cmdbase = skipwhite(cmdbase + 5);
5663 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005664 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005665 {
5666 cmdbase = skipwhite(cmdbase + 4);
5667 si.dwFlags = STARTF_USESHOWWINDOW;
5668 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005669 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005670 }
5671 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005672 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005673 {
5674 cmdbase = skipwhite(cmdbase + 2);
5675 flags = CREATE_NO_WINDOW;
5676 si.dwFlags = STARTF_USESTDHANDLES;
5677 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005678 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005679 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005680 NULL, // Security att.
5681 OPEN_EXISTING, // Open flags
5682 FILE_ATTRIBUTE_NORMAL, // File att.
5683 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005684 si.hStdOutput = si.hStdInput;
5685 si.hStdError = si.hStdInput;
5686 }
5687
Bram Moolenaar0f873732019-12-05 20:28:46 +01005688 // Remove a trailing ", ) and )" if they have a match
5689 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005690 if (cmdbase > cmd)
5691 {
5692 p = cmdbase + STRLEN(cmdbase);
5693 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5694 *--p = NUL;
5695 if (p > cmdbase && p[-1] == ')'
5696 && (*cmd =='(' || cmd[1] == '('))
5697 *--p = NUL;
5698 }
5699
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005700 newcmd = cmdbase;
5701 unescape_shellxquote(cmdbase, p_sxe);
5702
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005703 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005704 * If creating new console, arguments are passed to the
5705 * 'cmd.exe' as-is. If it's not, arguments are not treated
5706 * correctly for current 'cmd.exe'. So unescape characters in
5707 * shellxescape except '|' for avoiding to be treated as
5708 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005709 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005710 if (flags != CREATE_NEW_CONSOLE)
5711 {
5712 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005713 char_u *cmd_shell = mch_getenv("COMSPEC");
5714
5715 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005716 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005717
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005718 subcmd = vim_strsave_escaped_ext(cmdbase,
5719 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005720 if (subcmd != NULL)
5721 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005722 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005723 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005724 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005725 if (newcmd != NULL)
5726 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005727 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005728 else
5729 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005730 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005731 }
5732 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005733
5734 /*
5735 * Now, start the command as a process, so that it doesn't
5736 * inherit our handles which causes unpleasant dangling swap
5737 * files if we exit before the spawned process
5738 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005739 if (vim_create_process((char *)newcmd, FALSE, flags,
5740 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005741 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005742 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5743 > (HINSTANCE)32)
5744 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005745 else
5746 {
5747 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005748#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005749# ifdef VIMDLL
5750 if (gui.in_use)
5751# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005752 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005753#endif
5754 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005755
5756 if (newcmd != cmdbase)
5757 vim_free(newcmd);
5758
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005759 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005760 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005761 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005762 CloseHandle(si.hStdInput);
5763 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005764 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005765 CloseHandle(pi.hThread);
5766 CloseHandle(pi.hProcess);
5767 }
5768 else
5769 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005770 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005771#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005772 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005773 (!s_dont_use_vimrun && p_stmp ?
John Marriott9cb27a52025-06-08 16:05:53 +02005774 vimrun_path.length : STRLEN(p_sh) + STRLEN(p_shcf))
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005775 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005777 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005778
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005779 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005780 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005781 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005782#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005783 if (
5784# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005785 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005786# endif
5787 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005788 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005789 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5790 "External commands will not pause after completion.\n"
5791 "See :help win32-vimrun for more information.");
5792 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005793 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5794 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005795
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005796 if (wmsg != NULL && wtitle != NULL)
5797 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5798 vim_free(wmsg);
5799 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005800 need_vimrun_warning = FALSE;
5801 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005802 if (
5803# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005804 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005805# endif
5806 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005807 // Use vimrun to execute the command. It opens a console
5808 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005809 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
John Marriott9cb27a52025-06-08 16:05:53 +02005810 vimrun_path.string,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811 (msg_silent != 0 || (options & SHELL_DOOUT))
5812 ? "-s " : "",
5813 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005814 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005815# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005816 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005817# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005818 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005819 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005820 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5821 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005822 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005824 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005825 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005826 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005827 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829 }
5830 }
5831
5832 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005833 {
5834 // The shell may have messed with the mode, always set it.
5835 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005836 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005837 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005838
Bram Moolenaar0f873732019-12-05 20:28:46 +01005839 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005841#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005842 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005843 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005844#endif
5845 )
5846 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005847 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848 msg_putchar('\n');
5849 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851
ichizok378447f2023-05-11 22:25:42 +01005852 mch_signal(SIGINT, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005853 mch_signal(SIGBREAK, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005854 mch_signal(SIGILL, SIG_DFL);
5855 mch_signal(SIGFPE, SIG_DFL);
5856 mch_signal(SIGSEGV, SIG_DFL);
5857 mch_signal(SIGTERM, SIG_DFL);
5858 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005859
5860 return x;
5861}
5862
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005863#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005864 static HANDLE
5865job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005866 char_u *fname,
5867 DWORD dwDesiredAccess,
5868 DWORD dwShareMode,
5869 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5870 DWORD dwCreationDisposition,
5871 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005872{
5873 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005874 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005875
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005876 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005877 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005878 return INVALID_HANDLE_VALUE;
5879
5880 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5881 lpSecurityAttributes, dwCreationDisposition,
5882 dwFlagsAndAttributes, NULL);
5883 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005884 return h;
5885}
5886
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005887/*
5888 * Turn the dictionary "env" into a NUL separated list that can be used as the
5889 * environment argument of vim_create_process().
5890 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005891 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005892win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005893{
5894 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005895 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005896 LPVOID base = GetEnvironmentStringsW();
5897
Bram Moolenaar0f873732019-12-05 20:28:46 +01005898 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005899 if (ga_grow(gap, 1) == FAIL)
5900 return;
5901
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005902 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005903 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005904 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005905 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005906 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005907 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005908 typval_T *item = &dict_lookup(hi)->di_tv;
5909 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005910 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005911 --todo;
5912 if (wkey != NULL && wval != NULL)
5913 {
5914 size_t n;
5915 size_t lkey = wcslen(wkey);
5916 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005917
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005918 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005919 continue;
5920 for (n = 0; n < lkey; n++)
5921 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5922 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5923 for (n = 0; n < lval; n++)
5924 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5925 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5926 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005927 vim_free(wkey);
5928 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005929 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005930 }
5931 }
5932
Bram Moolenaar355757a2020-02-10 22:06:32 +01005933 if (base)
5934 {
5935 WCHAR *p = (WCHAR*) base;
5936
5937 // for last \0
5938 if (ga_grow(gap, 1) == FAIL)
5939 return;
5940
5941 while (*p != 0 || *(p + 1) != 0)
5942 {
5943 if (ga_grow(gap, 1) == OK)
5944 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5945 p++;
5946 }
Ken Takataad29f6a2023-09-16 13:56:02 +02005947 FreeEnvironmentStringsW(base);
Bram Moolenaar355757a2020-02-10 22:06:32 +01005948 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5949 }
5950
Bram Moolenaar493359e2018-06-12 20:25:52 +02005951# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005952 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005953# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005954 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005955 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005956# endif
5957# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005958 char_u *version = get_vim_var_str(VV_VERSION);
5959 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005960# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005961 // size of "VIM_SERVERNAME=" and value,
5962 // plus "VIM_TERMINAL=" and value,
5963 // plus two terminating NULs
5964 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005965# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005966 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005967# endif
5968# ifdef FEAT_TERMINAL
5969 + 13 + version_len + 2
5970# endif
5971 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005972
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005973 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005974 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005975# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005976 for (n = 0; n < 15; n++)
5977 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5978 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005979 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005980 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5981 (WCHAR)servername[n];
5982 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005983# endif
5984# ifdef FEAT_TERMINAL
5985 if (is_terminal)
5986 {
5987 for (n = 0; n < 13; n++)
5988 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5989 (WCHAR)"VIM_TERMINAL="[n];
5990 for (n = 0; n < version_len; n++)
5991 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5992 (WCHAR)version[n];
5993 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5994 }
5995# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005996 }
5997 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005998# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005999}
6000
Bram Moolenaarb091f302019-01-19 14:37:00 +01006001/*
6002 * Create a pair of pipes.
6003 * Return TRUE for success, FALSE for failure.
6004 */
6005 static BOOL
6006create_pipe_pair(HANDLE handles[2])
6007{
6008 static LONG s;
6009 char name[64];
6010 SECURITY_ATTRIBUTES sa;
6011
6012 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
6013 GetCurrentProcessId(),
6014 InterlockedIncrement(&s));
6015
6016 // Create named pipe. Max size of named pipe is 65535.
6017 handles[1] = CreateNamedPipe(
6018 name,
6019 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
6020 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01006021 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01006022
6023 if (handles[1] == INVALID_HANDLE_VALUE)
6024 return FALSE;
6025
6026 sa.nLength = sizeof(sa);
6027 sa.bInheritHandle = TRUE;
6028 sa.lpSecurityDescriptor = NULL;
6029
6030 handles[0] = CreateFile(name,
6031 FILE_GENERIC_READ,
6032 FILE_SHARE_READ, &sa,
6033 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
6034
6035 if (handles[0] == INVALID_HANDLE_VALUE)
6036 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01006037 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01006038 return FALSE;
6039 }
6040
6041 return TRUE;
6042}
6043
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006044 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006045mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006046{
6047 STARTUPINFO si;
6048 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006049 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006050 SECURITY_ATTRIBUTES saAttr;
6051 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01006052 HANDLE ifd[2];
6053 HANDLE ofd[2];
6054 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006055 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006056
6057 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
6058 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
6059 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
6060 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
6061 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
6062 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
6063 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
6064
6065 if (use_out_for_err && use_null_for_out)
6066 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01006067
6068 ifd[0] = INVALID_HANDLE_VALUE;
6069 ifd[1] = INVALID_HANDLE_VALUE;
6070 ofd[0] = INVALID_HANDLE_VALUE;
6071 ofd[1] = INVALID_HANDLE_VALUE;
6072 efd[0] = INVALID_HANDLE_VALUE;
6073 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00006074 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006075
Bram Moolenaar14207f42016-10-27 21:13:10 +02006076 jo = CreateJobObject(NULL, NULL);
6077 if (jo == NULL)
6078 {
6079 job->jv_status = JOB_FAILED;
6080 goto failed;
6081 }
6082
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006083 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006084 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006085
Bram Moolenaar76467df2016-02-12 19:30:26 +01006086 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006087 ZeroMemory(&si, sizeof(si));
6088 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01006089 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006090 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006091
Bram Moolenaard8070362016-02-15 21:56:54 +01006092 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
6093 saAttr.bInheritHandle = TRUE;
6094 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006095
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006096 if (use_file_for_in)
6097 {
6098 char_u *fname = options->jo_io_name[PART_IN];
6099
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006100 ifd[0] = job_io_file_open(fname, GENERIC_READ,
6101 FILE_SHARE_READ | FILE_SHARE_WRITE,
6102 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
6103 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01006104 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006105 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01006106 goto failed;
6107 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006108 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01006109 else if (!use_null_for_in
6110 && (!create_pipe_pair(ifd)
6111 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006112 goto failed;
6113
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006114 if (use_file_for_out)
6115 {
6116 char_u *fname = options->jo_io_name[PART_OUT];
6117
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006118 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
6119 FILE_SHARE_READ | FILE_SHARE_WRITE,
6120 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6121 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006122 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006123 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006124 goto failed;
6125 }
6126 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006127 else if (!use_null_for_out &&
6128 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006129 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006130 goto failed;
6131
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006132 if (use_file_for_err)
6133 {
6134 char_u *fname = options->jo_io_name[PART_ERR];
6135
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006136 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
6137 FILE_SHARE_READ | FILE_SHARE_WRITE,
6138 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6139 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006140 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006141 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006142 goto failed;
6143 }
6144 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006145 else if (!use_out_for_err && !use_null_for_err &&
6146 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006147 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01006148 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006149
Bram Moolenaard8070362016-02-15 21:56:54 +01006150 si.dwFlags |= STARTF_USESTDHANDLES;
6151 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006152 si.hStdOutput = ofd[1];
6153 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
6154
6155 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
6156 {
Bram Moolenaarde279892016-03-11 22:19:44 +01006157 if (options->jo_set & JO_CHANNEL)
6158 {
6159 channel = options->jo_channel;
6160 if (channel != NULL)
6161 ++channel->ch_refcount;
6162 }
6163 else
6164 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006165 if (channel == NULL)
6166 goto failed;
6167 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006168
6169 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006170 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006171 CREATE_DEFAULT_ERROR_MODE |
6172 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006173 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006174 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006175 &si, &pi,
6176 ga.ga_data,
6177 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006178 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006179 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006180 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006181 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006182 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006183
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006184 ga_clear(&ga);
6185
Bram Moolenaar14207f42016-10-27 21:13:10 +02006186 if (!AssignProcessToJobObject(jo, pi.hProcess))
6187 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006188 // if failing, switch the way to terminate
6189 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006190 CloseHandle(jo);
6191 jo = NULL;
6192 }
6193 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006194 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006195 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006196 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006197 job->jv_status = JOB_STARTED;
6198
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006199 CloseHandle(ifd[0]);
6200 CloseHandle(ofd[1]);
6201 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006202 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006203
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006204 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006205 if (channel != NULL)
6206 {
6207 channel_set_pipes(channel,
6208 use_file_for_in || use_null_for_in
6209 ? INVALID_FD : (sock_T)ifd[1],
6210 use_file_for_out || use_null_for_out
6211 ? INVALID_FD : (sock_T)ofd[0],
6212 use_out_for_err || use_file_for_err || use_null_for_err
6213 ? INVALID_FD : (sock_T)efd[0]);
6214 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006215 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006216 return;
6217
6218failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006219 CloseHandle(ifd[0]);
6220 CloseHandle(ofd[0]);
6221 CloseHandle(efd[0]);
6222 CloseHandle(ifd[1]);
6223 CloseHandle(ofd[1]);
6224 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006225 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006226 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006227}
6228
6229 char *
6230mch_job_status(job_T *job)
6231{
6232 DWORD dwExitCode = 0;
6233
Bram Moolenaar76467df2016-02-12 19:30:26 +01006234 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6235 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006236 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006237 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006238 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006239 {
6240 ch_log(job->jv_channel, "Job ended");
6241 job->jv_status = JOB_ENDED;
6242 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006243 return "dead";
6244 }
6245 return "run";
6246}
6247
Bram Moolenaar97792de2016-10-15 18:36:49 +02006248 job_T *
6249mch_detect_ended_job(job_T *job_list)
6250{
6251 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6252 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6253 job_T *job = job_list;
6254
6255 while (job != NULL)
6256 {
6257 DWORD n;
6258 DWORD result;
6259
6260 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6261 && job != NULL; job = job->jv_next)
6262 {
6263 if (job->jv_status == JOB_STARTED)
6264 {
6265 jobHandles[n] = job->jv_proc_info.hProcess;
6266 jobArray[n] = job;
6267 ++n;
6268 }
6269 }
6270 if (n == 0)
6271 continue;
6272 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6273 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6274 {
6275 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6276
6277 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6278 return wait_job;
6279 }
6280 }
6281 return NULL;
6282}
6283
Bram Moolenaarfb630902016-10-29 14:55:00 +02006284 static BOOL
6285terminate_all(HANDLE process, int code)
6286{
6287 PROCESSENTRY32 pe;
6288 HANDLE h = INVALID_HANDLE_VALUE;
6289 DWORD pid = GetProcessId(process);
6290
6291 if (pid != 0)
6292 {
6293 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6294 if (h != INVALID_HANDLE_VALUE)
6295 {
6296 pe.dwSize = sizeof(PROCESSENTRY32);
6297 if (!Process32First(h, &pe))
6298 goto theend;
6299
6300 do
6301 {
6302 if (pe.th32ParentProcessID == pid)
6303 {
6304 HANDLE ph = OpenProcess(
6305 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6306 if (ph != NULL)
6307 {
6308 terminate_all(ph, code);
6309 CloseHandle(ph);
6310 }
6311 }
6312 } while (Process32Next(h, &pe));
6313
6314 CloseHandle(h);
6315 }
6316 }
6317
6318theend:
6319 return TerminateProcess(process, code);
6320}
6321
6322/*
6323 * Send a (deadly) signal to "job".
6324 * Return FAIL if it didn't work.
6325 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006326 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006327mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006328{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006329 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006330
Bram Moolenaar923d9262016-02-25 20:56:01 +01006331 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006332 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006333 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006334 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006335 {
6336 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6337 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006338 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006339 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006340 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006341 }
6342
6343 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6344 return FAIL;
6345 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006346 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6347 job->jv_proc_info.dwProcessId)
6348 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006349 FreeConsole();
6350 return ret;
6351}
6352
6353/*
6354 * Clear the data related to "job".
6355 */
6356 void
6357mch_clear_job(job_T *job)
6358{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006359 if (job->jv_status == JOB_FAILED)
6360 return;
6361
6362 if (job->jv_job_object != NULL)
6363 CloseHandle(job->jv_job_object);
6364 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006365}
6366#endif
6367
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006369#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370
6371/*
6372 * Start termcap mode
6373 */
6374 static void
6375termcap_mode_start(void)
6376{
6377 DWORD cmodein;
6378
6379 if (g_fTermcapMode)
6380 return;
6381
6382 SaveConsoleBuffer(&g_cbNonTermcap);
6383
6384 if (g_cbTermcap.IsValid)
6385 {
6386 /*
6387 * We've been in termcap mode before. Restore certain screen
6388 * characteristics, including the buffer size and the window
6389 * size. Since we will be redrawing the screen, we don't need
6390 * to restore the actual contents of the buffer.
6391 */
6392 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006393 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006394 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6395 Rows = g_cbTermcap.Info.dwSize.Y;
6396 Columns = g_cbTermcap.Info.dwSize.X;
6397 }
6398 else
6399 {
6400 /*
6401 * This is our first time entering termcap mode. Clear the console
6402 * screen buffer, and resize the buffer to match the current window
6403 * size. We will use this as the size of our editing environment.
6404 */
6405 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006406 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6408 }
6409
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411
6412 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006414 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006415 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006416 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6417 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006418 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006419 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006420 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006421 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6422 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006423 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006424 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425
6426 redraw_later_clear();
6427 g_fTermcapMode = TRUE;
6428}
6429
6430
6431/*
6432 * End termcap mode
6433 */
6434 static void
6435termcap_mode_end(void)
6436{
6437 DWORD cmodein;
6438 ConsoleBuffer *cb;
6439 COORD coord;
6440 DWORD dwDummy;
6441
6442 if (!g_fTermcapMode)
6443 return;
6444
6445 SaveConsoleBuffer(&g_cbTermcap);
6446
6447 GetConsoleMode(g_hConIn, &cmodein);
6448 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006449 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6450 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006452# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006453 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006454# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006456# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006457 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006458 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459
William Breslerded59132024-10-08 21:30:48 +02006460 // Switch back to main screen buffer.
6461 if (exiting && use_alternate_screen_buffer)
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +02006462 vtp_printf("\033[?1049l");
William Breslerded59132024-10-08 21:30:48 +02006463
Christopher Plewright1140b512022-11-12 18:46:05 +00006464 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006465 {
6466 /*
6467 * Clear anything that happens to be on the current line.
6468 */
6469 coord.X = 0;
6470 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006471 FillConsoleOutputCharacter(g_hConOut, ' ',
6472 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006473 /*
6474 * The following is just for aesthetics. If we are exiting without
6475 * restoring the screen, then we want to have a prompt string
6476 * appear at the bottom line. However, the command interpreter
6477 * seems to always advance the cursor one line before displaying
6478 * the prompt string, which causes the screen to scroll. To
6479 * counter this, move the cursor up one line before exiting.
6480 */
6481 if (exiting && !p_rs)
6482 coord.Y--;
6483 /*
6484 * Position the cursor at the leftmost column of the desired row.
6485 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006486 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006488 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 g_fTermcapMode = FALSE;
6490}
Christopher Plewright38804d62022-11-09 23:55:52 +00006491#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492
6493
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006494#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006495 void
6496mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006497 char_u *s UNUSED,
6498 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006500 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501}
6502
6503#else
6504
6505/*
6506 * clear `n' chars, starting from `coord'
6507 */
6508 static void
6509clear_chars(
6510 COORD coord,
6511 DWORD n)
6512{
Christopher Plewright38804d62022-11-09 23:55:52 +00006513 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006514 {
6515 DWORD dwDummy;
6516
6517 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6518 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6519 &dwDummy);
6520 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006521 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006522 {
6523 set_console_color_rgb();
6524 gotoxy(coord.X + 1, coord.Y + 1);
6525 vtp_printf("\033[%dX", n);
6526 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527}
6528
6529
6530/*
6531 * Clear the screen
6532 */
6533 static void
6534clear_screen(void)
6535{
6536 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006537
Christopher Plewright38804d62022-11-09 23:55:52 +00006538 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006539 clear_chars(g_coord, Rows * Columns);
6540 else
6541 {
6542 set_console_color_rgb();
6543 gotoxy(1, 1);
6544 vtp_printf("\033[2J");
6545 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546}
6547
6548
6549/*
6550 * Clear to end of display
6551 */
6552 static void
6553clear_to_end_of_display(void)
6554{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006555 COORD save = g_coord;
6556
Christopher Plewright38804d62022-11-09 23:55:52 +00006557 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006558 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006560 else
6561 {
6562 set_console_color_rgb();
6563 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6564 vtp_printf("\033[0J");
6565
6566 gotoxy(save.X + 1, save.Y + 1);
6567 g_coord = save;
6568 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569}
6570
6571
6572/*
6573 * Clear to end of line
6574 */
6575 static void
6576clear_to_end_of_line(void)
6577{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006578 COORD save = g_coord;
6579
Christopher Plewright38804d62022-11-09 23:55:52 +00006580 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006581 clear_chars(g_coord, Columns - g_coord.X);
6582 else
6583 {
6584 set_console_color_rgb();
6585 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6586 vtp_printf("\033[0K");
6587
6588 gotoxy(save.X + 1, save.Y + 1);
6589 g_coord = save;
6590 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591}
6592
6593
6594/*
6595 * Scroll the scroll region up by `cLines' lines
6596 */
6597 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006598scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599{
6600 COORD oldcoord = g_coord;
6601
6602 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6603 delete_lines(cLines);
6604
6605 g_coord = oldcoord;
6606}
6607
6608
6609/*
6610 * Set the scroll region
6611 */
6612 static void
6613set_scroll_region(
6614 unsigned left,
6615 unsigned top,
6616 unsigned right,
6617 unsigned bottom)
6618{
6619 if (left >= right
6620 || top >= bottom
6621 || right > (unsigned) Columns - 1
6622 || bottom > (unsigned) Rows - 1)
6623 return;
6624
6625 g_srScrollRegion.Left = left;
6626 g_srScrollRegion.Top = top;
6627 g_srScrollRegion.Right = right;
6628 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006629}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006630
Bram Moolenaar6982f422019-02-16 16:48:01 +01006631 static void
6632set_scroll_region_tb(
6633 unsigned top,
6634 unsigned bottom)
6635{
6636 if (top >= bottom || bottom > (unsigned)Rows - 1)
6637 return;
6638
6639 g_srScrollRegion.Top = top;
6640 g_srScrollRegion.Bottom = bottom;
6641}
6642
6643 static void
6644set_scroll_region_lr(
6645 unsigned left,
6646 unsigned right)
6647{
6648 if (left >= right || right > (unsigned)Columns - 1)
6649 return;
6650
6651 g_srScrollRegion.Left = left;
6652 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653}
6654
6655
6656/*
6657 * Insert `cLines' lines at the current cursor position
6658 */
6659 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006660insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006662 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 COORD dest;
6664 CHAR_INFO fill;
6665
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006666 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6667
Bram Moolenaar6982f422019-02-16 16:48:01 +01006668 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 dest.Y = g_coord.Y + cLines;
6670
Bram Moolenaar6982f422019-02-16 16:48:01 +01006671 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 source.Top = g_coord.Y;
6673 source.Right = g_srScrollRegion.Right;
6674 source.Bottom = g_srScrollRegion.Bottom - cLines;
6675
Bram Moolenaar6982f422019-02-16 16:48:01 +01006676 clip.Left = g_srScrollRegion.Left;
6677 clip.Top = g_coord.Y;
6678 clip.Right = g_srScrollRegion.Right;
6679 clip.Bottom = g_srScrollRegion.Bottom;
6680
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006681 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006682 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006683 fill.Attributes = g_attrCurrent;
6684 else
6685 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006687 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006688
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006689 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6690
Bram Moolenaar6982f422019-02-16 16:48:01 +01006691 // Here we have to deal with a win32 console flake: If the scroll
6692 // region looks like abc and we scroll c to a and fill with d we get
6693 // cbd... if we scroll block c one line at a time to a, we get cdd...
6694 // vim expects cdd consistently... So we have to deal with that
6695 // here... (this also occurs scrolling the same way in the other
6696 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006697
6698 if (source.Bottom < dest.Y)
6699 {
6700 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006701 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702
Bram Moolenaar6982f422019-02-16 16:48:01 +01006703 coord.X = source.Left;
6704 for (i = clip.Top; i < dest.Y; ++i)
6705 {
6706 coord.Y = i;
6707 clear_chars(coord, source.Right - source.Left + 1);
6708 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006710
Christopher Plewright38804d62022-11-09 23:55:52 +00006711 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006712 {
6713 COORD coord;
6714 int i;
6715
6716 coord.X = source.Left;
6717 for (i = source.Top; i < dest.Y; ++i)
6718 {
6719 coord.Y = i;
6720 clear_chars(coord, source.Right - source.Left + 1);
6721 }
6722 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723}
6724
6725
6726/*
6727 * Delete `cLines' lines at the current cursor position
6728 */
6729 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006730delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006732 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733 COORD dest;
6734 CHAR_INFO fill;
6735 int nb;
6736
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006737 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6738
Bram Moolenaar6982f422019-02-16 16:48:01 +01006739 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740 dest.Y = g_coord.Y;
6741
Bram Moolenaar6982f422019-02-16 16:48:01 +01006742 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743 source.Top = g_coord.Y + cLines;
6744 source.Right = g_srScrollRegion.Right;
6745 source.Bottom = g_srScrollRegion.Bottom;
6746
Bram Moolenaar6982f422019-02-16 16:48:01 +01006747 clip.Left = g_srScrollRegion.Left;
6748 clip.Top = g_coord.Y;
6749 clip.Right = g_srScrollRegion.Right;
6750 clip.Bottom = g_srScrollRegion.Bottom;
6751
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006752 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006753 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006754 fill.Attributes = g_attrCurrent;
6755 else
6756 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006758 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006759
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006760 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6761
Bram Moolenaar6982f422019-02-16 16:48:01 +01006762 // Here we have to deal with a win32 console flake; See insert_lines()
6763 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764
6765 nb = dest.Y + (source.Bottom - source.Top) + 1;
6766
6767 if (nb < source.Top)
6768 {
6769 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006770 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771
Bram Moolenaar6982f422019-02-16 16:48:01 +01006772 coord.X = source.Left;
6773 for (i = nb; i < clip.Bottom; ++i)
6774 {
6775 coord.Y = i;
6776 clear_chars(coord, source.Right - source.Left + 1);
6777 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006779
Christopher Plewright38804d62022-11-09 23:55:52 +00006780 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006781 {
6782 COORD coord;
6783 int i;
6784
6785 coord.X = source.Left;
6786 for (i = nb; i <= source.Bottom; ++i)
6787 {
6788 coord.Y = i;
6789 clear_chars(coord, source.Right - source.Left + 1);
6790 }
6791 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792}
6793
6794
6795/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006796 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 */
6798 static void
6799gotoxy(
6800 unsigned x,
6801 unsigned y)
6802{
6803 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6804 return;
6805
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006806 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006807 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006808 // There are reports of double-width characters not displayed
6809 // correctly. This workaround should fix it, similar to how it's done
6810 // for VTP.
6811 g_coord.X = 0;
6812 SetConsoleCursorPosition(g_hConOut, g_coord);
6813
Bram Moolenaar2313b612019-09-27 14:14:32 +02006814 // external cursor coords are 1-based; internal are 0-based
6815 g_coord.X = x - 1;
6816 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006817 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006818 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006819 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006820 {
6821 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006822 // destruction. Insider build bug. Always enabled because it's cheap
6823 // and avoids mistakes with recognizing the build.
6824 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006825
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006826 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006827
6828 g_coord.X = x - 1;
6829 g_coord.Y = y - 1;
6830 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831}
6832
6833
6834/*
6835 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006836 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837 */
6838 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006839textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006841 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842
6843 SetConsoleTextAttribute(g_hConOut, wAttr);
6844}
6845
6846
6847 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006848textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006849{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006850 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851
Christopher Plewright38804d62022-11-09 23:55:52 +00006852 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006853 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6854 else
6855 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006856}
6857
6858
6859 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006860textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006861{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006862 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863
Christopher Plewright38804d62022-11-09 23:55:52 +00006864 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006865 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6866 else
6867 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006868}
6869
6870
6871/*
6872 * restore the default text attribute (whatever we started with)
6873 */
6874 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006875normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876{
Christopher Plewright38804d62022-11-09 23:55:52 +00006877 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006878 textattr(g_attrDefault);
6879 else
6880 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881}
6882
6883
6884static WORD g_attrPreStandout = 0;
6885
6886/*
6887 * Make the text standout, by brightening it
6888 */
6889 static void
6890standout(void)
6891{
6892 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006893
Bram Moolenaar071d4272004-06-13 20:20:40 +00006894 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6895}
6896
6897
6898/*
6899 * Turn off standout mode
6900 */
6901 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006902standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903{
6904 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006906
6907 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908}
6909
6910
6911/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006912 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913 */
6914 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006915mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916{
6917 char_u *p;
6918 int n;
6919
6920 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6921 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006922 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006923# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006924 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006925# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006926 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927 {
6928 p = T_ME + 2;
6929 n = getdigits(&p);
6930 if (*p == 'm' && n > 0)
6931 {
6932 cterm_normal_fg_color = (n & 0xf) + 1;
6933 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6934 }
6935 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006936# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006937 cterm_normal_fg_gui_color = INVALCOLOR;
6938 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006939# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940}
6941
6942
6943/*
6944 * visual bell: flash the screen
6945 */
6946 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006947visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006948{
6949 COORD coordOrigin = {0, 0};
6950 WORD attrFlash = ~g_attrCurrent & 0xff;
6951
6952 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006953 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006955# ifdef FEAT_TERMGUICOLORS
6956 if (!(p_tgc || t_colors >= 256))
6957# endif
6958 {
6959 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6960 if (oldattrs == NULL)
6961 return;
6962 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006963 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006964 }
6965
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6967 coordOrigin, &dwDummy);
6968
Bram Moolenaar0f873732019-12-05 20:28:46 +01006969 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006970
6971 if (oldattrs != NULL)
6972 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006973 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006975 vim_free(oldattrs);
6976 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977}
6978
6979
6980/*
6981 * Make the cursor visible or invisible
6982 */
6983 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006984cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985{
6986 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006987
Christopher Plewright38804d62022-11-09 23:55:52 +00006988 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006989 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6990
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006991# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006993# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994}
6995
6996
6997/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006998 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006999 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00007000 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007001 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007003 char_u *pchBuf,
7004 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007005{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007006 COORD coord = g_coord;
7007 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007008 DWORD n, cchwritten;
7009 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007010 static WCHAR *unicodebuf = NULL;
7011 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007012 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007013 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007014 static WCHAR *utf8spbuf = NULL;
7015 static int utf8splength;
7016 static DWORD utf8spcells;
7017 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007018
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007019 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007020 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007021 utf8usingbuf = &unicodebuf;
7022 do
7023 {
7024 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
7025 unicodebuf, unibuflen);
7026 if (length && length <= unibuflen)
7027 break;
7028 vim_free(unicodebuf);
7029 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
7030 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01007031 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007032 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007033 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007034 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
7035 {
7036 if (utf8usingbuf != &utf8spbuf)
7037 {
7038 if (utf8spbuf == NULL)
7039 {
7040 cells = mb_string2cells((char_u *)" ", 1);
7041 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
7042 utf8spbuf = LALLOC_MULT(WCHAR, length);
7043 if (utf8spbuf != NULL)
7044 {
7045 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
7046 utf8usingbuf = &utf8spbuf;
7047 utf8splength = length;
7048 utf8spcells = cells;
7049 }
7050 }
7051 else
7052 {
7053 utf8usingbuf = &utf8spbuf;
7054 length = utf8splength;
7055 cells = utf8spcells;
7056 }
7057 }
7058 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007059
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007060 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007061 {
7062 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
7063 coord, &written);
7064 // When writing fails or didn't write a single character, pretend one
7065 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007066 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007067 coord, &cchwritten) == 0
7068 || cchwritten == 0 || cchwritten == (DWORD)-1)
7069 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007070 }
7071 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007072 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007073 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007074 NULL) == 0 || cchwritten == 0)
7075 cchwritten = 1;
7076 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007077
K.Takata135e1522022-01-29 15:27:58 +00007078 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007079 {
7080 written = cbToWrite;
7081 g_coord.X += (SHORT)cells;
7082 }
7083 else
7084 {
7085 char_u *p = pchBuf;
7086 for (n = 0; n < cchwritten; n++)
7087 MB_CPTR_ADV(p);
7088 written = p - pchBuf;
7089 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007090 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091
7092 while (g_coord.X > g_srScrollRegion.Right)
7093 {
7094 g_coord.X -= (SHORT) Columns;
7095 if (g_coord.Y < g_srScrollRegion.Bottom)
7096 g_coord.Y++;
7097 }
7098
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007099 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007100 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007101 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102
7103 return written;
7104}
7105
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007106 static char_u *
7107get_seq(
7108 int *args,
7109 int *count,
7110 char_u *head)
7111{
7112 int argc;
7113 char_u *p;
7114
7115 if (head == NULL || *head != '\033')
7116 return NULL;
7117
7118 argc = 0;
7119 p = head;
7120 ++p;
7121 do
7122 {
7123 ++p;
7124 args[argc] = getdigits(&p);
7125 argc += (argc < 15) ? 1 : 0;
7126 } while (*p == ';');
7127 *count = argc;
7128
7129 return p;
7130}
7131
7132 static char_u *
7133get_sgr(
7134 int *args,
7135 int *count,
7136 char_u *head)
7137{
7138 char_u *p = get_seq(args, count, head);
7139
7140 return (p && *p == 'm') ? ++p : NULL;
7141}
7142
7143/*
7144 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
7145 */
7146 static char_u *
7147sgrn2(
7148 char_u *head,
7149 int n)
7150{
7151 int argc;
7152 int args[16];
7153 char_u *p = get_sgr(args, &argc, head);
7154
7155 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
7156}
7157
7158/*
7159 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7160 */
7161 static char_u *
7162sgrnc(
7163 char_u *head,
7164 int n)
7165{
7166 int argc;
7167 int args[16];
7168 char_u *p = get_sgr(args, &argc, head);
7169
7170 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7171 ? p : NULL;
7172}
7173
7174 static char_u *
7175skipblank(char_u *q)
7176{
7177 char_u *p = q;
7178
7179 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7180 ++p;
7181 return p;
7182}
7183
7184/*
7185 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7186 * NULL.
7187 */
7188 static char_u *
7189sgrn2c(
7190 char_u *head,
7191 int n)
7192{
7193 char_u *p = sgrn2(head, n);
7194
7195 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7196}
7197
7198/*
7199 * If there is only a newline between the sequence immediately following it,
7200 * a pointer to the character following the newline is returned.
7201 * Otherwise NULL.
7202 */
7203 static char_u *
7204sgrn2cn(
7205 char_u *head,
7206 int n)
7207{
7208 char_u *p = sgrn2(head, n);
7209
7210 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7211}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007212
7213/*
7214 * mch_write(): write the output buffer to the screen, translating ESC
7215 * sequences into calls to console output routines.
7216 */
7217 void
7218mch_write(
7219 char_u *s,
7220 int len)
7221{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007222 char_u *end = s + len;
7223
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007224# ifdef VIMDLL
7225 if (gui.in_use)
7226 return;
7227# endif
7228
Bram Moolenaar071d4272004-06-13 20:20:40 +00007229 if (!term_console)
7230 {
7231 write(1, s, (unsigned)len);
7232 return;
7233 }
7234
Bram Moolenaar0f873732019-12-05 20:28:46 +01007235 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236 while (len--)
7237 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007238 int prefix = -1;
7239 char_u ch;
7240
7241 // While processing a sequence, on rare occasions it seems that another
7242 // sequence may be inserted asynchronously.
7243 if (len < 0)
7244 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007245 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007246 return;
7247 }
7248
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007249 while (s + ++prefix < end)
7250 {
7251 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007252 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7253 && ch != '\a' && ch != '\033'))
7254 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007255 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007256
7257 if (p_wd)
7258 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007259 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260 if (prefix != 0)
7261 prefix = 1;
7262 }
7263
7264 if (prefix != 0)
7265 {
7266 DWORD nWritten;
7267
7268 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007269# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270 if (fdDump)
7271 {
7272 fputc('>', fdDump);
7273 fwrite(s, sizeof(char_u), nWritten, fdDump);
7274 fputs("<\n", fdDump);
7275 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007276# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007277 len -= (nWritten - 1);
7278 s += nWritten;
7279 }
7280 else if (s[0] == '\n')
7281 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007282 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007283 if (g_coord.Y == g_srScrollRegion.Bottom)
7284 {
7285 scroll(1);
7286 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7287 }
7288 else
7289 {
7290 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7291 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007292# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293 if (fdDump)
7294 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007295# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296 s++;
7297 }
7298 else if (s[0] == '\r')
7299 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007300 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007301 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007302# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303 if (fdDump)
7304 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007305# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306 s++;
7307 }
7308 else if (s[0] == '\b')
7309 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007310 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007311 if (g_coord.X > g_srScrollRegion.Left)
7312 g_coord.X--;
7313 else if (g_coord.Y > g_srScrollRegion.Top)
7314 {
7315 g_coord.X = g_srScrollRegion.Right;
7316 g_coord.Y--;
7317 }
7318 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007319# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007320 if (fdDump)
7321 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007322# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007323 s++;
7324 }
7325 else if (s[0] == '\a')
7326 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007327 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007328 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007329# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007330 if (fdDump)
7331 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007332# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007333 s++;
7334 }
7335 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7336 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007337# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007338 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007339# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007340 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007341 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007342 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343
7344 switch (s[2])
7345 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007346 case '0': case '1': case '2': case '3': case '4':
7347 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007348 if (*(p = get_seq(args, &argc, s)) != 'm')
7349 goto notsgr;
7350
7351 p = s;
7352
7353 // Handling frequent optional sequences. Output to the screen
7354 // takes too long, so do not output as much as possible.
7355
7356 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7357 // resetFG,FG,BG are omitted.
7358 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007359 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007360 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7361 len = len + 1 - (int)(p - s);
7362 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007364 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007365
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007366 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7367 // omitted.
7368 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7369 p = sp;
7370
7371 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7372 // omitted.
7373 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7374 p = sp;
7375
7376 // If BG,BG of SGR are connected, the first BG can be omitted.
7377 if (sgrn2((sp = sgrn2(p, 48)), 48))
7378 p = sp;
7379
7380 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007381 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007382 if (sgrn2((sp = sgrnc(p, 39)), 38))
7383 p = sp;
7384
7385 p = get_seq(args, &argc, p);
7386
7387notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007388 arg1 = args[0];
7389 arg2 = args[1];
7390 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007391 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007392 if (argc == 1 && args[0] == 0)
7393 normvideo();
7394 else if (argc == 1)
7395 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007396 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007397 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007398 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007399 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007400 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007401 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007402 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007404 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007405 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007406 gotoxy(arg2, arg1);
7407 }
7408 else if (argc == 2 && *p == 'r')
7409 {
7410 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7411 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007412 else if (argc == 2 && *p == 'R')
7413 {
7414 set_scroll_region_tb(arg1, arg2);
7415 }
7416 else if (argc == 2 && *p == 'V')
7417 {
7418 set_scroll_region_lr(arg1, arg2);
7419 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007420 else if (argc == 1 && *p == 'A')
7421 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 gotoxy(g_coord.X + 1,
7423 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7424 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007425 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 {
7427 textbackground((WORD) arg1);
7428 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007429 else if (argc == 1 && *p == 'C')
7430 {
7431 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7432 g_coord.Y + 1);
7433 }
7434 else if (argc == 1 && *p == 'f')
7435 {
7436 textcolor((WORD) arg1);
7437 }
7438 else if (argc == 1 && *p == 'H')
7439 {
7440 gotoxy(1, arg1);
7441 }
7442 else if (argc == 1 && *p == 'L')
7443 {
7444 insert_lines(arg1);
7445 }
7446 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007447 {
7448 delete_lines(arg1);
7449 }
7450
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007451 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007452 s = p + 1;
7453 break;
7454
Bram Moolenaar071d4272004-06-13 20:20:40 +00007455 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007456 gotoxy(g_coord.X + 1,
7457 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7458 goto got3;
7459
7460 case 'B':
7461 visual_bell();
7462 goto got3;
7463
7464 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007465 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7466 g_coord.Y + 1);
7467 goto got3;
7468
7469 case 'E':
7470 termcap_mode_end();
7471 goto got3;
7472
7473 case 'F':
7474 standout();
7475 goto got3;
7476
7477 case 'f':
7478 standend();
7479 goto got3;
7480
7481 case 'H':
7482 gotoxy(1, 1);
7483 goto got3;
7484
7485 case 'j':
7486 clear_to_end_of_display();
7487 goto got3;
7488
7489 case 'J':
7490 clear_screen();
7491 goto got3;
7492
7493 case 'K':
7494 clear_to_end_of_line();
7495 goto got3;
7496
7497 case 'L':
7498 insert_lines(1);
7499 goto got3;
7500
7501 case 'M':
7502 delete_lines(1);
7503 goto got3;
7504
7505 case 'S':
7506 termcap_mode_start();
7507 goto got3;
7508
7509 case 'V':
7510 cursor_visible(TRUE);
7511 goto got3;
7512
7513 case 'v':
7514 cursor_visible(FALSE);
7515 goto got3;
7516
7517 got3:
7518 s += 3;
7519 len -= 2;
7520 }
7521
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007522# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007523 if (fdDump)
7524 {
7525 fputs("ESC | ", fdDump);
7526 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7527 fputc('\n', fdDump);
7528 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007529# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530 }
K.Takatadf5320c2022-09-01 13:20:16 +01007531 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7532 {
7533 int l = 2;
7534
Keith Thompson184f71c2024-01-04 21:19:04 +01007535 if (SAFE_isdigit(s[l]))
K.Takatadf5320c2022-09-01 13:20:16 +01007536 l++;
7537 if (s[l] == ' ' && s[l + 1] == 'q')
7538 {
7539 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007540 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007541 vtp_printf("%.*s", l + 2, s); // Pass through
7542 s += l + 2;
7543 len -= l + 1;
7544 }
7545 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007546 else
7547 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007548 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549 DWORD nWritten;
7550
7551 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007552# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553 if (fdDump)
7554 {
7555 fputc('>', fdDump);
7556 fwrite(s, sizeof(char_u), nWritten, fdDump);
7557 fputs("<\n", fdDump);
7558 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007559# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560
7561 len -= (nWritten - 1);
7562 s += nWritten;
7563 }
7564 }
7565
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007566# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567 if (fdDump)
7568 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007569# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007570}
7571
Bram Moolenaar0f873732019-12-05 20:28:46 +01007572#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573
7574
7575/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007576 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007577 */
7578 void
7579mch_delay(
7580 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007581 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007582{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007583#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007584 Sleep((int)msec); // never wait for input
7585#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007586# ifdef VIMDLL
7587 if (gui.in_use)
7588 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007589 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007590 return;
7591 }
7592# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007593 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007594# ifdef FEAT_MZSCHEME
7595 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7596 {
7597 int towait = p_mzq;
7598
Bram Moolenaar0f873732019-12-05 20:28:46 +01007599 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007600 while (msec > 0)
7601 {
7602 mzvim_check_threads();
7603 if (msec < towait)
7604 towait = msec;
7605 Sleep(towait);
7606 msec -= towait;
7607 }
7608 }
7609 else
7610# endif
7611 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007612 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007613 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007614#endif
7615}
7616
7617
7618/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007619 * This version of remove is not scared by a readonly (backup) file.
7620 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621 * Return 0 for success, -1 for failure.
7622 */
7623 int
7624mch_remove(char_u *name)
7625{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007626 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007627 int n;
7628
Bram Moolenaar203258c2016-01-17 22:15:16 +01007629 /*
7630 * On Windows, deleting a directory's symbolic link is done by
7631 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7632 */
7633 if (mch_isdir(name) && mch_is_symbolic_link(name))
7634 return mch_rmdir(name);
7635
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007636 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7637
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007638 wn = enc_to_utf16(name, NULL);
7639 if (wn == NULL)
7640 return -1;
7641
7642 n = DeleteFileW(wn) ? 0 : -1;
7643 vim_free(wn);
7644 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007645}
7646
7647
7648/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007649 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007650 */
7651 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007652mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007653{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007654#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7655# ifdef VIMDLL
7656 if (!gui.in_use)
7657# endif
7658 if (g_fCtrlCPressed || g_fCBrkPressed)
7659 {
7660 ctrl_break_was_pressed = g_fCBrkPressed;
7661 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7662 got_int = TRUE;
7663 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664#endif
7665}
7666
Bram Moolenaar0f873732019-12-05 20:28:46 +01007667// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007668#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007669
7670/*
7671 * How much main memory in KiB that can be used by VIM.
7672 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007673 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007674mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007675{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007676 MEMORYSTATUSEX ms;
7677
Bram Moolenaar0f873732019-12-05 20:28:46 +01007678 // Need to use GlobalMemoryStatusEx() when there is more memory than
7679 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007680 ms.dwLength = sizeof(MEMORYSTATUSEX);
7681 GlobalMemoryStatusEx(&ms);
7682 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007683 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007684 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007685 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007686 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007687 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007688 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007689 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007690 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007691 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007692 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007693 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007694}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007695
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007697 * mch_wrename() works around a bug in rename (aka MoveFile) in
Nir Lichtman563e8ec2024-09-30 19:42:28 +02007698 * Windows, the bug can be demonstrated with the following scenario:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007699 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
Nir Lichtman563e8ec2024-09-30 19:42:28 +02007700 * "abcdef~1.txt" again.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007701 *
7702 * Like rename(), returns 0 upon success, non-zero upon failure.
7703 * Should probably set errno appropriately when errors occur.
7704 */
7705 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007706mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007708 WCHAR *p;
John Marriotte5297e32025-06-15 16:50:38 +02007709 WCHAR *q;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007710 WCHAR szTempFile[_MAX_PATH + 1];
7711 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007712 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007713
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007714 // No need to play tricks unless the file name contains a "~" as the
7715 // seventh character.
John Marriotte5297e32025-06-15 16:50:38 +02007716 for (p = q = wold; *p != L'\0'; ++p)
7717 {
7718 switch (*p)
7719 {
7720 case L'/':
7721 case L'\\':
7722 case L':':
7723 if (*(p + 1) != L'\0')
7724 q = p + 1; // point to the character after the path
7725 // separator.
7726 break;
7727
7728 default:
7729 break;
7730 }
7731 }
7732
7733 // If the length of the file name is less than 8 characters or the seventh
7734 // character is not a "~', do a normal move.
7735 if ((int)(p - q) < 8 || q[6] != L'~')
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007736 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007737
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007738 // Get base path of new file name. Undocumented feature: If pszNewFile is
7739 // a directory, no error is returned and pszFilePart will be NULL.
7740 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007741 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007742 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007743
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007744 // Get (and create) a unique temporary file name in directory of new file
7745 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007746 return -2;
7747
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007748 // blow the temp file away
7749 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007750 return -3;
7751
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007752 // rename old file to the temp file
7753 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007754 return -4;
7755
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007756 // now create an empty file called pszOldFile; this prevents the operating
7757 // system using pszOldFile as an alias (SFN) if we're renaming within the
7758 // same directory. For example, we're editing a file called
7759 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7760 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7761 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7762 // cause all sorts of problems later in buf_write(). So, we create an
7763 // empty file called filena~1.txt and the system will have to find some
7764 // other SFN for filena~1.txt~, such as filena~2.txt
7765 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007766 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7767 return -5;
7768 if (!CloseHandle(hf))
7769 return -6;
7770
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007771 // rename the temp file to the new file
7772 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007774 // Renaming failed. Rename the file back to its old name, so that it
7775 // looks like nothing happened.
7776 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007777 return -7;
7778 }
7779
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007780 // Seems to be left around on Novell filesystems
7781 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007782
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007783 // finally, remove the empty old file
7784 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007785 return -8;
7786
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007787 return 0;
7788}
7789
7790
7791/*
7792 * Converts the filenames to UTF-16, then call mch_wrename().
7793 * Like rename(), returns 0 upon success, non-zero upon failure.
7794 */
7795 int
7796mch_rename(
7797 const char *pszOldFile,
7798 const char *pszNewFile)
7799{
7800 WCHAR *wold = NULL;
7801 WCHAR *wnew = NULL;
7802 int retval = -1;
7803
7804 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7805 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7806 if (wold != NULL && wnew != NULL)
7807 retval = mch_wrename(wold, wnew);
7808 vim_free(wold);
7809 vim_free(wnew);
7810 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811}
7812
7813/*
7814 * Get the default shell for the current hardware platform
7815 */
7816 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007817default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007818{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007819 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007820}
7821
7822/*
7823 * mch_access() extends access() to do more detailed check on network drives.
7824 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7825 */
7826 int
7827mch_access(char *n, int p)
7828{
7829 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007830 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007831 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007832
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007833 wn = enc_to_utf16((char_u *)n, NULL);
7834 if (wn == NULL)
7835 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007836
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007837 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007838 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007839 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007840
7841 if (p & R_OK)
7842 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007843 // Read check is performed by seeing if we can do a find file on
7844 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007845 int i;
7846 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007847
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007848 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7849 TempNameW[i] = wn[i];
7850 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7851 TempNameW[i++] = '\\';
7852 TempNameW[i++] = '*';
7853 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007854
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007855 hFile = FindFirstFileW(TempNameW, &d);
7856 if (hFile == INVALID_HANDLE_VALUE)
7857 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007858 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007859 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007860 }
7861
7862 if (p & W_OK)
7863 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007864 // Trying to create a temporary file in the directory should catch
7865 // directories on read-only network shares. However, in
7866 // directories whose ACL allows writes but denies deletes will end
7867 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007868 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7869 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007870 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007871 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007872 }
7873 }
7874 else
7875 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007876 // Don't consider a file read-only if another process has opened it.
7877 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7878
Bram Moolenaar0f873732019-12-05 20:28:46 +01007879 // Trying to open the file for the required access does ACL, read-only
7880 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007881 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7882 | ((p & R_OK) ? GENERIC_READ : 0);
7883
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007884 hFile = CreateFileW(wn, access_mode, share_mode,
7885 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007886 if (hFile == INVALID_HANDLE_VALUE)
7887 goto getout;
7888 CloseHandle(hFile);
7889 }
7890
Bram Moolenaar0f873732019-12-05 20:28:46 +01007891 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007893 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007894 return retval;
7895}
7896
Bram Moolenaar071d4272004-06-13 20:20:40 +00007897/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007898 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007899 */
7900 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007901mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902{
7903 WCHAR *wn;
7904 int f;
7905
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007906 wn = enc_to_utf16((char_u *)name, NULL);
7907 if (wn == NULL)
7908 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007909
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007910 f = _wopen(wn, flags, mode);
7911 vim_free(wn);
7912 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007913}
7914
7915/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007916 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007917 */
7918 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007919mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007920{
7921 WCHAR *wn, *wm;
7922 FILE *f = NULL;
7923
Bram Moolenaara12a1612019-01-24 16:39:02 +01007924#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007925 // Work around an annoying assertion in the Microsoft debug CRT
7926 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007927 char newMode = mode[strlen(mode) - 1];
7928 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007929
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007930 _get_fmode(&oldMode);
7931 if (newMode == 't')
7932 _set_fmode(_O_TEXT);
7933 else if (newMode == 'b')
7934 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007935#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007936 wn = enc_to_utf16((char_u *)name, NULL);
7937 wm = enc_to_utf16((char_u *)mode, NULL);
7938 if (wn != NULL && wm != NULL)
7939 f = _wfopen(wn, wm);
7940 vim_free(wn);
7941 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007942
Bram Moolenaara12a1612019-01-24 16:39:02 +01007943#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007944 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007945#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007946 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007947}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007948
Bram Moolenaar071d4272004-06-13 20:20:40 +00007949/*
7950 * SUB STREAM (aka info stream) handling:
7951 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007952 * NTFS can have sub streams for each file. The normal contents of a file is
7953 * stored in the main stream, and extra contents (author information, title and
7954 * so on) can be stored in a sub stream. After Windows 2000, the user can
7955 * access and store this information in sub streams via an explorer's property
7956 * menu item in the right click menu. This information in sub streams was lost
7957 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007958 *
7959 * Incomplete explanation:
7960 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7961 * More useful info and an example:
7962 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7963 */
7964
7965/*
7966 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7967 * and write to stream "substream" of file "to".
7968 * Errors are ignored.
7969 */
7970 static void
7971copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7972{
7973 HANDLE hTo;
7974 WCHAR *to_name;
7975
John Marriott738df382025-06-05 20:49:39 +02007976 to_name = alloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7977 if (to_name == NULL)
7978 return;
7979
Bram Moolenaar071d4272004-06-13 20:20:40 +00007980 wcscpy(to_name, to);
7981 wcscat(to_name, substream);
7982
7983 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7984 FILE_ATTRIBUTE_NORMAL, NULL);
7985 if (hTo != INVALID_HANDLE_VALUE)
7986 {
7987 long done;
7988 DWORD todo;
7989 DWORD readcnt, written;
7990 char buf[4096];
7991
Bram Moolenaar0f873732019-12-05 20:28:46 +01007992 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007993 for (done = 0; done < len; done += written)
7994 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007995 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007996 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7997 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007998 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7999 FALSE, FALSE, context)
8000 || readcnt != todo
8001 || !WriteFile(hTo, buf, todo, &written, NULL)
8002 || written != todo)
8003 break;
8004 }
8005 CloseHandle(hTo);
8006 }
8007
8008 free(to_name);
8009}
8010
8011/*
8012 * Copy info streams from file "from" to file "to".
8013 */
8014 static void
8015copy_infostreams(char_u *from, char_u *to)
8016{
8017 WCHAR *fromw;
8018 WCHAR *tow;
8019 HANDLE sh;
8020 WIN32_STREAM_ID sid;
8021 int headersize;
8022 WCHAR streamname[_MAX_PATH];
8023 DWORD readcount;
8024 void *context = NULL;
8025 DWORD lo, hi;
8026 int len;
8027
Bram Moolenaar0f873732019-12-05 20:28:46 +01008028 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008029 fromw = enc_to_utf16(from, NULL);
8030 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008031 if (fromw != NULL && tow != NULL)
8032 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008033 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008034 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
8035 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
8036 if (sh != INVALID_HANDLE_VALUE)
8037 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008038 // Use BackupRead() to find the info streams. Repeat until we
8039 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008040 for (;;)
8041 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008042 // Get the header to find the length of the stream name. If
8043 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008044 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008045 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008046 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
8047 &readcount, FALSE, FALSE, &context)
8048 || readcount == 0)
8049 break;
8050
Bram Moolenaar0f873732019-12-05 20:28:46 +01008051 // We only deal with streams that have a name. The normal
8052 // file data appears to be without a name, even though docs
8053 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008054 if (sid.dwStreamNameSize > 0)
8055 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008056 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008057 if (!BackupRead(sh, (LPBYTE)streamname,
8058 sid.dwStreamNameSize,
8059 &readcount, FALSE, FALSE, &context))
8060 break;
8061
Bram Moolenaar0f873732019-12-05 20:28:46 +01008062 // Copy an info stream with a name ":anything:$DATA".
8063 // Skip "::$DATA", it has no stream name (examples suggest
8064 // it might be used for the normal file contents).
8065 // Note that BackupRead() counts bytes, but the name is in
8066 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008067 len = readcount / sizeof(WCHAR);
8068 streamname[len] = 0;
8069 if (len > 7 && wcsicmp(streamname + len - 6,
8070 L":$DATA") == 0)
8071 {
8072 streamname[len - 6] = 0;
8073 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00008074 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008075 }
8076 }
8077
Bram Moolenaar0f873732019-12-05 20:28:46 +01008078 // Advance to the next stream. We might try seeking too far,
8079 // but BackupSeek() doesn't skip over stream borders, thus
8080 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00008081 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00008082 &lo, &hi, &context);
8083 }
8084
Bram Moolenaar0f873732019-12-05 20:28:46 +01008085 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008086 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
8087
8088 CloseHandle(sh);
8089 }
8090 }
8091 vim_free(fromw);
8092 vim_free(tow);
8093}
Bram Moolenaar071d4272004-06-13 20:20:40 +00008094
8095/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008096 * ntdll.dll definitions
8097 */
8098#define FileEaInformation 7
8099#ifndef STATUS_SUCCESS
8100# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
8101#endif
8102
8103typedef struct _FILE_FULL_EA_INFORMATION_ {
8104 ULONG NextEntryOffset;
8105 UCHAR Flags;
8106 UCHAR EaNameLength;
8107 USHORT EaValueLength;
8108 CHAR EaName[1];
8109} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
8110
8111typedef struct _FILE_EA_INFORMATION_ {
8112 ULONG EaSize;
8113} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
8114
Paul Ollis65745772022-06-05 16:55:54 +01008115#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008116typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
8117 PHANDLE FileHandle,
8118 ACCESS_MASK DesiredAccess,
8119 POBJECT_ATTRIBUTES ObjectAttributes,
8120 PIO_STATUS_BLOCK IoStatusBlock,
8121 ULONG ShareAccess,
8122 ULONG OpenOptions);
8123typedef NTSTATUS (NTAPI *PfnNtClose)(
8124 HANDLE Handle);
8125typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008126 HANDLE FileHandle,
8127 PIO_STATUS_BLOCK IoStatusBlock,
8128 PVOID Buffer,
8129 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008130typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
8131 HANDLE FileHandle,
8132 PIO_STATUS_BLOCK IoStatusBlock,
8133 PVOID Buffer,
8134 ULONG Length,
8135 BOOLEAN ReturnSingleEntry,
8136 PVOID EaList,
8137 ULONG EaListLength,
8138 PULONG EaIndex,
8139 BOOLEAN RestartScan);
8140typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008141 HANDLE FileHandle,
8142 PIO_STATUS_BLOCK IoStatusBlock,
8143 PVOID FileInformation,
8144 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008145 FILE_INFORMATION_CLASS FileInformationClass);
8146typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
8147 PUNICODE_STRING DestinationString,
8148 PCWSTR SourceString);
8149
8150PfnNtOpenFile pNtOpenFile = NULL;
8151PfnNtClose pNtClose = NULL;
8152PfnNtSetEaFile pNtSetEaFile = NULL;
8153PfnNtQueryEaFile pNtQueryEaFile = NULL;
8154PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
8155PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01008156#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008157
8158/*
8159 * Load ntdll.dll functions.
8160 */
8161 static BOOL
8162load_ntdll(void)
8163{
8164 static int loaded = -1;
8165
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008166 if (loaded != -1)
8167 return (BOOL) loaded;
8168
8169 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8170 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008171 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008172 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8173 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8174 pNtSetEaFile = (PfnNtSetEaFile)
8175 GetProcAddress(hNtdll, "NtSetEaFile");
8176 pNtQueryEaFile = (PfnNtQueryEaFile)
8177 GetProcAddress(hNtdll, "NtQueryEaFile");
8178 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8179 GetProcAddress(hNtdll, "NtQueryInformationFile");
8180 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8181 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008182 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008183 if (pNtOpenFile == NULL
8184 || pNtClose == NULL
8185 || pNtSetEaFile == NULL
8186 || pNtQueryEaFile == NULL
8187 || pNtQueryInformationFile == NULL
8188 || pRtlInitUnicodeString == NULL)
8189 loaded = FALSE;
8190 else
8191 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008192 return (BOOL) loaded;
8193}
8194
8195/*
8196 * Copy extended attributes (EA) from file "from" to file "to".
8197 */
8198 static void
8199copy_extattr(char_u *from, char_u *to)
8200{
8201 char_u *fromf = NULL;
8202 char_u *tof = NULL;
8203 WCHAR *fromw = NULL;
8204 WCHAR *tow = NULL;
8205 UNICODE_STRING u;
8206 HANDLE h;
8207 OBJECT_ATTRIBUTES oa;
8208 IO_STATUS_BLOCK iosb;
8209 FILE_EA_INFORMATION_ eainfo = {0};
8210 void *ea = NULL;
8211
8212 if (!load_ntdll())
8213 return;
8214
8215 // Convert the file names to the fully qualified object names.
8216 fromf = alloc(STRLEN(from) + 5);
8217 tof = alloc(STRLEN(to) + 5);
8218 if (fromf == NULL || tof == NULL)
8219 goto theend;
8220 STRCPY(fromf, "\\??\\");
John Marriott9cb27a52025-06-08 16:05:53 +02008221 STRCPY(fromf + STRLEN_LITERAL("\\??\\"), from);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008222 STRCPY(tof, "\\??\\");
John Marriott9cb27a52025-06-08 16:05:53 +02008223 STRCPY(tof + STRLEN_LITERAL("\\??\\"), to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008224
8225 // Convert the names to wide characters.
8226 fromw = enc_to_utf16(fromf, NULL);
8227 tow = enc_to_utf16(tof, NULL);
8228 if (fromw == NULL || tow == NULL)
8229 goto theend;
8230
8231 // Get the EA.
8232 pRtlInitUnicodeString(&u, fromw);
8233 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8234 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8235 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8236 goto theend;
8237 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8238 FileEaInformation);
8239 if (eainfo.EaSize != 0)
8240 {
8241 ea = alloc(eainfo.EaSize);
8242 if (ea != NULL)
8243 {
8244 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8245 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8246 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008247 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008248 }
8249 }
8250 }
8251 pNtClose(h);
8252
8253 // Set the EA.
8254 if (ea != NULL)
8255 {
8256 pRtlInitUnicodeString(&u, tow);
8257 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8258 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8259 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8260 goto theend;
8261
8262 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8263 pNtClose(h);
8264 }
8265
8266theend:
8267 vim_free(fromf);
8268 vim_free(tof);
8269 vim_free(fromw);
8270 vim_free(tow);
8271 vim_free(ea);
8272}
8273
8274/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008275 * Copy file attributes from file "from" to file "to".
8276 * For Windows NT and later we copy info streams.
8277 * Always returns zero, errors are ignored.
8278 */
8279 int
8280mch_copy_file_attribute(char_u *from, char_u *to)
8281{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008282 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008283 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008284 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008285 return 0;
8286}
8287
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008288
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008289/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008290 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008291 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008292static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008293static LPWSTR *ArglistW = NULL;
8294static int global_argc = 0;
8295static char **global_argv;
8296
Bram Moolenaar0f873732019-12-05 20:28:46 +01008297static int used_file_argc = 0; // last argument in global_argv[] used
8298 // for the argument list.
8299static int *used_file_indexes = NULL; // indexes in global_argv[] for
8300 // command line arguments added to
8301 // the argument list
8302static int used_file_count = 0; // nr of entries in used_file_indexes
8303static int used_file_literal = FALSE; // take file names literally
8304static int used_file_full_path = FALSE; // file name was full path
8305static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008306static int used_alist_count = 0;
8307
8308
8309/*
8310 * Get the command line arguments. Unicode version.
8311 * Returns argc. Zero when something fails.
8312 */
8313 int
8314get_cmd_argsW(char ***argvp)
8315{
8316 char **argv = NULL;
8317 int argc = 0;
8318 int i;
8319
Bram Moolenaar14993322014-09-09 12:25:33 +02008320 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008321 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8322 if (ArglistW != NULL)
8323 {
John Marriott738df382025-06-05 20:49:39 +02008324 argv = alloc((nArgsW + 1) * sizeof(char *));
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008325 if (argv != NULL)
8326 {
8327 argc = nArgsW;
8328 argv[argc] = NULL;
8329 for (i = 0; i < argc; ++i)
8330 {
8331 int len;
8332
K.Takatadc73b4b2021-06-08 18:32:36 +02008333 // Convert each Unicode argument to UTF-8.
8334 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008335 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008336 (LPSTR *)&argv[i], &len, 0, 0);
8337 if (argv[i] == NULL)
8338 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008339 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008340 while (i > 0)
8341 free(argv[--i]);
8342 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008343 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008344 argc = 0;
8345 }
8346 }
8347 }
8348 }
8349
8350 global_argc = argc;
8351 global_argv = argv;
8352 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008353 {
8354 if (used_file_indexes != NULL)
8355 free(used_file_indexes);
John Marriott738df382025-06-05 20:49:39 +02008356 used_file_indexes = alloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008357 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008358
8359 if (argvp != NULL)
8360 *argvp = argv;
8361 return argc;
8362}
8363
8364 void
8365free_cmd_argsW(void)
8366{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008367 if (ArglistW == NULL)
8368 return;
8369
8370 GlobalFree(ArglistW);
8371 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008372}
8373
8374/*
8375 * Remember "name" is an argument that was added to the argument list.
8376 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8377 * is called.
8378 */
8379 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008380used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008381{
8382 int i;
8383
8384 if (used_file_indexes == NULL)
8385 return;
8386 for (i = used_file_argc + 1; i < global_argc; ++i)
8387 if (STRCMP(global_argv[i], name) == 0)
8388 {
8389 used_file_argc = i;
8390 used_file_indexes[used_file_count++] = i;
8391 break;
8392 }
8393 used_file_literal = literal;
8394 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008395 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008396}
8397
8398/*
8399 * Remember the length of the argument list as it was. If it changes then we
8400 * leave it alone when 'encoding' is set.
8401 */
8402 void
8403set_alist_count(void)
8404{
8405 used_alist_count = GARGCOUNT;
8406}
8407
8408/*
8409 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008410 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008411 * and convert them to 'encoding'.
8412 */
8413 void
8414fix_arg_enc(void)
8415{
8416 int i;
8417 int idx;
8418 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008419 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008420
Bram Moolenaar0f873732019-12-05 20:28:46 +01008421 // Safety checks:
8422 // - if argument count differs between the wide and non-wide argument
8423 // list, something must be wrong.
8424 // - the file name arguments must have been located.
8425 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008426 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008427 || ArglistW == NULL
8428 || used_file_indexes == NULL
8429 || used_file_count == 0
8430 || used_alist_count != GARGCOUNT)
8431 return;
8432
Bram Moolenaar0f873732019-12-05 20:28:46 +01008433 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008434 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008435 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008436 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008437 for (i = 0; i < GARGCOUNT; ++i)
8438 fnum_list[i] = GARGLIST[i].ae_fnum;
8439
Bram Moolenaar0f873732019-12-05 20:28:46 +01008440 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008441 alist_clear(&global_alist);
8442 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008443 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008444
8445 for (i = 0; i < used_file_count; ++i)
8446 {
8447 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008448 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008449 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008450 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008451 int literal = used_file_literal;
8452
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008453#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008454 // When using diff mode may need to concatenate file name to
8455 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008456 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8457 && !mch_isdir(alist_name(&GARGLIST[0])))
8458 {
8459 char_u *r;
8460
8461 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8462 if (r != NULL)
8463 {
8464 vim_free(str);
8465 str = r;
8466 }
8467 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008468#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008469 // Re-use the old buffer by renaming it. When not using literal
8470 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008471 if (used_file_literal)
8472 buf_set_name(fnum_list[i], str);
8473
Bram Moolenaar0f873732019-12-05 20:28:46 +01008474 // Check backtick literal. backtick literal is already expanded in
8475 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008476 if (literal == FALSE)
8477 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008478 size_t len = STRLEN(str);
8479
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008480 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8481 literal = TRUE;
8482 }
8483 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008484 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008485 }
8486
8487 if (!used_file_literal)
8488 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008489 // Now expand wildcards in the arguments.
8490 // Temporarily add '(' and ')' to 'isfname'. These are valid
8491 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008492 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008493 // Also, unset wildignore to not be influenced by this option.
8494 // The arguments specified in command-line should be kept even if
8495 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008496 // Use :legacy so that it also works when in Vim9 script.
8497 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8498 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008499 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008500 do_cmdline_cmd(
8501 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8502 do_cmdline_cmd(
8503 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008504 }
8505
Bram Moolenaar0f873732019-12-05 20:28:46 +01008506 // If wildcard expansion failed, we are editing the first file of the
8507 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008508 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8509 {
8510 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008511 if (GARGCOUNT == 1 && used_file_full_path
8512 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8513 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008514 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008515
8516 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008517}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008518
8519 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008520mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008521{
8522 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008523 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008524
Bram Moolenaar964b3742019-05-24 18:54:09 +02008525 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008526 if (envbuf == NULL)
8527 return -1;
8528
8529 sprintf((char *)envbuf, "%s=%s", var, value);
8530
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008531 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008532
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008533 vim_free(envbuf);
8534 if (p == NULL)
8535 return -1;
8536 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008537#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008538 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008539#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008540 // Unlike Un*x systems, we can free the string for _wputenv().
8541 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008542
8543 return 0;
8544}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008545
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008546/*
8547 * Support for 256 colors and 24-bit colors was added in Windows 10
8548 * version 1703 (Creators update).
8549 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008550#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8551
8552/*
8553 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008554 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008555 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008556#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008557
8558/*
8559 * ConPTY differences between versions, need different logic.
8560 * version 1903 (May 2019 update).
8561 */
8562#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8563
8564/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008565 * version 1909 (November 2019 update).
8566 */
8567#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8568
8569/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008570 * Stay ahead of the next update, and when it's done, fix this.
8571 * version ? (2020 update, temporarily use the build number of insider preview)
8572 */
8573#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8574
8575/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008576 * Confirm until this version. Also the logic changes.
8577 * insider preview.
8578 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008579#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008580
8581/*
8582 * Not stable now.
8583 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008584#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008585// Notes:
8586// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8587// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8588// preview which had a build 19587. And, not sure how stable that was?
8589// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8590// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008591
8592 static void
8593vtp_flag_init(void)
8594{
8595 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008596#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008597 DWORD mode;
8598 HANDLE out;
8599
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008600# ifdef VIMDLL
8601 if (!gui.in_use)
8602# endif
8603 {
8604 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008605
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008606 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8607 GetConsoleMode(out, &mode);
8608 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8609 if (SetConsoleMode(out, mode) == 0)
8610 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008611
8612 // VTP uses alternate screen buffer.
8613 // But, not if running in a nested terminal
8614 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8615 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008616 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008617#endif
8618
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008619 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008620 conpty_working = 1;
8621 if (ver >= CONPTY_STABLE_BUILD)
8622 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008623
Bram Moolenaar57da6982019-09-13 22:30:11 +02008624 if (ver <= CONPTY_INSIDER_BUILD)
8625 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008626 if (ver <= CONPTY_1909_BUILD)
8627 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008628 if (ver <= CONPTY_1903_BUILD)
8629 conpty_type = 2;
8630 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8631 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008632
8633 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8634 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008635}
8636
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008637#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008638
8639 static void
8640vtp_init(void)
8641{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008642# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008643 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8644 csbi.cbSize = sizeof(csbi);
8645 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8646 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8647 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8648 store_console_bg_rgb = save_console_bg_rgb;
8649 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008650
Christopher Plewrightd343c602023-01-22 18:58:30 +00008651 COLORREF bg;
8652 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8653 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8654 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008655
Christopher Plewrightd343c602023-01-22 18:58:30 +00008656 COLORREF fg;
8657 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8658 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8659 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008660# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008661 set_console_color_rgb();
8662}
8663
8664 static void
8665vtp_exit(void)
8666{
Bram Moolenaardf543822020-01-30 11:53:59 +01008667 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008668}
8669
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008670 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008671vtp_printf(
8672 char *format,
8673 ...)
8674{
8675 char_u buf[100];
8676 va_list list;
8677 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008678 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008679
Nir Lichtman6cd2d1d2023-11-11 11:27:41 +01008680 if (silent_mode)
8681 return 0;
8682
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008683 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008684 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008685 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008686 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008687 return (int)result;
8688}
8689
8690 static void
8691vtp_sgr_bulk(
8692 int arg)
8693{
8694 int args[1];
8695
8696 args[0] = arg;
8697 vtp_sgr_bulks(1, args);
8698}
8699
K.Takata6e1d31e2022-02-03 13:05:32 +00008700# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008701 if ((*p-- = "0123456789"[(n = x % 10)]) \
8702 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8703 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8704
K.Takata6e1d31e2022-02-03 13:05:32 +00008705# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008706 case x: \
8707 FAST256(newargs[x - 1]);
8708
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008709 static void
8710vtp_sgr_bulks(
8711 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008712 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008713{
K.Takata6e1d31e2022-02-03 13:05:32 +00008714# define MAXSGR 16
8715# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008716 char_u buf[SGRBUFSIZE];
8717 char_u *p;
8718 int in, out;
8719 int newargs[16];
8720 static int sgrfgr = -1, sgrfgg, sgrfgb;
8721 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008722
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008723 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008724 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008725 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008726 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008727 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008728 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008729
8730 in = out = 0;
8731 while (in < argc)
8732 {
8733 int s = args[in];
8734 int copylen = 1;
8735
8736 if (s == 38)
8737 {
8738 if (argc - in >= 5 && args[in + 1] == 2)
8739 {
8740 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8741 && sgrfgb == args[in + 4])
8742 {
8743 in += 5;
8744 copylen = 0;
8745 }
8746 else
8747 {
8748 sgrfgr = args[in + 2];
8749 sgrfgg = args[in + 3];
8750 sgrfgb = args[in + 4];
8751 copylen = 5;
8752 }
8753 }
8754 else if (argc - in >= 3 && args[in + 1] == 5)
8755 {
8756 sgrfgr = -1;
8757 copylen = 3;
8758 }
8759 }
8760 else if (s == 48)
8761 {
8762 if (argc - in >= 5 && args[in + 1] == 2)
8763 {
8764 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8765 && sgrbgb == args[in + 4])
8766 {
8767 in += 5;
8768 copylen = 0;
8769 }
8770 else
8771 {
8772 sgrbgr = args[in + 2];
8773 sgrbgg = args[in + 3];
8774 sgrbgb = args[in + 4];
8775 copylen = 5;
8776 }
8777 }
8778 else if (argc - in >= 3 && args[in + 1] == 5)
8779 {
8780 sgrbgr = -1;
8781 copylen = 3;
8782 }
8783 }
8784 else if (30 <= s && s <= 39)
8785 sgrfgr = -1;
8786 else if (90 <= s && s <= 97)
8787 sgrfgr = -1;
8788 else if (40 <= s && s <= 49)
8789 sgrbgr = -1;
8790 else if (100 <= s && s <= 107)
8791 sgrbgr = -1;
8792 else if (s == 0)
8793 sgrfgr = sgrbgr = -1;
8794
8795 while (copylen--)
8796 newargs[out++] = args[in++];
8797 }
8798
8799 p = &buf[sizeof(buf) - 1];
8800 *p-- = 'm';
8801
8802 switch (out)
8803 {
8804 int n, m;
8805 DWORD r;
8806
8807 FAST256CASE(16);
8808 *p-- = ';';
8809 FAST256CASE(15);
8810 *p-- = ';';
8811 FAST256CASE(14);
8812 *p-- = ';';
8813 FAST256CASE(13);
8814 *p-- = ';';
8815 FAST256CASE(12);
8816 *p-- = ';';
8817 FAST256CASE(11);
8818 *p-- = ';';
8819 FAST256CASE(10);
8820 *p-- = ';';
8821 FAST256CASE(9);
8822 *p-- = ';';
8823 FAST256CASE(8);
8824 *p-- = ';';
8825 FAST256CASE(7);
8826 *p-- = ';';
8827 FAST256CASE(6);
8828 *p-- = ';';
8829 FAST256CASE(5);
8830 *p-- = ';';
8831 FAST256CASE(4);
8832 *p-- = ';';
8833 FAST256CASE(3);
8834 *p-- = ';';
8835 FAST256CASE(2);
8836 *p-- = ';';
8837 FAST256CASE(1);
8838 *p-- = '[';
8839 *p = '\033';
8840 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8841 default:
8842 break;
8843 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008844}
8845
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008846 static void
8847wt_init(void)
8848{
Christopher Plewright1140b512022-11-12 18:46:05 +00008849 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008850}
8851
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008852# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008853 static int
8854ctermtoxterm(
8855 int cterm)
8856{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008857 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008858
8859 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8860 return (((int)r << 16) | ((int)g << 8) | (int)b);
8861}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008862# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008863
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008864 static void
8865set_console_color_rgb(void)
8866{
8867# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008868 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008869 guicolor_T fg, bg;
8870 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008871
Christopher Plewright38804d62022-11-09 23:55:52 +00008872 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008873 return;
8874
Bram Moolenaara050b942019-12-02 21:35:31 +01008875 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8876
Christopher Plewright38804d62022-11-09 23:55:52 +00008877 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008878 {
8879 term_fg_rgb_color(fg);
8880 term_bg_rgb_color(bg);
8881 return;
8882 }
8883
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008884 if (use_alternate_screen_buffer)
8885 return;
8886
Christopher Plewrightd343c602023-01-22 18:58:30 +00008887 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8888 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008889
Christopher Plewrightd343c602023-01-22 18:58:30 +00008890 csbi.cbSize = sizeof(csbi);
8891 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008892
Christopher Plewrightd343c602023-01-22 18:58:30 +00008893 csbi.cbSize = sizeof(csbi);
8894 csbi.srWindow.Right += 1;
8895 csbi.srWindow.Bottom += 1;
8896 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8897 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8898 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8899 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8900 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008901# endif
8902}
8903
Bram Moolenaara050b942019-12-02 21:35:31 +01008904# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8905 void
8906get_default_console_color(
8907 int *cterm_fg,
8908 int *cterm_bg,
8909 guicolor_T *gui_fg,
8910 guicolor_T *gui_bg)
8911{
8912 int id;
8913 guicolor_T guifg = INVALCOLOR;
8914 guicolor_T guibg = INVALCOLOR;
8915 int ctermfg = 0;
8916 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008917 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008918
8919 id = syn_name2id((char_u *)"Normal");
8920 if (id > 0 && p_tgc)
8921 syn_id2colors(id, &guifg, &guibg);
8922 if (guifg == INVALCOLOR)
8923 {
8924 ctermfg = -1;
8925 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008926 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008927 if (ctermfg != -1)
8928 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008929 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008930 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8931 cterm_normal_fg_gui_color = guifg;
8932 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008933 }
8934 if (guibg == INVALCOLOR)
8935 {
8936 ctermbg = -1;
8937 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008938 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008939 if (ctermbg != -1)
8940 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008941 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008942 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8943 cterm_normal_bg_gui_color = guibg;
8944 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008945 }
8946
8947 *cterm_fg = ctermfg;
8948 *cterm_bg = ctermbg;
8949 *gui_fg = guifg;
8950 *gui_bg = guibg;
8951}
8952# endif
8953
Bram Moolenaardf543822020-01-30 11:53:59 +01008954/*
8955 * Set the console colors to the original colors or the last set colors.
8956 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008957 static void
8958reset_console_color_rgb(void)
8959{
8960# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008961 if (use_alternate_screen_buffer)
8962 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008963
Christopher Plewright38804d62022-11-09 23:55:52 +00008964 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8965
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008966 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008967 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008968
8969 csbi.cbSize = sizeof(csbi);
8970 csbi.srWindow.Right += 1;
8971 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008972 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8973 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008974 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008975# endif
8976}
8977
8978/*
8979 * Set the console colors to the original colors.
8980 */
8981 static void
8982restore_console_color_rgb(void)
8983{
8984# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008985 if (use_alternate_screen_buffer)
8986 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008987
K.Takata27b53be2022-09-18 12:25:49 +01008988 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008989
8990 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008991 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008992
8993 csbi.cbSize = sizeof(csbi);
8994 csbi.srWindow.Right += 1;
8995 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008996 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8997 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008998 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008999# endif
9000}
9001
9002 void
9003control_console_color_rgb(void)
9004{
Christopher Plewright38804d62022-11-09 23:55:52 +00009005 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01009006 set_console_color_rgb();
9007 else
9008 reset_console_color_rgb();
9009}
9010
9011 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01009012use_vtp(void)
9013{
9014 return USE_VTP;
9015}
9016
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02009017 int
9018is_term_win32(void)
9019{
9020 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
9021}
9022
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01009023 int
9024has_vtp_working(void)
9025{
9026 return vtp_working;
9027}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01009028
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01009029#endif
9030
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01009031 int
9032has_conpty_working(void)
9033{
9034 return conpty_working;
9035}
9036
9037 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02009038get_conpty_type(void)
9039{
9040 return conpty_type;
9041}
9042
9043 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01009044is_conpty_stable(void)
9045{
9046 return conpty_stable;
9047}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01009048
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02009049 int
9050get_conpty_fix_type(void)
9051{
9052 return conpty_fix_type;
9053}
9054
Bram Moolenaarafde13b2019-04-28 19:46:49 +02009055#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01009056 void
9057resize_console_buf(void)
9058{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00009059 if (use_alternate_screen_buffer)
9060 return;
9061
Bram Moolenaar78d21da2019-02-17 15:00:52 +01009062 CONSOLE_SCREEN_BUFFER_INFO csbi;
9063 COORD coord;
9064 SMALL_RECT newsize;
9065
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00009066 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
9067 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01009068
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00009069 coord.X = SRWIDTH(csbi.srWindow);
9070 coord.Y = SRHEIGHT(csbi.srWindow);
9071 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01009072
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00009073 newsize.Left = 0;
9074 newsize.Top = 0;
9075 newsize.Right = coord.X - 1;
9076 newsize.Bottom = coord.Y - 1;
9077 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
9078
9079 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01009080}
9081#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009082
9083 char *
9084GetWin32Error(void)
9085{
K.Takatad68b2fc2022-02-12 11:18:37 +00009086 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009087 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00009088
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009089 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
9090 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00009091 if (oldmsg != NULL)
9092 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00009093 if (msg == NULL)
9094 return NULL;
9095
9096 // remove trailing \r\n
9097 char *pcrlf = strstr(msg, "\r\n");
9098 if (pcrlf != NULL)
John Marriotte5297e32025-06-15 16:50:38 +02009099 *pcrlf = NUL;
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00009100 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009101 return msg;
9102}
Paul Ollis65745772022-06-05 16:55:54 +01009103
9104#if defined(FEAT_RELTIME) || defined(PROTO)
9105static HANDLE timer_handle;
9106static int timer_active = FALSE;
9107
9108/*
9109 * Calls to start_timeout alternate the return value pointer between the two
9110 * entries in timeout_flags. If the previously active timeout is very close to
9111 * expiring when start_timeout() is called then a race condition means that the
9112 * set_flag() function may still be invoked after the previous timer is
9113 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
9114 * timeouts.
9115 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009116static sig_atomic_t timeout_flags[2];
9117static int timeout_flag_idx = 0;
9118static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01009119
9120
9121 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01009122set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01009123{
John Marriott2c7ccaa2025-05-26 20:25:38 +02009124 *(sig_atomic_t *)param = TRUE;
Paul Ollis65745772022-06-05 16:55:54 +01009125}
9126
9127/*
9128 * Stop any active timeout.
9129 */
9130 void
9131stop_timeout(void)
9132{
9133 if (timer_active)
9134 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01009135 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01009136 timer_active = FALSE;
9137 if (!ret && GetLastError() != ERROR_IO_PENDING)
9138 {
9139 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
9140 }
9141 }
9142 *timeout_flag = FALSE;
9143}
9144
9145/*
9146 * Start the timeout timer.
9147 *
9148 * The period is defined in milliseconds.
9149 *
9150 * The return value is a pointer to a flag that is initialised to 0. If the
9151 * timeout expires, the flag is set to 1. This will only return pointers to
9152 * static memory; i.e. any pointer returned by this function may always be
9153 * safely dereferenced.
9154 *
9155 * This function is not expected to fail, but if it does it still returns a
9156 * valid flag pointer; the flag will remain stuck at zero.
9157 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009158 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01009159start_timeout(long msec)
9160{
Paul Ollis65745772022-06-05 16:55:54 +01009161 BOOL ret;
9162
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009163 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009164
9165 stop_timeout();
9166 ret = CreateTimerQueueTimer(
9167 &timer_handle, NULL, set_flag, timeout_flag,
9168 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9169 if (!ret)
9170 {
9171 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9172 }
9173 else
9174 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009175 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009176 timer_active = TRUE;
9177 *timeout_flag = FALSE;
9178 }
9179 return timeout_flag;
9180}
9181#endif